@drift-labs/common 1.0.7 → 1.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js +9 -2
  2. package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js.map +1 -1
  3. package/lib/drift/Drift/clients/CentralServerDrift/index.d.ts +21 -6
  4. package/lib/drift/Drift/clients/CentralServerDrift/index.js +63 -6
  5. package/lib/drift/Drift/clients/CentralServerDrift/index.js.map +1 -1
  6. package/lib/drift/Drift/clients/CentralServerDrift/markets.d.ts +7 -0
  7. package/lib/drift/Drift/clients/CentralServerDrift/markets.js +16 -0
  8. package/lib/drift/Drift/clients/CentralServerDrift/markets.js.map +1 -0
  9. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js +4 -3
  10. package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js.map +1 -1
  11. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js +3 -4
  12. package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js.map +1 -1
  13. package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.d.ts +4 -2
  14. package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js +5 -5
  15. package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js.map +1 -1
  16. package/lib/drift/base/actions/user/delete.d.ts +4 -4
  17. package/lib/drift/base/actions/user/delete.js +4 -4
  18. package/lib/drift/base/actions/user/delete.js.map +1 -1
  19. package/lib/drift/cli.js +87 -2
  20. package/lib/drift/cli.js.map +1 -1
  21. package/lib/drift/example.js +2 -0
  22. package/lib/drift/example.js.map +1 -1
  23. package/lib/types/historyServer.d.ts +4 -0
  24. package/lib/types/historyServer.js.map +1 -1
  25. package/package.json +1 -1
@@ -82,12 +82,19 @@ class DriftOperations {
82
82
  const { depositAmount, depositSpotMarketIndex, newAccountName, maxLeverage, poolId = constants_1.MAIN_POOL_ID, referrerName, } = params;
83
83
  const spotMarketConfig = market_1.MARKET_UTILS.getMarketConfig(this.driftClient.env, sdk_1.MarketType.SPOT, depositSpotMarketIndex);
84
84
  const customMaxMarginRatio = trading_1.TRADING_UTILS.convertLeverageToMarginRatio(maxLeverage !== null && maxLeverage !== void 0 ? maxLeverage : 0);
85
+ let userStatsAccount = undefined;
86
+ try {
87
+ userStatsAccount = (_a = this.driftClient.userStats) === null || _a === void 0 ? void 0 : _a.getAccount();
88
+ }
89
+ catch (error) {
90
+ // ignore
91
+ }
85
92
  const { transaction, subAccountId } = await (0, create_1.createUserAndDepositCollateralBaseTxn)({
86
93
  driftClient: this.driftClient,
87
94
  amount: depositAmount.val,
88
95
  spotMarketConfig: spotMarketConfig,
89
96
  authority: this.driftClient.wallet.publicKey,
90
- userStatsAccount: (_a = this.driftClient.userStats) === null || _a === void 0 ? void 0 : _a.getAccount(),
97
+ userStatsAccount: userStatsAccount,
91
98
  accountName: newAccountName,
92
99
  referrerName,
93
100
  customMaxMarginRatio,
@@ -129,7 +136,7 @@ class DriftOperations {
129
136
  }
130
137
  const deleteTxn = await (0, delete_1.deleteUserTxn)({
131
138
  driftClient: this.driftClient,
132
- user: user.userClient,
139
+ userPublicKey: user.userClient.userAccountPublicKey,
133
140
  txParams: this.getTxParams(),
134
141
  });
135
142
  const { txSig } = await this.driftClient.sendTransaction(deleteTxn);
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/drift/Drift/clients/AuthorityDrift/DriftOperations/index.ts"],"names":[],"mappings":";;;AAAA,yCAWyB;AAEzB,kEAAqE;AACrE,wDAAwD;AACxD,oEAAuE;AAEvE,mEAAyE;AACzE,iEAA6F;AAC7F,qEAA2E;AAC3E,iEAAqE;AACrE,uEAA6E;AAU7E,4EAAmF;AACnF,0GAG0E;AAC1E,8DAAoE;AACpE,gHAAmH;AAEn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C,eAAe,CAAC,CAAC;QAE1E,OAAO,KAAK,CAAC;IACd,CAAC;;AAhpBF,0CAipBC;AAhpBgB,iCAAiB,GAAa;IAC7C,iBAAiB,EAAE,KAAM;IACzB,wBAAwB,EAAE,IAAI;IAC9B,4BAA4B,EAAE,GAAG;CACjC,CAAC;AAEc,uCAAuB,GAAG,IAAI,GAAG,EAAE,GAAG,OAAS,CAAC,CAAC,+GAA+G;AA4oBjL;;;;;;;;;;;GAWG","sourcesContent":["import {\n\tBigNum,\n\tDriftClient,\n\tJupiterClient,\n\tMarketType,\n\tMAX_LEVERAGE_ORDER_SIZE,\n\tQuoteResponse,\n\tSwapMode,\n\tTxParams,\n\tUser,\n\tZERO,\n} from '@drift-labs/sdk';\nimport { TransactionSignature } from '@solana/web3.js';\nimport { MARKET_UTILS } from '../../../../../common-ui-utils/market';\nimport { MAIN_POOL_ID } from '../../../../../constants';\nimport { TRADING_UTILS } from '../../../../../common-ui-utils/trading';\nimport { UserAccountCache } from '../../../stores/UserAccountCache';\nimport { createDepositTxn } from '../../../../base/actions/spot/deposit';\nimport { createUserAndDepositCollateralBaseTxn } from '../../../../base/actions/user/create';\nimport { createWithdrawTxn } from '../../../../base/actions/spot/withdraw';\nimport { deleteUserTxn } from '../../../../base/actions/user/delete';\nimport { createSettlePnlTxn } from '../../../../base/actions/perp/settlePnl';\nimport {\n\tCreateUserAndDepositParams,\n\tDepositParams,\n\tWithdrawParams,\n\tPerpOrderParams,\n\tSwapParams,\n\tSettleAccountPnlParams,\n\tCancelOrdersParams,\n} from './types';\nimport { createCancelOrdersTxn } from '../../../../base/actions/trade/cancelOrder';\nimport {\n\tcreateOpenPerpMarketOrder,\n\tOpenPerpMarketOrderParams,\n} from '../../../../base/actions/trade/openPerpOrder/openPerpMarketOrder';\nimport { createSwapTxn } from '../../../../base/actions/trade/swap';\nimport { createOpenPerpNonMarketOrder } from '../../../../base/actions/trade/openPerpOrder/openPerpNonMarketOrder';\n\n/**\n * Handles majority of the relevant operations on the Drift program including deposits,\n * withdrawals, position management, and trading operations.\n *\n * This class encapsulates the trading logic and provides a clean API for\n * executing various trading operations while handling common patterns like\n * token address resolution and transaction preparation.\n */\nexport class DriftOperations {\n\tstatic readonly DEFAULT_TX_PARAMS: TxParams = {\n\t\tcomputeUnitsPrice: 50_000,\n\t\tuseSimulatedComputeUnits: true,\n\t\tcomputeUnitsBufferMultiplier: 1.3,\n\t};\n\n\tstatic readonly MAX_COMPUTE_UNITS_PRICE = 1e15 / 10 / 1_400_000; // 1e15 = 1 SOL worth of micro lamports; 1e15 / 10 = 0.1 SOL worth of micro lamports; 1.4M = max compute units;\n\n\t/**\n\t * Creates a new DriftOperations instance.\n\t *\n\t * @param driftClient - The DriftClient instance for executing transactions\n\t * @param getUserAccountCache - Function to get the user account cache. We lazily load the user account cache, so that we always get the latest user account data.\n\t * @param getPriorityFee - Function to get current priority fee in micro lamports\n\t */\n\tconstructor(\n\t\tprivate driftClient: DriftClient,\n\t\tprivate getUserAccountCache: () => UserAccountCache,\n\t\tprivate dlobServerHttpUrl: string,\n\t\tprivate swiftServerUrl: string,\n\t\tprivate getPriorityFee: () => number\n\t) {}\n\n\t/**\n\t * Gets transaction parameters with dynamic priority fees.\n\t * Falls back to default if priority fee function is not available.\n\t */\n\tprivate getTxParams(overrides?: Partial<TxParams>): TxParams {\n\t\tconst unsafePriorityFee = Math.floor(\n\t\t\tthis.getPriorityFee() ??\n\t\t\t\tDriftOperations.DEFAULT_TX_PARAMS.computeUnitsPrice\n\t\t);\n\n\t\tconst safePriorityFee = Math.min(\n\t\t\tunsafePriorityFee,\n\t\t\tDriftOperations.MAX_COMPUTE_UNITS_PRICE\n\t\t);\n\n\t\treturn {\n\t\t\t...DriftOperations.DEFAULT_TX_PARAMS,\n\t\t\tcomputeUnitsPrice: safePriorityFee,\n\t\t\t...overrides,\n\t\t};\n\t}\n\n\t/**\n\t * Creates a new user account and deposits initial collateral.\n\t *\n\t * This method handles the complete onboarding flow for new users including:\n\t * - Validating that the subaccount doesn't already exist\n\t * - Resolving referrer information if provided\n\t * - Getting the correct token address for deposits\n\t * - Creating the user account with custom leverage settings\n\t * - Subscribing to the new user's account updates\n\t *\n\t * @param params - The parameters for user creation and initial deposit\n\t * @returns Promise resolving to transaction signature and user account public key\n\t *\n\t * @throws Error if subaccount already exists\n\t *\n\t * @example\n\t * ```typescript\n\t * const result = await tradingOps.createUserAndDeposit({\n\t * depositAmount: new BigNum(100),\n\t * depositSpotMarketIndex: 0, // USDC\n\t * name: \"Trading Account\",\n\t * maxLeverage: 5,\n\t * subAccountId: 0\n\t * });\n\t * ```\n\t */\n\tasync createUserAndDeposit(params: CreateUserAndDepositParams): Promise<{\n\t\ttxSig: TransactionSignature;\n\t\tuser: User;\n\t}> {\n\t\tconst {\n\t\t\tdepositAmount,\n\t\t\tdepositSpotMarketIndex,\n\t\t\tnewAccountName,\n\t\t\tmaxLeverage,\n\t\t\tpoolId = MAIN_POOL_ID,\n\t\t\treferrerName,\n\t\t} = params;\n\n\t\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tdepositSpotMarketIndex\n\t\t);\n\n\t\tconst customMaxMarginRatio = TRADING_UTILS.convertLeverageToMarginRatio(\n\t\t\tmaxLeverage ?? 0\n\t\t);\n\n\t\tconst { transaction, subAccountId } =\n\t\t\tawait createUserAndDepositCollateralBaseTxn({\n\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\tamount: depositAmount.val,\n\t\t\t\tspotMarketConfig: spotMarketConfig,\n\t\t\t\tauthority: this.driftClient.wallet.publicKey,\n\t\t\t\tuserStatsAccount: this.driftClient.userStats?.getAccount(),\n\t\t\t\taccountName: newAccountName,\n\t\t\t\treferrerName,\n\t\t\t\tcustomMaxMarginRatio,\n\t\t\t\tpoolId,\n\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(transaction);\n\n\t\tawait this.driftClient.addUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t); // adds user to driftclient's user map, subscribes to user account data\n\t\tconst user = this.driftClient.getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tuser.eventEmitter.on('update', () => {\n\t\t\tthis.getUserAccountCache().updateUserAccount(user);\n\t\t});\n\n\t\treturn {\n\t\t\ttxSig,\n\t\t\tuser,\n\t\t};\n\t}\n\n\t/**\n\t * Deletes a user account.\n\t *\n\t * This method removes a user's sub-account from the Drift.\n\t *\n\t * @param subAccountId - The ID of the sub-account to delete\n\t * @returns A promise that resolves to the transaction signature of the deletion\n\t *\n\t * @throws {Error} When the user account is not found in the cache\n\t *\n\t * @example\n\t * ```typescript\n\t * // Delete user sub-account with ID 0\n\t * const txSignature = await tradingOps.deleteUser(0);\n\t * console.log('User deleted with transaction:', txSignature);\n\t * ```\n\t */\n\tasync deleteUser(subAccountId: number): Promise<TransactionSignature> {\n\t\tconst user = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!user) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst deleteTxn = await deleteUserTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuser: user.userClient,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(deleteTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Deposits collateral into a user's spot market position.\n\t *\n\t * This method handles depositing tokens into a user's account, with optional\n\t * support for max borrow repayment scenarios where the deposit amount may be\n\t * over-estimated to ensure complete repayment of borrowed funds.\n\t *\n\t * @param params - The deposit parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.deposit({\n\t * subAccountId: 0,\n\t * amount: new BigNum(50),\n\t * spotMarketIndex: 0, // USDC\n\t * isMaxBorrowRepayment: false\n\t * });\n\t * ```\n\t */\n\tasync deposit(params: DepositParams): Promise<TransactionSignature> {\n\t\tconst { subAccountId, amount, spotMarketIndex, isMaxBorrowRepayment } =\n\t\t\tparams;\n\n\t\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tspotMarketIndex\n\t\t);\n\n\t\tconst user = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!user) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst depositTxn = await createDepositTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuser: user.userClient,\n\t\t\tamount: amount,\n\t\t\tspotMarketConfig: spotMarketConfig,\n\t\t\tisMaxBorrowRepayment,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(depositTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Withdraws collateral from a user's spot market position.\n\t *\n\t * This method handles withdrawing tokens from a user's account with options\n\t * for borrowing (if allowBorrow is true) or reduce-only withdrawals. For max\n\t * withdrawals with reduce-only, the amount is over-estimated to ensure\n\t * complete withdrawal.\n\t *\n\t * @param params - The withdrawal parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.withdraw({\n\t * subAccountId: 0,\n\t * amount: new BigNum(25),\n\t * spotMarketIndex: 0, // USDC\n\t * allowBorrow: false,\n\t * isMax: false\n\t * });\n\t * ```\n\t */\n\tasync withdraw(params: WithdrawParams): Promise<TransactionSignature> {\n\t\tconst {\n\t\t\tsubAccountId,\n\t\t\tamount,\n\t\t\tspotMarketIndex,\n\t\t\tisBorrow = false,\n\t\t\tisMax = false,\n\t\t} = params;\n\n\t\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tspotMarketIndex\n\t\t);\n\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst withdrawTxn = await createWithdrawTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tamount,\n\t\t\tspotMarketConfig,\n\t\t\tuser: accountData.userClient,\n\t\t\tisBorrow,\n\t\t\tisMax,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(withdrawTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Opens a perpetual market order (placeholder for future implementation).\n\t *\n\t * This method will handle opening long or short positions in perpetual markets\n\t * with support for market and limit orders, reduce-only orders, and post-only orders.\n\t *\n\t * @param params - The perp order parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.openPerpMarketOrder({\n\t * marketIndex: 0, // SOL-PERP\n\t * direction: 'long',\n\t * baseAssetAmount: new BigNum(1), // 1 SOL\n\t * orderType: 'market',\n\t * subAccountId: 0\n\t * });\n\t * ```\n\t */\n\tasync openPerpOrder(\n\t\tparams: PerpOrderParams\n\t): Promise<TransactionSignature | void> {\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tparams.subAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst user = accountData.userClient;\n\n\t\tconst processBracketOrders = (bracketOrdersInput?: {\n\t\t\ttakeProfitPrice?: BigNum;\n\t\t\tstopLossPrice?: BigNum;\n\t\t}) => {\n\t\t\tconst bracketOrders: OpenPerpMarketOrderParams['bracketOrders'] = {};\n\n\t\t\tif (bracketOrdersInput?.takeProfitPrice) {\n\t\t\t\tbracketOrders.takeProfit = {\n\t\t\t\t\ttriggerPrice: bracketOrdersInput.takeProfitPrice.val,\n\t\t\t\t\tbaseAssetAmount: params.size.val,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (bracketOrdersInput?.stopLossPrice) {\n\t\t\t\tbracketOrders.stopLoss = {\n\t\t\t\t\ttriggerPrice: bracketOrdersInput.stopLossPrice.val,\n\t\t\t\t\tbaseAssetAmount: params.size.val,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn bracketOrders;\n\t\t};\n\n\t\tconst amountBN = params.isMaxLeverage\n\t\t\t? MAX_LEVERAGE_ORDER_SIZE\n\t\t\t: params.size.val;\n\n\t\tswitch (params.orderConfig.orderType) {\n\t\t\tcase 'market': {\n\t\t\t\tconst useSwift = !params.orderConfig.disableSwift;\n\n\t\t\t\tconst bracketOrders = processBracketOrders(\n\t\t\t\t\tparams.orderConfig.bracketOrders\n\t\t\t\t);\n\n\t\t\t\t// we split the logic for SWIFT and non-SWIFT orders to achieve better type inference\n\t\t\t\tif (useSwift) {\n\t\t\t\t\tconst swiftOrderResult = await createOpenPerpMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\tuseSwift: true,\n\t\t\t\t\t\tswiftOptions: {\n\t\t\t\t\t\t\t// @ts-ignore TODO: we might want to add signMessage to the IWallet interface\n\t\t\t\t\t\t\twallet: this.driftClient.wallet,\n\t\t\t\t\t\t\tswiftServerUrl: this.swiftServerUrl,\n\t\t\t\t\t\t\t...params.orderConfig.swiftOptions,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\tdlobServerHttpUrl: this.dlobServerHttpUrl,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\toptionalAuctionParamsInputs:\n\t\t\t\t\t\t\tparams.orderConfig.optionalAuctionParamsInputs,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn swiftOrderResult;\n\t\t\t\t} else {\n\t\t\t\t\tconst result = await createOpenPerpMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\toptionalAuctionParamsInputs:\n\t\t\t\t\t\t\tparams.orderConfig.optionalAuctionParamsInputs,\n\t\t\t\t\t\tdlobServerHttpUrl: this.dlobServerHttpUrl,\n\t\t\t\t\t\tuseSwift: false,\n\t\t\t\t\t});\n\n\t\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(result);\n\n\t\t\t\t\treturn txSig;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcase 'limit': {\n\t\t\t\tconst useSwift = !params.orderConfig.disableSwift;\n\n\t\t\t\tconst bracketOrders = processBracketOrders(\n\t\t\t\t\tparams.orderConfig.bracketOrders\n\t\t\t\t);\n\n\t\t\t\t// we split the logic for SWIFT and non-SWIFT orders to achieve better type inference\n\t\t\t\tif (useSwift) {\n\t\t\t\t\tconst swiftOrderResult = await createOpenPerpNonMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\torderConfig: {\n\t\t\t\t\t\t\torderType: 'limit',\n\t\t\t\t\t\t\tlimitPrice: params.orderConfig.limitPrice.val,\n\t\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\t},\n\t\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\t\tpostOnly: params.postOnly,\n\t\t\t\t\t\tuseSwift: true,\n\t\t\t\t\t\tswiftOptions: {\n\t\t\t\t\t\t\t// @ts-ignore TODO: we might want to add signMessage to the IWallet interface\n\t\t\t\t\t\t\twallet: this.driftClient.wallet,\n\t\t\t\t\t\t\tswiftServerUrl: this.swiftServerUrl,\n\t\t\t\t\t\t\t...params.orderConfig.swiftOptions,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\n\t\t\t\t\treturn swiftOrderResult;\n\t\t\t\t} else {\n\t\t\t\t\tconst txn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\torderConfig: {\n\t\t\t\t\t\t\torderType: 'limit',\n\t\t\t\t\t\t\tlimitPrice: params.orderConfig.limitPrice.val,\n\t\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\t},\n\t\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\t\tpostOnly: params.postOnly,\n\t\t\t\t\t\tuseSwift: false,\n\t\t\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t\t\t});\n\n\t\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\t\t\t\treturn txSig;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcase 'takeProfit':\n\t\t\tcase 'stopLoss': {\n\t\t\t\tconst txn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\tamount: amountBN,\n\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\torderConfig: {\n\t\t\t\t\t\torderType: params.orderConfig.orderType,\n\t\t\t\t\t\ttriggerPrice: params.orderConfig.triggerPrice.val,\n\t\t\t\t\t\tlimitPrice: params.orderConfig.limitPrice?.val ?? ZERO,\n\t\t\t\t\t},\n\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\tuseSwift: false,\n\t\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t\t});\n\n\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\t\t\treturn txSig;\n\t\t\t}\n\t\t\tcase 'oracleLimit': {\n\t\t\t\tconst txn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\tamount: amountBN,\n\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\torderConfig: {\n\t\t\t\t\t\torderType: 'oracleLimit',\n\t\t\t\t\t\toraclePriceOffset: params.orderConfig.oraclePriceOffset.val,\n\t\t\t\t\t},\n\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\tuseSwift: false,\n\t\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t\t});\n\n\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\t\t\treturn txSig;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tconst _exhaustiveCheck: never = params.orderConfig;\n\t\t\t\tthrow new Error('Invalid order type');\n\t\t\t}\n\t\t}\n\t}\n\n\tasync getSwapQuote(\n\t\tparams: Omit<SwapParams, 'jupiterQuote'> & {\n\t\t\tslippageBps?: number;\n\t\t\tswapMode?: SwapMode;\n\t\t\tonlyDirectRoutes?: boolean;\n\t\t}\n\t): Promise<QuoteResponse> {\n\t\tconst jupiterClient = new JupiterClient({\n\t\t\tconnection: this.driftClient.connection,\n\t\t});\n\n\t\tconst inputMint = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tparams.fromMarketIndex\n\t\t).mint;\n\t\tconst outputMint = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tparams.toMarketIndex\n\t\t).mint;\n\n\t\tconst jupiterQuote = await jupiterClient.getQuote({\n\t\t\tinputMint,\n\t\t\toutputMint,\n\t\t\tamount: params.amount.val,\n\t\t\tslippageBps: params.slippageBps,\n\t\t\tswapMode: params.swapMode,\n\t\t\tonlyDirectRoutes: params.onlyDirectRoutes,\n\t\t});\n\n\t\treturn jupiterQuote;\n\t}\n\n\t/**\n\t * Executes a swap between two spot markets (placeholder for future implementation).\n\t *\n\t * This method will handle swapping between different spot markets through\n\t * the Drift protocol's swap functionality.\n\t *\n\t * @param params - The swap parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.executeSwap({\n\t * fromMarketIndex: 0, // USDC\n\t * toMarketIndex: 1, // SOL\n\t * amount: new BigNum(100),\n\t * subAccountId: 0,\n\t * minReceiveAmount: new BigNum(0.5)\n\t * });\n\t * ```\n\t */\n\tasync swap(params: SwapParams): Promise<TransactionSignature> {\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tparams.subAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst jupiterClient = new JupiterClient({\n\t\t\tconnection: this.driftClient.connection,\n\t\t});\n\n\t\tconst jupiterQuote = params.jupiterQuote\n\t\t\t? params.jupiterQuote\n\t\t\t: await this.getSwapQuote(params);\n\n\t\tconst swapTxn = await createSwapTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tjupiterClient,\n\t\t\tuser: accountData.userClient,\n\t\t\tswapFromMarketIndex: params.fromMarketIndex,\n\t\t\tswapToMarketIndex: params.toMarketIndex,\n\t\t\tamount: params.amount.val,\n\t\t\tquote: jupiterQuote,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(swapTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Settles P&L and funding for all perp position.\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.settlePnl({\n\t * subAccountId: 0,\n\t * marketIndex: 0, // SOL-PERP\n\t * counterpartySubAccountId: 1\n\t * });\n\t * ```\n\t */\n\tasync settleAccountPnl(\n\t\tparams: SettleAccountPnlParams\n\t): Promise<TransactionSignature> {\n\t\tconst { subAccountId } = params;\n\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst marketIndexes = accountData.openPerpPositions.map(\n\t\t\t(position) => position.marketIndex\n\t\t);\n\n\t\tconst settlePnlTxn = await createSettlePnlTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuser: accountData.userClient,\n\t\t\tmarketIndexes,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(settlePnlTxn);\n\n\t\treturn txSig;\n\t}\n\n\tasync cancelOrders(\n\t\tparams: CancelOrdersParams\n\t): Promise<TransactionSignature> {\n\t\tconst { subAccountId, orderIds } = params;\n\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst cancelOrdersTxn = await createCancelOrdersTxn(\n\t\t\tthis.driftClient,\n\t\t\taccountData.userClient,\n\t\t\torderIds,\n\t\t\tthis.getTxParams()\n\t\t);\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(cancelOrdersTxn);\n\n\t\treturn txSig;\n\t}\n}\n\n/**\n * TODO:\n * - transfer between subaccounts\n * - close position?\n * - close multiple positions\n * - edit open order\n * - create user only\n *\n * - open spot order\n * - rename subaccount\n * - withdraw dust positions\n */\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/drift/Drift/clients/AuthorityDrift/DriftOperations/index.ts"],"names":[],"mappings":";;;AAAA,yCAYyB;AAEzB,kEAAqE;AACrE,wDAAwD;AACxD,oEAAuE;AAEvE,mEAAyE;AACzE,iEAA6F;AAC7F,qEAA2E;AAC3E,iEAAqE;AACrE,uEAA6E;AAU7E,4EAAmF;AACnF,0GAG0E;AAC1E,8DAAoE;AACpE,gHAAmH;AAEnH;;;;;;;GAOG;AACH,MAAa,eAAe;IAS3B;;;;;;OAMG;IACH,YACS,WAAwB,EACxB,mBAA2C,EAC3C,iBAAyB,EACzB,cAAsB,EACtB,cAA4B;QAJ5B,gBAAW,GAAX,WAAW,CAAa;QACxB,wBAAmB,GAAnB,mBAAmB,CAAwB;QAC3C,sBAAiB,GAAjB,iBAAiB,CAAQ;QACzB,mBAAc,GAAd,cAAc,CAAQ;QACtB,mBAAc,GAAd,cAAc,CAAc;IAClC,CAAC;IAEJ;;;OAGG;IACK,WAAW,CAAC,SAA6B;;QAChD,MAAM,iBAAiB,GAAG,IAAI,CAAC,KAAK,CACnC,MAAA,IAAI,CAAC,cAAc,EAAE,mCACpB,eAAe,CAAC,iBAAiB,CAAC,iBAAiB,CACpD,CAAC;QAEF,MAAM,eAAe,GAAG,IAAI,CAAC,GAAG,CAC/B,iBAAiB,EACjB,eAAe,CAAC,uBAAuB,CACvC,CAAC;QAEF,OAAO;YACN,GAAG,eAAe,CAAC,iBAAiB;YACpC,iBAAiB,EAAE,eAAe;YAClC,GAAG,SAAS;SACZ,CAAC;IACH,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;;;;;OAyBG;IACH,KAAK,CAAC,oBAAoB,CAAC,MAAkC;;QAI5D,MAAM,EACL,aAAa,EACb,sBAAsB,EACtB,cAAc,EACd,WAAW,EACX,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IACd,CAAC;IAED,KAAK,CAAC,YAAY,CACjB,MAA0B;QAE1B,MAAM,EAAE,YAAY,EAAE,QAAQ,EAAE,GAAG,MAAM,CAAC;QAE1C,MAAM,WAAW,GAAG,IAAI,CAAC,mBAAmB,EAAE,CAAC,OAAO,CACrD,YAAY,EACZ,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,SAAS,CACjC,CAAC;QAEF,IAAI,CAAC,WAAW,EAAE,CAAC;YAClB,MAAM,IAAI,KAAK,CAAC,gBAAgB,CAAC,CAAC;QACnC,CAAC;QAED,MAAM,eAAe,GAAG,MAAM,IAAA,mCAAqB,EAClD,IAAI,CAAC,WAAW,EAChB,WAAW,CAAC,UAAU,EACtB,QAAQ,EACR,IAAI,CAAC,WAAW,EAAE,CAClB,CAAC;QAEF,MAAM,EAAE,KAAK,EAAE,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,eAAe,CAAC,eAAe,CAAC,CAAC;QAE1E,OAAO,KAAK,CAAC;IACd,CAAC;;AAxpBF,0CAypBC;AAxpBgB,iCAAiB,GAAa;IAC7C,iBAAiB,EAAE,KAAM;IACzB,wBAAwB,EAAE,IAAI;IAC9B,4BAA4B,EAAE,GAAG;CACjC,CAAC;AAEc,uCAAuB,GAAG,IAAI,GAAG,EAAE,GAAG,OAAS,CAAC,CAAC,+GAA+G;AAopBjL;;;;;;;;;;;GAWG","sourcesContent":["import {\n\tBigNum,\n\tDriftClient,\n\tJupiterClient,\n\tMarketType,\n\tMAX_LEVERAGE_ORDER_SIZE,\n\tQuoteResponse,\n\tSwapMode,\n\tTxParams,\n\tUser,\n\tUserStatsAccount,\n\tZERO,\n} from '@drift-labs/sdk';\nimport { TransactionSignature } from '@solana/web3.js';\nimport { MARKET_UTILS } from '../../../../../common-ui-utils/market';\nimport { MAIN_POOL_ID } from '../../../../../constants';\nimport { TRADING_UTILS } from '../../../../../common-ui-utils/trading';\nimport { UserAccountCache } from '../../../stores/UserAccountCache';\nimport { createDepositTxn } from '../../../../base/actions/spot/deposit';\nimport { createUserAndDepositCollateralBaseTxn } from '../../../../base/actions/user/create';\nimport { createWithdrawTxn } from '../../../../base/actions/spot/withdraw';\nimport { deleteUserTxn } from '../../../../base/actions/user/delete';\nimport { createSettlePnlTxn } from '../../../../base/actions/perp/settlePnl';\nimport {\n\tCreateUserAndDepositParams,\n\tDepositParams,\n\tWithdrawParams,\n\tPerpOrderParams,\n\tSwapParams,\n\tSettleAccountPnlParams,\n\tCancelOrdersParams,\n} from './types';\nimport { createCancelOrdersTxn } from '../../../../base/actions/trade/cancelOrder';\nimport {\n\tcreateOpenPerpMarketOrder,\n\tOpenPerpMarketOrderParams,\n} from '../../../../base/actions/trade/openPerpOrder/openPerpMarketOrder';\nimport { createSwapTxn } from '../../../../base/actions/trade/swap';\nimport { createOpenPerpNonMarketOrder } from '../../../../base/actions/trade/openPerpOrder/openPerpNonMarketOrder';\n\n/**\n * Handles majority of the relevant operations on the Drift program including deposits,\n * withdrawals, position management, and trading operations.\n *\n * This class encapsulates the trading logic and provides a clean API for\n * executing various trading operations while handling common patterns like\n * token address resolution and transaction preparation.\n */\nexport class DriftOperations {\n\tstatic readonly DEFAULT_TX_PARAMS: TxParams = {\n\t\tcomputeUnitsPrice: 50_000,\n\t\tuseSimulatedComputeUnits: true,\n\t\tcomputeUnitsBufferMultiplier: 1.3,\n\t};\n\n\tstatic readonly MAX_COMPUTE_UNITS_PRICE = 1e15 / 10 / 1_400_000; // 1e15 = 1 SOL worth of micro lamports; 1e15 / 10 = 0.1 SOL worth of micro lamports; 1.4M = max compute units;\n\n\t/**\n\t * Creates a new DriftOperations instance.\n\t *\n\t * @param driftClient - The DriftClient instance for executing transactions\n\t * @param getUserAccountCache - Function to get the user account cache. We lazily load the user account cache, so that we always get the latest user account data.\n\t * @param getPriorityFee - Function to get current priority fee in micro lamports\n\t */\n\tconstructor(\n\t\tprivate driftClient: DriftClient,\n\t\tprivate getUserAccountCache: () => UserAccountCache,\n\t\tprivate dlobServerHttpUrl: string,\n\t\tprivate swiftServerUrl: string,\n\t\tprivate getPriorityFee: () => number\n\t) {}\n\n\t/**\n\t * Gets transaction parameters with dynamic priority fees.\n\t * Falls back to default if priority fee function is not available.\n\t */\n\tprivate getTxParams(overrides?: Partial<TxParams>): TxParams {\n\t\tconst unsafePriorityFee = Math.floor(\n\t\t\tthis.getPriorityFee() ??\n\t\t\t\tDriftOperations.DEFAULT_TX_PARAMS.computeUnitsPrice\n\t\t);\n\n\t\tconst safePriorityFee = Math.min(\n\t\t\tunsafePriorityFee,\n\t\t\tDriftOperations.MAX_COMPUTE_UNITS_PRICE\n\t\t);\n\n\t\treturn {\n\t\t\t...DriftOperations.DEFAULT_TX_PARAMS,\n\t\t\tcomputeUnitsPrice: safePriorityFee,\n\t\t\t...overrides,\n\t\t};\n\t}\n\n\t/**\n\t * Creates a new user account and deposits initial collateral.\n\t *\n\t * This method handles the complete onboarding flow for new users including:\n\t * - Validating that the subaccount doesn't already exist\n\t * - Resolving referrer information if provided\n\t * - Getting the correct token address for deposits\n\t * - Creating the user account with custom leverage settings\n\t * - Subscribing to the new user's account updates\n\t *\n\t * @param params - The parameters for user creation and initial deposit\n\t * @returns Promise resolving to transaction signature and user account public key\n\t *\n\t * @throws Error if subaccount already exists\n\t *\n\t * @example\n\t * ```typescript\n\t * const result = await tradingOps.createUserAndDeposit({\n\t * depositAmount: new BigNum(100),\n\t * depositSpotMarketIndex: 0, // USDC\n\t * name: \"Trading Account\",\n\t * maxLeverage: 5,\n\t * subAccountId: 0\n\t * });\n\t * ```\n\t */\n\tasync createUserAndDeposit(params: CreateUserAndDepositParams): Promise<{\n\t\ttxSig: TransactionSignature;\n\t\tuser: User;\n\t}> {\n\t\tconst {\n\t\t\tdepositAmount,\n\t\t\tdepositSpotMarketIndex,\n\t\t\tnewAccountName,\n\t\t\tmaxLeverage,\n\t\t\tpoolId = MAIN_POOL_ID,\n\t\t\treferrerName,\n\t\t} = params;\n\n\t\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tdepositSpotMarketIndex\n\t\t);\n\n\t\tconst customMaxMarginRatio = TRADING_UTILS.convertLeverageToMarginRatio(\n\t\t\tmaxLeverage ?? 0\n\t\t);\n\n\t\tlet userStatsAccount: UserStatsAccount | undefined = undefined;\n\n\t\ttry {\n\t\t\tuserStatsAccount = this.driftClient.userStats?.getAccount();\n\t\t} catch (error) {\n\t\t\t// ignore\n\t\t}\n\n\t\tconst { transaction, subAccountId } =\n\t\t\tawait createUserAndDepositCollateralBaseTxn({\n\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\tamount: depositAmount.val,\n\t\t\t\tspotMarketConfig: spotMarketConfig,\n\t\t\t\tauthority: this.driftClient.wallet.publicKey,\n\t\t\t\tuserStatsAccount: userStatsAccount,\n\t\t\t\taccountName: newAccountName,\n\t\t\t\treferrerName,\n\t\t\t\tcustomMaxMarginRatio,\n\t\t\t\tpoolId,\n\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(transaction);\n\n\t\tawait this.driftClient.addUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t); // adds user to driftclient's user map, subscribes to user account data\n\t\tconst user = this.driftClient.getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tuser.eventEmitter.on('update', () => {\n\t\t\tthis.getUserAccountCache().updateUserAccount(user);\n\t\t});\n\n\t\treturn {\n\t\t\ttxSig,\n\t\t\tuser,\n\t\t};\n\t}\n\n\t/**\n\t * Deletes a user account.\n\t *\n\t * This method removes a user's sub-account from the Drift.\n\t *\n\t * @param subAccountId - The ID of the sub-account to delete\n\t * @returns A promise that resolves to the transaction signature of the deletion\n\t *\n\t * @throws {Error} When the user account is not found in the cache\n\t *\n\t * @example\n\t * ```typescript\n\t * // Delete user sub-account with ID 0\n\t * const txSignature = await tradingOps.deleteUser(0);\n\t * console.log('User deleted with transaction:', txSignature);\n\t * ```\n\t */\n\tasync deleteUser(subAccountId: number): Promise<TransactionSignature> {\n\t\tconst user = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!user) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst deleteTxn = await deleteUserTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuserPublicKey: user.userClient.userAccountPublicKey,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(deleteTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Deposits collateral into a user's spot market position.\n\t *\n\t * This method handles depositing tokens into a user's account, with optional\n\t * support for max borrow repayment scenarios where the deposit amount may be\n\t * over-estimated to ensure complete repayment of borrowed funds.\n\t *\n\t * @param params - The deposit parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.deposit({\n\t * subAccountId: 0,\n\t * amount: new BigNum(50),\n\t * spotMarketIndex: 0, // USDC\n\t * isMaxBorrowRepayment: false\n\t * });\n\t * ```\n\t */\n\tasync deposit(params: DepositParams): Promise<TransactionSignature> {\n\t\tconst { subAccountId, amount, spotMarketIndex, isMaxBorrowRepayment } =\n\t\t\tparams;\n\n\t\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tspotMarketIndex\n\t\t);\n\n\t\tconst user = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!user) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst depositTxn = await createDepositTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuser: user.userClient,\n\t\t\tamount: amount,\n\t\t\tspotMarketConfig: spotMarketConfig,\n\t\t\tisMaxBorrowRepayment,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(depositTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Withdraws collateral from a user's spot market position.\n\t *\n\t * This method handles withdrawing tokens from a user's account with options\n\t * for borrowing (if allowBorrow is true) or reduce-only withdrawals. For max\n\t * withdrawals with reduce-only, the amount is over-estimated to ensure\n\t * complete withdrawal.\n\t *\n\t * @param params - The withdrawal parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.withdraw({\n\t * subAccountId: 0,\n\t * amount: new BigNum(25),\n\t * spotMarketIndex: 0, // USDC\n\t * allowBorrow: false,\n\t * isMax: false\n\t * });\n\t * ```\n\t */\n\tasync withdraw(params: WithdrawParams): Promise<TransactionSignature> {\n\t\tconst {\n\t\t\tsubAccountId,\n\t\t\tamount,\n\t\t\tspotMarketIndex,\n\t\t\tisBorrow = false,\n\t\t\tisMax = false,\n\t\t} = params;\n\n\t\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tspotMarketIndex\n\t\t);\n\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst withdrawTxn = await createWithdrawTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tamount,\n\t\t\tspotMarketConfig,\n\t\t\tuser: accountData.userClient,\n\t\t\tisBorrow,\n\t\t\tisMax,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(withdrawTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Opens a perpetual market order (placeholder for future implementation).\n\t *\n\t * This method will handle opening long or short positions in perpetual markets\n\t * with support for market and limit orders, reduce-only orders, and post-only orders.\n\t *\n\t * @param params - The perp order parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.openPerpMarketOrder({\n\t * marketIndex: 0, // SOL-PERP\n\t * direction: 'long',\n\t * baseAssetAmount: new BigNum(1), // 1 SOL\n\t * orderType: 'market',\n\t * subAccountId: 0\n\t * });\n\t * ```\n\t */\n\tasync openPerpOrder(\n\t\tparams: PerpOrderParams\n\t): Promise<TransactionSignature | void> {\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tparams.subAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst user = accountData.userClient;\n\n\t\tconst processBracketOrders = (bracketOrdersInput?: {\n\t\t\ttakeProfitPrice?: BigNum;\n\t\t\tstopLossPrice?: BigNum;\n\t\t}) => {\n\t\t\tconst bracketOrders: OpenPerpMarketOrderParams['bracketOrders'] = {};\n\n\t\t\tif (bracketOrdersInput?.takeProfitPrice) {\n\t\t\t\tbracketOrders.takeProfit = {\n\t\t\t\t\ttriggerPrice: bracketOrdersInput.takeProfitPrice.val,\n\t\t\t\t\tbaseAssetAmount: params.size.val,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (bracketOrdersInput?.stopLossPrice) {\n\t\t\t\tbracketOrders.stopLoss = {\n\t\t\t\t\ttriggerPrice: bracketOrdersInput.stopLossPrice.val,\n\t\t\t\t\tbaseAssetAmount: params.size.val,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn bracketOrders;\n\t\t};\n\n\t\tconst amountBN = params.isMaxLeverage\n\t\t\t? MAX_LEVERAGE_ORDER_SIZE\n\t\t\t: params.size.val;\n\n\t\tswitch (params.orderConfig.orderType) {\n\t\t\tcase 'market': {\n\t\t\t\tconst useSwift = !params.orderConfig.disableSwift;\n\n\t\t\t\tconst bracketOrders = processBracketOrders(\n\t\t\t\t\tparams.orderConfig.bracketOrders\n\t\t\t\t);\n\n\t\t\t\t// we split the logic for SWIFT and non-SWIFT orders to achieve better type inference\n\t\t\t\tif (useSwift) {\n\t\t\t\t\tconst swiftOrderResult = await createOpenPerpMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\tuseSwift: true,\n\t\t\t\t\t\tswiftOptions: {\n\t\t\t\t\t\t\t// @ts-ignore TODO: we might want to add signMessage to the IWallet interface\n\t\t\t\t\t\t\twallet: this.driftClient.wallet,\n\t\t\t\t\t\t\tswiftServerUrl: this.swiftServerUrl,\n\t\t\t\t\t\t\t...params.orderConfig.swiftOptions,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\tdlobServerHttpUrl: this.dlobServerHttpUrl,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\toptionalAuctionParamsInputs:\n\t\t\t\t\t\t\tparams.orderConfig.optionalAuctionParamsInputs,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn swiftOrderResult;\n\t\t\t\t} else {\n\t\t\t\t\tconst result = await createOpenPerpMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\toptionalAuctionParamsInputs:\n\t\t\t\t\t\t\tparams.orderConfig.optionalAuctionParamsInputs,\n\t\t\t\t\t\tdlobServerHttpUrl: this.dlobServerHttpUrl,\n\t\t\t\t\t\tuseSwift: false,\n\t\t\t\t\t});\n\n\t\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(result);\n\n\t\t\t\t\treturn txSig;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcase 'limit': {\n\t\t\t\tconst useSwift = !params.orderConfig.disableSwift;\n\n\t\t\t\tconst bracketOrders = processBracketOrders(\n\t\t\t\t\tparams.orderConfig.bracketOrders\n\t\t\t\t);\n\n\t\t\t\t// we split the logic for SWIFT and non-SWIFT orders to achieve better type inference\n\t\t\t\tif (useSwift) {\n\t\t\t\t\tconst swiftOrderResult = await createOpenPerpNonMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\torderConfig: {\n\t\t\t\t\t\t\torderType: 'limit',\n\t\t\t\t\t\t\tlimitPrice: params.orderConfig.limitPrice.val,\n\t\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\t},\n\t\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\t\tpostOnly: params.postOnly,\n\t\t\t\t\t\tuseSwift: true,\n\t\t\t\t\t\tswiftOptions: {\n\t\t\t\t\t\t\t// @ts-ignore TODO: we might want to add signMessage to the IWallet interface\n\t\t\t\t\t\t\twallet: this.driftClient.wallet,\n\t\t\t\t\t\t\tswiftServerUrl: this.swiftServerUrl,\n\t\t\t\t\t\t\t...params.orderConfig.swiftOptions,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\n\t\t\t\t\treturn swiftOrderResult;\n\t\t\t\t} else {\n\t\t\t\t\tconst txn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\torderConfig: {\n\t\t\t\t\t\t\torderType: 'limit',\n\t\t\t\t\t\t\tlimitPrice: params.orderConfig.limitPrice.val,\n\t\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\t},\n\t\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\t\tpostOnly: params.postOnly,\n\t\t\t\t\t\tuseSwift: false,\n\t\t\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t\t\t});\n\n\t\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\t\t\t\treturn txSig;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcase 'takeProfit':\n\t\t\tcase 'stopLoss': {\n\t\t\t\tconst txn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\tamount: amountBN,\n\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\torderConfig: {\n\t\t\t\t\t\torderType: params.orderConfig.orderType,\n\t\t\t\t\t\ttriggerPrice: params.orderConfig.triggerPrice.val,\n\t\t\t\t\t\tlimitPrice: params.orderConfig.limitPrice?.val ?? ZERO,\n\t\t\t\t\t},\n\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\tuseSwift: false,\n\t\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t\t});\n\n\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\t\t\treturn txSig;\n\t\t\t}\n\t\t\tcase 'oracleLimit': {\n\t\t\t\tconst txn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\tamount: amountBN,\n\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\torderConfig: {\n\t\t\t\t\t\torderType: 'oracleLimit',\n\t\t\t\t\t\toraclePriceOffset: params.orderConfig.oraclePriceOffset.val,\n\t\t\t\t\t},\n\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\tuseSwift: false,\n\t\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t\t});\n\n\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\t\t\treturn txSig;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tconst _exhaustiveCheck: never = params.orderConfig;\n\t\t\t\tthrow new Error('Invalid order type');\n\t\t\t}\n\t\t}\n\t}\n\n\tasync getSwapQuote(\n\t\tparams: Omit<SwapParams, 'jupiterQuote'> & {\n\t\t\tslippageBps?: number;\n\t\t\tswapMode?: SwapMode;\n\t\t\tonlyDirectRoutes?: boolean;\n\t\t}\n\t): Promise<QuoteResponse> {\n\t\tconst jupiterClient = new JupiterClient({\n\t\t\tconnection: this.driftClient.connection,\n\t\t});\n\n\t\tconst inputMint = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tparams.fromMarketIndex\n\t\t).mint;\n\t\tconst outputMint = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tparams.toMarketIndex\n\t\t).mint;\n\n\t\tconst jupiterQuote = await jupiterClient.getQuote({\n\t\t\tinputMint,\n\t\t\toutputMint,\n\t\t\tamount: params.amount.val,\n\t\t\tslippageBps: params.slippageBps,\n\t\t\tswapMode: params.swapMode,\n\t\t\tonlyDirectRoutes: params.onlyDirectRoutes,\n\t\t});\n\n\t\treturn jupiterQuote;\n\t}\n\n\t/**\n\t * Executes a swap between two spot markets (placeholder for future implementation).\n\t *\n\t * This method will handle swapping between different spot markets through\n\t * the Drift protocol's swap functionality.\n\t *\n\t * @param params - The swap parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.executeSwap({\n\t * fromMarketIndex: 0, // USDC\n\t * toMarketIndex: 1, // SOL\n\t * amount: new BigNum(100),\n\t * subAccountId: 0,\n\t * minReceiveAmount: new BigNum(0.5)\n\t * });\n\t * ```\n\t */\n\tasync swap(params: SwapParams): Promise<TransactionSignature> {\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tparams.subAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst jupiterClient = new JupiterClient({\n\t\t\tconnection: this.driftClient.connection,\n\t\t});\n\n\t\tconst jupiterQuote = params.jupiterQuote\n\t\t\t? params.jupiterQuote\n\t\t\t: await this.getSwapQuote(params);\n\n\t\tconst swapTxn = await createSwapTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tjupiterClient,\n\t\t\tuser: accountData.userClient,\n\t\t\tswapFromMarketIndex: params.fromMarketIndex,\n\t\t\tswapToMarketIndex: params.toMarketIndex,\n\t\t\tamount: params.amount.val,\n\t\t\tquote: jupiterQuote,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(swapTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Settles P&L and funding for all perp position.\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.settlePnl({\n\t * subAccountId: 0,\n\t * marketIndex: 0, // SOL-PERP\n\t * counterpartySubAccountId: 1\n\t * });\n\t * ```\n\t */\n\tasync settleAccountPnl(\n\t\tparams: SettleAccountPnlParams\n\t): Promise<TransactionSignature> {\n\t\tconst { subAccountId } = params;\n\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst marketIndexes = accountData.openPerpPositions.map(\n\t\t\t(position) => position.marketIndex\n\t\t);\n\n\t\tconst settlePnlTxn = await createSettlePnlTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuser: accountData.userClient,\n\t\t\tmarketIndexes,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(settlePnlTxn);\n\n\t\treturn txSig;\n\t}\n\n\tasync cancelOrders(\n\t\tparams: CancelOrdersParams\n\t): Promise<TransactionSignature> {\n\t\tconst { subAccountId, orderIds } = params;\n\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst cancelOrdersTxn = await createCancelOrdersTxn(\n\t\t\tthis.driftClient,\n\t\t\taccountData.userClient,\n\t\t\torderIds,\n\t\t\tthis.getTxParams()\n\t\t);\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(cancelOrdersTxn);\n\n\t\treturn txSig;\n\t}\n}\n\n/**\n * TODO:\n * - transfer between subaccounts\n * - close position?\n * - close multiple positions\n * - edit open order\n * - create user only\n *\n * - open spot order\n * - rename subaccount\n * - withdraw dust positions\n */\n"]}
@@ -1,7 +1,7 @@
1
- import { BN, DriftClientConfig, DriftEnv, MarketType, OrderTriggerCondition, PositionDirection, PublicKey, QuoteResponse, SwapMode, User } from '@drift-labs/sdk';
1
+ import { BN, DriftClientConfig, DriftEnv, MarketType, OrderTriggerCondition, PositionDirection, PublicKey, QuoteResponse, SwapMode, TxParams, User } from '@drift-labs/sdk';
2
2
  import { Transaction, VersionedTransaction } from '@solana/web3.js';
3
- import { MarketId } from '../../../../types';
4
3
  import { CentralServerGetOpenPerpMarketOrderTxnParams, CentralServerGetOpenPerpNonMarketOrderTxnParams } from './types';
4
+ import { CentralServerDriftMarkets } from './markets';
5
5
  /**
6
6
  * A Drift client that fetches user data on-demand, while market data is continuously subscribed to.
7
7
  *
@@ -15,18 +15,19 @@ export declare class CentralServerDrift {
15
15
  * The public endpoints that can be used to retrieve Drift data / interact with the Drift program.
16
16
  */
17
17
  private _driftEndpoints;
18
+ readonly markets: CentralServerDriftMarkets;
18
19
  /**
19
20
  * @param solanaRpcEndpoint - The Solana RPC endpoint to use for reading RPC data.
20
21
  * @param driftEnv - The drift environment to use for the drift client.
21
- * @param activeTradeMarket - The active trade market to use for the drift client. This is used to subscribe to the market account, oracle data and mark price more frequently compared to the other markets.
22
- * @param additionalDriftClientConfig - Additional DriftClient config to use for the DriftClient.
22
+ * @param supportedPerpMarkets - The perp markets indexes to support. See https://github.com/drift-labs/protocol-v2/blob/master/sdk/src/constants/perpMarkets.ts for all available markets. It is recommended to only include markets that will be used.
23
+ * @param supportedSpotMarkets - The spot markets indexes to support. See https://github.com/drift-labs/protocol-v2/blob/master/sdk/src/constants/spotMarkets.ts for all available markets. It is recommended to only include markets that will be used.
23
24
  */
24
25
  constructor(config: {
25
26
  solanaRpcEndpoint: string;
26
27
  driftEnv: DriftEnv;
28
+ supportedPerpMarkets: number[];
29
+ supportedSpotMarkets: number[];
27
30
  additionalDriftClientConfig?: Partial<Omit<DriftClientConfig, 'env'>>;
28
- activeTradeMarket?: MarketId;
29
- marketsToSubscribe?: MarketId[];
30
31
  });
31
32
  subscribe(): Promise<void>;
32
33
  /**
@@ -50,7 +51,21 @@ export declare class CentralServerDrift {
50
51
  * @param userAccountPublicKey - The user account public key
51
52
  */
52
53
  getUser(userAccountPublicKey: PublicKey): Promise<User>;
54
+ getCreateAndDepositTxn(authority: PublicKey, amount: BN, spotMarketIndex: number, options?: {
55
+ referrerName?: string;
56
+ accountName?: string;
57
+ poolId?: number;
58
+ fromSubAccountId?: number;
59
+ customMaxMarginRatio?: number;
60
+ }): Promise<{
61
+ transaction: VersionedTransaction | Transaction;
62
+ userAccountPublicKey: PublicKey;
63
+ subAccountId: number;
64
+ }>;
53
65
  getDepositTxn(userAccountPublicKey: PublicKey, amount: BN, spotMarketIndex: number): Promise<VersionedTransaction | Transaction>;
66
+ getDeleteUserTxn(userAccountPublicKey: PublicKey, options?: {
67
+ txParams?: TxParams;
68
+ }): Promise<VersionedTransaction | Transaction>;
54
69
  getWithdrawTxn(userAccountPublicKey: PublicKey, amount: BN, spotMarketIndex: number, options?: {
55
70
  isBorrow?: boolean;
56
71
  isMax?: boolean;
@@ -14,7 +14,10 @@ const openPerpNonMarketOrder_1 = require("../../../base/actions/trade/openPerpOr
14
14
  const editOrder_1 = require("../../../base/actions/trade/editOrder");
15
15
  const cancelOrder_1 = require("../../../base/actions/trade/cancelOrder");
16
16
  const swap_1 = require("../../../base/actions/trade/swap");
17
+ const create_1 = require("../../../base/actions/user/create");
18
+ const delete_1 = require("../../../base/actions/user/delete");
17
19
  const EnvironmentConstants_1 = require("../../../../EnvironmentConstants");
20
+ const markets_1 = require("./markets");
18
21
  /**
19
22
  * A Drift client that fetches user data on-demand, while market data is continuously subscribed to.
20
23
  *
@@ -24,8 +27,8 @@ class CentralServerDrift {
24
27
  /**
25
28
  * @param solanaRpcEndpoint - The Solana RPC endpoint to use for reading RPC data.
26
29
  * @param driftEnv - The drift environment to use for the drift client.
27
- * @param activeTradeMarket - The active trade market to use for the drift client. This is used to subscribe to the market account, oracle data and mark price more frequently compared to the other markets.
28
- * @param additionalDriftClientConfig - Additional DriftClient config to use for the DriftClient.
30
+ * @param supportedPerpMarkets - The perp markets indexes to support. See https://github.com/drift-labs/protocol-v2/blob/master/sdk/src/constants/perpMarkets.ts for all available markets. It is recommended to only include markets that will be used.
31
+ * @param supportedSpotMarkets - The spot markets indexes to support. See https://github.com/drift-labs/protocol-v2/blob/master/sdk/src/constants/spotMarkets.ts for all available markets. It is recommended to only include markets that will be used.
29
32
  */
30
33
  constructor(config) {
31
34
  const driftEnv = config.driftEnv;
@@ -33,6 +36,11 @@ class CentralServerDrift {
33
36
  const driftProgramID = new sdk_1.PublicKey(sdk_1.DRIFT_PROGRAM_ID);
34
37
  const accountLoader = new sdk_1.CustomizedCadenceBulkAccountLoader(connection, constants_1.DEFAULT_ACCOUNT_LOADER_COMMITMENT, constants_1.DEFAULT_ACCOUNT_LOADER_POLLING_FREQUENCY_MS);
35
38
  const wallet = commonUiUtils_1.COMMON_UI_UTILS.createPlaceholderIWallet(); // use random wallet to initialize a central-server instance
39
+ const allPerpMarketConfigs = driftEnv === 'devnet' ? sdk_1.DevnetPerpMarkets : sdk_1.MainnetPerpMarkets;
40
+ const allSpotMarketConfigs = driftEnv === 'devnet' ? sdk_1.DevnetSpotMarkets : sdk_1.MainnetSpotMarkets;
41
+ this._perpMarketConfigs = config.supportedPerpMarkets.map((marketIndex) => allPerpMarketConfigs.find((market) => market.marketIndex === marketIndex));
42
+ this.spotMarketConfigs = config.supportedSpotMarkets.map((marketIndex) => allSpotMarketConfigs.find((market) => market.marketIndex === marketIndex));
43
+ const oracleInfos = (0, sdk_1.getMarketsAndOraclesForSubscription)(driftEnv, this._perpMarketConfigs, this.spotMarketConfigs);
36
44
  const driftClientConfig = {
37
45
  env: driftEnv,
38
46
  connection,
@@ -47,9 +55,13 @@ class CentralServerDrift {
47
55
  includeDelegates: false,
48
56
  skipLoadUsers: true,
49
57
  delistedMarketSetting: sdk_1.DelistedMarketSetting.Unsubscribe,
58
+ perpMarketIndexes: this._perpMarketConfigs.map((market) => market.marketIndex),
59
+ spotMarketIndexes: this.spotMarketConfigs.map((market) => market.marketIndex),
60
+ oracleInfos: oracleInfos.oracleInfos,
50
61
  ...config.additionalDriftClientConfig,
51
62
  };
52
63
  this.driftClient = new sdk_1.DriftClient(driftClientConfig);
64
+ this.markets = new markets_1.CentralServerDriftMarkets(this.driftClient);
53
65
  const txSender = new sdk_1.WhileValidTxSender({
54
66
  connection,
55
67
  wallet,
@@ -60,10 +72,6 @@ class CentralServerDrift {
60
72
  retrySleep: constants_1.DEFAULT_TX_SENDER_RETRY_INTERVAL,
61
73
  });
62
74
  this.driftClient.txSender = txSender;
63
- this._perpMarketConfigs =
64
- driftEnv === 'devnet' ? sdk_1.DevnetPerpMarkets : sdk_1.MainnetPerpMarkets;
65
- this.spotMarketConfigs =
66
- driftEnv === 'devnet' ? sdk_1.DevnetSpotMarkets : sdk_1.MainnetSpotMarkets;
67
75
  // set up Drift endpoints
68
76
  const driftDlobServerHttpUrlToUse = EnvironmentConstants_1.EnvironmentConstants.dlobServerHttpUrl[config.driftEnv === 'devnet' ? 'dev' : 'mainnet'];
69
77
  const swiftServerUrlToUse = EnvironmentConstants_1.EnvironmentConstants.swiftServerUrl[config.driftEnv === 'devnet' ? 'staging' : 'mainnet'];
@@ -159,6 +167,46 @@ class CentralServerDrift {
159
167
  await user.subscribe();
160
168
  return user;
161
169
  }
170
+ async getCreateAndDepositTxn(authority, amount, spotMarketIndex, options) {
171
+ const spotMarketConfig = this.spotMarketConfigs.find((market) => market.marketIndex === spotMarketIndex);
172
+ if (!spotMarketConfig) {
173
+ throw new Error(`Spot market config not found for index ${spotMarketIndex}`);
174
+ }
175
+ const userStatsAccount = await (0, sdk_1.fetchUserStatsAccount)(this.driftClient.connection, this.driftClient.program, authority);
176
+ const originalWallet = this.driftClient.wallet;
177
+ const originalAuthority = this.driftClient.authority;
178
+ const authorityWallet = {
179
+ publicKey: authority,
180
+ signTransaction: () => Promise.reject('This is a placeholder - do not sign with this wallet'),
181
+ signAllTransactions: () => Promise.reject('This is a placeholder - do not sign with this wallet'),
182
+ };
183
+ try {
184
+ this.driftClient.wallet = authorityWallet;
185
+ // @ts-ignore
186
+ this.driftClient.provider.wallet = authorityWallet;
187
+ this.driftClient.txHandler.updateWallet(authorityWallet);
188
+ this.driftClient.authority = authority;
189
+ return await (0, create_1.createUserAndDepositCollateralBaseTxn)({
190
+ driftClient: this.driftClient,
191
+ amount,
192
+ spotMarketConfig,
193
+ authority,
194
+ userStatsAccount,
195
+ referrerName: options === null || options === void 0 ? void 0 : options.referrerName,
196
+ accountName: options === null || options === void 0 ? void 0 : options.accountName,
197
+ poolId: options === null || options === void 0 ? void 0 : options.poolId,
198
+ fromSubAccountId: options === null || options === void 0 ? void 0 : options.fromSubAccountId,
199
+ customMaxMarginRatio: options === null || options === void 0 ? void 0 : options.customMaxMarginRatio,
200
+ });
201
+ }
202
+ finally {
203
+ this.driftClient.wallet = originalWallet;
204
+ this.driftClient.txHandler.updateWallet(originalWallet);
205
+ // @ts-ignore
206
+ this.driftClient.provider.wallet = originalWallet;
207
+ this.driftClient.authority = originalAuthority;
208
+ }
209
+ }
162
210
  async getDepositTxn(userAccountPublicKey, amount, spotMarketIndex) {
163
211
  return this.driftClientContextWrapper(userAccountPublicKey, async (user) => {
164
212
  const spotMarketConfig = this.spotMarketConfigs.find((market) => market.marketIndex === spotMarketIndex);
@@ -174,6 +222,15 @@ class CentralServerDrift {
174
222
  return depositTxn;
175
223
  });
176
224
  }
225
+ async getDeleteUserTxn(userAccountPublicKey, options) {
226
+ return this.driftClientContextWrapper(userAccountPublicKey, async () => {
227
+ return (0, delete_1.deleteUserTxn)({
228
+ driftClient: this.driftClient,
229
+ userPublicKey: userAccountPublicKey,
230
+ txParams: options === null || options === void 0 ? void 0 : options.txParams,
231
+ });
232
+ });
233
+ }
177
234
  async getWithdrawTxn(userAccountPublicKey, amount, spotMarketIndex, options) {
178
235
  return this.driftClientContextWrapper(userAccountPublicKey, async (user) => {
179
236
  const spotMarketConfig = this.spotMarketConfigs.find((market) => market.marketIndex === spotMarketIndex);
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/drift/Drift/clients/CentralServerDrift/index.ts"],"names":[],"mappings":";;;AAAA,yCAyByB;AACzB,6CAAgF;AAChF,6EAA4E;AAC5E,+CAKyB;AAEzB,gEAAsE;AACtE,kEAAwE;AACxE,4EAAkF;AAClF,oEAA0E;AAC1E,uGAA0G;AAC1G,6GAG0E;AAC1E,qEAA2E;AAC3E,yEAAgF;AAChF,2DAAiE;AAKjE,2EAAwE;AAMxE;;;;GAIG;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E;oBACT,wBAAwB,EAAE,IAAI;oBAC9B,4BAA4B,EAAE,GAAG;iBACjC;aACD,CAAC,CAAC;YAEH,OAAO,OAAO,CAAC;QAChB,CAAC,CACD,CAAC;IACH,CAAC;IAEM,KAAK,CAAC,qBAAqB,CAAC,EAAsC;QACxE,OAAO,IAAI,CAAC,WAAW,CAAC,eAAe,CAAC,EAAE,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;IACzE,CAAC;CACD;AAnjBD,gDAmjBC","sourcesContent":["import {\n\tBigNum,\n\tBN,\n\tCustomizedCadenceBulkAccountLoader,\n\tDelistedMarketSetting,\n\tDevnetPerpMarkets,\n\tDevnetSpotMarkets,\n\tDRIFT_PROGRAM_ID,\n\tDriftClient,\n\tDriftClientConfig,\n\tDriftEnv,\n\tJupiterClient,\n\tMainnetPerpMarkets,\n\tMainnetSpotMarkets,\n\tMarketType,\n\tOneShotUserAccountSubscriber,\n\tOrderTriggerCondition,\n\tPerpMarketConfig,\n\tPositionDirection,\n\tPublicKey,\n\tQuoteResponse,\n\tSpotMarketConfig,\n\tSwapMode,\n\tUser,\n\tWhileValidTxSender,\n} from '@drift-labs/sdk';\nimport { Connection, Transaction, VersionedTransaction } from '@solana/web3.js';\nimport { COMMON_UI_UTILS } from '../../../../common-ui-utils/commonUiUtils';\nimport {\n\tDEFAULT_ACCOUNT_LOADER_COMMITMENT,\n\tDEFAULT_ACCOUNT_LOADER_POLLING_FREQUENCY_MS,\n\tDEFAULT_TX_SENDER_CONFIRMATION_STRATEGY,\n\tDEFAULT_TX_SENDER_RETRY_INTERVAL,\n} from '../../constants';\nimport { MarketId } from '../../../../types';\nimport { createDepositTxn } from '../../../base/actions/spot/deposit';\nimport { createWithdrawTxn } from '../../../base/actions/spot/withdraw';\nimport { createSettleFundingTxn } from '../../../base/actions/perp/settleFunding';\nimport { createSettlePnlTxn } from '../../../base/actions/perp/settlePnl';\nimport { createOpenPerpMarketOrder } from '../../../base/actions/trade/openPerpOrder/openPerpMarketOrder';\nimport {\n\tcreateOpenPerpNonMarketOrder,\n\tOpenPerpNonMarketOrderParams,\n} from '../../../base/actions/trade/openPerpOrder/openPerpNonMarketOrder';\nimport { createEditOrderTxn } from '../../../base/actions/trade/editOrder';\nimport { createCancelOrdersTxn } from '../../../base/actions/trade/cancelOrder';\nimport { createSwapTxn } from '../../../base/actions/trade/swap';\nimport {\n\tTxnOrSwiftResult,\n\tWithTxnParams,\n} from '../../../base/actions/trade/openPerpOrder/types';\nimport { EnvironmentConstants } from '../../../../EnvironmentConstants';\nimport {\n\tCentralServerGetOpenPerpMarketOrderTxnParams,\n\tCentralServerGetOpenPerpNonMarketOrderTxnParams,\n} from './types';\n\n/**\n * A Drift client that fetches user data on-demand, while market data is continuously subscribed to.\n *\n * This is useful for an API server that fetches user data on-demand, and return transaction messages specific to a given user\n */\nexport class CentralServerDrift {\n\tprivate driftClient: DriftClient;\n\tprivate _perpMarketConfigs: PerpMarketConfig[];\n\tprivate spotMarketConfigs: SpotMarketConfig[];\n\t/**\n\t * The public endpoints that can be used to retrieve Drift data / interact with the Drift program.\n\t */\n\tprivate _driftEndpoints: {\n\t\tdlobServerHttpUrl: string;\n\t\tswiftServerUrl: string;\n\t};\n\n\t/**\n\t * @param solanaRpcEndpoint - The Solana RPC endpoint to use for reading RPC data.\n\t * @param driftEnv - The drift environment to use for the drift client.\n\t * @param activeTradeMarket - The active trade market to use for the drift client. This is used to subscribe to the market account, oracle data and mark price more frequently compared to the other markets.\n\t * @param additionalDriftClientConfig - Additional DriftClient config to use for the DriftClient.\n\t */\n\tconstructor(config: {\n\t\tsolanaRpcEndpoint: string;\n\t\tdriftEnv: DriftEnv;\n\t\tadditionalDriftClientConfig?: Partial<Omit<DriftClientConfig, 'env'>>;\n\t\tactiveTradeMarket?: MarketId;\n\t\tmarketsToSubscribe?: MarketId[];\n\t}) {\n\t\tconst driftEnv = config.driftEnv;\n\n\t\tconst connection = new Connection(config.solanaRpcEndpoint);\n\t\tconst driftProgramID = new PublicKey(DRIFT_PROGRAM_ID);\n\t\tconst accountLoader = new CustomizedCadenceBulkAccountLoader(\n\t\t\tconnection,\n\t\t\tDEFAULT_ACCOUNT_LOADER_COMMITMENT,\n\t\t\tDEFAULT_ACCOUNT_LOADER_POLLING_FREQUENCY_MS\n\t\t);\n\n\t\tconst wallet = COMMON_UI_UTILS.createPlaceholderIWallet(); // use random wallet to initialize a central-server instance\n\n\t\tconst driftClientConfig: DriftClientConfig = {\n\t\t\tenv: driftEnv,\n\t\t\tconnection,\n\t\t\twallet,\n\t\t\tprogramID: driftProgramID,\n\t\t\tenableMetricsEvents: false,\n\t\t\taccountSubscription: {\n\t\t\t\ttype: 'polling',\n\t\t\t\taccountLoader,\n\t\t\t},\n\t\t\tuserStats: false,\n\t\t\tincludeDelegates: false,\n\t\t\tskipLoadUsers: true,\n\t\t\tdelistedMarketSetting: DelistedMarketSetting.Unsubscribe,\n\t\t\t...config.additionalDriftClientConfig,\n\t\t};\n\t\tthis.driftClient = new DriftClient(driftClientConfig);\n\n\t\tconst txSender = new WhileValidTxSender({\n\t\t\tconnection,\n\t\t\twallet,\n\t\t\tadditionalConnections: [],\n\t\t\tadditionalTxSenderCallbacks: [],\n\t\t\ttxHandler: this.driftClient.txHandler,\n\t\t\tconfirmationStrategy: DEFAULT_TX_SENDER_CONFIRMATION_STRATEGY,\n\t\t\tretrySleep: DEFAULT_TX_SENDER_RETRY_INTERVAL,\n\t\t});\n\n\t\tthis.driftClient.txSender = txSender;\n\t\tthis._perpMarketConfigs =\n\t\t\tdriftEnv === 'devnet' ? DevnetPerpMarkets : MainnetPerpMarkets;\n\t\tthis.spotMarketConfigs =\n\t\t\tdriftEnv === 'devnet' ? DevnetSpotMarkets : MainnetSpotMarkets;\n\n\t\t// set up Drift endpoints\n\t\tconst driftDlobServerHttpUrlToUse =\n\t\t\tEnvironmentConstants.dlobServerHttpUrl[\n\t\t\t\tconfig.driftEnv === 'devnet' ? 'dev' : 'mainnet'\n\t\t\t];\n\t\tconst swiftServerUrlToUse =\n\t\t\tEnvironmentConstants.swiftServerUrl[\n\t\t\t\tconfig.driftEnv === 'devnet' ? 'staging' : 'mainnet'\n\t\t\t];\n\t\tthis._driftEndpoints = {\n\t\t\tdlobServerHttpUrl: driftDlobServerHttpUrlToUse,\n\t\t\tswiftServerUrl: swiftServerUrlToUse,\n\t\t};\n\t}\n\n\tpublic async subscribe() {\n\t\tawait this.driftClient.subscribe();\n\t}\n\n\t/**\n\t * Manages DriftClient state for transaction creation with proper setup and cleanup.\n\t * This abstraction handles:\n\t * - User creation and subscription\n\t * - Authority management\n\t * - Wallet replacement for correct transaction signing\n\t * - Cleanup and state restoration\n\t *\n\t * @param userAccountPublicKey - The user account public key\n\t * @param operation - The transaction creation operation to execute\n\t * @returns The result of the operation\n\t */\n\tprivate async driftClientContextWrapper<T>(\n\t\tuserAccountPublicKey: PublicKey,\n\t\toperation: (user: User) => Promise<T>\n\t): Promise<T> {\n\t\tconst user = new User({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuserAccountPublicKey,\n\t\t\taccountSubscription: {\n\t\t\t\ttype: 'custom',\n\t\t\t\tuserAccountSubscriber: new OneShotUserAccountSubscriber(\n\t\t\t\t\tthis.driftClient.program,\n\t\t\t\t\tuserAccountPublicKey,\n\t\t\t\t\tundefined,\n\t\t\t\t\tundefined\n\t\t\t\t),\n\t\t\t},\n\t\t});\n\n\t\t// Store original state\n\t\tconst originalWallet = this.driftClient.wallet;\n\t\tconst originalAuthority = this.driftClient.authority;\n\n\t\ttry {\n\t\t\t// Setup: Subscribe to user and configure DriftClient\n\t\t\tawait user.subscribe();\n\n\t\t\tconst authority = user.getUserAccount().authority;\n\t\t\tthis.driftClient.authority = authority;\n\n\t\t\tconst success = await this.driftClient.addUser(\n\t\t\t\tuser.getUserAccount().subAccountId,\n\t\t\t\tauthority\n\t\t\t);\n\n\t\t\tif (!success) {\n\t\t\t\tthrow new Error('Failed to add user to DriftClient');\n\t\t\t}\n\n\t\t\t// Replace wallet with user's authority to ensure correct transaction signing\n\t\t\t// This is necessary because DriftClient adds wallet.publicKey to instructions\n\t\t\tconst userWallet = {\n\t\t\t\tpublicKey: authority,\n\t\t\t\tsignTransaction: () =>\n\t\t\t\t\tPromise.reject(\n\t\t\t\t\t\t'This is a placeholder - do not sign with this wallet'\n\t\t\t\t\t),\n\t\t\t\tsignAllTransactions: () =>\n\t\t\t\t\tPromise.reject(\n\t\t\t\t\t\t'This is a placeholder - do not sign with this wallet'\n\t\t\t\t\t),\n\t\t\t};\n\n\t\t\t// Update wallet in all places that reference it\n\t\t\tthis.driftClient.wallet = userWallet;\n\t\t\t//@ts-ignore\n\t\t\tthis.driftClient.provider.wallet = userWallet;\n\t\t\tthis.driftClient.txHandler.updateWallet(userWallet);\n\n\t\t\t// Execute the operation\n\t\t\tconst result = await operation(user);\n\n\t\t\treturn result;\n\t\t} finally {\n\t\t\t// Cleanup: Always restore original state and unsubscribe\n\t\t\tthis.driftClient.wallet = originalWallet;\n\t\t\tthis.driftClient.txHandler.updateWallet(originalWallet);\n\t\t\tthis.driftClient.authority = originalAuthority;\n\n\t\t\ttry {\n\t\t\t\tawait user.unsubscribe();\n\t\t\t\tthis.driftClient.users.clear();\n\t\t\t} catch (cleanupError) {\n\t\t\t\tconsole.warn('Error during cleanup:', cleanupError);\n\t\t\t\t// Don't throw cleanup errors, but log them\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Returns a User object for a given user account public key. This fetches the user account data once.\n\t *\n\t * You may read more about the User object [here](https://github.com/drift-labs/protocol-v2/blob/master/sdk/src/user.ts)\n\t *\n\t * @param userAccountPublicKey - The user account public key\n\t */\n\tpublic async getUser(userAccountPublicKey: PublicKey): Promise<User> {\n\t\tconst oneShotUserAccountSubscriber = new OneShotUserAccountSubscriber(\n\t\t\tthis.driftClient.program,\n\t\t\tuserAccountPublicKey,\n\t\t\tundefined,\n\t\t\tundefined\n\t\t);\n\t\tconst user = new User({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuserAccountPublicKey,\n\t\t\taccountSubscription: {\n\t\t\t\ttype: 'custom',\n\t\t\t\tuserAccountSubscriber: oneShotUserAccountSubscriber,\n\t\t\t},\n\t\t});\n\t\tawait user.subscribe();\n\t\treturn user;\n\t}\n\n\tpublic async getDepositTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tamount: BN,\n\t\tspotMarketIndex: number\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst spotMarketConfig = this.spotMarketConfigs.find(\n\t\t\t\t\t(market) => market.marketIndex === spotMarketIndex\n\t\t\t\t);\n\n\t\t\t\tif (!spotMarketConfig) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Spot market config not found for index ${spotMarketIndex}`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst depositTxn = await createDepositTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tamount: BigNum.from(amount, spotMarketConfig.precisionExp),\n\t\t\t\t\tspotMarketConfig,\n\t\t\t\t});\n\n\t\t\t\treturn depositTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\tpublic async getWithdrawTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tamount: BN,\n\t\tspotMarketIndex: number,\n\t\toptions?: {\n\t\t\tisBorrow?: boolean;\n\t\t\tisMax?: boolean;\n\t\t}\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst spotMarketConfig = this.spotMarketConfigs.find(\n\t\t\t\t\t(market) => market.marketIndex === spotMarketIndex\n\t\t\t\t);\n\n\t\t\t\tif (!spotMarketConfig) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Spot market config not found for index ${spotMarketIndex}`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst withdrawTxn = await createWithdrawTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tamount: BigNum.from(amount, spotMarketConfig.precisionExp),\n\t\t\t\t\tspotMarketConfig,\n\t\t\t\t\tisBorrow: options?.isBorrow,\n\t\t\t\t\tisMax: options?.isMax,\n\t\t\t\t});\n\n\t\t\t\treturn withdrawTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\tpublic async getSettleFundingTxn(\n\t\tuserAccountPublicKey: PublicKey\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst settleFundingTxn = await createSettleFundingTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t});\n\n\t\t\t\treturn settleFundingTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\tpublic async getSettlePnlTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tmarketIndexes: number[]\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst settlePnlTxn = await createSettlePnlTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tmarketIndexes,\n\t\t\t\t});\n\n\t\t\t\treturn settlePnlTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\t// overloads for better type inference\n\tpublic async getOpenPerpMarketOrderTxn(\n\t\tparams: CentralServerGetOpenPerpMarketOrderTxnParams<true>\n\t): Promise<void>;\n\tpublic async getOpenPerpMarketOrderTxn(\n\t\tparams: CentralServerGetOpenPerpMarketOrderTxnParams<false>\n\t): Promise<Transaction | VersionedTransaction>;\n\tpublic async getOpenPerpMarketOrderTxn<T extends boolean>({\n\t\tuserAccountPublicKey,\n\t\t...rest\n\t}: CentralServerGetOpenPerpMarketOrderTxnParams<T>): Promise<\n\t\tTxnOrSwiftResult<T>\n\t> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user): Promise<TxnOrSwiftResult<T>> => {\n\t\t\t\tconst { useSwift, swiftOptions, placeAndTake, ...otherProps } = rest;\n\n\t\t\t\tif (useSwift) {\n\t\t\t\t\tconst swiftOrderResult = await createOpenPerpMarketOrder({\n\t\t\t\t\t\t...otherProps,\n\t\t\t\t\t\tuseSwift: true,\n\t\t\t\t\t\tswiftOptions: {\n\t\t\t\t\t\t\t...swiftOptions,\n\t\t\t\t\t\t\tswiftServerUrl: this._driftEndpoints.swiftServerUrl,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdlobServerHttpUrl: this._driftEndpoints.dlobServerHttpUrl,\n\t\t\t\t\t});\n\t\t\t\t\treturn swiftOrderResult as TxnOrSwiftResult<T>;\n\t\t\t\t} else {\n\t\t\t\t\tconst openPerpMarketOrderTxn = await createOpenPerpMarketOrder({\n\t\t\t\t\t\t...otherProps,\n\t\t\t\t\t\tplaceAndTake,\n\t\t\t\t\t\tuseSwift: false,\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdlobServerHttpUrl: this._driftEndpoints.dlobServerHttpUrl,\n\t\t\t\t\t});\n\t\t\t\t\treturn openPerpMarketOrderTxn as TxnOrSwiftResult<T>;\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a perp non-market order with amount and asset type\n\t */\n\tpublic async getOpenPerpNonMarketOrderTxn(\n\t\tparams: CentralServerGetOpenPerpNonMarketOrderTxnParams<true>\n\t): Promise<void>;\n\tpublic async getOpenPerpNonMarketOrderTxn(\n\t\tparams: CentralServerGetOpenPerpNonMarketOrderTxnParams<false>\n\t): Promise<Transaction | VersionedTransaction>;\n\tpublic async getOpenPerpNonMarketOrderTxn<T extends boolean>({\n\t\tuserAccountPublicKey,\n\t\t...rest\n\t}: WithTxnParams<\n\t\tOmit<OpenPerpNonMarketOrderParams<T>, 'driftClient' | 'user'>\n\t> & {\n\t\tuserAccountPublicKey: PublicKey;\n\t}): Promise<TxnOrSwiftResult<T>> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst { useSwift, swiftOptions, ...otherProps } = rest;\n\n\t\t\t\tif (useSwift) {\n\t\t\t\t\tconst swiftOrderResult = await createOpenPerpNonMarketOrder({\n\t\t\t\t\t\t...otherProps,\n\t\t\t\t\t\tuseSwift: true,\n\t\t\t\t\t\tswiftOptions: {\n\t\t\t\t\t\t\t...swiftOptions,\n\t\t\t\t\t\t\tswiftServerUrl: this._driftEndpoints.swiftServerUrl,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdlobServerHttpUrl: this._driftEndpoints.dlobServerHttpUrl,\n\t\t\t\t\t});\n\t\t\t\t\treturn swiftOrderResult as TxnOrSwiftResult<T>;\n\t\t\t\t} else {\n\t\t\t\t\tconst openPerpNonMarketOrderTxn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\t\t...otherProps,\n\t\t\t\t\t\tuseSwift: false,\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdlobServerHttpUrl: this._driftEndpoints.dlobServerHttpUrl,\n\t\t\t\t\t});\n\t\t\t\t\treturn openPerpNonMarketOrderTxn as TxnOrSwiftResult<T>;\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a transaction to edit an existing order\n\t */\n\tpublic async getEditOrderTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\torderId: number,\n\t\teditOrderParams: {\n\t\t\tnewDirection?: PositionDirection;\n\t\t\tnewBaseAmount?: BN;\n\t\t\tnewLimitPrice?: BN;\n\t\t\tnewOraclePriceOffset?: number;\n\t\t\tnewTriggerPrice?: BN;\n\t\t\tnewTriggerCondition?: OrderTriggerCondition;\n\t\t\tauctionDuration?: number;\n\t\t\tauctionStartPrice?: BN;\n\t\t\tauctionEndPrice?: BN;\n\t\t\treduceOnly?: boolean;\n\t\t\tpostOnly?: boolean;\n\t\t\tbitFlags?: number;\n\t\t\tmaxTs?: BN;\n\t\t\tpolicy?: number;\n\t\t}\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst editOrderTxn = await createEditOrderTxn(\n\t\t\t\t\tthis.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\torderId,\n\t\t\t\t\teditOrderParams\n\t\t\t\t);\n\n\t\t\t\treturn editOrderTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a transaction to cancel specific orders by their IDs\n\t */\n\tpublic async getCancelOrdersTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\torderIds: number[]\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst cancelOrdersTxn = await createCancelOrdersTxn(\n\t\t\t\t\tthis.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\torderIds\n\t\t\t\t);\n\n\t\t\t\treturn cancelOrdersTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a transaction to cancel all orders for a user\n\t */\n\tpublic async getCancelAllOrdersTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tmarketType?: MarketType,\n\t\tmarketIndex?: number,\n\t\tdirection?: PositionDirection\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst ix = await this.driftClient.getCancelOrdersIx(\n\t\t\t\t\tmarketType ?? null,\n\t\t\t\t\tmarketIndex ?? null,\n\t\t\t\t\tdirection ?? null,\n\t\t\t\t\tuser.getUserAccount().subAccountId\n\t\t\t\t);\n\n\t\t\t\tconst cancelAllOrdersTxn = await this.driftClient.buildTransaction(ix);\n\n\t\t\t\treturn cancelAllOrdersTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a swap transaction between two spot markets using Jupiter\n\t */\n\tpublic async getSwapTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tfromMarketIndex: number,\n\t\ttoMarketIndex: number,\n\t\tamount: BN,\n\t\toptions?: {\n\t\t\tslippageBps?: number;\n\t\t\tswapMode?: SwapMode;\n\t\t\tonlyDirectRoutes?: boolean;\n\t\t\tquote?: QuoteResponse;\n\t\t}\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst fromSpotMarketConfig = this.spotMarketConfigs.find(\n\t\t\t\t\t(market) => market.marketIndex === fromMarketIndex\n\t\t\t\t);\n\t\t\t\tconst toSpotMarketConfig = this.spotMarketConfigs.find(\n\t\t\t\t\t(market) => market.marketIndex === toMarketIndex\n\t\t\t\t);\n\n\t\t\t\tif (!fromSpotMarketConfig) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`From spot market config not found for index ${fromMarketIndex}`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tif (!toSpotMarketConfig) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`To spot market config not found for index ${toMarketIndex}`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Initialize Jupiter client\n\t\t\t\tconst jupiterClient = new JupiterClient({\n\t\t\t\t\tconnection: this.driftClient.connection,\n\t\t\t\t});\n\n\t\t\t\t// Get quote if not provided\n\t\t\t\tlet quote = options?.quote;\n\t\t\t\tif (!quote) {\n\t\t\t\t\tquote = await jupiterClient.getQuote({\n\t\t\t\t\t\tinputMint: fromSpotMarketConfig.mint,\n\t\t\t\t\t\toutputMint: toSpotMarketConfig.mint,\n\t\t\t\t\t\tamount,\n\t\t\t\t\t\tslippageBps: options?.slippageBps ?? 10, // Default 0.1%\n\t\t\t\t\t\tswapMode: options?.swapMode ?? 'ExactIn',\n\t\t\t\t\t\tonlyDirectRoutes: options?.onlyDirectRoutes ?? false,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tconst swapTxn = await createSwapTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tjupiterClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tswapFromMarketIndex: fromMarketIndex,\n\t\t\t\t\tswapToMarketIndex: toMarketIndex,\n\t\t\t\t\tamount,\n\t\t\t\t\tquote,\n\t\t\t\t\ttxParams: {\n\t\t\t\t\t\tuseSimulatedComputeUnits: true,\n\t\t\t\t\t\tcomputeUnitsBufferMultiplier: 1.5,\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\treturn swapTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\tpublic async sendSignedTransaction(tx: VersionedTransaction | Transaction) {\n\t\treturn this.driftClient.sendTransaction(tx, undefined, undefined, true);\n\t}\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/drift/Drift/clients/CentralServerDrift/index.ts"],"names":[],"mappings":";;;AAAA,yCA4ByB;AACzB,6CAAgF;AAChF,6EAA4E;AAC5E,+CAKyB;AACzB,gEAAsE;AACtE,kEAAwE;AACxE,4EAAkF;AAClF,oEAA0E;AAC1E,uGAA0G;AAC1G,6GAG0E;AAC1E,qEAA2E;AAC3E,yEAAgF;AAChF,2DAAiE;AACjE,8DAA0F;AAC1F,8DAAkE;AAKlE,2EAAwE;AAKxE,uCAAsD;AAEtD;;;;GAIG;AACH,MAAa,kBAAkB;IAc9B;;;;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,CAAC,IAAI;oBACpC,UAAU,EAAE,kBAAkB,CAAC,IAAI;oBACnC,MAAM;oBACN,WAAW,EAAE,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,WAAW,mCAAI,EAAE,EAAE,eAAe;oBACxD,QAAQ,EAAE,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,QAAQ,mCAAI,SAAS;oBACxC,gBAAgB,EAAE,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,gBAAgB,mCAAI,KAAK;iBACpD,CAAC,CAAC;YACJ,CAAC;YAED,MAAM,OAAO,GAAG,MAAM,IAAA,oBAAa,EAAC;gBACnC,WAAW,EAAE,IAAI,CAAC,WAAW;gBAC7B,aAAa;gBACb,IAAI;gBACJ,mBAAmB,EAAE,eAAe;gBACpC,iBAAiB,EAAE,aAAa;gBAChC,MAAM;gBACN,KAAK;gBACL,QAAQ,EAAE;oBACT,wBAAwB,EAAE,IAAI;oBAC9B,4BAA4B,EAAE,GAAG;iBACjC;aACD,CAAC,CAAC;YAEH,OAAO,OAAO,CAAC;QAChB,CAAC,CACD,CAAC;IACH,CAAC;IAEM,KAAK,CAAC,qBAAqB,CAAC,EAAsC;QACxE,OAAO,IAAI,CAAC,WAAW,CAAC,eAAe,CAAC,EAAE,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;IACzE,CAAC;CACD;AAhqBD,gDAgqBC","sourcesContent":["import {\n\tBigNum,\n\tBN,\n\tCustomizedCadenceBulkAccountLoader,\n\tDelistedMarketSetting,\n\tDevnetPerpMarkets,\n\tDevnetSpotMarkets,\n\tDRIFT_PROGRAM_ID,\n\tDriftClient,\n\tDriftClientConfig,\n\tDriftEnv,\n\tfetchUserStatsAccount,\n\tgetMarketsAndOraclesForSubscription,\n\tJupiterClient,\n\tMainnetPerpMarkets,\n\tMainnetSpotMarkets,\n\tMarketType,\n\tOneShotUserAccountSubscriber,\n\tOrderTriggerCondition,\n\tPerpMarketConfig,\n\tPositionDirection,\n\tPublicKey,\n\tQuoteResponse,\n\tSpotMarketConfig,\n\tSwapMode,\n\tTxParams,\n\tUser,\n\tWhileValidTxSender,\n} from '@drift-labs/sdk';\nimport { Connection, Transaction, VersionedTransaction } from '@solana/web3.js';\nimport { COMMON_UI_UTILS } from '../../../../common-ui-utils/commonUiUtils';\nimport {\n\tDEFAULT_ACCOUNT_LOADER_COMMITMENT,\n\tDEFAULT_ACCOUNT_LOADER_POLLING_FREQUENCY_MS,\n\tDEFAULT_TX_SENDER_CONFIRMATION_STRATEGY,\n\tDEFAULT_TX_SENDER_RETRY_INTERVAL,\n} from '../../constants';\nimport { createDepositTxn } from '../../../base/actions/spot/deposit';\nimport { createWithdrawTxn } from '../../../base/actions/spot/withdraw';\nimport { createSettleFundingTxn } from '../../../base/actions/perp/settleFunding';\nimport { createSettlePnlTxn } from '../../../base/actions/perp/settlePnl';\nimport { createOpenPerpMarketOrder } from '../../../base/actions/trade/openPerpOrder/openPerpMarketOrder';\nimport {\n\tcreateOpenPerpNonMarketOrder,\n\tOpenPerpNonMarketOrderParams,\n} from '../../../base/actions/trade/openPerpOrder/openPerpNonMarketOrder';\nimport { createEditOrderTxn } from '../../../base/actions/trade/editOrder';\nimport { createCancelOrdersTxn } from '../../../base/actions/trade/cancelOrder';\nimport { createSwapTxn } from '../../../base/actions/trade/swap';\nimport { createUserAndDepositCollateralBaseTxn } from '../../../base/actions/user/create';\nimport { deleteUserTxn } from '../../../base/actions/user/delete';\nimport {\n\tTxnOrSwiftResult,\n\tWithTxnParams,\n} from '../../../base/actions/trade/openPerpOrder/types';\nimport { EnvironmentConstants } from '../../../../EnvironmentConstants';\nimport {\n\tCentralServerGetOpenPerpMarketOrderTxnParams,\n\tCentralServerGetOpenPerpNonMarketOrderTxnParams,\n} from './types';\nimport { CentralServerDriftMarkets } from './markets';\n\n/**\n * A Drift client that fetches user data on-demand, while market data is continuously subscribed to.\n *\n * This is useful for an API server that fetches user data on-demand, and return transaction messages specific to a given user\n */\nexport class CentralServerDrift {\n\tprivate driftClient: DriftClient;\n\tprivate _perpMarketConfigs: PerpMarketConfig[];\n\tprivate spotMarketConfigs: SpotMarketConfig[];\n\t/**\n\t * The public endpoints that can be used to retrieve Drift data / interact with the Drift program.\n\t */\n\tprivate _driftEndpoints: {\n\t\tdlobServerHttpUrl: string;\n\t\tswiftServerUrl: string;\n\t};\n\n\tpublic readonly markets: CentralServerDriftMarkets;\n\n\t/**\n\t * @param solanaRpcEndpoint - The Solana RPC endpoint to use for reading RPC data.\n\t * @param driftEnv - The drift environment to use for the drift client.\n\t * @param supportedPerpMarkets - The perp markets indexes to support. See https://github.com/drift-labs/protocol-v2/blob/master/sdk/src/constants/perpMarkets.ts for all available markets. It is recommended to only include markets that will be used.\n\t * @param supportedSpotMarkets - The spot markets indexes to support. See https://github.com/drift-labs/protocol-v2/blob/master/sdk/src/constants/spotMarkets.ts for all available markets. It is recommended to only include markets that will be used.\n\t */\n\tconstructor(config: {\n\t\tsolanaRpcEndpoint: string;\n\t\tdriftEnv: DriftEnv;\n\t\tsupportedPerpMarkets: number[];\n\t\tsupportedSpotMarkets: number[];\n\t\tadditionalDriftClientConfig?: Partial<Omit<DriftClientConfig, 'env'>>;\n\t}) {\n\t\tconst driftEnv = config.driftEnv;\n\n\t\tconst connection = new Connection(config.solanaRpcEndpoint);\n\t\tconst driftProgramID = new PublicKey(DRIFT_PROGRAM_ID);\n\t\tconst accountLoader = new CustomizedCadenceBulkAccountLoader(\n\t\t\tconnection,\n\t\t\tDEFAULT_ACCOUNT_LOADER_COMMITMENT,\n\t\t\tDEFAULT_ACCOUNT_LOADER_POLLING_FREQUENCY_MS\n\t\t);\n\n\t\tconst wallet = COMMON_UI_UTILS.createPlaceholderIWallet(); // use random wallet to initialize a central-server instance\n\n\t\tconst allPerpMarketConfigs =\n\t\t\tdriftEnv === 'devnet' ? DevnetPerpMarkets : MainnetPerpMarkets;\n\t\tconst allSpotMarketConfigs =\n\t\t\tdriftEnv === 'devnet' ? DevnetSpotMarkets : MainnetSpotMarkets;\n\t\tthis._perpMarketConfigs = config.supportedPerpMarkets.map((marketIndex) =>\n\t\t\tallPerpMarketConfigs.find((market) => market.marketIndex === marketIndex)\n\t\t);\n\t\tthis.spotMarketConfigs = config.supportedSpotMarkets.map((marketIndex) =>\n\t\t\tallSpotMarketConfigs.find((market) => market.marketIndex === marketIndex)\n\t\t);\n\n\t\tconst oracleInfos = getMarketsAndOraclesForSubscription(\n\t\t\tdriftEnv,\n\t\t\tthis._perpMarketConfigs,\n\t\t\tthis.spotMarketConfigs\n\t\t);\n\n\t\tconst driftClientConfig: DriftClientConfig = {\n\t\t\tenv: driftEnv,\n\t\t\tconnection,\n\t\t\twallet,\n\t\t\tprogramID: driftProgramID,\n\t\t\tenableMetricsEvents: false,\n\t\t\taccountSubscription: {\n\t\t\t\ttype: 'polling',\n\t\t\t\taccountLoader,\n\t\t\t},\n\t\t\tuserStats: false,\n\t\t\tincludeDelegates: false,\n\t\t\tskipLoadUsers: true,\n\t\t\tdelistedMarketSetting: DelistedMarketSetting.Unsubscribe,\n\t\t\tperpMarketIndexes: this._perpMarketConfigs.map(\n\t\t\t\t(market) => market.marketIndex\n\t\t\t),\n\t\t\tspotMarketIndexes: this.spotMarketConfigs.map(\n\t\t\t\t(market) => market.marketIndex\n\t\t\t),\n\t\t\toracleInfos: oracleInfos.oracleInfos,\n\t\t\t...config.additionalDriftClientConfig,\n\t\t};\n\t\tthis.driftClient = new DriftClient(driftClientConfig);\n\t\tthis.markets = new CentralServerDriftMarkets(this.driftClient);\n\n\t\tconst txSender = new WhileValidTxSender({\n\t\t\tconnection,\n\t\t\twallet,\n\t\t\tadditionalConnections: [],\n\t\t\tadditionalTxSenderCallbacks: [],\n\t\t\ttxHandler: this.driftClient.txHandler,\n\t\t\tconfirmationStrategy: DEFAULT_TX_SENDER_CONFIRMATION_STRATEGY,\n\t\t\tretrySleep: DEFAULT_TX_SENDER_RETRY_INTERVAL,\n\t\t});\n\n\t\tthis.driftClient.txSender = txSender;\n\n\t\t// set up Drift endpoints\n\t\tconst driftDlobServerHttpUrlToUse =\n\t\t\tEnvironmentConstants.dlobServerHttpUrl[\n\t\t\t\tconfig.driftEnv === 'devnet' ? 'dev' : 'mainnet'\n\t\t\t];\n\t\tconst swiftServerUrlToUse =\n\t\t\tEnvironmentConstants.swiftServerUrl[\n\t\t\t\tconfig.driftEnv === 'devnet' ? 'staging' : 'mainnet'\n\t\t\t];\n\t\tthis._driftEndpoints = {\n\t\t\tdlobServerHttpUrl: driftDlobServerHttpUrlToUse,\n\t\t\tswiftServerUrl: swiftServerUrlToUse,\n\t\t};\n\t}\n\n\tpublic async subscribe() {\n\t\tawait this.driftClient.subscribe();\n\t}\n\n\t/**\n\t * Manages DriftClient state for transaction creation with proper setup and cleanup.\n\t * This abstraction handles:\n\t * - User creation and subscription\n\t * - Authority management\n\t * - Wallet replacement for correct transaction signing\n\t * - Cleanup and state restoration\n\t *\n\t * @param userAccountPublicKey - The user account public key\n\t * @param operation - The transaction creation operation to execute\n\t * @returns The result of the operation\n\t */\n\tprivate async driftClientContextWrapper<T>(\n\t\tuserAccountPublicKey: PublicKey,\n\t\toperation: (user: User) => Promise<T>\n\t): Promise<T> {\n\t\tconst user = new User({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuserAccountPublicKey,\n\t\t\taccountSubscription: {\n\t\t\t\ttype: 'custom',\n\t\t\t\tuserAccountSubscriber: new OneShotUserAccountSubscriber(\n\t\t\t\t\tthis.driftClient.program,\n\t\t\t\t\tuserAccountPublicKey,\n\t\t\t\t\tundefined,\n\t\t\t\t\tundefined\n\t\t\t\t),\n\t\t\t},\n\t\t});\n\n\t\t// Store original state\n\t\tconst originalWallet = this.driftClient.wallet;\n\t\tconst originalAuthority = this.driftClient.authority;\n\n\t\ttry {\n\t\t\t// Setup: Subscribe to user and configure DriftClient\n\t\t\tawait user.subscribe();\n\n\t\t\tconst authority = user.getUserAccount().authority;\n\t\t\tthis.driftClient.authority = authority;\n\n\t\t\tconst success = await this.driftClient.addUser(\n\t\t\t\tuser.getUserAccount().subAccountId,\n\t\t\t\tauthority\n\t\t\t);\n\n\t\t\tif (!success) {\n\t\t\t\tthrow new Error('Failed to add user to DriftClient');\n\t\t\t}\n\n\t\t\t// Replace wallet with user's authority to ensure correct transaction signing\n\t\t\t// This is necessary because DriftClient adds wallet.publicKey to instructions\n\t\t\tconst userWallet = {\n\t\t\t\tpublicKey: authority,\n\t\t\t\tsignTransaction: () =>\n\t\t\t\t\tPromise.reject(\n\t\t\t\t\t\t'This is a placeholder - do not sign with this wallet'\n\t\t\t\t\t),\n\t\t\t\tsignAllTransactions: () =>\n\t\t\t\t\tPromise.reject(\n\t\t\t\t\t\t'This is a placeholder - do not sign with this wallet'\n\t\t\t\t\t),\n\t\t\t};\n\n\t\t\t// Update wallet in all places that reference it\n\t\t\tthis.driftClient.wallet = userWallet;\n\t\t\t//@ts-ignore\n\t\t\tthis.driftClient.provider.wallet = userWallet;\n\t\t\tthis.driftClient.txHandler.updateWallet(userWallet);\n\n\t\t\t// Execute the operation\n\t\t\tconst result = await operation(user);\n\n\t\t\treturn result;\n\t\t} finally {\n\t\t\t// Cleanup: Always restore original state and unsubscribe\n\t\t\tthis.driftClient.wallet = originalWallet;\n\t\t\tthis.driftClient.txHandler.updateWallet(originalWallet);\n\t\t\tthis.driftClient.authority = originalAuthority;\n\n\t\t\ttry {\n\t\t\t\tawait user.unsubscribe();\n\t\t\t\tthis.driftClient.users.clear();\n\t\t\t} catch (cleanupError) {\n\t\t\t\tconsole.warn('Error during cleanup:', cleanupError);\n\t\t\t\t// Don't throw cleanup errors, but log them\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Returns a User object for a given user account public key. This fetches the user account data once.\n\t *\n\t * You may read more about the User object [here](https://github.com/drift-labs/protocol-v2/blob/master/sdk/src/user.ts)\n\t *\n\t * @param userAccountPublicKey - The user account public key\n\t */\n\tpublic async getUser(userAccountPublicKey: PublicKey): Promise<User> {\n\t\tconst oneShotUserAccountSubscriber = new OneShotUserAccountSubscriber(\n\t\t\tthis.driftClient.program,\n\t\t\tuserAccountPublicKey,\n\t\t\tundefined,\n\t\t\tundefined\n\t\t);\n\t\tconst user = new User({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuserAccountPublicKey,\n\t\t\taccountSubscription: {\n\t\t\t\ttype: 'custom',\n\t\t\t\tuserAccountSubscriber: oneShotUserAccountSubscriber,\n\t\t\t},\n\t\t});\n\t\tawait user.subscribe();\n\t\treturn user;\n\t}\n\n\tpublic async getCreateAndDepositTxn(\n\t\tauthority: PublicKey,\n\t\tamount: BN,\n\t\tspotMarketIndex: number,\n\t\toptions?: {\n\t\t\treferrerName?: string;\n\t\t\taccountName?: string;\n\t\t\tpoolId?: number;\n\t\t\tfromSubAccountId?: number;\n\t\t\tcustomMaxMarginRatio?: number;\n\t\t}\n\t): Promise<{\n\t\ttransaction: VersionedTransaction | Transaction;\n\t\tuserAccountPublicKey: PublicKey;\n\t\tsubAccountId: number;\n\t}> {\n\t\tconst spotMarketConfig = this.spotMarketConfigs.find(\n\t\t\t(market) => market.marketIndex === spotMarketIndex\n\t\t);\n\n\t\tif (!spotMarketConfig) {\n\t\t\tthrow new Error(\n\t\t\t\t`Spot market config not found for index ${spotMarketIndex}`\n\t\t\t);\n\t\t}\n\n\t\tconst userStatsAccount = await fetchUserStatsAccount(\n\t\t\tthis.driftClient.connection,\n\t\t\tthis.driftClient.program,\n\t\t\tauthority\n\t\t);\n\n\t\tconst originalWallet = this.driftClient.wallet;\n\t\tconst originalAuthority = this.driftClient.authority;\n\n\t\tconst authorityWallet = {\n\t\t\tpublicKey: authority,\n\t\t\tsignTransaction: () =>\n\t\t\t\tPromise.reject('This is a placeholder - do not sign with this wallet'),\n\t\t\tsignAllTransactions: () =>\n\t\t\t\tPromise.reject('This is a placeholder - do not sign with this wallet'),\n\t\t};\n\n\t\ttry {\n\t\t\tthis.driftClient.wallet = authorityWallet;\n\t\t\t// @ts-ignore\n\t\t\tthis.driftClient.provider.wallet = authorityWallet;\n\t\t\tthis.driftClient.txHandler.updateWallet(authorityWallet);\n\t\t\tthis.driftClient.authority = authority;\n\n\t\t\treturn await createUserAndDepositCollateralBaseTxn({\n\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\tamount,\n\t\t\t\tspotMarketConfig,\n\t\t\t\tauthority,\n\t\t\t\tuserStatsAccount,\n\t\t\t\treferrerName: options?.referrerName,\n\t\t\t\taccountName: options?.accountName,\n\t\t\t\tpoolId: options?.poolId,\n\t\t\t\tfromSubAccountId: options?.fromSubAccountId,\n\t\t\t\tcustomMaxMarginRatio: options?.customMaxMarginRatio,\n\t\t\t});\n\t\t} finally {\n\t\t\tthis.driftClient.wallet = originalWallet;\n\t\t\tthis.driftClient.txHandler.updateWallet(originalWallet);\n\t\t\t// @ts-ignore\n\t\t\tthis.driftClient.provider.wallet = originalWallet;\n\t\t\tthis.driftClient.authority = originalAuthority;\n\t\t}\n\t}\n\n\tpublic async getDepositTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tamount: BN,\n\t\tspotMarketIndex: number\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst spotMarketConfig = this.spotMarketConfigs.find(\n\t\t\t\t\t(market) => market.marketIndex === spotMarketIndex\n\t\t\t\t);\n\n\t\t\t\tif (!spotMarketConfig) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Spot market config not found for index ${spotMarketIndex}`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst depositTxn = await createDepositTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tamount: BigNum.from(amount, spotMarketConfig.precisionExp),\n\t\t\t\t\tspotMarketConfig,\n\t\t\t\t});\n\n\t\t\t\treturn depositTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\tpublic async getDeleteUserTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\toptions?: {\n\t\t\ttxParams?: TxParams;\n\t\t}\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(userAccountPublicKey, async () => {\n\t\t\treturn deleteUserTxn({\n\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\tuserPublicKey: userAccountPublicKey,\n\t\t\t\ttxParams: options?.txParams,\n\t\t\t});\n\t\t});\n\t}\n\n\tpublic async getWithdrawTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tamount: BN,\n\t\tspotMarketIndex: number,\n\t\toptions?: {\n\t\t\tisBorrow?: boolean;\n\t\t\tisMax?: boolean;\n\t\t}\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst spotMarketConfig = this.spotMarketConfigs.find(\n\t\t\t\t\t(market) => market.marketIndex === spotMarketIndex\n\t\t\t\t);\n\n\t\t\t\tif (!spotMarketConfig) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Spot market config not found for index ${spotMarketIndex}`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst withdrawTxn = await createWithdrawTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tamount: BigNum.from(amount, spotMarketConfig.precisionExp),\n\t\t\t\t\tspotMarketConfig,\n\t\t\t\t\tisBorrow: options?.isBorrow,\n\t\t\t\t\tisMax: options?.isMax,\n\t\t\t\t});\n\n\t\t\t\treturn withdrawTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\tpublic async getSettleFundingTxn(\n\t\tuserAccountPublicKey: PublicKey\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst settleFundingTxn = await createSettleFundingTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t});\n\n\t\t\t\treturn settleFundingTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\tpublic async getSettlePnlTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tmarketIndexes: number[]\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst settlePnlTxn = await createSettlePnlTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tmarketIndexes,\n\t\t\t\t});\n\n\t\t\t\treturn settlePnlTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\t// overloads for better type inference\n\tpublic async getOpenPerpMarketOrderTxn(\n\t\tparams: CentralServerGetOpenPerpMarketOrderTxnParams<true>\n\t): Promise<void>;\n\tpublic async getOpenPerpMarketOrderTxn(\n\t\tparams: CentralServerGetOpenPerpMarketOrderTxnParams<false>\n\t): Promise<Transaction | VersionedTransaction>;\n\tpublic async getOpenPerpMarketOrderTxn<T extends boolean>({\n\t\tuserAccountPublicKey,\n\t\t...rest\n\t}: CentralServerGetOpenPerpMarketOrderTxnParams<T>): Promise<\n\t\tTxnOrSwiftResult<T>\n\t> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user): Promise<TxnOrSwiftResult<T>> => {\n\t\t\t\tconst { useSwift, swiftOptions, placeAndTake, ...otherProps } = rest;\n\n\t\t\t\tif (useSwift) {\n\t\t\t\t\tconst swiftOrderResult = await createOpenPerpMarketOrder({\n\t\t\t\t\t\t...otherProps,\n\t\t\t\t\t\tuseSwift: true,\n\t\t\t\t\t\tswiftOptions: {\n\t\t\t\t\t\t\t...swiftOptions,\n\t\t\t\t\t\t\tswiftServerUrl: this._driftEndpoints.swiftServerUrl,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdlobServerHttpUrl: this._driftEndpoints.dlobServerHttpUrl,\n\t\t\t\t\t});\n\t\t\t\t\treturn swiftOrderResult as TxnOrSwiftResult<T>;\n\t\t\t\t} else {\n\t\t\t\t\tconst openPerpMarketOrderTxn = await createOpenPerpMarketOrder({\n\t\t\t\t\t\t...otherProps,\n\t\t\t\t\t\tplaceAndTake,\n\t\t\t\t\t\tuseSwift: false,\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdlobServerHttpUrl: this._driftEndpoints.dlobServerHttpUrl,\n\t\t\t\t\t});\n\t\t\t\t\treturn openPerpMarketOrderTxn as TxnOrSwiftResult<T>;\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a perp non-market order with amount and asset type\n\t */\n\tpublic async getOpenPerpNonMarketOrderTxn(\n\t\tparams: CentralServerGetOpenPerpNonMarketOrderTxnParams<true>\n\t): Promise<void>;\n\tpublic async getOpenPerpNonMarketOrderTxn(\n\t\tparams: CentralServerGetOpenPerpNonMarketOrderTxnParams<false>\n\t): Promise<Transaction | VersionedTransaction>;\n\tpublic async getOpenPerpNonMarketOrderTxn<T extends boolean>({\n\t\tuserAccountPublicKey,\n\t\t...rest\n\t}: WithTxnParams<\n\t\tOmit<OpenPerpNonMarketOrderParams<T>, 'driftClient' | 'user'>\n\t> & {\n\t\tuserAccountPublicKey: PublicKey;\n\t}): Promise<TxnOrSwiftResult<T>> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst { useSwift, swiftOptions, ...otherProps } = rest;\n\n\t\t\t\tif (useSwift) {\n\t\t\t\t\tconst swiftOrderResult = await createOpenPerpNonMarketOrder({\n\t\t\t\t\t\t...otherProps,\n\t\t\t\t\t\tuseSwift: true,\n\t\t\t\t\t\tswiftOptions: {\n\t\t\t\t\t\t\t...swiftOptions,\n\t\t\t\t\t\t\tswiftServerUrl: this._driftEndpoints.swiftServerUrl,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdlobServerHttpUrl: this._driftEndpoints.dlobServerHttpUrl,\n\t\t\t\t\t});\n\t\t\t\t\treturn swiftOrderResult as TxnOrSwiftResult<T>;\n\t\t\t\t} else {\n\t\t\t\t\tconst openPerpNonMarketOrderTxn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\t\t...otherProps,\n\t\t\t\t\t\tuseSwift: false,\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdlobServerHttpUrl: this._driftEndpoints.dlobServerHttpUrl,\n\t\t\t\t\t});\n\t\t\t\t\treturn openPerpNonMarketOrderTxn as TxnOrSwiftResult<T>;\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a transaction to edit an existing order\n\t */\n\tpublic async getEditOrderTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\torderId: number,\n\t\teditOrderParams: {\n\t\t\tnewDirection?: PositionDirection;\n\t\t\tnewBaseAmount?: BN;\n\t\t\tnewLimitPrice?: BN;\n\t\t\tnewOraclePriceOffset?: number;\n\t\t\tnewTriggerPrice?: BN;\n\t\t\tnewTriggerCondition?: OrderTriggerCondition;\n\t\t\tauctionDuration?: number;\n\t\t\tauctionStartPrice?: BN;\n\t\t\tauctionEndPrice?: BN;\n\t\t\treduceOnly?: boolean;\n\t\t\tpostOnly?: boolean;\n\t\t\tbitFlags?: number;\n\t\t\tmaxTs?: BN;\n\t\t\tpolicy?: number;\n\t\t}\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst editOrderTxn = await createEditOrderTxn(\n\t\t\t\t\tthis.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\torderId,\n\t\t\t\t\teditOrderParams\n\t\t\t\t);\n\n\t\t\t\treturn editOrderTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a transaction to cancel specific orders by their IDs\n\t */\n\tpublic async getCancelOrdersTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\torderIds: number[]\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst cancelOrdersTxn = await createCancelOrdersTxn(\n\t\t\t\t\tthis.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\torderIds\n\t\t\t\t);\n\n\t\t\t\treturn cancelOrdersTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a transaction to cancel all orders for a user\n\t */\n\tpublic async getCancelAllOrdersTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tmarketType?: MarketType,\n\t\tmarketIndex?: number,\n\t\tdirection?: PositionDirection\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst ix = await this.driftClient.getCancelOrdersIx(\n\t\t\t\t\tmarketType ?? null,\n\t\t\t\t\tmarketIndex ?? null,\n\t\t\t\t\tdirection ?? null,\n\t\t\t\t\tuser.getUserAccount().subAccountId\n\t\t\t\t);\n\n\t\t\t\tconst cancelAllOrdersTxn = await this.driftClient.buildTransaction(ix);\n\n\t\t\t\treturn cancelAllOrdersTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a swap transaction between two spot markets using Jupiter\n\t */\n\tpublic async getSwapTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tfromMarketIndex: number,\n\t\ttoMarketIndex: number,\n\t\tamount: BN,\n\t\toptions?: {\n\t\t\tslippageBps?: number;\n\t\t\tswapMode?: SwapMode;\n\t\t\tonlyDirectRoutes?: boolean;\n\t\t\tquote?: QuoteResponse;\n\t\t}\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst fromSpotMarketConfig = this.spotMarketConfigs.find(\n\t\t\t\t\t(market) => market.marketIndex === fromMarketIndex\n\t\t\t\t);\n\t\t\t\tconst toSpotMarketConfig = this.spotMarketConfigs.find(\n\t\t\t\t\t(market) => market.marketIndex === toMarketIndex\n\t\t\t\t);\n\n\t\t\t\tif (!fromSpotMarketConfig) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`From spot market config not found for index ${fromMarketIndex}`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tif (!toSpotMarketConfig) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`To spot market config not found for index ${toMarketIndex}`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Initialize Jupiter client\n\t\t\t\tconst jupiterClient = new JupiterClient({\n\t\t\t\t\tconnection: this.driftClient.connection,\n\t\t\t\t});\n\n\t\t\t\t// Get quote if not provided\n\t\t\t\tlet quote = options?.quote;\n\t\t\t\tif (!quote) {\n\t\t\t\t\tquote = await jupiterClient.getQuote({\n\t\t\t\t\t\tinputMint: fromSpotMarketConfig.mint,\n\t\t\t\t\t\toutputMint: toSpotMarketConfig.mint,\n\t\t\t\t\t\tamount,\n\t\t\t\t\t\tslippageBps: options?.slippageBps ?? 10, // Default 0.1%\n\t\t\t\t\t\tswapMode: options?.swapMode ?? 'ExactIn',\n\t\t\t\t\t\tonlyDirectRoutes: options?.onlyDirectRoutes ?? false,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tconst swapTxn = await createSwapTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tjupiterClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tswapFromMarketIndex: fromMarketIndex,\n\t\t\t\t\tswapToMarketIndex: toMarketIndex,\n\t\t\t\t\tamount,\n\t\t\t\t\tquote,\n\t\t\t\t\ttxParams: {\n\t\t\t\t\t\tuseSimulatedComputeUnits: true,\n\t\t\t\t\t\tcomputeUnitsBufferMultiplier: 1.5,\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\treturn swapTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\tpublic async sendSignedTransaction(tx: VersionedTransaction | Transaction) {\n\t\treturn this.driftClient.sendTransaction(tx, undefined, undefined, true);\n\t}\n}\n"]}
@@ -0,0 +1,7 @@
1
+ import { DriftClient, PerpMarketAccount, SpotMarketAccount } from '@drift-labs/sdk';
2
+ export declare class CentralServerDriftMarkets {
3
+ private readonly driftClient;
4
+ constructor(driftClient: DriftClient);
5
+ getPerpMarketAccount(marketIndex: number): Promise<PerpMarketAccount | undefined>;
6
+ getSpotMarketAccount(marketIndex: number): Promise<SpotMarketAccount | undefined>;
7
+ }
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CentralServerDriftMarkets = void 0;
4
+ class CentralServerDriftMarkets {
5
+ constructor(driftClient) {
6
+ this.driftClient = driftClient;
7
+ }
8
+ async getPerpMarketAccount(marketIndex) {
9
+ return this.driftClient.getPerpMarketAccount(marketIndex);
10
+ }
11
+ async getSpotMarketAccount(marketIndex) {
12
+ return this.driftClient.getSpotMarketAccount(marketIndex);
13
+ }
14
+ }
15
+ exports.CentralServerDriftMarkets = CentralServerDriftMarkets;
16
+ //# sourceMappingURL=markets.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"markets.js","sourceRoot":"","sources":["../../../../../src/drift/Drift/clients/CentralServerDrift/markets.ts"],"names":[],"mappings":";;;AAMA,MAAa,yBAAyB;IACrC,YAA6B,WAAwB;QAAxB,gBAAW,GAAX,WAAW,CAAa;IAAG,CAAC;IAEzD,KAAK,CAAC,oBAAoB,CACzB,WAAmB;QAEnB,OAAO,IAAI,CAAC,WAAW,CAAC,oBAAoB,CAAC,WAAW,CAAC,CAAC;IAC3D,CAAC;IAED,KAAK,CAAC,oBAAoB,CACzB,WAAmB;QAEnB,OAAO,IAAI,CAAC,WAAW,CAAC,oBAAoB,CAAC,WAAW,CAAC,CAAC;IAC3D,CAAC;CACD;AAdD,8DAcC","sourcesContent":["import {\n\tDriftClient,\n\tPerpMarketAccount,\n\tSpotMarketAccount,\n} from '@drift-labs/sdk';\n\nexport class CentralServerDriftMarkets {\n\tconstructor(private readonly driftClient: DriftClient) {}\n\n\tasync getPerpMarketAccount(\n\t\tmarketIndex: number\n\t): Promise<PerpMarketAccount | undefined> {\n\t\treturn this.driftClient.getPerpMarketAccount(marketIndex);\n\t}\n\n\tasync getSpotMarketAccount(\n\t\tmarketIndex: number\n\t): Promise<SpotMarketAccount | undefined> {\n\t\treturn this.driftClient.getSpotMarketAccount(marketIndex);\n\t}\n}\n"]}
@@ -28,7 +28,7 @@ async function createSwiftMarketOrder({ driftClient, user, assetType, marketInde
28
28
  optionalAuctionParamsInputs,
29
29
  });
30
30
  const oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;
31
- const totalQuoteAmount = amount.mul(oraclePrice).div(sdk_1.PRICE_PRECISION);
31
+ const totalQuoteAmount = amount.mul(oraclePrice).div(sdk_1.BASE_PRECISION);
32
32
  const bitFlags = order_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, totalQuoteAmount, direction);
33
33
  const orderParams = {
34
34
  ...fetchedOrderParams,
@@ -40,6 +40,7 @@ async function createSwiftMarketOrder({ driftClient, user, assetType, marketInde
40
40
  await (0, openSwiftOrder_1.prepSignAndSendSwiftOrder)({
41
41
  driftClient,
42
42
  subAccountId: userAccount.subAccountId,
43
+ userAccountPubKey: user.userAccountPublicKey,
43
44
  marketIndex,
44
45
  slotBuffer,
45
46
  swiftOptions,
@@ -80,7 +81,7 @@ const createPlaceAndTakePerpMarketOrderIx = async ({ assetType, direction, dlobS
80
81
  }),
81
82
  ]);
82
83
  const oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;
83
- const totalQuoteAmount = amount.mul(oraclePrice).div(sdk_1.PRICE_PRECISION);
84
+ const totalQuoteAmount = amount.mul(oraclePrice).div(sdk_1.BASE_PRECISION);
84
85
  const bitFlags = order_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, totalQuoteAmount, direction);
85
86
  fetchedOrderParams.bitFlags = bitFlags;
86
87
  fetchedOrderParams.userOrderId = userOrderId;
@@ -158,7 +159,7 @@ const createOpenPerpMarketOrderIxs = async ({ driftClient, user, assetType, mark
158
159
  optionalAuctionParamsInputs,
159
160
  });
160
161
  const oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;
161
- const totalQuoteAmount = amount.mul(oraclePrice).div(sdk_1.PRICE_PRECISION);
162
+ const totalQuoteAmount = amount.mul(oraclePrice).div(sdk_1.BASE_PRECISION);
162
163
  const bitFlags = order_1.ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(marketIndex, driftClient, user, totalQuoteAmount, direction);
163
164
  const orderParams = {
164
165
  ...fetchedOrderParams,