@drift-labs/common 1.0.7 → 1.0.8
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.
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js +8 -1
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js +1 -0
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js +1 -0
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.d.ts +4 -2
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js +5 -5
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js.map +1 -1
- package/lib/drift/cli.js +4 -2
- package/lib/drift/cli.js.map +1 -1
- 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:
|
|
97
|
+
userStatsAccount: userStatsAccount,
|
|
91
98
|
accountName: newAccountName,
|
|
92
99
|
referrerName,
|
|
93
100
|
customMaxMarginRatio,
|
|
@@ -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;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;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O,KAAK,CAAC;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;;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,GAA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AAa;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\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"]}
|
|
@@ -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,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.ts"],"names":[],"mappings":";;;AAAA,yCAUyB;AAMzB,mDAAqD;AACrD,sDAG2B;AAC3B,kEAA6E;AAC7E,8CAIuB;AACvB,mEAA6E;AAE7E,kEAAyE;AA2CzE;;GAEG;AACI,KAAK,UAAU,sBAAsB,CAAC,EAC5C,WAAW,EACX,IAAI,EACJ,SAAS,EACT,WAAW,EACX,SAAS,EACT,MAAM,EACN,aAAa,EACb,iBAAiB,EACjB,2BAA2B,EAC3B,YAAY,EACZ,WAAW,GAAG,CAAC,GACyB;IACxC,IAAI,MAAM,CAAC,MAAM,EAAE,EAAE,CAAC;QACrB,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;IACrD,CAAC;IAED,mCAAmC;IACnC,MAAM,kBAAkB,GAAG,MAAM,IAAA,oCAAuB,EAAC;QACxD,WAAW;QACX,IAAI;QACJ,SAAS;QACT,WAAW;QACX,UAAU,EAAE,gBAAU,CAAC,IAAI;QAC3B,SAAS;QACT,MAAM;QACN,iBAAiB;QACjB,2BAA2B;KAC3B,CAAC,CAAC;IAEH,MAAM,WAAW,GAAG,WAAW,CAAC,0BAA0B,CAAC,WAAW,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G,MAAM,WAAW,CAAC,SAAS,CAAC,gBAAgB,CAAC;QAC3E,YAAY,EAAE,YAAY;QAC1B,SAAS,EAAE,CAAC;QACZ,UAAU,EAAE,WAAW,CAAC,UAAU;QAClC,mBAAmB,EAAE,WAAW;QAChC,iCAAiC,EAChC,WAAW,CAAC,2BAA2B,CAAC,IAAI,CAAC,WAAW,CAAC;QAC1D,QAAQ,EAAE,MAAM,CAAC,QAAQ;KACzB,CAAC,CAAC;IAEH,OAAO,sBAAsB,CAAC;AAC/B,CAAC,CAAC;AAlBW,QAAA,4BAA4B,gCAkBvC;AAEF;;;;;;;;;;;;;;;GAeG;AACI,MAAM,yBAAyB,GAAG,KAAK,EAC7C,MAAsE,EACvC,EAAE;IACjC,MAAM,EAAE,QAAQ,EAAE,YAAY,EAAE,GAAG,IAAI,EAAE,GAAG,MAAM,CAAC;IAEnD,wDAAwD;IACxD,IAAI,QAAQ,EAAE,CAAC;QACd,IAAI,CAAC,YAAY,EAAE,CAAC;YACnB,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;QACnE,CAAC;QAED,MAAM,gBAAgB,GAAG,MAAM,sBAAsB,CAAC;YACrD,GAAG,IAAI;YACP,YAAY;SACZ,CAAC,CAAC;QAEH,OAAO,gBAAuC,CAAC;IAChD,CAAC;IAED,MAAM,sBAAsB,GAAG,MAAM,IAAA,oCAA4B,EAAC,IAAI,CAAC,CAAC;IAExE,OAAO,sBAA6C,CAAC;AACtD,CAAC,CAAC;AAtBW,QAAA,yBAAyB,6BAsBpC","sourcesContent":["import {\n\tDriftClient,\n\tUser,\n\tBN,\n\tPositionDirection,\n\tOptionalOrderParams,\n\tMarketType,\n\tgetUserStatsAccountPublicKey,\n\tReferrerInfo,\n\tPRICE_PRECISION,\n} from '@drift-labs/sdk';\nimport {\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport {\n\tprepSignAndSendSwiftOrder,\n\tSwiftOrderOptions,\n} from '../openSwiftOrder';\nimport { buildNonMarketOrderParams } from '../../../../../utils/orderParams';\nimport {\n\tfetchAuctionOrderParams,\n\tfetchTopMakers,\n\tOptionalAuctionParamsRequestInputs,\n} from '../dlobServer';\nimport { ORDER_COMMON_UTILS } from '../../../../../../common-ui-utils/order';\nimport { TxnOrSwiftResult, WithTxnParams } from '../types';\nimport { NoTopMakersError } from '../../../../../Drift/constants/errors';\nimport { PlaceAndTakeParams, OptionalTriggerOrderParams } from '../types';\n\nexport interface OpenPerpMarketOrderBaseParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tassetType: 'base' | 'quote';\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\tamount: BN;\n\tdlobServerHttpUrl: string;\n\t// mainly used for UI order identification\n\tuserOrderId?: number;\n\tplaceAndTake?: PlaceAndTakeParams;\n\toptionalAuctionParamsInputs?: OptionalAuctionParamsRequestInputs;\n\tbracketOrders?: {\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t};\n}\n\nexport interface OpenPerpMarketOrderBaseParamsWithSwift\n\textends Omit<OpenPerpMarketOrderBaseParams, 'placeAndTake'> {\n\tswiftOptions: SwiftOrderOptions;\n}\n\nexport type OpenPerpMarketOrderParams<\n\tT extends boolean = boolean,\n\tS extends Omit<SwiftOrderOptions, 'swiftServerUrl'> = Omit<\n\t\tSwiftOrderOptions,\n\t\t'swiftServerUrl'\n\t>\n> = T extends true\n\t? OpenPerpMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tswiftOptions: S;\n\t\t\tplaceAndTake?: never;\n\t }\n\t: OpenPerpMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tplaceAndTake?: PlaceAndTakeParams;\n\t\t\tswiftOptions?: never;\n\t };\n/**\n * Creates and submits a Swift (signed message) order. Only available for perp orders.\n */\nexport async function createSwiftMarketOrder({\n\tdriftClient,\n\tuser,\n\tassetType,\n\tmarketIndex,\n\tdirection,\n\tamount,\n\tbracketOrders,\n\tdlobServerHttpUrl,\n\toptionalAuctionParamsInputs,\n\tswiftOptions,\n\tuserOrderId = 0,\n}: OpenPerpMarketOrderBaseParamsWithSwift): Promise<void> {\n\tif (amount.isZero()) {\n\t\tthrow new Error('Amount must be greater than zero');\n\t}\n\n\t// Get order parameters from server\n\tconst fetchedOrderParams = await fetchAuctionOrderParams({\n\t\tdriftClient,\n\t\tuser,\n\t\tassetType,\n\t\tmarketIndex,\n\t\tmarketType: MarketType.PERP,\n\t\tdirection,\n\t\tamount,\n\t\tdlobServerHttpUrl,\n\t\toptionalAuctionParamsInputs,\n\t});\n\n\tconst oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;\n\tconst totalQuoteAmount = amount.mul(oraclePrice).div(PRICE_PRECISION);\n\n\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\tmarketIndex,\n\t\tdriftClient,\n\t\tuser,\n\t\ttotalQuoteAmount,\n\t\tdirection\n\t);\n\n\tconst orderParams = {\n\t\t...fetchedOrderParams,\n\t\tuserOrderId,\n\t\tbitFlags,\n\t};\n\n\tconst userAccount = user.getUserAccount();\n\tconst slotBuffer = swiftOptions.signedMessageOrderSlotBuffer || 7;\n\n\tawait prepSignAndSendSwiftOrder({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tmarketIndex,\n\t\tslotBuffer,\n\t\tswiftOptions,\n\t\torderParams: {\n\t\t\tmain: orderParams,\n\t\t\ttakeProfit: bracketOrders?.takeProfit,\n\t\t\tstopLoss: bracketOrders?.stopLoss,\n\t\t},\n\t});\n}\n\n/**\n * Creates a placeAndTake transaction instruction.\n * Fallbacks to a regular market order if no top makers are found.\n */\nexport const createPlaceAndTakePerpMarketOrderIx = async ({\n\tassetType,\n\tdirection,\n\tdlobServerHttpUrl,\n\tmarketIndex,\n\tdriftClient,\n\tuser,\n\tuserOrderId,\n\tamount,\n\treferrerInfo,\n\tauctionDurationPercentage,\n\toptionalAuctionParamsInputs,\n}: OpenPerpMarketOrderBaseParams & {\n\tdirection: PositionDirection;\n\tdlobServerHttpUrl: string;\n\tmarketIndex: number;\n\tdriftClient: DriftClient;\n\tuser: User;\n\treferrerInfo?: ReferrerInfo;\n\tauctionDurationPercentage?: number;\n}) => {\n\tconst counterPartySide = ENUM_UTILS.match(direction, PositionDirection.LONG)\n\t\t? 'ask'\n\t\t: 'bid';\n\n\tconst [fetchedOrderParams, topMakersResult] = await Promise.all([\n\t\tfetchAuctionOrderParams({\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tassetType,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tamount,\n\t\t\tdlobServerHttpUrl,\n\t\t\toptionalAuctionParamsInputs,\n\t\t}),\n\t\tfetchTopMakers({\n\t\t\tdlobServerHttpUrl,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tside: counterPartySide,\n\t\t\tlimit: 4,\n\t\t}),\n\t]);\n\n\tconst oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;\n\tconst totalQuoteAmount = amount.mul(oraclePrice).div(PRICE_PRECISION);\n\n\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\tmarketIndex,\n\t\tdriftClient,\n\t\tuser,\n\t\ttotalQuoteAmount,\n\t\tdirection\n\t);\n\tfetchedOrderParams.bitFlags = bitFlags;\n\tfetchedOrderParams.userOrderId = userOrderId;\n\n\tif (!topMakersResult || topMakersResult.length === 0) {\n\t\tthrow new NoTopMakersError('No top makers found', fetchedOrderParams);\n\t}\n\n\tconst topMakersInfo = topMakersResult.map((maker) => ({\n\t\tmaker: maker.userAccountPubKey,\n\t\tmakerUserAccount: maker.userAccount,\n\t\tmakerStats: getUserStatsAccountPublicKey(\n\t\t\tdriftClient.program.programId,\n\t\t\tmaker.userAccount.authority\n\t\t),\n\t}));\n\n\tconst placeAndTakeIx = await driftClient.getPlaceAndTakePerpOrderIx(\n\t\tfetchedOrderParams,\n\t\ttopMakersInfo,\n\t\treferrerInfo,\n\t\tundefined,\n\t\tauctionDurationPercentage,\n\t\tuser.getUserAccount().subAccountId\n\t);\n\n\treturn placeAndTakeIx;\n};\n\n/**\n * Creates transaction instructions for opening a perp market order.\n * If swiftOptions is provided, it will create a Swift (signed message) order instead.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param assetType - Whether the amount is in base or quote units\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n *\n * @returns Promise resolving to an array of transaction instructions for regular orders\n */\nexport const createOpenPerpMarketOrderIxs = async ({\n\tdriftClient,\n\tuser,\n\tassetType,\n\tmarketIndex,\n\tdirection,\n\tamount,\n\tbracketOrders,\n\tdlobServerHttpUrl,\n\tplaceAndTake,\n\tuserOrderId,\n\toptionalAuctionParamsInputs = {},\n}: OpenPerpMarketOrderBaseParams): Promise<TransactionInstruction[]> => {\n\tif (!amount || amount.isZero()) {\n\t\tthrow new Error('Amount must be greater than zero');\n\t}\n\n\tconst allOrders: OptionalOrderParams[] = [];\n\tconst allIxs: TransactionInstruction[] = [];\n\n\tif (placeAndTake?.enable) {\n\t\ttry {\n\t\t\tconst placeAndTakeIx = await createPlaceAndTakePerpMarketOrderIx({\n\t\t\t\tassetType,\n\t\t\t\tamount,\n\t\t\t\tdirection,\n\t\t\t\tdlobServerHttpUrl,\n\t\t\t\tmarketIndex,\n\t\t\t\tdriftClient,\n\t\t\t\tuser,\n\t\t\t\tuserOrderId,\n\t\t\t\treferrerInfo: placeAndTake.referrerInfo,\n\t\t\t\tauctionDurationPercentage: placeAndTake.auctionDurationPercentage,\n\t\t\t\toptionalAuctionParamsInputs,\n\t\t\t});\n\t\t\tallIxs.push(placeAndTakeIx);\n\t\t} catch (e) {\n\t\t\tif (e instanceof NoTopMakersError) {\n\t\t\t\t// fallback to regular order\n\t\t\t\tallOrders.push(e.orderParams);\n\t\t\t} else {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tconst fetchedOrderParams = await fetchAuctionOrderParams({\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tassetType,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tamount,\n\t\t\tdlobServerHttpUrl,\n\t\t\toptionalAuctionParamsInputs,\n\t\t});\n\n\t\tconst oraclePrice =\n\t\t\tdriftClient.getOracleDataForPerpMarket(marketIndex).price;\n\t\tconst totalQuoteAmount = amount.mul(oraclePrice).div(PRICE_PRECISION);\n\n\t\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\t\tmarketIndex,\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\ttotalQuoteAmount,\n\t\t\tdirection\n\t\t);\n\n\t\tconst orderParams = {\n\t\t\t...fetchedOrderParams,\n\t\t\tuserOrderId,\n\t\t\tbitFlags,\n\t\t};\n\n\t\tallOrders.push(orderParams);\n\t}\n\n\tconst bracketOrdersDirection = ENUM_UTILS.match(\n\t\tdirection,\n\t\tPositionDirection.LONG\n\t)\n\t\t? PositionDirection.SHORT\n\t\t: PositionDirection.LONG;\n\n\tif (bracketOrders?.takeProfit) {\n\t\tconst takeProfitParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount: bracketOrders.takeProfit.baseAssetAmount ?? amount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'takeProfit',\n\t\t\t\ttriggerPrice: bracketOrders.takeProfit.triggerPrice,\n\t\t\t\tlimitPrice: bracketOrders.takeProfit.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: bracketOrders.takeProfit.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(takeProfitParams);\n\t}\n\n\tif (bracketOrders?.stopLoss) {\n\t\tconst stopLossParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount: bracketOrders.stopLoss.baseAssetAmount ?? amount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'stopLoss',\n\t\t\t\ttriggerPrice: bracketOrders.stopLoss.triggerPrice,\n\t\t\t\tlimitPrice: bracketOrders.stopLoss.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: bracketOrders.stopLoss.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(stopLossParams);\n\t}\n\n\t// Regular order flow - create transaction instruction\n\tif (allOrders.length > 0) {\n\t\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(allOrders);\n\t\tallIxs.push(placeOrderIx);\n\t}\n\n\treturn allIxs;\n};\n\n/**\n * Creates a complete transaction for opening a perp market order.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n *\n * @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)\n */\nexport const createOpenPerpMarketOrderTxn = async (\n\tparams: WithTxnParams<OpenPerpMarketOrderBaseParams>\n): Promise<Transaction | VersionedTransaction> => {\n\tconst { driftClient } = params;\n\n\t// Regular order flow - create transaction instruction and build transaction\n\tconst placeOrderIx = await createOpenPerpMarketOrderIxs(params);\n\tconst openPerpMarketOrderTxn = await driftClient.txHandler.buildTransaction({\n\t\tinstructions: placeOrderIx,\n\t\ttxVersion: 0,\n\t\tconnection: driftClient.connection,\n\t\tpreFlightCommitment: 'confirmed',\n\t\tfetchAllMarketLookupTableAccounts:\n\t\t\tdriftClient.fetchAllLookupTableAccounts.bind(driftClient),\n\t\ttxParams: params.txParams,\n\t});\n\n\treturn openPerpMarketOrderTxn;\n};\n\n/**\n * Creates a transaction or swift order for a perp market order.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n * @param useSwift - Whether to use Swift (signed message) orders instead of regular transactions\n * @param swiftOptions - Options for Swift (signed message) orders. Required if useSwift is true\n * @param userOrderId - The user order id for UI identification\n *\n * @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)\n */\nexport const createOpenPerpMarketOrder = async <T extends boolean>(\n\tparams: WithTxnParams<OpenPerpMarketOrderParams<T, SwiftOrderOptions>>\n): Promise<TxnOrSwiftResult<T>> => {\n\tconst { useSwift, swiftOptions, ...rest } = params;\n\n\t// If useSwift is true, return the Swift result directly\n\tif (useSwift) {\n\t\tif (!swiftOptions) {\n\t\t\tthrow new Error('swiftOptions is required when useSwift is true');\n\t\t}\n\n\t\tconst swiftOrderResult = await createSwiftMarketOrder({\n\t\t\t...rest,\n\t\t\tswiftOptions,\n\t\t});\n\n\t\treturn swiftOrderResult as TxnOrSwiftResult<T>;\n\t}\n\n\tconst openPerpMarketOrderTxn = await createOpenPerpMarketOrderTxn(rest);\n\n\treturn openPerpMarketOrderTxn as TxnOrSwiftResult<T>;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.ts"],"names":[],"mappings":";;;AAAA,yCAUyB;AAMzB,mDAAqD;AACrD,sDAG2B;AAC3B,kEAA6E;AAC7E,8CAIuB;AACvB,m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IAAI,CAAC,YAAY,EAAE,CAAC;YACnB,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;QACnE,CAAC;QAED,MAAM,gBAAgB,GAAG,MAAM,sBAAsB,CAAC;YACrD,GAAG,IAAI;YACP,YAAY;SACZ,CAAC,CAAC;QAEH,OAAO,gBAAuC,CAAC;IAChD,CAAC;IAED,MAAM,sBAAsB,GAAG,MAAM,IAAA,oCAA4B,EAAC,IAAI,CAAC,CAAC;IAExE,OAAO,sBAA6C,CAAC;AACtD,CAAC,CAAC;AAtBW,QAAA,yBAAyB,6BAsBpC","sourcesContent":["import {\n\tDriftClient,\n\tUser,\n\tBN,\n\tPositionDirection,\n\tOptionalOrderParams,\n\tMarketType,\n\tgetUserStatsAccountPublicKey,\n\tReferrerInfo,\n\tPRICE_PRECISION,\n} from '@drift-labs/sdk';\nimport {\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport {\n\tprepSignAndSendSwiftOrder,\n\tSwiftOrderOptions,\n} from '../openSwiftOrder';\nimport { buildNonMarketOrderParams } from '../../../../../utils/orderParams';\nimport {\n\tfetchAuctionOrderParams,\n\tfetchTopMakers,\n\tOptionalAuctionParamsRequestInputs,\n} from '../dlobServer';\nimport { ORDER_COMMON_UTILS } from '../../../../../../common-ui-utils/order';\nimport { TxnOrSwiftResult, WithTxnParams } from '../types';\nimport { NoTopMakersError } from '../../../../../Drift/constants/errors';\nimport { PlaceAndTakeParams, OptionalTriggerOrderParams } from '../types';\n\nexport interface OpenPerpMarketOrderBaseParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tassetType: 'base' | 'quote';\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\tamount: BN;\n\tdlobServerHttpUrl: string;\n\t// mainly used for UI order identification\n\tuserOrderId?: number;\n\tplaceAndTake?: PlaceAndTakeParams;\n\toptionalAuctionParamsInputs?: OptionalAuctionParamsRequestInputs;\n\tbracketOrders?: {\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t};\n}\n\nexport interface OpenPerpMarketOrderBaseParamsWithSwift\n\textends Omit<OpenPerpMarketOrderBaseParams, 'placeAndTake'> {\n\tswiftOptions: SwiftOrderOptions;\n}\n\nexport type OpenPerpMarketOrderParams<\n\tT extends boolean = boolean,\n\tS extends Omit<SwiftOrderOptions, 'swiftServerUrl'> = Omit<\n\t\tSwiftOrderOptions,\n\t\t'swiftServerUrl'\n\t>\n> = T extends true\n\t? OpenPerpMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tswiftOptions: S;\n\t\t\tplaceAndTake?: never;\n\t }\n\t: OpenPerpMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tplaceAndTake?: PlaceAndTakeParams;\n\t\t\tswiftOptions?: never;\n\t };\n/**\n * Creates and submits a Swift (signed message) order. Only available for perp orders.\n */\nexport async function createSwiftMarketOrder({\n\tdriftClient,\n\tuser,\n\tassetType,\n\tmarketIndex,\n\tdirection,\n\tamount,\n\tbracketOrders,\n\tdlobServerHttpUrl,\n\toptionalAuctionParamsInputs,\n\tswiftOptions,\n\tuserOrderId = 0,\n}: OpenPerpMarketOrderBaseParamsWithSwift): Promise<void> {\n\tif (amount.isZero()) {\n\t\tthrow new Error('Amount must be greater than zero');\n\t}\n\n\t// Get order parameters from server\n\tconst fetchedOrderParams = await fetchAuctionOrderParams({\n\t\tdriftClient,\n\t\tuser,\n\t\tassetType,\n\t\tmarketIndex,\n\t\tmarketType: MarketType.PERP,\n\t\tdirection,\n\t\tamount,\n\t\tdlobServerHttpUrl,\n\t\toptionalAuctionParamsInputs,\n\t});\n\n\tconst oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;\n\tconst totalQuoteAmount = amount.mul(oraclePrice).div(PRICE_PRECISION);\n\n\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\tmarketIndex,\n\t\tdriftClient,\n\t\tuser,\n\t\ttotalQuoteAmount,\n\t\tdirection\n\t);\n\n\tconst orderParams = {\n\t\t...fetchedOrderParams,\n\t\tuserOrderId,\n\t\tbitFlags,\n\t};\n\n\tconst userAccount = user.getUserAccount();\n\tconst slotBuffer = swiftOptions.signedMessageOrderSlotBuffer || 7;\n\n\tawait prepSignAndSendSwiftOrder({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tuserAccountPubKey: user.userAccountPublicKey,\n\t\tmarketIndex,\n\t\tslotBuffer,\n\t\tswiftOptions,\n\t\torderParams: {\n\t\t\tmain: orderParams,\n\t\t\ttakeProfit: bracketOrders?.takeProfit,\n\t\t\tstopLoss: bracketOrders?.stopLoss,\n\t\t},\n\t});\n}\n\n/**\n * Creates a placeAndTake transaction instruction.\n * Fallbacks to a regular market order if no top makers are found.\n */\nexport const createPlaceAndTakePerpMarketOrderIx = async ({\n\tassetType,\n\tdirection,\n\tdlobServerHttpUrl,\n\tmarketIndex,\n\tdriftClient,\n\tuser,\n\tuserOrderId,\n\tamount,\n\treferrerInfo,\n\tauctionDurationPercentage,\n\toptionalAuctionParamsInputs,\n}: OpenPerpMarketOrderBaseParams & {\n\tdirection: PositionDirection;\n\tdlobServerHttpUrl: string;\n\tmarketIndex: number;\n\tdriftClient: DriftClient;\n\tuser: User;\n\treferrerInfo?: ReferrerInfo;\n\tauctionDurationPercentage?: number;\n}) => {\n\tconst counterPartySide = ENUM_UTILS.match(direction, PositionDirection.LONG)\n\t\t? 'ask'\n\t\t: 'bid';\n\n\tconst [fetchedOrderParams, topMakersResult] = await Promise.all([\n\t\tfetchAuctionOrderParams({\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tassetType,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tamount,\n\t\t\tdlobServerHttpUrl,\n\t\t\toptionalAuctionParamsInputs,\n\t\t}),\n\t\tfetchTopMakers({\n\t\t\tdlobServerHttpUrl,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tside: counterPartySide,\n\t\t\tlimit: 4,\n\t\t}),\n\t]);\n\n\tconst oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;\n\tconst totalQuoteAmount = amount.mul(oraclePrice).div(PRICE_PRECISION);\n\n\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\tmarketIndex,\n\t\tdriftClient,\n\t\tuser,\n\t\ttotalQuoteAmount,\n\t\tdirection\n\t);\n\tfetchedOrderParams.bitFlags = bitFlags;\n\tfetchedOrderParams.userOrderId = userOrderId;\n\n\tif (!topMakersResult || topMakersResult.length === 0) {\n\t\tthrow new NoTopMakersError('No top makers found', fetchedOrderParams);\n\t}\n\n\tconst topMakersInfo = topMakersResult.map((maker) => ({\n\t\tmaker: maker.userAccountPubKey,\n\t\tmakerUserAccount: maker.userAccount,\n\t\tmakerStats: getUserStatsAccountPublicKey(\n\t\t\tdriftClient.program.programId,\n\t\t\tmaker.userAccount.authority\n\t\t),\n\t}));\n\n\tconst placeAndTakeIx = await driftClient.getPlaceAndTakePerpOrderIx(\n\t\tfetchedOrderParams,\n\t\ttopMakersInfo,\n\t\treferrerInfo,\n\t\tundefined,\n\t\tauctionDurationPercentage,\n\t\tuser.getUserAccount().subAccountId\n\t);\n\n\treturn placeAndTakeIx;\n};\n\n/**\n * Creates transaction instructions for opening a perp market order.\n * If swiftOptions is provided, it will create a Swift (signed message) order instead.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param assetType - Whether the amount is in base or quote units\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n *\n * @returns Promise resolving to an array of transaction instructions for regular orders\n */\nexport const createOpenPerpMarketOrderIxs = async ({\n\tdriftClient,\n\tuser,\n\tassetType,\n\tmarketIndex,\n\tdirection,\n\tamount,\n\tbracketOrders,\n\tdlobServerHttpUrl,\n\tplaceAndTake,\n\tuserOrderId,\n\toptionalAuctionParamsInputs = {},\n}: OpenPerpMarketOrderBaseParams): Promise<TransactionInstruction[]> => {\n\tif (!amount || amount.isZero()) {\n\t\tthrow new Error('Amount must be greater than zero');\n\t}\n\n\tconst allOrders: OptionalOrderParams[] = [];\n\tconst allIxs: TransactionInstruction[] = [];\n\n\tif (placeAndTake?.enable) {\n\t\ttry {\n\t\t\tconst placeAndTakeIx = await createPlaceAndTakePerpMarketOrderIx({\n\t\t\t\tassetType,\n\t\t\t\tamount,\n\t\t\t\tdirection,\n\t\t\t\tdlobServerHttpUrl,\n\t\t\t\tmarketIndex,\n\t\t\t\tdriftClient,\n\t\t\t\tuser,\n\t\t\t\tuserOrderId,\n\t\t\t\treferrerInfo: placeAndTake.referrerInfo,\n\t\t\t\tauctionDurationPercentage: placeAndTake.auctionDurationPercentage,\n\t\t\t\toptionalAuctionParamsInputs,\n\t\t\t});\n\t\t\tallIxs.push(placeAndTakeIx);\n\t\t} catch (e) {\n\t\t\tif (e instanceof NoTopMakersError) {\n\t\t\t\t// fallback to regular order\n\t\t\t\tallOrders.push(e.orderParams);\n\t\t\t} else {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tconst fetchedOrderParams = await fetchAuctionOrderParams({\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tassetType,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tamount,\n\t\t\tdlobServerHttpUrl,\n\t\t\toptionalAuctionParamsInputs,\n\t\t});\n\n\t\tconst oraclePrice =\n\t\t\tdriftClient.getOracleDataForPerpMarket(marketIndex).price;\n\t\tconst totalQuoteAmount = amount.mul(oraclePrice).div(PRICE_PRECISION);\n\n\t\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\t\tmarketIndex,\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\ttotalQuoteAmount,\n\t\t\tdirection\n\t\t);\n\n\t\tconst orderParams = {\n\t\t\t...fetchedOrderParams,\n\t\t\tuserOrderId,\n\t\t\tbitFlags,\n\t\t};\n\n\t\tallOrders.push(orderParams);\n\t}\n\n\tconst bracketOrdersDirection = ENUM_UTILS.match(\n\t\tdirection,\n\t\tPositionDirection.LONG\n\t)\n\t\t? PositionDirection.SHORT\n\t\t: PositionDirection.LONG;\n\n\tif (bracketOrders?.takeProfit) {\n\t\tconst takeProfitParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount: bracketOrders.takeProfit.baseAssetAmount ?? amount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'takeProfit',\n\t\t\t\ttriggerPrice: bracketOrders.takeProfit.triggerPrice,\n\t\t\t\tlimitPrice: bracketOrders.takeProfit.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: bracketOrders.takeProfit.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(takeProfitParams);\n\t}\n\n\tif (bracketOrders?.stopLoss) {\n\t\tconst stopLossParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount: bracketOrders.stopLoss.baseAssetAmount ?? amount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'stopLoss',\n\t\t\t\ttriggerPrice: bracketOrders.stopLoss.triggerPrice,\n\t\t\t\tlimitPrice: bracketOrders.stopLoss.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: bracketOrders.stopLoss.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(stopLossParams);\n\t}\n\n\t// Regular order flow - create transaction instruction\n\tif (allOrders.length > 0) {\n\t\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(allOrders);\n\t\tallIxs.push(placeOrderIx);\n\t}\n\n\treturn allIxs;\n};\n\n/**\n * Creates a complete transaction for opening a perp market order.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n *\n * @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)\n */\nexport const createOpenPerpMarketOrderTxn = async (\n\tparams: WithTxnParams<OpenPerpMarketOrderBaseParams>\n): Promise<Transaction | VersionedTransaction> => {\n\tconst { driftClient } = params;\n\n\t// Regular order flow - create transaction instruction and build transaction\n\tconst placeOrderIx = await createOpenPerpMarketOrderIxs(params);\n\tconst openPerpMarketOrderTxn = await driftClient.txHandler.buildTransaction({\n\t\tinstructions: placeOrderIx,\n\t\ttxVersion: 0,\n\t\tconnection: driftClient.connection,\n\t\tpreFlightCommitment: 'confirmed',\n\t\tfetchAllMarketLookupTableAccounts:\n\t\t\tdriftClient.fetchAllLookupTableAccounts.bind(driftClient),\n\t\ttxParams: params.txParams,\n\t});\n\n\treturn openPerpMarketOrderTxn;\n};\n\n/**\n * Creates a transaction or swift order for a perp market order.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n * @param useSwift - Whether to use Swift (signed message) orders instead of regular transactions\n * @param swiftOptions - Options for Swift (signed message) orders. Required if useSwift is true\n * @param userOrderId - The user order id for UI identification\n *\n * @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)\n */\nexport const createOpenPerpMarketOrder = async <T extends boolean>(\n\tparams: WithTxnParams<OpenPerpMarketOrderParams<T, SwiftOrderOptions>>\n): Promise<TxnOrSwiftResult<T>> => {\n\tconst { useSwift, swiftOptions, ...rest } = params;\n\n\t// If useSwift is true, return the Swift result directly\n\tif (useSwift) {\n\t\tif (!swiftOptions) {\n\t\t\tthrow new Error('swiftOptions is required when useSwift is true');\n\t\t}\n\n\t\tconst swiftOrderResult = await createSwiftMarketOrder({\n\t\t\t...rest,\n\t\t\tswiftOptions,\n\t\t});\n\n\t\treturn swiftOrderResult as TxnOrSwiftResult<T>;\n\t}\n\n\tconst openPerpMarketOrderTxn = await createOpenPerpMarketOrderTxn(rest);\n\n\treturn openPerpMarketOrderTxn as TxnOrSwiftResult<T>;\n};\n"]}
|
|
@@ -237,6 +237,7 @@ const createSwiftLimitOrder = async (params) => {
|
|
|
237
237
|
await (0, openSwiftOrder_1.prepSignAndSendSwiftOrder)({
|
|
238
238
|
driftClient,
|
|
239
239
|
subAccountId: userAccount.subAccountId,
|
|
240
|
+
userAccountPubKey: user.userAccountPublicKey,
|
|
240
241
|
marketIndex,
|
|
241
242
|
slotBuffer,
|
|
242
243
|
swiftOptions,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.ts"],"names":[],"mappings":";;;;;;AAAA,yCAcyB;AAMzB,sDAG2B;AAC3B,kEAG0C;AAC1C,mDAAqD;AACrD,8CAAwD;AACxD,uEAG2C;AAC3C,gEAA6E;AAC7E,oEAAuC;AA8CvC,MAAM,0BAA0B,GAAG,KAAK,EAAE,EACzC,WAAW,EACX,IAAI,EACJ,WAAW,EACX,SAAS,EACT,eAAe,EACf,WAAW,GAAG,CAAC,EACf,UAAU,GAAG,KAAK,EAClB,QAAQ,GAAG,oBAAc,CAAC,IAAI,EAC9B,WAAW,GAMX,EAAgC,EAAE;IAClC,MAAM,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AC;IAED,MAAM,cAAc,GAAG,MAAM,IAAA,uCAA+B,EAAC,MAAM,CAAC,CAAC;IAErE,OAAO,cAAqC,CAAC;AAC9C,CAAC,CAAC;AAlCW,QAAA,4BAA4B,gCAkCvC","sourcesContent":["import {\n\tDriftClient,\n\tUser,\n\tBN,\n\tMarketType,\n\tPostOnlyParams,\n\tgetLimitOrderParams,\n\tOptionalOrderParams,\n\tPRICE_PRECISION_EXP,\n\tBigNum,\n\toraclePriceBands as getOraclePriceBands,\n\tPositionDirection,\n\tOrderParamsBitFlag,\n\tPRICE_PRECISION,\n} from '@drift-labs/sdk';\nimport {\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport {\n\tprepSignAndSendSwiftOrder,\n\tSwiftOrderOptions,\n} from '../openSwiftOrder';\nimport {\n\tbuildNonMarketOrderParams,\n\tresolveBaseAssetAmount,\n} from '../../../../../utils/orderParams';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport { fetchAuctionOrderParams } from '../dlobServer';\nimport {\n\tCOMMON_UI_UTILS,\n\tORDER_COMMON_UTILS,\n} from '../../../../../../common-ui-utils';\nimport { createPlaceAndTakePerpMarketOrderIx } from '../openPerpMarketOrder';\nimport invariant from 'tiny-invariant';\nimport {\n\tTxnOrSwiftResult,\n\tLimitAuctionConfig,\n\tLimitOrderParamsOrderConfig,\n\tNonMarketOrderParamsConfig,\n\tWithTxnParams,\n} from '../types';\n\nexport interface OpenPerpNonMarketOrderBaseParams\n\textends Omit<NonMarketOrderParamsConfig, 'marketType' | 'baseAssetAmount'> {\n\tdriftClient: DriftClient;\n\tuser: User;\n\t// Either new approach\n\tamount?: BN;\n\tassetType?: 'base' | 'quote';\n\t// Or legacy approach\n\tbaseAssetAmount?: BN;\n\t// Common optional params\n\treduceOnly?: boolean;\n\tpostOnly?: PostOnlyParams;\n\tuserOrderId?: number;\n\tautoEnterHighLeverageModeBufferPct?: number;\n}\n\nexport interface OpenPerpNonMarketOrderParamsWithSwift\n\textends OpenPerpNonMarketOrderBaseParams {\n\tswiftOptions: SwiftOrderOptions;\n}\n\nexport type OpenPerpNonMarketOrderParams<\n\tT extends boolean = boolean,\n\tS extends Omit<SwiftOrderOptions, 'swiftServerUrl'> = Omit<\n\t\tSwiftOrderOptions,\n\t\t'swiftServerUrl'\n\t>\n> = T extends true\n\t? OpenPerpNonMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tswiftOptions: S;\n\t }\n\t: OpenPerpNonMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tswiftOptions?: never;\n\t };\n\nconst getLimitAuctionOrderParams = async ({\n\tdriftClient,\n\tuser,\n\tmarketIndex,\n\tdirection,\n\tbaseAssetAmount,\n\tuserOrderId = 0,\n\treduceOnly = false,\n\tpostOnly = PostOnlyParams.NONE,\n\torderConfig,\n}: OpenPerpNonMarketOrderBaseParams & {\n\tbaseAssetAmount: BN;\n\torderConfig: LimitOrderParamsOrderConfig & {\n\t\tlimitAuction: LimitAuctionConfig;\n\t};\n}): Promise<OptionalOrderParams> => {\n\tconst orderParams = await fetchAuctionOrderParams({\n\t\tdriftClient,\n\t\tuser,\n\t\tassetType: 'base',\n\t\tmarketIndex,\n\t\tmarketType: MarketType.PERP,\n\t\tdirection,\n\t\tamount: baseAssetAmount,\n\t\tdlobServerHttpUrl: orderConfig.limitAuction.dlobServerHttpUrl,\n\t\toptionalAuctionParamsInputs:\n\t\t\torderConfig.limitAuction.optionalLimitAuctionParams,\n\t});\n\n\tconst perpMarketAccount = driftClient.getPerpMarketAccount(marketIndex);\n\n\tinvariant(perpMarketAccount, 'Perp market account not found');\n\tinvariant(orderConfig.limitAuction.oraclePrice, 'Oracle price not found');\n\tinvariant(orderParams.auctionStartPrice, 'Auction start price not found');\n\n\tconst oraclePriceBands = orderConfig.limitAuction.oraclePrice\n\t\t? getOraclePriceBands(perpMarketAccount, {\n\t\t\t\tprice: orderConfig.limitAuction.oraclePrice,\n\t\t })\n\t\t: undefined;\n\tconst auctionDuration = ORDER_COMMON_UTILS.getPerpAuctionDuration(\n\t\torderConfig.limitPrice.sub(orderParams.auctionStartPrice).abs(),\n\t\torderConfig.limitAuction.oraclePrice,\n\t\tperpMarketAccount.contractTier\n\t);\n\tconst limitAuctionParams = COMMON_UI_UTILS.getLimitAuctionParams({\n\t\tdirection,\n\t\tinputPrice: BigNum.from(orderConfig.limitPrice, PRICE_PRECISION_EXP),\n\t\tstartPriceFromSettings: orderParams.auctionStartPrice,\n\t\tduration: auctionDuration,\n\t\tauctionStartPriceOffset: orderConfig.limitAuction.auctionStartPriceOffset,\n\t\toraclePriceBands,\n\t});\n\n\tconst limitAuctionOrderParams = getLimitOrderParams({\n\t\tmarketIndex,\n\t\tmarketType: MarketType.PERP,\n\t\tdirection,\n\t\tbaseAssetAmount,\n\t\treduceOnly,\n\t\tpostOnly,\n\t\tprice: orderConfig.limitPrice,\n\t\tuserOrderId,\n\t\t...limitAuctionParams,\n\t});\n\n\tconst oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;\n\tconst totalQuoteAmount = baseAssetAmount\n\t\t.mul(oraclePrice)\n\t\t.div(PRICE_PRECISION);\n\n\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\tmarketIndex,\n\t\tdriftClient,\n\t\tuser,\n\t\ttotalQuoteAmount,\n\t\tdirection\n\t);\n\n\treturn {\n\t\t...limitAuctionOrderParams,\n\t\tbitFlags,\n\t};\n};\n\n/**\n * Creates a transaction instruction to open multiple non-market orders.\n */\nexport const createMultipleOpenPerpNonMarketOrderIx = async (params: {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\torderParamsConfigs: NonMarketOrderParamsConfig[];\n\tenterHighLeverageMode?: boolean;\n}): Promise<TransactionInstruction> => {\n\tconst { driftClient, orderParamsConfigs } = params;\n\n\tconst orderParams = orderParamsConfigs.map(buildNonMarketOrderParams);\n\n\tif (params.enterHighLeverageMode && orderParams.length > 0) {\n\t\torderParams[0].bitFlags = OrderParamsBitFlag.UpdateHighLeverageMode;\n\t}\n\n\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(orderParams);\n\treturn placeOrderIx;\n};\n\n/**\n * Creates a transaction instruction to open a non-market order.\n * Allows for bracket orders to be opened in the same transaction.\n *\n * If `limitAuction` is enabled, a placeAndTake order is created to simulate a market auction order,\n * with the end price being the limit price.\n */\nexport const createOpenPerpNonMarketOrderIxs = async (\n\tparams: OpenPerpNonMarketOrderBaseParams\n): Promise<TransactionInstruction[]> => {\n\tconst {\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\tdirection,\n\t\treduceOnly = false,\n\t\tpostOnly = PostOnlyParams.NONE,\n\t\torderConfig,\n\t\tuserOrderId = 0,\n\t} = params;\n\t// Support both new (amount + assetType) and legacy (baseAssetAmount) approaches\n\tconst finalBaseAssetAmount = resolveBaseAssetAmount({\n\t\tamount: 'amount' in params ? params.amount : undefined,\n\t\tassetType: 'assetType' in params ? params.assetType : undefined,\n\t\tbaseAssetAmount:\n\t\t\t'baseAssetAmount' in params ? params.baseAssetAmount : undefined,\n\t\tlimitPrice:\n\t\t\t'limitPrice' in params.orderConfig\n\t\t\t\t? params.orderConfig.limitPrice\n\t\t\t\t: undefined,\n\t});\n\n\tif (!finalBaseAssetAmount || finalBaseAssetAmount.isZero()) {\n\t\tthrow new Error('Final base asset amount must be greater than zero');\n\t}\n\n\tconst allOrders: OptionalOrderParams[] = [];\n\tconst allIxs: TransactionInstruction[] = [];\n\n\t// handle limit auction\n\tif (orderConfig.orderType === 'limit' && orderConfig.limitAuction?.enable) {\n\t\tconst limitAuctionOrderParams = await getLimitAuctionOrderParams({\n\t\t\t...params,\n\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\torderConfig: orderConfig as LimitOrderParamsOrderConfig & {\n\t\t\t\tlimitAuction: LimitAuctionConfig;\n\t\t\t},\n\t\t});\n\n\t\tlet createdPlaceAndTakeIx = false;\n\n\t\t// if it is a limit auction order, we create a placeAndTake order to simulate a market order.\n\t\t// this is useful when a limit order is crossing, and we want to achieve the best fill price through a placeAndTake.\n\t\t// falls back to limit order with auction params if the placeAndTake order creation fails\n\t\tif (\n\t\t\tlimitAuctionOrderParams.auctionDuration &&\n\t\t\tlimitAuctionOrderParams.auctionDuration > 0 &&\n\t\t\torderConfig.limitAuction?.usePlaceAndTake?.enable\n\t\t) {\n\t\t\ttry {\n\t\t\t\tconst placeAndTakeIx = await createPlaceAndTakePerpMarketOrderIx({\n\t\t\t\t\tassetType: 'base',\n\t\t\t\t\tamount: finalBaseAssetAmount,\n\t\t\t\t\tdirection,\n\t\t\t\t\tdlobServerHttpUrl: orderConfig.limitAuction.dlobServerHttpUrl,\n\t\t\t\t\tmarketIndex,\n\t\t\t\t\tdriftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tuserOrderId,\n\t\t\t\t\toptionalAuctionParamsInputs:\n\t\t\t\t\t\torderConfig.limitAuction.optionalLimitAuctionParams,\n\t\t\t\t\tauctionDurationPercentage:\n\t\t\t\t\t\torderConfig.limitAuction.usePlaceAndTake.auctionDurationPercentage,\n\t\t\t\t\treferrerInfo: orderConfig.limitAuction.usePlaceAndTake.referrerInfo,\n\t\t\t\t});\n\t\t\t\tallIxs.push(placeAndTakeIx);\n\t\t\t\tcreatedPlaceAndTakeIx = true;\n\t\t\t} catch (e) {\n\t\t\t\tconsole.error(\n\t\t\t\t\t'Failed to create placeAndTake order for limit auction order',\n\t\t\t\t\te\n\t\t\t\t);\n\t\t\t\tcreatedPlaceAndTakeIx = false;\n\t\t\t}\n\t\t}\n\n\t\t// fallback to normal limit order with auction params\n\t\tif (!createdPlaceAndTakeIx) {\n\t\t\tallOrders.push(limitAuctionOrderParams);\n\t\t}\n\t} else {\n\t\tconst orderParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\torderConfig,\n\t\t\treduceOnly,\n\t\t\tpostOnly,\n\t\t\tuserOrderId,\n\t\t});\n\n\t\tconst oraclePrice =\n\t\t\tdriftClient.getOracleDataForPerpMarket(marketIndex).price;\n\t\tconst totalQuoteAmount = finalBaseAssetAmount\n\t\t\t.mul(oraclePrice)\n\t\t\t.div(PRICE_PRECISION);\n\n\t\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\t\tmarketIndex,\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\ttotalQuoteAmount,\n\t\t\tdirection\n\t\t);\n\t\torderParams.bitFlags = bitFlags;\n\n\t\tallOrders.push(orderParams);\n\t}\n\n\tconst bracketOrdersDirection = ENUM_UTILS.match(\n\t\tdirection,\n\t\tPositionDirection.LONG\n\t)\n\t\t? PositionDirection.SHORT\n\t\t: PositionDirection.LONG;\n\n\tif ('bracketOrders' in orderConfig && orderConfig.bracketOrders?.takeProfit) {\n\t\tconst takeProfitParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount:\n\t\t\t\torderConfig.bracketOrders.takeProfit.baseAssetAmount ??\n\t\t\t\tfinalBaseAssetAmount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'takeProfit',\n\t\t\t\ttriggerPrice: orderConfig.bracketOrders.takeProfit.triggerPrice,\n\t\t\t\tlimitPrice: orderConfig.bracketOrders.takeProfit.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: orderConfig.bracketOrders.takeProfit.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(takeProfitParams);\n\t}\n\n\tif ('bracketOrders' in orderConfig && orderConfig.bracketOrders?.stopLoss) {\n\t\tconst stopLossParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount:\n\t\t\t\torderConfig.bracketOrders.stopLoss.baseAssetAmount ??\n\t\t\t\tfinalBaseAssetAmount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'stopLoss',\n\t\t\t\ttriggerPrice: orderConfig.bracketOrders.stopLoss.triggerPrice,\n\t\t\t\tlimitPrice: orderConfig.bracketOrders.stopLoss.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: orderConfig.bracketOrders.stopLoss.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(stopLossParams);\n\t}\n\n\tif (allOrders.length > 0) {\n\t\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(allOrders);\n\t\tallIxs.push(placeOrderIx);\n\t}\n\n\treturn allIxs;\n};\n\nexport const MINIMUM_SWIFT_LIMIT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 35;\n\nexport const createSwiftLimitOrder = async (\n\tparams: OpenPerpNonMarketOrderParamsWithSwift & {\n\t\torderConfig: LimitOrderParamsOrderConfig;\n\t}\n): Promise<void> => {\n\tconst { driftClient, user, marketIndex, swiftOptions, orderConfig } = params;\n\n\tconst limitPrice = orderConfig.limitPrice;\n\n\tif (limitPrice.isZero()) {\n\t\tthrow new Error('LIMIT orders require limitPrice');\n\t}\n\n\t// Support both new (amount + assetType) and legacy (baseAssetAmount) approaches\n\tconst finalBaseAssetAmount = resolveBaseAssetAmount({\n\t\tamount: 'amount' in params ? params.amount : undefined,\n\t\tassetType: 'assetType' in params ? params.assetType : undefined,\n\t\tbaseAssetAmount:\n\t\t\t'baseAssetAmount' in params ? params.baseAssetAmount : undefined,\n\t\tlimitPrice,\n\t});\n\n\tconst orderParams = orderConfig.limitAuction?.enable\n\t\t? await getLimitAuctionOrderParams({\n\t\t\t\t...params,\n\t\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\t\torderConfig: orderConfig as LimitOrderParamsOrderConfig & {\n\t\t\t\t\tlimitAuction: LimitAuctionConfig;\n\t\t\t\t},\n\t\t })\n\t\t: buildNonMarketOrderParams({\n\t\t\t\tmarketIndex,\n\t\t\t\tmarketType: MarketType.PERP,\n\t\t\t\tdirection: params.direction,\n\t\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\t\torderConfig,\n\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\tpostOnly: params.postOnly,\n\t\t\t\tuserOrderId: params.userOrderId,\n\t\t });\n\n\tconst userAccount = user.getUserAccount();\n\tconst slotBuffer = Math.max(\n\t\t(swiftOptions.signedMessageOrderSlotBuffer || 0) +\n\t\t\t(orderParams.auctionDuration || 0),\n\t\tMINIMUM_SWIFT_LIMIT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS\n\t); // limit orders require a much larger buffer, to replace the auction duration usually found in market orders\n\n\tawait prepSignAndSendSwiftOrder({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tmarketIndex,\n\t\tslotBuffer,\n\t\tswiftOptions,\n\t\torderParams: {\n\t\t\tmain: orderParams,\n\t\t\ttakeProfit: orderConfig.bracketOrders?.takeProfit,\n\t\t\tstopLoss: orderConfig.bracketOrders?.stopLoss,\n\t\t},\n\t});\n};\n\nexport const createOpenPerpNonMarketOrderTxn = async (\n\tparams: WithTxnParams<OpenPerpNonMarketOrderBaseParams>\n): Promise<Transaction | VersionedTransaction> => {\n\tconst { driftClient } = params;\n\n\tconst instructions = await createOpenPerpNonMarketOrderIxs(params);\n\n\tconst openPerpNonMarketOrderTxn = await driftClient.buildTransaction(\n\t\tinstructions,\n\t\tparams.txParams\n\t);\n\n\treturn openPerpNonMarketOrderTxn;\n};\n\nexport const createOpenPerpNonMarketOrder = async <T extends boolean>(\n\tparams: WithTxnParams<OpenPerpNonMarketOrderParams<T, SwiftOrderOptions>>\n): Promise<TxnOrSwiftResult<T>> => {\n\tconst { swiftOptions, useSwift, orderConfig } = params;\n\n\t// If useSwift is true, return the Swift result directly\n\tif (useSwift) {\n\t\tif (orderConfig.orderType !== 'limit') {\n\t\t\tthrow new Error('Only limit orders are supported with Swift');\n\t\t}\n\n\t\tif (!swiftOptions) {\n\t\t\tthrow new Error('swiftOptions is required when useSwift is true');\n\t\t}\n\n\t\tif (\n\t\t\tparams.postOnly &&\n\t\t\t!ENUM_UTILS.match(params.postOnly, PostOnlyParams.NONE)\n\t\t) {\n\t\t\tthrow new Error('Post only orders are not supported with Swift');\n\t\t}\n\n\t\tconst swiftOrderResult = await createSwiftLimitOrder({\n\t\t\t...params,\n\t\t\tswiftOptions,\n\t\t\torderConfig,\n\t\t});\n\n\t\treturn swiftOrderResult as TxnOrSwiftResult<T>;\n\t}\n\n\tconst marketOrderTxn = await createOpenPerpNonMarketOrderTxn(params);\n\n\treturn marketOrderTxn as TxnOrSwiftResult<T>;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.ts"],"names":[],"mappings":";;;;;;AAAA,yCAcyB;AAMzB,sDAG2B;AAC3B,kEAG0C;AAC1C,mDAAqD;AACrD,8CAAwD;AACxD,uEAG2C;AAC3C,gEAA6E;AAC7E,oEAAuC;AA8CvC,MAAM,0BAA0B,GAAG,KAAK,EAAE,EACzC,WAAW,EACX,IAAI,EACJ,WAAW,EACX,SAAS,EACT,eAAe,EACf,WAAW,GAAG,CAAC,EACf,UAAU,GAAG,KAAK,EAClB,QAAQ,GAAG,oBAAc,CAAC,IAAI,EAC9B,WAAW,GAMX,EAAgC,EAAE;IAClC,MAAM,WAAW,GAAG,MAAM,IAAA,oCAAuB,EAAC;QACjD,WAAW;QACX,IAAI;QACJ,SAAS,EAAE,MAAM;QACjB,WAAW;QACX,UAAU,EAAE,gBAAU,CAAC,IAAI;QAC3B,SAAS;QACT,MAAM,EAAE,eAAe;QACvB,iBAAiB,EAAE,WAAW,CAAC,YAAY,CAAC,iBAAiB;QAC7D,2BAA2B,EAC1B,WAAW,CAAC,YAAY,CAAC,0BAA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\n\tOptionalOrderParams,\n\tPRICE_PRECISION_EXP,\n\tBigNum,\n\toraclePriceBands as getOraclePriceBands,\n\tPositionDirection,\n\tOrderParamsBitFlag,\n\tPRICE_PRECISION,\n} from '@drift-labs/sdk';\nimport {\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport {\n\tprepSignAndSendSwiftOrder,\n\tSwiftOrderOptions,\n} from '../openSwiftOrder';\nimport {\n\tbuildNonMarketOrderParams,\n\tresolveBaseAssetAmount,\n} from '../../../../../utils/orderParams';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport { fetchAuctionOrderParams } from '../dlobServer';\nimport {\n\tCOMMON_UI_UTILS,\n\tORDER_COMMON_UTILS,\n} from '../../../../../../common-ui-utils';\nimport { createPlaceAndTakePerpMarketOrderIx } from '../openPerpMarketOrder';\nimport invariant from 'tiny-invariant';\nimport {\n\tTxnOrSwiftResult,\n\tLimitAuctionConfig,\n\tLimitOrderParamsOrderConfig,\n\tNonMarketOrderParamsConfig,\n\tWithTxnParams,\n} from '../types';\n\nexport interface OpenPerpNonMarketOrderBaseParams\n\textends Omit<NonMarketOrderParamsConfig, 'marketType' | 'baseAssetAmount'> {\n\tdriftClient: DriftClient;\n\tuser: User;\n\t// Either new approach\n\tamount?: BN;\n\tassetType?: 'base' | 'quote';\n\t// Or legacy approach\n\tbaseAssetAmount?: BN;\n\t// Common optional params\n\treduceOnly?: boolean;\n\tpostOnly?: PostOnlyParams;\n\tuserOrderId?: number;\n\tautoEnterHighLeverageModeBufferPct?: number;\n}\n\nexport interface OpenPerpNonMarketOrderParamsWithSwift\n\textends OpenPerpNonMarketOrderBaseParams {\n\tswiftOptions: SwiftOrderOptions;\n}\n\nexport type OpenPerpNonMarketOrderParams<\n\tT extends boolean = boolean,\n\tS extends Omit<SwiftOrderOptions, 'swiftServerUrl'> = Omit<\n\t\tSwiftOrderOptions,\n\t\t'swiftServerUrl'\n\t>\n> = T extends true\n\t? OpenPerpNonMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tswiftOptions: S;\n\t }\n\t: OpenPerpNonMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tswiftOptions?: never;\n\t };\n\nconst getLimitAuctionOrderParams = async ({\n\tdriftClient,\n\tuser,\n\tmarketIndex,\n\tdirection,\n\tbaseAssetAmount,\n\tuserOrderId = 0,\n\treduceOnly = false,\n\tpostOnly = PostOnlyParams.NONE,\n\torderConfig,\n}: OpenPerpNonMarketOrderBaseParams & {\n\tbaseAssetAmount: BN;\n\torderConfig: LimitOrderParamsOrderConfig & {\n\t\tlimitAuction: LimitAuctionConfig;\n\t};\n}): Promise<OptionalOrderParams> => {\n\tconst orderParams = await fetchAuctionOrderParams({\n\t\tdriftClient,\n\t\tuser,\n\t\tassetType: 'base',\n\t\tmarketIndex,\n\t\tmarketType: MarketType.PERP,\n\t\tdirection,\n\t\tamount: baseAssetAmount,\n\t\tdlobServerHttpUrl: orderConfig.limitAuction.dlobServerHttpUrl,\n\t\toptionalAuctionParamsInputs:\n\t\t\torderConfig.limitAuction.optionalLimitAuctionParams,\n\t});\n\n\tconst perpMarketAccount = driftClient.getPerpMarketAccount(marketIndex);\n\n\tinvariant(perpMarketAccount, 'Perp market account not found');\n\tinvariant(orderConfig.limitAuction.oraclePrice, 'Oracle price not found');\n\tinvariant(orderParams.auctionStartPrice, 'Auction start price not found');\n\n\tconst oraclePriceBands = orderConfig.limitAuction.oraclePrice\n\t\t? getOraclePriceBands(perpMarketAccount, {\n\t\t\t\tprice: orderConfig.limitAuction.oraclePrice,\n\t\t })\n\t\t: undefined;\n\tconst auctionDuration = ORDER_COMMON_UTILS.getPerpAuctionDuration(\n\t\torderConfig.limitPrice.sub(orderParams.auctionStartPrice).abs(),\n\t\torderConfig.limitAuction.oraclePrice,\n\t\tperpMarketAccount.contractTier\n\t);\n\tconst limitAuctionParams = COMMON_UI_UTILS.getLimitAuctionParams({\n\t\tdirection,\n\t\tinputPrice: BigNum.from(orderConfig.limitPrice, PRICE_PRECISION_EXP),\n\t\tstartPriceFromSettings: orderParams.auctionStartPrice,\n\t\tduration: auctionDuration,\n\t\tauctionStartPriceOffset: orderConfig.limitAuction.auctionStartPriceOffset,\n\t\toraclePriceBands,\n\t});\n\n\tconst limitAuctionOrderParams = getLimitOrderParams({\n\t\tmarketIndex,\n\t\tmarketType: MarketType.PERP,\n\t\tdirection,\n\t\tbaseAssetAmount,\n\t\treduceOnly,\n\t\tpostOnly,\n\t\tprice: orderConfig.limitPrice,\n\t\tuserOrderId,\n\t\t...limitAuctionParams,\n\t});\n\n\tconst oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;\n\tconst totalQuoteAmount = baseAssetAmount\n\t\t.mul(oraclePrice)\n\t\t.div(PRICE_PRECISION);\n\n\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\tmarketIndex,\n\t\tdriftClient,\n\t\tuser,\n\t\ttotalQuoteAmount,\n\t\tdirection\n\t);\n\n\treturn {\n\t\t...limitAuctionOrderParams,\n\t\tbitFlags,\n\t};\n};\n\n/**\n * Creates a transaction instruction to open multiple non-market orders.\n */\nexport const createMultipleOpenPerpNonMarketOrderIx = async (params: {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\torderParamsConfigs: NonMarketOrderParamsConfig[];\n\tenterHighLeverageMode?: boolean;\n}): Promise<TransactionInstruction> => {\n\tconst { driftClient, orderParamsConfigs } = params;\n\n\tconst orderParams = orderParamsConfigs.map(buildNonMarketOrderParams);\n\n\tif (params.enterHighLeverageMode && orderParams.length > 0) {\n\t\torderParams[0].bitFlags = OrderParamsBitFlag.UpdateHighLeverageMode;\n\t}\n\n\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(orderParams);\n\treturn placeOrderIx;\n};\n\n/**\n * Creates a transaction instruction to open a non-market order.\n * Allows for bracket orders to be opened in the same transaction.\n *\n * If `limitAuction` is enabled, a placeAndTake order is created to simulate a market auction order,\n * with the end price being the limit price.\n */\nexport const createOpenPerpNonMarketOrderIxs = async (\n\tparams: OpenPerpNonMarketOrderBaseParams\n): Promise<TransactionInstruction[]> => {\n\tconst {\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\tdirection,\n\t\treduceOnly = false,\n\t\tpostOnly = PostOnlyParams.NONE,\n\t\torderConfig,\n\t\tuserOrderId = 0,\n\t} = params;\n\t// Support both new (amount + assetType) and legacy (baseAssetAmount) approaches\n\tconst finalBaseAssetAmount = resolveBaseAssetAmount({\n\t\tamount: 'amount' in params ? params.amount : undefined,\n\t\tassetType: 'assetType' in params ? params.assetType : undefined,\n\t\tbaseAssetAmount:\n\t\t\t'baseAssetAmount' in params ? params.baseAssetAmount : undefined,\n\t\tlimitPrice:\n\t\t\t'limitPrice' in params.orderConfig\n\t\t\t\t? params.orderConfig.limitPrice\n\t\t\t\t: undefined,\n\t});\n\n\tif (!finalBaseAssetAmount || finalBaseAssetAmount.isZero()) {\n\t\tthrow new Error('Final base asset amount must be greater than zero');\n\t}\n\n\tconst allOrders: OptionalOrderParams[] = [];\n\tconst allIxs: TransactionInstruction[] = [];\n\n\t// handle limit auction\n\tif (orderConfig.orderType === 'limit' && orderConfig.limitAuction?.enable) {\n\t\tconst limitAuctionOrderParams = await getLimitAuctionOrderParams({\n\t\t\t...params,\n\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\torderConfig: orderConfig as LimitOrderParamsOrderConfig & {\n\t\t\t\tlimitAuction: LimitAuctionConfig;\n\t\t\t},\n\t\t});\n\n\t\tlet createdPlaceAndTakeIx = false;\n\n\t\t// if it is a limit auction order, we create a placeAndTake order to simulate a market order.\n\t\t// this is useful when a limit order is crossing, and we want to achieve the best fill price through a placeAndTake.\n\t\t// falls back to limit order with auction params if the placeAndTake order creation fails\n\t\tif (\n\t\t\tlimitAuctionOrderParams.auctionDuration &&\n\t\t\tlimitAuctionOrderParams.auctionDuration > 0 &&\n\t\t\torderConfig.limitAuction?.usePlaceAndTake?.enable\n\t\t) {\n\t\t\ttry {\n\t\t\t\tconst placeAndTakeIx = await createPlaceAndTakePerpMarketOrderIx({\n\t\t\t\t\tassetType: 'base',\n\t\t\t\t\tamount: finalBaseAssetAmount,\n\t\t\t\t\tdirection,\n\t\t\t\t\tdlobServerHttpUrl: orderConfig.limitAuction.dlobServerHttpUrl,\n\t\t\t\t\tmarketIndex,\n\t\t\t\t\tdriftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tuserOrderId,\n\t\t\t\t\toptionalAuctionParamsInputs:\n\t\t\t\t\t\torderConfig.limitAuction.optionalLimitAuctionParams,\n\t\t\t\t\tauctionDurationPercentage:\n\t\t\t\t\t\torderConfig.limitAuction.usePlaceAndTake.auctionDurationPercentage,\n\t\t\t\t\treferrerInfo: orderConfig.limitAuction.usePlaceAndTake.referrerInfo,\n\t\t\t\t});\n\t\t\t\tallIxs.push(placeAndTakeIx);\n\t\t\t\tcreatedPlaceAndTakeIx = true;\n\t\t\t} catch (e) {\n\t\t\t\tconsole.error(\n\t\t\t\t\t'Failed to create placeAndTake order for limit auction order',\n\t\t\t\t\te\n\t\t\t\t);\n\t\t\t\tcreatedPlaceAndTakeIx = false;\n\t\t\t}\n\t\t}\n\n\t\t// fallback to normal limit order with auction params\n\t\tif (!createdPlaceAndTakeIx) {\n\t\t\tallOrders.push(limitAuctionOrderParams);\n\t\t}\n\t} else {\n\t\tconst orderParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\torderConfig,\n\t\t\treduceOnly,\n\t\t\tpostOnly,\n\t\t\tuserOrderId,\n\t\t});\n\n\t\tconst oraclePrice =\n\t\t\tdriftClient.getOracleDataForPerpMarket(marketIndex).price;\n\t\tconst totalQuoteAmount = finalBaseAssetAmount\n\t\t\t.mul(oraclePrice)\n\t\t\t.div(PRICE_PRECISION);\n\n\t\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\t\tmarketIndex,\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\ttotalQuoteAmount,\n\t\t\tdirection\n\t\t);\n\t\torderParams.bitFlags = bitFlags;\n\n\t\tallOrders.push(orderParams);\n\t}\n\n\tconst bracketOrdersDirection = ENUM_UTILS.match(\n\t\tdirection,\n\t\tPositionDirection.LONG\n\t)\n\t\t? PositionDirection.SHORT\n\t\t: PositionDirection.LONG;\n\n\tif ('bracketOrders' in orderConfig && orderConfig.bracketOrders?.takeProfit) {\n\t\tconst takeProfitParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount:\n\t\t\t\torderConfig.bracketOrders.takeProfit.baseAssetAmount ??\n\t\t\t\tfinalBaseAssetAmount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'takeProfit',\n\t\t\t\ttriggerPrice: orderConfig.bracketOrders.takeProfit.triggerPrice,\n\t\t\t\tlimitPrice: orderConfig.bracketOrders.takeProfit.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: orderConfig.bracketOrders.takeProfit.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(takeProfitParams);\n\t}\n\n\tif ('bracketOrders' in orderConfig && orderConfig.bracketOrders?.stopLoss) {\n\t\tconst stopLossParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount:\n\t\t\t\torderConfig.bracketOrders.stopLoss.baseAssetAmount ??\n\t\t\t\tfinalBaseAssetAmount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'stopLoss',\n\t\t\t\ttriggerPrice: orderConfig.bracketOrders.stopLoss.triggerPrice,\n\t\t\t\tlimitPrice: orderConfig.bracketOrders.stopLoss.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: orderConfig.bracketOrders.stopLoss.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(stopLossParams);\n\t}\n\n\tif (allOrders.length > 0) {\n\t\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(allOrders);\n\t\tallIxs.push(placeOrderIx);\n\t}\n\n\treturn allIxs;\n};\n\nexport const MINIMUM_SWIFT_LIMIT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 35;\n\nexport const createSwiftLimitOrder = async (\n\tparams: OpenPerpNonMarketOrderParamsWithSwift & {\n\t\torderConfig: LimitOrderParamsOrderConfig;\n\t}\n): Promise<void> => {\n\tconst { driftClient, user, marketIndex, swiftOptions, orderConfig } = params;\n\n\tconst limitPrice = orderConfig.limitPrice;\n\n\tif (limitPrice.isZero()) {\n\t\tthrow new Error('LIMIT orders require limitPrice');\n\t}\n\n\t// Support both new (amount + assetType) and legacy (baseAssetAmount) approaches\n\tconst finalBaseAssetAmount = resolveBaseAssetAmount({\n\t\tamount: 'amount' in params ? params.amount : undefined,\n\t\tassetType: 'assetType' in params ? params.assetType : undefined,\n\t\tbaseAssetAmount:\n\t\t\t'baseAssetAmount' in params ? params.baseAssetAmount : undefined,\n\t\tlimitPrice,\n\t});\n\n\tconst orderParams = orderConfig.limitAuction?.enable\n\t\t? await getLimitAuctionOrderParams({\n\t\t\t\t...params,\n\t\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\t\torderConfig: orderConfig as LimitOrderParamsOrderConfig & {\n\t\t\t\t\tlimitAuction: LimitAuctionConfig;\n\t\t\t\t},\n\t\t })\n\t\t: buildNonMarketOrderParams({\n\t\t\t\tmarketIndex,\n\t\t\t\tmarketType: MarketType.PERP,\n\t\t\t\tdirection: params.direction,\n\t\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\t\torderConfig,\n\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\tpostOnly: params.postOnly,\n\t\t\t\tuserOrderId: params.userOrderId,\n\t\t });\n\n\tconst userAccount = user.getUserAccount();\n\tconst slotBuffer = Math.max(\n\t\t(swiftOptions.signedMessageOrderSlotBuffer || 0) +\n\t\t\t(orderParams.auctionDuration || 0),\n\t\tMINIMUM_SWIFT_LIMIT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS\n\t); // limit orders require a much larger buffer, to replace the auction duration usually found in market orders\n\n\tawait prepSignAndSendSwiftOrder({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tuserAccountPubKey: user.userAccountPublicKey,\n\t\tmarketIndex,\n\t\tslotBuffer,\n\t\tswiftOptions,\n\t\torderParams: {\n\t\t\tmain: orderParams,\n\t\t\ttakeProfit: orderConfig.bracketOrders?.takeProfit,\n\t\t\tstopLoss: orderConfig.bracketOrders?.stopLoss,\n\t\t},\n\t});\n};\n\nexport const createOpenPerpNonMarketOrderTxn = async (\n\tparams: WithTxnParams<OpenPerpNonMarketOrderBaseParams>\n): Promise<Transaction | VersionedTransaction> => {\n\tconst { driftClient } = params;\n\n\tconst instructions = await createOpenPerpNonMarketOrderIxs(params);\n\n\tconst openPerpNonMarketOrderTxn = await driftClient.buildTransaction(\n\t\tinstructions,\n\t\tparams.txParams\n\t);\n\n\treturn openPerpNonMarketOrderTxn;\n};\n\nexport const createOpenPerpNonMarketOrder = async <T extends boolean>(\n\tparams: WithTxnParams<OpenPerpNonMarketOrderParams<T, SwiftOrderOptions>>\n): Promise<TxnOrSwiftResult<T>> => {\n\tconst { swiftOptions, useSwift, orderConfig } = params;\n\n\t// If useSwift is true, return the Swift result directly\n\tif (useSwift) {\n\t\tif (orderConfig.orderType !== 'limit') {\n\t\t\tthrow new Error('Only limit orders are supported with Swift');\n\t\t}\n\n\t\tif (!swiftOptions) {\n\t\t\tthrow new Error('swiftOptions is required when useSwift is true');\n\t\t}\n\n\t\tif (\n\t\t\tparams.postOnly &&\n\t\t\t!ENUM_UTILS.match(params.postOnly, PostOnlyParams.NONE)\n\t\t) {\n\t\t\tthrow new Error('Post only orders are not supported with Swift');\n\t\t}\n\n\t\tconst swiftOrderResult = await createSwiftLimitOrder({\n\t\t\t...params,\n\t\t\tswiftOptions,\n\t\t\torderConfig,\n\t\t});\n\n\t\treturn swiftOrderResult as TxnOrSwiftResult<T>;\n\t}\n\n\tconst marketOrderTxn = await createOpenPerpNonMarketOrderTxn(params);\n\n\treturn marketOrderTxn as TxnOrSwiftResult<T>;\n};\n"]}
|
|
@@ -9,7 +9,8 @@ export declare const MINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 5;
|
|
|
9
9
|
export interface SwiftOrderOptions {
|
|
10
10
|
wallet: {
|
|
11
11
|
signMessage: (message: Uint8Array) => Promise<Uint8Array>;
|
|
12
|
-
|
|
12
|
+
takerAuthority: PublicKey;
|
|
13
|
+
signingAuthority?: PublicKey;
|
|
13
14
|
};
|
|
14
15
|
swiftServerUrl: string;
|
|
15
16
|
signedMessageOrderSlotBuffer?: number;
|
|
@@ -161,6 +162,7 @@ export declare const sendSwiftOrder: ({ driftClient, marketId, hexEncodedSwiftOr
|
|
|
161
162
|
type PrepSignAndSendSwiftOrderParams = {
|
|
162
163
|
driftClient: DriftClient;
|
|
163
164
|
subAccountId: number;
|
|
165
|
+
userAccountPubKey: PublicKey;
|
|
164
166
|
marketIndex: number;
|
|
165
167
|
slotBuffer: number;
|
|
166
168
|
swiftOptions: SwiftOrderOptions;
|
|
@@ -175,5 +177,5 @@ type PrepSignAndSendSwiftOrderParams = {
|
|
|
175
177
|
* Callbacks can be provided to handle the events of the Swift order.
|
|
176
178
|
* Returns a promise that resolves when the Swift order has reached a terminal state (i.e. confirmed, expired, or errored).
|
|
177
179
|
*/
|
|
178
|
-
export declare const prepSignAndSendSwiftOrder: ({ driftClient, subAccountId, marketIndex, slotBuffer, swiftOptions, orderParams, }: PrepSignAndSendSwiftOrderParams) => Promise<void>;
|
|
180
|
+
export declare const prepSignAndSendSwiftOrder: ({ driftClient, subAccountId, userAccountPubKey, marketIndex, slotBuffer, swiftOptions, orderParams, }: PrepSignAndSendSwiftOrderParams) => Promise<void>;
|
|
179
181
|
export {};
|
|
@@ -157,13 +157,13 @@ exports.sendSwiftOrder = sendSwiftOrder;
|
|
|
157
157
|
* Callbacks can be provided to handle the events of the Swift order.
|
|
158
158
|
* Returns a promise that resolves when the Swift order has reached a terminal state (i.e. confirmed, expired, or errored).
|
|
159
159
|
*/
|
|
160
|
-
const prepSignAndSendSwiftOrder = async ({ driftClient, subAccountId, marketIndex, slotBuffer, swiftOptions, orderParams, }) => {
|
|
161
|
-
var _a, _b, _c, _d;
|
|
160
|
+
const prepSignAndSendSwiftOrder = async ({ driftClient, subAccountId, userAccountPubKey, marketIndex, slotBuffer, swiftOptions, orderParams, }) => {
|
|
161
|
+
var _a, _b, _c, _d, _e;
|
|
162
162
|
const currentSlot = await driftClient.connection.getSlot('confirmed');
|
|
163
163
|
const { hexEncodedSwiftOrderMessage, signedMsgOrderUuid, signedMsgOrderParamsMessage, } = (0, exports.prepSwiftOrder)({
|
|
164
164
|
driftClient,
|
|
165
165
|
takerUserAccount: {
|
|
166
|
-
pubKey:
|
|
166
|
+
pubKey: userAccountPubKey,
|
|
167
167
|
subAccountId: subAccountId,
|
|
168
168
|
},
|
|
169
169
|
currentSlot,
|
|
@@ -192,8 +192,8 @@ const prepSignAndSendSwiftOrder = async ({ driftClient, subAccountId, marketInde
|
|
|
192
192
|
hexEncodedSwiftOrderMessageString: hexEncodedSwiftOrderMessage.string,
|
|
193
193
|
signedMessage,
|
|
194
194
|
signedMsgOrderUuid,
|
|
195
|
-
takerAuthority: swiftOptions.wallet.
|
|
196
|
-
signingAuthority: swiftOptions.wallet.
|
|
195
|
+
takerAuthority: swiftOptions.wallet.takerAuthority,
|
|
196
|
+
signingAuthority: (_e = swiftOptions.wallet.signingAuthority) !== null && _e !== void 0 ? _e : swiftOptions.wallet.takerAuthority,
|
|
197
197
|
auctionDuration: orderParams.main.auctionDuration || undefined,
|
|
198
198
|
});
|
|
199
199
|
const wrapSwiftOrderEvent = (swiftOrderEvent) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.ts"],"names":[],"mappings":";;;AAAA,yCAKyB;AACzB,yCAOyB;AACzB,uEAO+C;AAC/C,mDAAmD;AAItC,QAAA,2CAA2C,GAAG,CAAC,CAAC;AAChD,QAAA,mDAAmD,GAAG,CAAC,CAAC;AAyErE;;;;;;;;;;;;;;;;GAgBG;AACI,MAAM,cAAc,GAAG,CAAC,EAC9B,WAAW,EACX,gBAAgB,EAChB,WAAW,EACX,UAAU,EACV,WAAW,EACX,UAAU,GAAG,EAAE,GACO,EAUrB,EAAE;IACH,MAAM,eAAe,GAAG,IAAA,oBAAc,EAAC;QACtC,GAAG,WAAW,CAAC,IAAI;QACnB,eAAe,EAAE,WAAW,CAAC,IAAI,CAAC,eAAe,IAAI,IAAI,EAAE,6EAA6E;KACxI,CAAC,CAAC;IAEH,gFAAgF;IAChF,MAAM,gBAAgB,GAAG,IAAI,QAAE,CAAC,WAAW,GAAG,UAAU,CAAC,CAAC;IAE1D,MAAM,kBAAkB,GAAG,IAAA,2BAAqB,GAAE,CAAC;IAEnD,MAAM,+BAA+B,GAAG;QACvC,oBAAoB,EAAE,eAAe;QACrC,IAAI,EAAE,kBAAkB;QACxB,IAAI,EAAE,gBAAgB;QACtB,mBAAmB,EAAE,WAAW,CAAC,QAAQ;YACxC,CAAC,CAAC;gBACA,eAAe,EAAE,WAAW,CAAC,QAAQ,CAAC,eAAe;gBACrD,YAAY,EAAE,WAAW,CAAC,QAAQ,CAAC,YAAY;aAC9C;YACH,CAAC,CAAC,IAAI;QACP,qBAAqB,EAAE,WAAW,CAAC,UAAU;YAC5C,CAAC,CAAC;gBACA,eAAe,EAAE,WAAW,CAAC,UAAU,CAAC,eAAe;gBACvD,YAAY,EAAE,WAAW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AK,WAAW,EAAE,CAAC;YAC1C,MAAA,MAAA,YAAY,CAAC,SAAS,0CAAE,WAAW,mDAClC,mBAAmB,CAAC,eAAe,CAAC,CACpC,CAAC;YACF,mBAAmB,CAAC,YAAY,CAAC,CAAC;QACnC,CAAC;QACD,IAAI,eAAe,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YACxC,MAAA,MAAA,YAAY,CAAC,SAAS,0CAAE,SAAS,mDAAG,mBAAmB,CAAC,eAAe,CAAC,CAAC,CAAC;YAC1E,mBAAmB,CAAC,YAAY,CAAC,CAAC;QACnC,CAAC;QACD,IAAI,eAAe,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YACxC,MAAA,MAAA,YAAY,CAAC,SAAS,0CAAE,SAAS,mDAAG,mBAAmB,CAAC,eAAe,CAAC,CAAC,CAAC;YAC1E,mBAAmB,CAAC,YAAY,CAAC,CAAC;QACnC,CAAC;IACF,CAAC,CAAC,CAAC;IAEH,OAAO,OAAO,CAAC;AAChB,CAAC,CAAC;AA7GW,QAAA,yBAAyB,6BA6GpC","sourcesContent":["import {\n\tgetSignedMsgUserAccountPublicKey,\n\tSignedMsgOrderParamsDelegateMessage,\n\tSignedMsgOrderParamsMessage,\n\tSLOT_TIME_ESTIMATE_MS,\n} from '@drift-labs/sdk';\nimport {\n\tBN,\n\tDriftClient,\n\tgenerateSignedMsgUuid,\n\tgetOrderParams,\n\tOptionalOrderParams,\n\tPublicKey,\n} from '@drift-labs/sdk';\nimport {\n\tSwiftClient,\n\tSwiftOrderConfirmedEvent,\n\tSwiftOrderErroredEvent,\n\tSwiftOrderEvent,\n\tSwiftOrderEventWithParams,\n\tSwiftOrderSentEvent,\n} from '../../../../../../clients/swiftClient';\nimport { MarketId } from '../../../../../../types';\nimport { Observable, Subscription } from 'rxjs';\nimport { OptionalTriggerOrderParams } from '../types';\n\nexport const SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 5;\nexport const MINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 5;\n\nexport interface SwiftOrderOptions {\n\twallet: {\n\t\tsignMessage: (message: Uint8Array) => Promise<Uint8Array>;\n\t\tpublicKey: PublicKey;\n\t};\n\tswiftServerUrl: string;\n\tsignedMessageOrderSlotBuffer?: number;\n\tisDelegate?: boolean;\n\tcallbacks?: {\n\t\tonOrderParamsMessagePrepped?: (\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSigningExpiry?: (\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSigningSuccess?: (\n\t\t\tsignedMessage: Uint8Array,\n\t\t\t// we add the following here, because the onSigningSuccess callback is called before the order is sent to the swift server\n\t\t\torderUuid: Uint8Array,\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSent?: (\n\t\t\tswiftSentEvent: SwiftOrderEventWithParams<SwiftOrderSentEvent>\n\t\t) => void;\n\t\tonConfirmed?: (\n\t\t\tswiftConfirmedEvent: SwiftOrderEventWithParams<SwiftOrderConfirmedEvent>\n\t\t) => void;\n\t\tonExpired?: (\n\t\t\tswiftExpiredEvent: SwiftOrderEventWithParams<SwiftOrderErroredEvent>\n\t\t) => void;\n\t\tonErrored?: (\n\t\t\tswiftErroredEvent: SwiftOrderEventWithParams<SwiftOrderErroredEvent>\n\t\t) => void;\n\t};\n}\n\nexport type SwiftOrderObservable = Observable<SwiftOrderEvent>;\n\ninterface PrepSwiftOrderParams {\n\t/** The Drift client instance */\n\tdriftClient: DriftClient;\n\t/** The taker user account information */\n\ttakerUserAccount: {\n\t\t/** Public key of the user account */\n\t\tpubKey: PublicKey;\n\t\t/** User account ID */\n\t\tsubAccountId: number;\n\t};\n\t/** Current blockchain slot number */\n\tcurrentSlot: number;\n\t/** Whether this is a delegate order */\n\tisDelegate: boolean;\n\t/** Order parameters including main order and optional stop loss/take profit */\n\torderParams: {\n\t\t/** Main order parameters */\n\t\tmain: OptionalOrderParams;\n\t\t/** Optional stop loss order parameters */\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t\t/** Optional take profit order parameters */\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t};\n\t/** Buffer slots to account for signing time (default: 2 slots ~1 second). If a user is required to manually sign the message, this should be a higher number. */\n\tslotBuffer?: number;\n}\n\n/**\n * Prepares a swift order by encoding the order parameters into a message format\n * suitable for signing and sending to the Swift server.\n *\n * @param driftClient - The Drift client instance\n * @param takerUserAccount - The taker user account information\n * @param currentSlot - Current blockchain slot number\n * @param isDelegate - Whether this is a delegate order\n * @param orderParams - Order parameters including main order and optional stop loss/take profit\n * @param slotBuffer - Buffer slots to account for signing time (default: 35 slots ~14 seconds). Use this default value if it is not an auction order, else used an estimate number of slots to sign the message.\n *\n * @returns An object containing:\n * - `hexEncodedSwiftOrderMessage`: The encoded order message in both Uint8Array and string formats. The Uint8Array format is for a wallet to sign, while the string format is used to send to the SWIFT server.\n * - `signedMsgOrderParamsMessage`: The signed message order parameters\n * - `slotForSignedMsg`: The slot number for the signed message\n * - `signedMsgOrderUuid`: Unique identifier for the signed message order\n */\nexport const prepSwiftOrder = ({\n\tdriftClient,\n\ttakerUserAccount,\n\tcurrentSlot,\n\tisDelegate,\n\torderParams,\n\tslotBuffer = 35,\n}: PrepSwiftOrderParams): {\n\thexEncodedSwiftOrderMessage: {\n\t\tuInt8Array: Uint8Array;\n\t\tstring: string;\n\t};\n\tsignedMsgOrderParamsMessage:\n\t\t| SignedMsgOrderParamsMessage\n\t\t| SignedMsgOrderParamsDelegateMessage;\n\tslotForSignedMsg: BN;\n\tsignedMsgOrderUuid: Uint8Array;\n} => {\n\tconst mainOrderParams = getOrderParams({\n\t\t...orderParams.main,\n\t\tauctionDuration: orderParams.main.auctionDuration || null, // swift server expects auctionDuration to be null if not set, won't handle 0\n\t});\n\n\t// buffer for time the user takes to sign a message and send to the swift server\n\tconst slotForSignedMsg = new BN(currentSlot + slotBuffer);\n\n\tconst signedMsgOrderUuid = generateSignedMsgUuid();\n\n\tconst baseSignedMsgOrderParamsMessage = {\n\t\tsignedMsgOrderParams: mainOrderParams,\n\t\tuuid: signedMsgOrderUuid,\n\t\tslot: slotForSignedMsg,\n\t\tstopLossOrderParams: orderParams.stopLoss\n\t\t\t? {\n\t\t\t\t\tbaseAssetAmount: orderParams.stopLoss.baseAssetAmount,\n\t\t\t\t\ttriggerPrice: orderParams.stopLoss.triggerPrice,\n\t\t\t }\n\t\t\t: null,\n\t\ttakeProfitOrderParams: orderParams.takeProfit\n\t\t\t? {\n\t\t\t\t\tbaseAssetAmount: orderParams.takeProfit.baseAssetAmount,\n\t\t\t\t\ttriggerPrice: orderParams.takeProfit.triggerPrice,\n\t\t\t }\n\t\t\t: null,\n\t};\n\n\tconst signedMsgOrderParamsMessage:\n\t\t| SignedMsgOrderParamsMessage\n\t\t| SignedMsgOrderParamsDelegateMessage = isDelegate\n\t\t? {\n\t\t\t\t...baseSignedMsgOrderParamsMessage,\n\t\t\t\ttakerPubkey: takerUserAccount.pubKey,\n\t\t }\n\t\t: {\n\t\t\t\t...baseSignedMsgOrderParamsMessage,\n\t\t\t\tsubAccountId: takerUserAccount.subAccountId,\n\t\t };\n\n\tconst encodedOrderMessage = driftClient.encodeSignedMsgOrderParamsMessage(\n\t\tsignedMsgOrderParamsMessage,\n\t\tisDelegate\n\t);\n\tconst hexEncodedSwiftOrderMessage = Buffer.from(\n\t\tencodedOrderMessage.toString('hex')\n\t);\n\n\treturn {\n\t\thexEncodedSwiftOrderMessage: {\n\t\t\tuInt8Array: new Uint8Array(hexEncodedSwiftOrderMessage),\n\t\t\tstring: hexEncodedSwiftOrderMessage.toString(),\n\t\t},\n\t\tsignedMsgOrderParamsMessage,\n\t\tslotForSignedMsg,\n\t\tsignedMsgOrderUuid,\n\t};\n};\n\n/**\n * Error thrown when an auction slot has expired\n */\nexport class AuctionSlotExpiredError extends Error {\n\tname = 'AuctionSlotExpiredError';\n\n\t/**\n\t * Creates an instance of AuctionSlotExpiredError\n\t * @param message - Error message (default: 'Auction slot expired')\n\t */\n\tconstructor(message: string = 'Auction slot expired') {\n\t\tsuper(message);\n\t\tif (Error.captureStackTrace) {\n\t\t\tError.captureStackTrace(this, AuctionSlotExpiredError);\n\t\t}\n\t}\n}\n\ninterface SignOrderMsgParams {\n\t/** Wallet instance with message signing capability */\n\twallet: {\n\t\t/** Function to sign a message */\n\t\tsignMessage: (message: Uint8Array) => Promise<Uint8Array>;\n\t};\n\t/** Hex-encoded swift order message to sign */\n\thexEncodedSwiftOrderMessage: Uint8Array;\n\t/** Time in milliseconds till the auction expires */\n\texpirationTimeMs: number;\n\t/** Callback function called when the auction expires */\n\tonExpired?: () => void;\n}\n\n/**\n * Signs a swift order message with slot expiration monitoring.\n * Continuously monitors the current slot and rejects with AuctionSlotExpiredError\n * if the auction slot expires before signing is complete.\n *\n * @param wallet - Wallet instance with message signing capability\n * @param hexEncodedSwiftOrderMessage - Hex-encoded swift order message to sign\n * @param expirationTimeMs - Time in milliseconds till the auction expires\n * @param onExpired - Callback function called when the auction expires\n *\n * @returns Promise resolving to the signed message as Uint8Array\n * @throws {AuctionSlotExpiredError} When the auction slot expires before signing completes\n */\nexport const signSwiftOrderMsg = async ({\n\twallet,\n\thexEncodedSwiftOrderMessage,\n\texpirationTimeMs,\n\tonExpired,\n}: SignOrderMsgParams): Promise<Uint8Array> => {\n\tlet timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n\ttry {\n\t\t// Sign the message\n\t\tconst signedMessagePromise = wallet.signMessage(\n\t\t\thexEncodedSwiftOrderMessage\n\t\t);\n\n\t\tconst signingExpiredPromise = new Promise<never>((_resolve, reject) => {\n\t\t\ttimeoutId = setTimeout(() => {\n\t\t\t\tonExpired?.();\n\t\t\t\treject(new AuctionSlotExpiredError());\n\t\t\t}, expirationTimeMs);\n\t\t});\n\n\t\t// Ensure that the user signs the message before the expiration time\n\t\tconst signedMessage = await Promise.race([\n\t\t\tsignedMessagePromise,\n\t\t\tsigningExpiredPromise,\n\t\t]);\n\n\t\treturn signedMessage;\n\t} finally {\n\t\tif (timeoutId) {\n\t\t\tclearTimeout(timeoutId);\n\t\t}\n\t}\n};\n\n/**\n * Parameters for sending a swift order to the Swift server\n * @interface SendSwiftOrderParams\n */\ninterface SendSwiftOrderParams {\n\t/** The Drift client instance */\n\tdriftClient: DriftClient;\n\t/** Market identifier for the order */\n\tmarketId: MarketId;\n\t/** Hex-encoded swift order message as string */\n\thexEncodedSwiftOrderMessageString: string;\n\t/** The signed message from the wallet */\n\tsignedMessage: Uint8Array;\n\t/** Unique identifier for the signed message order */\n\tsignedMsgOrderUuid: Uint8Array;\n\t/** Public key of the taker authority */\n\ttakerAuthority: PublicKey;\n\t/** Public key of the signing authority */\n\tsigningAuthority: PublicKey;\n\t/** Duration of the auction in slots (optional) */\n\tauctionDuration?: number;\n}\n\n/**\n * Sends a swift order to the Swift server and handles the response.\n * Monitors the order status and calls appropriate callback functions based on the response type.\n *\n * @param driftClient - The Drift client instance\n * @param marketId - Market identifier for the order\n * @param hexEncodedSwiftOrderMessageString - Hex-encoded swift order message as string\n * @param signedMessage - The signed message from the wallet\n * @param signedMsgOrderUuid - Unique identifier for the signed message order\n * @param takerAuthority - Public key of the taker authority\n * @param signingAuthority - Public key of the signing authority\n * @param auctionDurationSlot - Duration of the auction in slots (optional)\n * @param swiftConfirmationSlotBuffer - Slot buffer for swift server confirmation time (default: 15)\n * @param onExpired - Callback function called when the order expires\n * @param onErrored - Callback function called when the order encounters an error\n * @param onConfirmed - Callback function called when the order is confirmed\n *\n * @returns Promise that resolves when the order processing is complete\n *\n */\nexport const sendSwiftOrder = ({\n\tdriftClient,\n\tmarketId,\n\thexEncodedSwiftOrderMessageString,\n\tsignedMessage,\n\tsignedMsgOrderUuid,\n\ttakerAuthority,\n\tsigningAuthority,\n\tauctionDuration,\n}: SendSwiftOrderParams): SwiftOrderObservable => {\n\tconst signedMsgUserOrdersAccountPubkey = getSignedMsgUserAccountPublicKey(\n\t\tdriftClient.program.programId,\n\t\ttakerAuthority\n\t);\n\n\tconst swiftOrderObservable = SwiftClient.sendAndConfirmSwiftOrderWS(\n\t\tdriftClient.connection,\n\t\tdriftClient,\n\t\tmarketId.marketIndex,\n\t\tmarketId.marketType,\n\t\thexEncodedSwiftOrderMessageString,\n\t\tBuffer.from(signedMessage),\n\t\ttakerAuthority,\n\t\tsignedMsgUserOrdersAccountPubkey,\n\t\tsignedMsgOrderUuid,\n\t\t((auctionDuration ?? 0) + 15) * SLOT_TIME_ESTIMATE_MS,\n\t\tsigningAuthority\n\t);\n\n\treturn swiftOrderObservable;\n};\n\ntype PrepSignAndSendSwiftOrderParams = {\n\tdriftClient: DriftClient;\n\tsubAccountId: number;\n\tmarketIndex: number;\n\tslotBuffer: number;\n\tswiftOptions: SwiftOrderOptions;\n\torderParams: {\n\t\tmain: OptionalOrderParams;\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t};\n};\n\n/**\n * Handles the full flow of the swift order, from preparing to signing and sending to the Swift server.\n * Callbacks can be provided to handle the events of the Swift order.\n * Returns a promise that resolves when the Swift order has reached a terminal state (i.e. confirmed, expired, or errored).\n */\nexport const prepSignAndSendSwiftOrder = async ({\n\tdriftClient,\n\tsubAccountId,\n\tmarketIndex,\n\tslotBuffer,\n\tswiftOptions,\n\torderParams,\n}: PrepSignAndSendSwiftOrderParams): Promise<void> => {\n\tconst currentSlot = await driftClient.connection.getSlot('confirmed');\n\n\tconst {\n\t\thexEncodedSwiftOrderMessage,\n\t\tsignedMsgOrderUuid,\n\t\tsignedMsgOrderParamsMessage,\n\t} = prepSwiftOrder({\n\t\tdriftClient,\n\t\ttakerUserAccount: {\n\t\t\tpubKey: swiftOptions.wallet.publicKey,\n\t\t\tsubAccountId: subAccountId,\n\t\t},\n\t\tcurrentSlot,\n\t\tisDelegate: swiftOptions.isDelegate || false,\n\t\torderParams,\n\t\tslotBuffer,\n\t});\n\n\tswiftOptions.callbacks?.onOrderParamsMessagePrepped?.(\n\t\tsignedMsgOrderParamsMessage\n\t);\n\n\tconst expirationTimeMs =\n\t\tMath.max(\n\t\t\tslotBuffer +\n\t\t\t\t(orderParams.main.auctionDuration || 0) -\n\t\t\t\tSWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS,\n\t\t\tMINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS\n\t\t) * SLOT_TIME_ESTIMATE_MS;\n\n\t// Ensure that the user signs the message before the expiration time\n\tconst signedMessage = await signSwiftOrderMsg({\n\t\twallet: swiftOptions.wallet,\n\t\thexEncodedSwiftOrderMessage: hexEncodedSwiftOrderMessage.uInt8Array,\n\t\texpirationTimeMs,\n\t\tonExpired: () =>\n\t\t\tswiftOptions.callbacks?.onSigningExpiry?.(signedMsgOrderParamsMessage),\n\t});\n\n\tswiftOptions.callbacks?.onSigningSuccess?.(\n\t\tsignedMessage,\n\t\tsignedMsgOrderUuid,\n\t\tsignedMsgOrderParamsMessage\n\t);\n\n\t// Initialize SwiftClient (required before using sendSwiftOrder)\n\tSwiftClient.init(swiftOptions.swiftServerUrl);\n\n\t// Create a promise-based wrapper for the sendSwiftOrder callback-based API\n\tconst swiftOrderObservable = sendSwiftOrder({\n\t\tdriftClient,\n\t\tmarketId: MarketId.createPerpMarket(marketIndex),\n\t\thexEncodedSwiftOrderMessageString: hexEncodedSwiftOrderMessage.string,\n\t\tsignedMessage,\n\t\tsignedMsgOrderUuid,\n\t\ttakerAuthority: swiftOptions.wallet.publicKey,\n\t\tsigningAuthority: swiftOptions.wallet.publicKey,\n\t\tauctionDuration: orderParams.main.auctionDuration || undefined,\n\t});\n\n\tconst wrapSwiftOrderEvent = <T extends SwiftOrderEvent>(\n\t\tswiftOrderEvent: T\n\t) => {\n\t\treturn {\n\t\t\t...swiftOrderEvent,\n\t\t\tswiftOrderUuid: signedMsgOrderUuid,\n\t\t\torderParamsMessage: signedMsgOrderParamsMessage,\n\t\t};\n\t};\n\n\tlet promiseResolver: (value: void | PromiseLike<void>) => void;\n\tconst promise = new Promise<void>((resolve) => {\n\t\tpromiseResolver = resolve;\n\t});\n\n\tconst handleTerminalEvent = (subscription: Subscription) => {\n\t\tsubscription.unsubscribe();\n\t\tpromiseResolver();\n\t};\n\n\tconst subscription = swiftOrderObservable.subscribe((swiftOrderEvent) => {\n\t\tif (swiftOrderEvent.type === 'sent') {\n\t\t\tswiftOptions.callbacks?.onSent?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t}\n\t\tif (swiftOrderEvent.type === 'confirmed') {\n\t\t\tswiftOptions.callbacks?.onConfirmed?.(\n\t\t\t\twrapSwiftOrderEvent(swiftOrderEvent)\n\t\t\t);\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t\tif (swiftOrderEvent.type === 'expired') {\n\t\t\tswiftOptions.callbacks?.onExpired?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t\tif (swiftOrderEvent.type === 'errored') {\n\t\t\tswiftOptions.callbacks?.onErrored?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t});\n\n\treturn promise;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.ts"],"names":[],"mappings":";;;AAAA,yCAKyB;AACzB,yCAOyB;AACzB,uEAO+C;AAC/C,mDAAmD;AAItC,QAAA,2CAA2C,GAAG,CAAC,CAAC;AAChD,QAAA,mDAAmD,GAAG,CAAC,CAAC;AA0ErE;;;;;;;;;;;;;;;;GAgBG;AACI,MAAM,cAAc,GAAG,CAAC,EA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;QACD,IAAI,eAAe,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YACxC,MAAA,MAAA,YAAY,CAAC,SAAS,0CAAE,SAAS,mDAAG,mBAAmB,CAAC,eAAe,CAAC,CAAC,CAAC;YAC1E,mBAAmB,CAAC,YAAY,CAAC,CAAC;QACnC,CAAC;IACF,CAAC,CAAC,CAAC;IAEH,OAAO,OAAO,CAAC;AAChB,CAAC,CAAC;AAhHW,QAAA,yBAAyB,6BAgHpC","sourcesContent":["import {\n\tgetSignedMsgUserAccountPublicKey,\n\tSignedMsgOrderParamsDelegateMessage,\n\tSignedMsgOrderParamsMessage,\n\tSLOT_TIME_ESTIMATE_MS,\n} from '@drift-labs/sdk';\nimport {\n\tBN,\n\tDriftClient,\n\tgenerateSignedMsgUuid,\n\tgetOrderParams,\n\tOptionalOrderParams,\n\tPublicKey,\n} from '@drift-labs/sdk';\nimport {\n\tSwiftClient,\n\tSwiftOrderConfirmedEvent,\n\tSwiftOrderErroredEvent,\n\tSwiftOrderEvent,\n\tSwiftOrderEventWithParams,\n\tSwiftOrderSentEvent,\n} from '../../../../../../clients/swiftClient';\nimport { MarketId } from '../../../../../../types';\nimport { Observable, Subscription } from 'rxjs';\nimport { OptionalTriggerOrderParams } from '../types';\n\nexport const SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 5;\nexport const MINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 5;\n\nexport interface SwiftOrderOptions {\n\twallet: {\n\t\tsignMessage: (message: Uint8Array) => Promise<Uint8Array>;\n\t\ttakerAuthority: PublicKey;\n\t\tsigningAuthority?: PublicKey;\n\t};\n\tswiftServerUrl: string;\n\tsignedMessageOrderSlotBuffer?: number;\n\tisDelegate?: boolean;\n\tcallbacks?: {\n\t\tonOrderParamsMessagePrepped?: (\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSigningExpiry?: (\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSigningSuccess?: (\n\t\t\tsignedMessage: Uint8Array,\n\t\t\t// we add the following here, because the onSigningSuccess callback is called before the order is sent to the swift server\n\t\t\torderUuid: Uint8Array,\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSent?: (\n\t\t\tswiftSentEvent: SwiftOrderEventWithParams<SwiftOrderSentEvent>\n\t\t) => void;\n\t\tonConfirmed?: (\n\t\t\tswiftConfirmedEvent: SwiftOrderEventWithParams<SwiftOrderConfirmedEvent>\n\t\t) => void;\n\t\tonExpired?: (\n\t\t\tswiftExpiredEvent: SwiftOrderEventWithParams<SwiftOrderErroredEvent>\n\t\t) => void;\n\t\tonErrored?: (\n\t\t\tswiftErroredEvent: SwiftOrderEventWithParams<SwiftOrderErroredEvent>\n\t\t) => void;\n\t};\n}\n\nexport type SwiftOrderObservable = Observable<SwiftOrderEvent>;\n\ninterface PrepSwiftOrderParams {\n\t/** The Drift client instance */\n\tdriftClient: DriftClient;\n\t/** The taker user account information */\n\ttakerUserAccount: {\n\t\t/** Public key of the user account */\n\t\tpubKey: PublicKey;\n\t\t/** User account ID */\n\t\tsubAccountId: number;\n\t};\n\t/** Current blockchain slot number */\n\tcurrentSlot: number;\n\t/** Whether this is a delegate order */\n\tisDelegate: boolean;\n\t/** Order parameters including main order and optional stop loss/take profit */\n\torderParams: {\n\t\t/** Main order parameters */\n\t\tmain: OptionalOrderParams;\n\t\t/** Optional stop loss order parameters */\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t\t/** Optional take profit order parameters */\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t};\n\t/** Buffer slots to account for signing time (default: 2 slots ~1 second). If a user is required to manually sign the message, this should be a higher number. */\n\tslotBuffer?: number;\n}\n\n/**\n * Prepares a swift order by encoding the order parameters into a message format\n * suitable for signing and sending to the Swift server.\n *\n * @param driftClient - The Drift client instance\n * @param takerUserAccount - The taker user account information\n * @param currentSlot - Current blockchain slot number\n * @param isDelegate - Whether this is a delegate order\n * @param orderParams - Order parameters including main order and optional stop loss/take profit\n * @param slotBuffer - Buffer slots to account for signing time (default: 35 slots ~14 seconds). Use this default value if it is not an auction order, else used an estimate number of slots to sign the message.\n *\n * @returns An object containing:\n * - `hexEncodedSwiftOrderMessage`: The encoded order message in both Uint8Array and string formats. The Uint8Array format is for a wallet to sign, while the string format is used to send to the SWIFT server.\n * - `signedMsgOrderParamsMessage`: The signed message order parameters\n * - `slotForSignedMsg`: The slot number for the signed message\n * - `signedMsgOrderUuid`: Unique identifier for the signed message order\n */\nexport const prepSwiftOrder = ({\n\tdriftClient,\n\ttakerUserAccount,\n\tcurrentSlot,\n\tisDelegate,\n\torderParams,\n\tslotBuffer = 35,\n}: PrepSwiftOrderParams): {\n\thexEncodedSwiftOrderMessage: {\n\t\tuInt8Array: Uint8Array;\n\t\tstring: string;\n\t};\n\tsignedMsgOrderParamsMessage:\n\t\t| SignedMsgOrderParamsMessage\n\t\t| SignedMsgOrderParamsDelegateMessage;\n\tslotForSignedMsg: BN;\n\tsignedMsgOrderUuid: Uint8Array;\n} => {\n\tconst mainOrderParams = getOrderParams({\n\t\t...orderParams.main,\n\t\tauctionDuration: orderParams.main.auctionDuration || null, // swift server expects auctionDuration to be null if not set, won't handle 0\n\t});\n\n\t// buffer for time the user takes to sign a message and send to the swift server\n\tconst slotForSignedMsg = new BN(currentSlot + slotBuffer);\n\n\tconst signedMsgOrderUuid = generateSignedMsgUuid();\n\n\tconst baseSignedMsgOrderParamsMessage = {\n\t\tsignedMsgOrderParams: mainOrderParams,\n\t\tuuid: signedMsgOrderUuid,\n\t\tslot: slotForSignedMsg,\n\t\tstopLossOrderParams: orderParams.stopLoss\n\t\t\t? {\n\t\t\t\t\tbaseAssetAmount: orderParams.stopLoss.baseAssetAmount,\n\t\t\t\t\ttriggerPrice: orderParams.stopLoss.triggerPrice,\n\t\t\t }\n\t\t\t: null,\n\t\ttakeProfitOrderParams: orderParams.takeProfit\n\t\t\t? {\n\t\t\t\t\tbaseAssetAmount: orderParams.takeProfit.baseAssetAmount,\n\t\t\t\t\ttriggerPrice: orderParams.takeProfit.triggerPrice,\n\t\t\t }\n\t\t\t: null,\n\t};\n\n\tconst signedMsgOrderParamsMessage:\n\t\t| SignedMsgOrderParamsMessage\n\t\t| SignedMsgOrderParamsDelegateMessage = isDelegate\n\t\t? {\n\t\t\t\t...baseSignedMsgOrderParamsMessage,\n\t\t\t\ttakerPubkey: takerUserAccount.pubKey,\n\t\t }\n\t\t: {\n\t\t\t\t...baseSignedMsgOrderParamsMessage,\n\t\t\t\tsubAccountId: takerUserAccount.subAccountId,\n\t\t };\n\n\tconst encodedOrderMessage = driftClient.encodeSignedMsgOrderParamsMessage(\n\t\tsignedMsgOrderParamsMessage,\n\t\tisDelegate\n\t);\n\tconst hexEncodedSwiftOrderMessage = Buffer.from(\n\t\tencodedOrderMessage.toString('hex')\n\t);\n\n\treturn {\n\t\thexEncodedSwiftOrderMessage: {\n\t\t\tuInt8Array: new Uint8Array(hexEncodedSwiftOrderMessage),\n\t\t\tstring: hexEncodedSwiftOrderMessage.toString(),\n\t\t},\n\t\tsignedMsgOrderParamsMessage,\n\t\tslotForSignedMsg,\n\t\tsignedMsgOrderUuid,\n\t};\n};\n\n/**\n * Error thrown when an auction slot has expired\n */\nexport class AuctionSlotExpiredError extends Error {\n\tname = 'AuctionSlotExpiredError';\n\n\t/**\n\t * Creates an instance of AuctionSlotExpiredError\n\t * @param message - Error message (default: 'Auction slot expired')\n\t */\n\tconstructor(message: string = 'Auction slot expired') {\n\t\tsuper(message);\n\t\tif (Error.captureStackTrace) {\n\t\t\tError.captureStackTrace(this, AuctionSlotExpiredError);\n\t\t}\n\t}\n}\n\ninterface SignOrderMsgParams {\n\t/** Wallet instance with message signing capability */\n\twallet: {\n\t\t/** Function to sign a message */\n\t\tsignMessage: (message: Uint8Array) => Promise<Uint8Array>;\n\t};\n\t/** Hex-encoded swift order message to sign */\n\thexEncodedSwiftOrderMessage: Uint8Array;\n\t/** Time in milliseconds till the auction expires */\n\texpirationTimeMs: number;\n\t/** Callback function called when the auction expires */\n\tonExpired?: () => void;\n}\n\n/**\n * Signs a swift order message with slot expiration monitoring.\n * Continuously monitors the current slot and rejects with AuctionSlotExpiredError\n * if the auction slot expires before signing is complete.\n *\n * @param wallet - Wallet instance with message signing capability\n * @param hexEncodedSwiftOrderMessage - Hex-encoded swift order message to sign\n * @param expirationTimeMs - Time in milliseconds till the auction expires\n * @param onExpired - Callback function called when the auction expires\n *\n * @returns Promise resolving to the signed message as Uint8Array\n * @throws {AuctionSlotExpiredError} When the auction slot expires before signing completes\n */\nexport const signSwiftOrderMsg = async ({\n\twallet,\n\thexEncodedSwiftOrderMessage,\n\texpirationTimeMs,\n\tonExpired,\n}: SignOrderMsgParams): Promise<Uint8Array> => {\n\tlet timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n\ttry {\n\t\t// Sign the message\n\t\tconst signedMessagePromise = wallet.signMessage(\n\t\t\thexEncodedSwiftOrderMessage\n\t\t);\n\n\t\tconst signingExpiredPromise = new Promise<never>((_resolve, reject) => {\n\t\t\ttimeoutId = setTimeout(() => {\n\t\t\t\tonExpired?.();\n\t\t\t\treject(new AuctionSlotExpiredError());\n\t\t\t}, expirationTimeMs);\n\t\t});\n\n\t\t// Ensure that the user signs the message before the expiration time\n\t\tconst signedMessage = await Promise.race([\n\t\t\tsignedMessagePromise,\n\t\t\tsigningExpiredPromise,\n\t\t]);\n\n\t\treturn signedMessage;\n\t} finally {\n\t\tif (timeoutId) {\n\t\t\tclearTimeout(timeoutId);\n\t\t}\n\t}\n};\n\n/**\n * Parameters for sending a swift order to the Swift server\n * @interface SendSwiftOrderParams\n */\ninterface SendSwiftOrderParams {\n\t/** The Drift client instance */\n\tdriftClient: DriftClient;\n\t/** Market identifier for the order */\n\tmarketId: MarketId;\n\t/** Hex-encoded swift order message as string */\n\thexEncodedSwiftOrderMessageString: string;\n\t/** The signed message from the wallet */\n\tsignedMessage: Uint8Array;\n\t/** Unique identifier for the signed message order */\n\tsignedMsgOrderUuid: Uint8Array;\n\t/** Public key of the taker authority */\n\ttakerAuthority: PublicKey;\n\t/** Public key of the signing authority */\n\tsigningAuthority: PublicKey;\n\t/** Duration of the auction in slots (optional) */\n\tauctionDuration?: number;\n}\n\n/**\n * Sends a swift order to the Swift server and handles the response.\n * Monitors the order status and calls appropriate callback functions based on the response type.\n *\n * @param driftClient - The Drift client instance\n * @param marketId - Market identifier for the order\n * @param hexEncodedSwiftOrderMessageString - Hex-encoded swift order message as string\n * @param signedMessage - The signed message from the wallet\n * @param signedMsgOrderUuid - Unique identifier for the signed message order\n * @param takerAuthority - Public key of the taker authority\n * @param signingAuthority - Public key of the signing authority\n * @param auctionDurationSlot - Duration of the auction in slots (optional)\n * @param swiftConfirmationSlotBuffer - Slot buffer for swift server confirmation time (default: 15)\n * @param onExpired - Callback function called when the order expires\n * @param onErrored - Callback function called when the order encounters an error\n * @param onConfirmed - Callback function called when the order is confirmed\n *\n * @returns Promise that resolves when the order processing is complete\n *\n */\nexport const sendSwiftOrder = ({\n\tdriftClient,\n\tmarketId,\n\thexEncodedSwiftOrderMessageString,\n\tsignedMessage,\n\tsignedMsgOrderUuid,\n\ttakerAuthority,\n\tsigningAuthority,\n\tauctionDuration,\n}: SendSwiftOrderParams): SwiftOrderObservable => {\n\tconst signedMsgUserOrdersAccountPubkey = getSignedMsgUserAccountPublicKey(\n\t\tdriftClient.program.programId,\n\t\ttakerAuthority\n\t);\n\n\tconst swiftOrderObservable = SwiftClient.sendAndConfirmSwiftOrderWS(\n\t\tdriftClient.connection,\n\t\tdriftClient,\n\t\tmarketId.marketIndex,\n\t\tmarketId.marketType,\n\t\thexEncodedSwiftOrderMessageString,\n\t\tBuffer.from(signedMessage),\n\t\ttakerAuthority,\n\t\tsignedMsgUserOrdersAccountPubkey,\n\t\tsignedMsgOrderUuid,\n\t\t((auctionDuration ?? 0) + 15) * SLOT_TIME_ESTIMATE_MS,\n\t\tsigningAuthority\n\t);\n\n\treturn swiftOrderObservable;\n};\n\ntype PrepSignAndSendSwiftOrderParams = {\n\tdriftClient: DriftClient;\n\tsubAccountId: number;\n\tuserAccountPubKey: PublicKey;\n\tmarketIndex: number;\n\tslotBuffer: number;\n\tswiftOptions: SwiftOrderOptions;\n\torderParams: {\n\t\tmain: OptionalOrderParams;\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t};\n};\n\n/**\n * Handles the full flow of the swift order, from preparing to signing and sending to the Swift server.\n * Callbacks can be provided to handle the events of the Swift order.\n * Returns a promise that resolves when the Swift order has reached a terminal state (i.e. confirmed, expired, or errored).\n */\nexport const prepSignAndSendSwiftOrder = async ({\n\tdriftClient,\n\tsubAccountId,\n\tuserAccountPubKey,\n\tmarketIndex,\n\tslotBuffer,\n\tswiftOptions,\n\torderParams,\n}: PrepSignAndSendSwiftOrderParams): Promise<void> => {\n\tconst currentSlot = await driftClient.connection.getSlot('confirmed');\n\n\tconst {\n\t\thexEncodedSwiftOrderMessage,\n\t\tsignedMsgOrderUuid,\n\t\tsignedMsgOrderParamsMessage,\n\t} = prepSwiftOrder({\n\t\tdriftClient,\n\t\ttakerUserAccount: {\n\t\t\tpubKey: userAccountPubKey,\n\t\t\tsubAccountId: subAccountId,\n\t\t},\n\t\tcurrentSlot,\n\t\tisDelegate: swiftOptions.isDelegate || false,\n\t\torderParams,\n\t\tslotBuffer,\n\t});\n\n\tswiftOptions.callbacks?.onOrderParamsMessagePrepped?.(\n\t\tsignedMsgOrderParamsMessage\n\t);\n\n\tconst expirationTimeMs =\n\t\tMath.max(\n\t\t\tslotBuffer +\n\t\t\t\t(orderParams.main.auctionDuration || 0) -\n\t\t\t\tSWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS,\n\t\t\tMINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS\n\t\t) * SLOT_TIME_ESTIMATE_MS;\n\n\t// Ensure that the user signs the message before the expiration time\n\tconst signedMessage = await signSwiftOrderMsg({\n\t\twallet: swiftOptions.wallet,\n\t\thexEncodedSwiftOrderMessage: hexEncodedSwiftOrderMessage.uInt8Array,\n\t\texpirationTimeMs,\n\t\tonExpired: () =>\n\t\t\tswiftOptions.callbacks?.onSigningExpiry?.(signedMsgOrderParamsMessage),\n\t});\n\n\tswiftOptions.callbacks?.onSigningSuccess?.(\n\t\tsignedMessage,\n\t\tsignedMsgOrderUuid,\n\t\tsignedMsgOrderParamsMessage\n\t);\n\n\t// Initialize SwiftClient (required before using sendSwiftOrder)\n\tSwiftClient.init(swiftOptions.swiftServerUrl);\n\n\t// Create a promise-based wrapper for the sendSwiftOrder callback-based API\n\tconst swiftOrderObservable = sendSwiftOrder({\n\t\tdriftClient,\n\t\tmarketId: MarketId.createPerpMarket(marketIndex),\n\t\thexEncodedSwiftOrderMessageString: hexEncodedSwiftOrderMessage.string,\n\t\tsignedMessage,\n\t\tsignedMsgOrderUuid,\n\t\ttakerAuthority: swiftOptions.wallet.takerAuthority,\n\t\tsigningAuthority:\n\t\t\tswiftOptions.wallet.signingAuthority ??\n\t\t\tswiftOptions.wallet.takerAuthority,\n\t\tauctionDuration: orderParams.main.auctionDuration || undefined,\n\t});\n\n\tconst wrapSwiftOrderEvent = <T extends SwiftOrderEvent>(\n\t\tswiftOrderEvent: T\n\t) => {\n\t\treturn {\n\t\t\t...swiftOrderEvent,\n\t\t\tswiftOrderUuid: signedMsgOrderUuid,\n\t\t\torderParamsMessage: signedMsgOrderParamsMessage,\n\t\t};\n\t};\n\n\tlet promiseResolver: (value: void | PromiseLike<void>) => void;\n\tconst promise = new Promise<void>((resolve) => {\n\t\tpromiseResolver = resolve;\n\t});\n\n\tconst handleTerminalEvent = (subscription: Subscription) => {\n\t\tsubscription.unsubscribe();\n\t\tpromiseResolver();\n\t};\n\n\tconst subscription = swiftOrderObservable.subscribe((swiftOrderEvent) => {\n\t\tif (swiftOrderEvent.type === 'sent') {\n\t\t\tswiftOptions.callbacks?.onSent?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t}\n\t\tif (swiftOrderEvent.type === 'confirmed') {\n\t\t\tswiftOptions.callbacks?.onConfirmed?.(\n\t\t\t\twrapSwiftOrderEvent(swiftOrderEvent)\n\t\t\t);\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t\tif (swiftOrderEvent.type === 'expired') {\n\t\t\tswiftOptions.callbacks?.onExpired?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t\tif (swiftOrderEvent.type === 'errored') {\n\t\t\tswiftOptions.callbacks?.onErrored?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t});\n\n\treturn promise;\n};\n"]}
|
package/lib/drift/cli.js
CHANGED
|
@@ -432,7 +432,8 @@ async function openPerpMarketOrderSwiftCommand(args) {
|
|
|
432
432
|
const signature = tweetnacl_1.sign.detached(message, wallet.payer.secretKey);
|
|
433
433
|
return new Uint8Array(signature);
|
|
434
434
|
},
|
|
435
|
-
|
|
435
|
+
takerAuthority: wallet.publicKey,
|
|
436
|
+
signingAuthority: wallet.publicKey,
|
|
436
437
|
},
|
|
437
438
|
callbacks: createSwiftOrderCallbacks('Open Perp Order'),
|
|
438
439
|
},
|
|
@@ -611,7 +612,8 @@ async function openPerpNonMarketOrderSwiftCommand(args) {
|
|
|
611
612
|
const signature = tweetnacl_1.sign.detached(message, wallet.payer.secretKey);
|
|
612
613
|
return new Uint8Array(signature);
|
|
613
614
|
},
|
|
614
|
-
|
|
615
|
+
takerAuthority: wallet.publicKey,
|
|
616
|
+
signingAuthority: wallet.publicKey,
|
|
615
617
|
},
|
|
616
618
|
callbacks: createSwiftOrderCallbacks('Open Perp Non-Market Order'),
|
|
617
619
|
};
|
package/lib/drift/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../../src/drift/cli.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0DAA4C;AAC5C,6CAAkE;AAClE,yCAYyB;AACzB,yCAAiC;AACjC,2EAAwE;AAExE,oCAAsC;AACtC,iDAA+C;AAC/C,2CAA6B;AAO7B,4CAA4C;AAC5C,MAAM,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;AACjC,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC;AAEzD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,uBAAuB;AACvB,IAAI,kBAAsC,CAAC;AAC3C,IAAI,MAAqB,CAAC;AAM1B;;GAEG;AACH,SAAS,SAAS,CAAC,IAAc;IAChC,MAAM,MAAM,GAAY,EAAE,CAAC;IAE3B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACtC,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;QACpB,IAAI,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;YAC1B,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YACjD,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;gBACzB,gCAAgC;gBAChC,IAAI,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;oBACzB,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,KAAK,CAA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AC9D,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACjB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import * as anchor from '@coral-xyz/anchor';\nimport { PublicKey, VersionedTransaction } from '@solana/web3.js';\nimport {\n\tBN,\n\tloadKeypair,\n\tPositionDirection,\n\tOrderType,\n\tPostOnlyParams,\n\tSwapMode,\n\tBASE_PRECISION,\n\tQUOTE_PRECISION,\n\tPRICE_PRECISION,\n\tMainnetSpotMarkets,\n\tDevnetSpotMarkets,\n} from '@drift-labs/sdk';\nimport { sign } from 'tweetnacl';\nimport { CentralServerDrift } from './Drift/clients/CentralServerDrift';\nimport { CentralServerSwiftOrderOptions } from './Drift/clients/CentralServerDrift/types';\nimport { ENUM_UTILS } from '../utils';\nimport { API_URLS } from './constants/apiUrls';\nimport * as path from 'path';\nimport {\n\tNonMarketOrderType,\n\tLimitOrderParamsOrderConfig,\n\tNonMarketOrderParamsConfig,\n} from './base/actions/trade/openPerpOrder/types';\n\n// Load environment variables from .env file\nconst dotenv = require('dotenv');\ndotenv.config({ path: path.resolve(__dirname, '.env') });\n\n/**\n * CLI Tool for CentralServerDrift client\n *\n * This CLI tool allows you to execute various Drift protocol operations via command line\n * with human-readable parameters that are automatically converted to the proper precision.\n *\n * Prerequisites:\n * - Create a .env file in the same directory as this CLI file with:\n * ANCHOR_WALLET=[private key byte array]\n * ENDPOINT=https://your-rpc-endpoint.com\n *\n * Usage Examples:\n * ts-node cli.ts deposit --marketIndex=0 --amount=2 --userAccount=11111111111111111111111111111111\n * ts-node cli.ts withdraw --marketIndex=0 --amount=1.5 --userAccount=11111111111111111111111111111111\n * ts-node cli.ts settleFunding --userAccount=11111111111111111111111111111111\n * ts-node cli.ts settlePnl --marketIndexes=0,1 --userAccount=11111111111111111111111111111111\n * ts-node cli.ts openPerpMarketOrder --marketIndex=0 --direction=long --amount=0.1 --assetType=base --userAccount=11111111111111111111111111111111\n * ts-node cli.ts openPerpMarketOrderSwift --marketIndex=0 --direction=short --amount=100 --assetType=quote --userAccount=11111111111111111111111111111111\n * ts-node cli.ts openPerpNonMarketOrder --marketIndex=0 --direction=long --baseAssetAmount=0.1 --orderType=limit --limitPrice=100 --userAccount=11111111111111111111111111111111\n * ts-node cli.ts openPerpNonMarketOrderSwift --marketIndex=0 --direction=long --baseAssetAmount=0.1 --orderType=limit --limitPrice=99.5 --userAccount=11111111111111111111111111111111\n * ts-node cli.ts editOrder --userAccount=11111111111111111111111111111111 --orderId=123 --newLimitPrice=105.5\n * ts-node cli.ts cancelOrder --userAccount=11111111111111111111111111111111 --orderIds=123,456,789\n * ts-node cli.ts cancelAllOrders --userAccount=11111111111111111111111111111111 --marketType=perp\n * ts-node cli.ts swap --userAccount=11111111111111111111111111111111 --fromMarketIndex=1 --toMarketIndex=0 --fromAmount=1.5 --slippage=100 --swapMode=ExactIn\n * ts-node cli.ts swap --userAccount=11111111111111111111111111111111 --fromMarketIndex=1 --toMarketIndex=0 --toAmount=150 --slippage=100 --swapMode=ExactOut\n */\n\n// Shared configuration\nlet centralServerDrift: CentralServerDrift;\nlet wallet: anchor.Wallet;\n\ninterface CliArgs {\n\t[key: string]: string | string[];\n}\n\n/**\n * Parse command line arguments into a key-value object\n */\nfunction parseArgs(args: string[]): CliArgs {\n\tconst parsed: CliArgs = {};\n\n\tfor (let i = 0; i < args.length; i++) {\n\t\tconst arg = args[i];\n\t\tif (arg.startsWith('--')) {\n\t\t\tconst [key, value] = arg.substring(2).split('=');\n\t\t\tif (value !== undefined) {\n\t\t\t\t// Handle comma-separated arrays\n\t\t\t\tif (value.includes(',')) {\n\t\t\t\t\tparsed[key] = value.split(',');\n\t\t\t\t} else {\n\t\t\t\t\tparsed[key] = value;\n\t\t\t\t}\n\t\t\t} else if (i + 1 < args.length && !args[i + 1].startsWith('--')) {\n\t\t\t\t// Handle space-separated values\n\t\t\t\tconst nextValue = args[i + 1];\n\t\t\t\tif (nextValue.includes(',')) {\n\t\t\t\t\tparsed[key] = nextValue.split(',');\n\t\t\t\t} else {\n\t\t\t\t\tparsed[key] = nextValue;\n\t\t\t\t}\n\t\t\t\ti++; // Skip the next argument as it's the value\n\t\t\t} else {\n\t\t\t\tparsed[key] = 'true'; // Boolean flag\n\t\t\t}\n\t\t}\n\t}\n\n\treturn parsed;\n}\n\n/**\n * Convert human-readable amount to BN with proper precision\n */\nfunction parseAmount(amount: string, precision: BN = QUOTE_PRECISION): BN {\n\tconst floatAmount = parseFloat(amount);\n\tif (isNaN(floatAmount)) {\n\t\tthrow new Error(`Invalid amount: ${amount}`);\n\t}\n\n\t// Convert to the proper precision\n\tconst scaledAmount = Math.floor(floatAmount * precision.toNumber());\n\treturn new BN(scaledAmount);\n}\n\n/**\n * Parse direction string to PositionDirection\n */\nfunction parseDirection(direction: string): PositionDirection {\n\tconst normalized = direction.toLowerCase();\n\tif (normalized === 'long' || normalized === 'buy') {\n\t\treturn PositionDirection.LONG;\n\t} else if (normalized === 'short' || normalized === 'sell') {\n\t\treturn PositionDirection.SHORT;\n\t} else {\n\t\tthrow new Error(\n\t\t\t`Invalid direction: ${direction}. Use 'long', 'short', 'buy', or 'sell'`\n\t\t);\n\t}\n}\n\n/**\n * Parse order type string to OrderType\n */\nfunction _parseOrderType(orderType: string): OrderType {\n\tconst normalized = orderType.toLowerCase();\n\tswitch (normalized) {\n\t\tcase 'limit':\n\t\t\treturn OrderType.LIMIT;\n\t\tcase 'market':\n\t\t\treturn OrderType.MARKET;\n\t\tcase 'oracle':\n\t\t\treturn OrderType.ORACLE;\n\t\tcase 'trigger_market':\n\t\tcase 'stopmarket':\n\t\t\treturn OrderType.TRIGGER_MARKET;\n\t\tcase 'trigger_limit':\n\t\tcase 'stoplimit':\n\t\t\treturn OrderType.TRIGGER_LIMIT;\n\t\tdefault:\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid order type: ${orderType}. Use 'limit', 'market', 'oracle', 'trigger_market', or 'trigger_limit'`\n\t\t\t);\n\t}\n}\n\n/**\n * Parse post only string to PostOnlyParams\n */\nfunction parsePostOnly(postOnly: string): PostOnlyParams {\n\tconst normalized = postOnly.toLowerCase();\n\tswitch (normalized) {\n\t\tcase 'none':\n\t\tcase 'false':\n\t\t\treturn PostOnlyParams.NONE;\n\t\tcase 'must_post_only':\n\t\tcase 'true':\n\t\t\treturn PostOnlyParams.MUST_POST_ONLY;\n\t\tcase 'try_post_only':\n\t\t\treturn PostOnlyParams.TRY_POST_ONLY;\n\t\tcase 'slide':\n\t\t\treturn PostOnlyParams.SLIDE;\n\t\tdefault:\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid post only: ${postOnly}. Use 'none', 'must_post_only', 'try_post_only', or 'slide'`\n\t\t\t);\n\t}\n}\n\n/**\n * Parse swap mode string to SwapMode\n */\nfunction parseSwapMode(swapMode: string): SwapMode {\n\tconst normalized = swapMode.toLowerCase();\n\tswitch (normalized) {\n\t\tcase 'exactin':\n\t\tcase 'exact_in':\n\t\t\treturn 'ExactIn';\n\t\tcase 'exactout':\n\t\tcase 'exact_out':\n\t\t\treturn 'ExactOut';\n\t\tdefault:\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid swap mode: ${swapMode}. Use 'ExactIn' or 'ExactOut'`\n\t\t\t);\n\t}\n}\n\n/**\n * Get the precision for a spot market based on environment and market index\n */\nfunction getMarketPrecision(\n\tmarketIndex: number,\n\tisMainnet: boolean = true\n): BN {\n\tconst markets = isMainnet ? MainnetSpotMarkets : DevnetSpotMarkets;\n\tconst market = markets.find((m) => m.marketIndex === marketIndex);\n\n\tif (!market) {\n\t\tconsole.warn(\n\t\t\t`⚠️ Market ${marketIndex} not found, using QUOTE_PRECISION as fallback`\n\t\t);\n\t\treturn QUOTE_PRECISION;\n\t}\n\n\treturn market.precision;\n}\n\n/**\n * Initialize CentralServerDrift instance\n */\nasync function initializeCentralServerDrift(): Promise<void> {\n\tconsole.log('🚀 Initializing CentralServerDrift...\\n');\n\n\t// Validate required environment variables\n\tif (!process.env.ANCHOR_WALLET) {\n\t\tthrow new Error('ANCHOR_WALLET must be set in .env file');\n\t}\n\n\tif (!process.env.ENDPOINT) {\n\t\tthrow new Error(\n\t\t\t'ENDPOINT environment variable must be set to your Solana RPC endpoint'\n\t\t);\n\t}\n\n\t// Set up the wallet\n\twallet = new anchor.Wallet(loadKeypair(process.env.ANCHOR_WALLET as string));\n\n\tconsole.log(`✅ Wallet Public Key: ${wallet.publicKey.toString()}`);\n\tconsole.log(`✅ RPC Endpoint: ${process.env.ENDPOINT}\\n`);\n\n\t// Initialize CentralServerDrift\n\tconsole.log('🏗️ Initializing CentralServerDrift...');\n\tcentralServerDrift = new CentralServerDrift({\n\t\tsolanaRpcEndpoint: process.env.ENDPOINT as string,\n\t\tdriftEnv: 'mainnet-beta', // Change to 'devnet' for devnet testing\n\t\tadditionalDriftClientConfig: {\n\t\t\ttxVersion: 0,\n\t\t\ttxParams: {\n\t\t\t\tcomputeUnits: 200000,\n\t\t\t\tcomputeUnitsPrice: 1000,\n\t\t\t},\n\t\t},\n\t});\n\n\tconsole.log('✅ CentralServerDrift instance created successfully\\n');\n\n\t// Subscribe to market data\n\tconsole.log('📡 Subscribing to market data...');\n\tawait centralServerDrift.subscribe();\n\tconsole.log('✅ Successfully subscribed to market data\\n');\n}\n\n/**\n * Execute a regular transaction\n */\nasync function executeTransaction(\n\ttxn: VersionedTransaction,\n\ttransactionType: string\n): Promise<void> {\n\tconsole.log(`✅ ${transactionType} transaction created successfully`);\n\tconsole.log('\\n📝 Signing Transaction...');\n\n\ttxn.sign([wallet.payer]);\n\tconsole.log('✅ Transaction signed successfully');\n\n\tconsole.log('\\n🚀 Sending transaction to the network...');\n\tconst { txSig } = await centralServerDrift.sendSignedTransaction(txn);\n\n\tconsole.log('✅ Transaction sent successfully!');\n\tconsole.log(`📋 Transaction Signature: ${txSig?.toString()}`);\n\tconsole.log(`🔍 View on Solscan: https://solscan.io/tx/${txSig?.toString()}`);\n}\n\nconst createSwiftOrderCallbacks = (\n\torderType: string\n): CentralServerSwiftOrderOptions['callbacks'] => {\n\tconst terminalCall = () => {\n\t\tconsole.log('🏁 Order monitoring completed');\n\t};\n\n\treturn {\n\t\tonSigningExpiry: () => {\n\t\t\tconsole.log('Swift order signing expired');\n\t\t},\n\t\tonSigningSuccess: (signedMessage, orderUuid, orderParamsMessage) => {\n\t\t\tconsole.log(\n\t\t\t\t'Swift order signed successfully. Signed message:',\n\t\t\t\tsignedMessage,\n\t\t\t\torderUuid,\n\t\t\t\torderParamsMessage\n\t\t\t);\n\t\t},\n\t\tonSent: () => {\n\t\t\tconsole.log(`✅ ${orderType} Swift order submitted successfully`);\n\t\t},\n\t\tonConfirmed: (event) => {\n\t\t\tconsole.log('✅ Order confirmed!');\n\t\t\tconsole.log(`📋 Order ID: ${event.orderId}`);\n\t\t\tconsole.log(`📋 Hash: ${event.hash}`);\n\t\t\tterminalCall();\n\t\t},\n\t\tonExpired: (event) => {\n\t\t\tconsole.error('⏰ Order expired:', event.message);\n\t\t\tterminalCall();\n\t\t},\n\t\tonErrored: (event) => {\n\t\t\tconsole.error('❌ Order failed:', event.message);\n\t\t\tconsole.error(`📋 Status: ${event.status}`);\n\t\t\tterminalCall();\n\t\t},\n\t};\n};\n\n/**\n * CLI Command: deposit\n */\nasync function depositCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndex = parseInt(args.marketIndex as string);\n\tconst amount = args.amount as string;\n\n\tif (!userAccount || isNaN(marketIndex) || !amount) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndex, --amount'\n\t\t);\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst amountBN = parseAmount(amount, QUOTE_PRECISION); // Most deposits are USDC (quote precision)\n\n\tconsole.log('--- 📥 Deposit Transaction ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Index: ${marketIndex}`);\n\tconsole.log(`💰 Amount: ${amount} (${amountBN.toString()} raw units)`);\n\n\tconst depositTxn = await centralServerDrift.getDepositTxn(\n\t\tuserAccountPubkey,\n\t\tamountBN,\n\t\tmarketIndex\n\t);\n\n\tawait executeTransaction(depositTxn as VersionedTransaction, 'Deposit');\n}\n\n/**\n * CLI Command: withdraw\n */\nasync function withdrawCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndex = parseInt(args.marketIndex as string);\n\tconst amount = args.amount as string;\n\tconst isBorrow = args.isBorrow === 'true';\n\tconst isMax = args.isMax === 'true';\n\n\tif (!userAccount || isNaN(marketIndex) || !amount) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndex, --amount'\n\t\t);\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst amountBN = parseAmount(amount, QUOTE_PRECISION);\n\n\tconsole.log('--- 📤 Withdraw Transaction ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Index: ${marketIndex}`);\n\tconsole.log(`💰 Amount: ${amount} (${amountBN.toString()} raw units)`);\n\tconsole.log(`💳 Is Borrow: ${isBorrow}`);\n\tconsole.log(`📊 Is Max: ${isMax}`);\n\n\tconst withdrawTxn = await centralServerDrift.getWithdrawTxn(\n\t\tuserAccountPubkey,\n\t\tamountBN,\n\t\tmarketIndex,\n\t\t{ isBorrow, isMax }\n\t);\n\n\tawait executeTransaction(withdrawTxn as VersionedTransaction, 'Withdraw');\n}\n\n/**\n * CLI Command: settleFunding\n */\nasync function settleFundingCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\n\tif (!userAccount) {\n\t\tthrow new Error('Required arguments: --userAccount');\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\n\tconsole.log('--- 💰 Settle Funding Transaction ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\n\tconst settleFundingTxn = await centralServerDrift.getSettleFundingTxn(\n\t\tuserAccountPubkey\n\t);\n\n\tawait executeTransaction(\n\t\tsettleFundingTxn as VersionedTransaction,\n\t\t'Settle Funding'\n\t);\n}\n\n/**\n * CLI Command: settlePnl\n */\nasync function settlePnlCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndexesArg = args.marketIndexes;\n\n\tif (!userAccount || !marketIndexesArg) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndexes (comma-separated)'\n\t\t);\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst marketIndexes = Array.isArray(marketIndexesArg)\n\t\t? marketIndexesArg.map((idx) => parseInt(idx))\n\t\t: [parseInt(marketIndexesArg as string)];\n\n\tconsole.log('--- 📈 Settle PnL Transaction ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`📊 Market Indexes: ${marketIndexes.join(', ')}`);\n\n\tconst settlePnlTxn = await centralServerDrift.getSettlePnlTxn(\n\t\tuserAccountPubkey,\n\t\tmarketIndexes\n\t);\n\n\tawait executeTransaction(settlePnlTxn as VersionedTransaction, 'Settle PnL');\n}\n\n/**\n * CLI Command: openPerpMarketOrder (regular transaction)\n */\nasync function openPerpMarketOrderCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndex = parseInt(args.marketIndex as string);\n\tconst direction = args.direction as string;\n\tconst amount = args.amount as string;\n\tconst assetType = (args.assetType as string) || 'base';\n\tconst dlobServerHttpUrl = API_URLS.DLOB;\n\n\tif (!userAccount || isNaN(marketIndex) || !direction || !amount) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndex, --direction, --amount'\n\t\t);\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst directionEnum = parseDirection(direction);\n\tconst precision = assetType === 'base' ? BASE_PRECISION : QUOTE_PRECISION;\n\tconst amountBN = parseAmount(amount, precision);\n\n\tconsole.log('--- 🎯 Open Perp Order Transaction ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Index: ${marketIndex}`);\n\tconsole.log(\n\t\t`📊 Direction: ${direction} (${ENUM_UTILS.toStr(directionEnum)})`\n\t);\n\tconsole.log(`💰 Amount: ${amount} (${amountBN.toString()} raw units)`);\n\tconsole.log(`💱 Asset Type: ${assetType}`);\n\tconsole.log(`🌐 DLOB Server: ${dlobServerHttpUrl}`);\n\n\tconst orderTxn = await centralServerDrift.getOpenPerpMarketOrderTxn({\n\t\tuserAccountPublicKey: userAccountPubkey,\n\t\tassetType: assetType as 'base' | 'quote',\n\t\tmarketIndex,\n\t\tdirection: directionEnum,\n\t\tamount: amountBN,\n\t\tuseSwift: false,\n\t});\n\n\tawait executeTransaction(orderTxn as VersionedTransaction, 'Open Perp Order');\n}\n\n/**\n * CLI Command: openPerpMarketOrderSwift (Swift signed message order)\n */\nasync function openPerpMarketOrderSwiftCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndex = parseInt(args.marketIndex as string);\n\tconst direction = args.direction as string;\n\tconst amount = args.amount as string;\n\tconst assetType = (args.assetType as string) || 'base';\n\tconst dlobServerHttpUrl = API_URLS.DLOB;\n\tconst swiftServerUrl = (args.swiftServerUrl as string) || API_URLS.SWIFT;\n\n\tif (!userAccount || isNaN(marketIndex) || !direction || !amount) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndex, --direction, --amount'\n\t\t);\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst directionEnum = parseDirection(direction);\n\tconst precision = assetType === 'base' ? BASE_PRECISION : QUOTE_PRECISION;\n\tconst amountBN = parseAmount(amount, precision);\n\n\tconsole.log('--- ⚡ Open Perp Order Swift ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Index: ${marketIndex}`);\n\tconsole.log(\n\t\t`📊 Direction: ${direction} (${ENUM_UTILS.toStr(directionEnum)})`\n\t);\n\tconsole.log(`💰 Amount: ${amount} (${amountBN.toString()} raw units)`);\n\tconsole.log(`💱 Asset Type: ${assetType}`);\n\tconsole.log(`🌐 DLOB Server: ${dlobServerHttpUrl}`);\n\tconsole.log(`⚡ Swift Server: ${swiftServerUrl}`);\n\tconsole.log(`🔑 Wallet Public Key: ${wallet.publicKey.toString()}`);\n\n\tconsole.log('\\n👁️ Monitoring order status...');\n\n\ttry {\n\t\tawait centralServerDrift.getOpenPerpMarketOrderTxn({\n\t\t\tuserAccountPublicKey: userAccountPubkey,\n\t\t\tassetType: assetType as 'base' | 'quote',\n\t\t\tmarketIndex,\n\t\t\tdirection: directionEnum,\n\t\t\tamount: amountBN,\n\t\t\tuseSwift: true,\n\t\t\tswiftOptions: {\n\t\t\t\twallet: {\n\t\t\t\t\tsignMessage: async (message: Uint8Array) => {\n\t\t\t\t\t\tconst signature = sign.detached(message, wallet.payer.secretKey);\n\t\t\t\t\t\treturn new Uint8Array(signature);\n\t\t\t\t\t},\n\t\t\t\t\tpublicKey: wallet.publicKey,\n\t\t\t\t},\n\t\t\t\tcallbacks: createSwiftOrderCallbacks('Open Perp Order'),\n\t\t\t},\n\t\t});\n\t\tconsole.log('✅ [CLI] Swift order finished');\n\t} catch (error) {\n\t\tconsole.error('❌ [CLI] Error creating Swift order:', error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * CLI Command: openPerpNonMarketOrder (regular limit/oracle order)\n */\nasync function openPerpNonMarketOrderCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndex = parseInt(args.marketIndex as string);\n\tconst direction = args.direction as string;\n\tconst amount = args.amount as string;\n\tconst assetType = (args.assetType as string) || 'base';\n\tconst baseAssetAmount = args.baseAssetAmount as string;\n\tconst orderType = args.orderType as NonMarketOrderType;\n\tconst limitPrice = args.limitPrice as string;\n\tconst triggerPrice = args.triggerPrice as string;\n\tconst reduceOnly = (args.reduceOnly as string) === 'true';\n\tconst postOnly = (args.postOnly as string) || 'none';\n\tconst oraclePriceOffset = args.oraclePriceOffset as string;\n\n\tif (!userAccount || isNaN(marketIndex) || !direction || !orderType) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndex, --direction, --orderType'\n\t\t);\n\t}\n\n\tif (!amount && !baseAssetAmount) {\n\t\tthrow new Error('Either --amount or --baseAssetAmount must be provided');\n\t}\n\n\t// Validate price requirements based on order type\n\tif (orderType === 'limit') {\n\t\tif (!limitPrice) {\n\t\t\tthrow new Error(`Order type '${orderType}' requires --limitPrice`);\n\t\t}\n\t} else if (orderType === 'takeProfit' || orderType === 'stopLoss') {\n\t\tif (!triggerPrice) {\n\t\t\tthrow new Error(`Order type '${orderType}' requires --triggerPrice`);\n\t\t}\n\t} else if (orderType === 'oracleLimit') {\n\t\tif (!oraclePriceOffset) {\n\t\t\tthrow new Error(`Order type '${orderType}' requires --oraclePriceOffset`);\n\t\t}\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst directionEnum = parseDirection(direction);\n\tconst postOnlyEnum = parsePostOnly(postOnly);\n\tconst limitPriceBN = limitPrice\n\t\t? parseAmount(limitPrice, PRICE_PRECISION)\n\t\t: undefined;\n\tconst triggerPriceBN = triggerPrice\n\t\t? parseAmount(triggerPrice, PRICE_PRECISION)\n\t\t: undefined;\n\tconst oraclePriceOffsetBN = oraclePriceOffset\n\t\t? parseAmount(oraclePriceOffset, PRICE_PRECISION)\n\t\t: undefined;\n\n\tconst orderConfig: NonMarketOrderParamsConfig['orderConfig'] =\n\t\torderType === 'limit'\n\t\t\t? {\n\t\t\t\t\torderType,\n\t\t\t\t\tlimitPrice: limitPriceBN!,\n\t\t\t }\n\t\t\t: orderType === 'takeProfit' || orderType === 'stopLoss'\n\t\t\t? {\n\t\t\t\t\torderType,\n\t\t\t\t\ttriggerPrice: triggerPriceBN!,\n\t\t\t }\n\t\t\t: {\n\t\t\t\t\torderType,\n\t\t\t\t\toraclePriceOffset: oraclePriceOffsetBN!,\n\t\t\t };\n\n\tconsole.log('--- 📋 Open Perp Non-Market Order ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Index: ${marketIndex}`);\n\tconsole.log(\n\t\t`📊 Direction: ${direction} (${ENUM_UTILS.toStr(directionEnum)})`\n\t);\n\n\tlet amountBN: BN;\n\tif (amount) {\n\t\tconst precision = assetType === 'base' ? BASE_PRECISION : QUOTE_PRECISION;\n\t\tamountBN = parseAmount(amount, precision);\n\t\tconsole.log(`💰 Amount: ${amount} (${amountBN.toString()} raw units)`);\n\t\tconsole.log(`💱 Asset Type: ${assetType}`);\n\t} else {\n\t\tamountBN = parseAmount(baseAssetAmount, BASE_PRECISION);\n\t\tconsole.log(\n\t\t\t`💰 Base Asset Amount: ${baseAssetAmount} (${amountBN.toString()} raw units)`\n\t\t);\n\t}\n\n\tif (limitPriceBN) {\n\t\tconsole.log(\n\t\t\t`💵 Limit Price: ${limitPrice} (${limitPriceBN.toString()} raw units)`\n\t\t);\n\t}\n\tif (triggerPriceBN) {\n\t\tconsole.log(\n\t\t\t`🎯 Trigger Price: ${triggerPrice} (${triggerPriceBN.toString()} raw units)`\n\t\t);\n\t}\n\tconsole.log(`📝 Order Type: ${orderType}`);\n\tconsole.log(`🔄 Reduce Only: ${reduceOnly}`);\n\tconsole.log(`📌 Post Only: ${postOnly} (${ENUM_UTILS.toStr(postOnlyEnum)})`);\n\n\t// Just call the main method - it will handle both approaches internally\n\tconst orderTxn = await centralServerDrift.getOpenPerpNonMarketOrderTxn({\n\t\tuserAccountPublicKey: userAccountPubkey,\n\t\tmarketIndex,\n\t\tdirection: directionEnum,\n\t\torderConfig,\n\t\tuseSwift: false,\n\t\treduceOnly,\n\t\tpostOnly: postOnlyEnum,\n\t\tassetType: assetType as 'base' | 'quote',\n\t\tamount: amountBN,\n\t});\n\n\tawait executeTransaction(\n\t\torderTxn as VersionedTransaction,\n\t\t'Open Perp Non-Market Order'\n\t);\n}\n\n/**\n * CLI Command: openPerpNonMarketOrderSwift (Swift signed message limit order)\n */\nasync function openPerpNonMarketOrderSwiftCommand(\n\targs: CliArgs\n): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndex = parseInt(args.marketIndex as string);\n\tconst direction = args.direction as string;\n\tconst amount = args.amount as string;\n\tconst assetType = (args.assetType as string) || 'base';\n\tconst baseAssetAmount = args.baseAssetAmount as string;\n\tconst orderType = args.orderType as NonMarketOrderType;\n\tconst limitPrice = args.limitPrice as string;\n\tconst reduceOnly = (args.reduceOnly as string) === 'true';\n\tconst postOnly = (args.postOnly as string) || 'none';\n\tconst swiftServerUrl = API_URLS.SWIFT;\n\n\tif (!userAccount || isNaN(marketIndex) || !direction || !orderType) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndex, --direction, --orderType'\n\t\t);\n\t}\n\n\tif (!amount && !baseAssetAmount) {\n\t\tthrow new Error('Either --amount or --baseAssetAmount must be provided');\n\t}\n\n\t// Swift orders only support LIMIT order type\n\tif (orderType.toLowerCase() !== 'limit') {\n\t\tthrow new Error('Swift orders only support LIMIT order type');\n\t}\n\n\t// LIMIT orders require limitPrice\n\tif (!limitPrice) {\n\t\tthrow new Error('LIMIT orders require --limitPrice');\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst directionEnum = parseDirection(direction);\n\tconst postOnlyEnum = parsePostOnly(postOnly);\n\tconst limitPriceBN = parseAmount(limitPrice, PRICE_PRECISION);\n\n\tconst orderConfig: LimitOrderParamsOrderConfig = {\n\t\torderType: 'limit',\n\t\tlimitPrice: limitPriceBN!,\n\t};\n\n\tconsole.log('--- ⚡ Open Perp Non-Market Order Swift ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Index: ${marketIndex}`);\n\tconsole.log(\n\t\t`📊 Direction: ${direction} (${ENUM_UTILS.toStr(directionEnum)})`\n\t);\n\n\tlet amountBN: BN;\n\tif (amount) {\n\t\tconst precision = assetType === 'base' ? BASE_PRECISION : QUOTE_PRECISION;\n\t\tamountBN = parseAmount(amount, precision);\n\t\tconsole.log(`💰 Amount: ${amount} (${amountBN.toString()} raw units)`);\n\t\tconsole.log(`💱 Asset Type: ${assetType}`);\n\t} else {\n\t\tamountBN = parseAmount(baseAssetAmount, BASE_PRECISION);\n\t\tconsole.log(\n\t\t\t`💰 Base Asset Amount: ${baseAssetAmount} (${amountBN.toString()} raw units)`\n\t\t);\n\t}\n\n\tconsole.log(\n\t\t`💵 Limit Price: ${limitPrice} (${limitPriceBN.toString()} raw units)`\n\t);\n\tconsole.log(`📝 Order Type: ${orderType})`);\n\tconsole.log(`🔄 Reduce Only: ${reduceOnly}`);\n\tconsole.log(`📌 Post Only: ${postOnly} (${ENUM_UTILS.toStr(postOnlyEnum)})`);\n\tconsole.log(`⚡ Swift Server: ${swiftServerUrl}`);\n\tconsole.log(`🔑 Wallet Public Key: ${wallet.publicKey.toString()}`);\n\n\ttry {\n\t\tconst swiftOptions: CentralServerSwiftOrderOptions = {\n\t\t\twallet: {\n\t\t\t\tsignMessage: async (message: Uint8Array) => {\n\t\t\t\t\tconst signature = sign.detached(message, wallet.payer.secretKey);\n\t\t\t\t\treturn new Uint8Array(signature);\n\t\t\t\t},\n\t\t\t\tpublicKey: wallet.publicKey,\n\t\t\t},\n\t\t\tcallbacks: createSwiftOrderCallbacks('Open Perp Non-Market Order'),\n\t\t};\n\n\t\tconsole.log('\\n👁️ Monitoring order status...');\n\n\t\t// Use the main method - it handles both approaches internally\n\t\tawait centralServerDrift.getOpenPerpNonMarketOrderTxn({\n\t\t\tuserAccountPublicKey: userAccountPubkey,\n\t\t\tmarketIndex,\n\t\t\tdirection: directionEnum,\n\t\t\torderConfig,\n\t\t\treduceOnly,\n\t\t\tpostOnly: postOnlyEnum,\n\t\t\tassetType: assetType as 'base' | 'quote',\n\t\t\tamount: amountBN,\n\t\t\tuseSwift: true,\n\t\t\tswiftOptions,\n\t\t});\n\n\t\tconsole.log('✅ [CLI] Swift order finished');\n\t} catch (error) {\n\t\tconsole.error('❌ [CLI] Error creating Swift non-market order:', error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * Show CLI usage information\n */\nfunction showUsage(): void {\n\tconsole.log('📋 Drift CLI Usage');\n\tconsole.log('');\n\tconsole.log('Available Commands:');\n\tconsole.log('');\n\n\tconsole.log('💰 deposit');\n\tconsole.log(\n\t\t' ts-node cli.ts deposit --userAccount=<pubkey> --marketIndex=<num> --amount=<num>'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts deposit --userAccount=11111111111111111111111111111111 --marketIndex=0 --amount=100'\n\t);\n\tconsole.log('');\n\n\tconsole.log('💸 withdraw');\n\tconsole.log(\n\t\t' ts-node cli.ts withdraw --userAccount=<pubkey> --marketIndex=<num> --amount=<num> [--isBorrow=<bool>] [--isMax=<bool>]'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts withdraw --userAccount=11111111111111111111111111111111 --marketIndex=0 --amount=50'\n\t);\n\tconsole.log('');\n\n\tconsole.log('🏦 settleFunding');\n\tconsole.log(' ts-node cli.ts settleFunding --userAccount=<pubkey>');\n\tconsole.log(\n\t\t' Example: ts-node cli.ts settleFunding --userAccount=11111111111111111111111111111111'\n\t);\n\tconsole.log('');\n\n\tconsole.log('📊 settlePnl');\n\tconsole.log(\n\t\t' ts-node cli.ts settlePnl --userAccount=<pubkey> --marketIndexes=<comma-separated>'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts settlePnl --userAccount=11111111111111111111111111111111 --marketIndexes=0,1'\n\t);\n\tconsole.log('');\n\n\tconsole.log('🎯 openPerpMarketOrder');\n\tconsole.log(\n\t\t' ts-node cli.ts openPerpMarketOrder --userAccount=<pubkey> --marketIndex=<num> --direction=<long|short> --amount=<num> [--assetType=<base|quote>]'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts openPerpMarketOrder --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=long --amount=0.1 --assetType=base'\n\t);\n\tconsole.log('');\n\n\tconsole.log('⚡ openPerpMarketOrderSwift');\n\tconsole.log(\n\t\t' ts-node cli.ts openPerpMarketOrderSwift --userAccount=<pubkey> --marketIndex=<num> --direction=<long|short> --amount=<num> [--assetType=<base|quote>]'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts openPerpMarketOrderSwift --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=short --amount=100 --assetType=quote'\n\t);\n\tconsole.log('');\n\n\tconsole.log('📋 openPerpNonMarketOrder');\n\tconsole.log(\n\t\t' ts-node cli.ts openPerpNonMarketOrder --userAccount=<pubkey> --marketIndex=<num> --direction=<long|short> --amount=<num> [--assetType=<base|quote>] --orderType=<limit|trigger_limit|trigger_market|oracle> [--limitPrice=<num>] [--triggerPrice=<num>] [--reduceOnly=<true|false>] [--postOnly=<none|must_post_only|try_post_only|slide>]'\n\t);\n\tconsole.log(\n\t\t' New LIMIT: ts-node cli.ts openPerpNonMarketOrder --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=long --amount=0.1 --assetType=base --orderType=limit --limitPrice=100'\n\t);\n\tconsole.log(\n\t\t' New QUOTE: ts-node cli.ts openPerpNonMarketOrder --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=long --amount=100 --assetType=quote --orderType=limit --limitPrice=100'\n\t);\n\tconsole.log(\n\t\t' Legacy: ts-node cli.ts openPerpNonMarketOrder --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=long --baseAssetAmount=0.1 --orderType=limit --limitPrice=100'\n\t);\n\tconsole.log('');\n\n\tconsole.log('⚡ openPerpNonMarketOrderSwift');\n\tconsole.log(\n\t\t' ts-node cli.ts openPerpNonMarketOrderSwift --userAccount=<pubkey> --marketIndex=<num> --direction=<long|short> --amount=<num> [--assetType=<base|quote>] --orderType=limit --limitPrice=<num> [--reduceOnly=<true|false>] [--postOnly=<none|must_post_only|try_post_only|slide>]'\n\t);\n\tconsole.log(\n\t\t' New: ts-node cli.ts openPerpNonMarketOrderSwift --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=long --amount=0.1 --assetType=base --orderType=limit --limitPrice=99.5'\n\t);\n\tconsole.log(\n\t\t' Legacy: ts-node cli.ts openPerpNonMarketOrderSwift --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=long --baseAssetAmount=0.1 --orderType=limit --limitPrice=99.5'\n\t);\n\tconsole.log('');\n\n\tconsole.log('✏️ editOrder');\n\tconsole.log(\n\t\t' ts-node cli.ts editOrder --userAccount=<pubkey> --orderId=<num> [--newDirection=<long|short>] [--newBaseAmount=<num>] [--newLimitPrice=<num>] [--newTriggerPrice=<num>] [--reduceOnly=<true|false>] [--postOnly=<true|false>]'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts editOrder --userAccount=11111111111111111111111111111111 --orderId=123 --newLimitPrice=105.5'\n\t);\n\tconsole.log('');\n\n\tconsole.log('❌ cancelOrder');\n\tconsole.log(\n\t\t' ts-node cli.ts cancelOrder --userAccount=<pubkey> --orderIds=<comma-separated-list>'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts cancelOrder --userAccount=11111111111111111111111111111111 --orderIds=123,456,789'\n\t);\n\tconsole.log('');\n\n\tconsole.log('🧹 cancelAllOrders');\n\tconsole.log(\n\t\t' ts-node cli.ts cancelAllOrders --userAccount=<pubkey> [--marketType=<perp|spot>] [--marketIndex=<num>] [--direction=<long|short>]'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts cancelAllOrders --userAccount=11111111111111111111111111111111 --marketType=perp'\n\t);\n\tconsole.log('');\n\n\tconsole.log('🔄 swap');\n\tconsole.log(\n\t\t' ts-node cli.ts swap --userAccount=<pubkey> --fromMarketIndex=<num> --toMarketIndex=<num> [--fromAmount=<num>] [--toAmount=<num>] [--slippage=<bps>] [--swapMode=<ExactIn|ExactOut>]'\n\t);\n\tconsole.log(\n\t\t' ExactIn: ts-node cli.ts swap --userAccount=11111111111111111111111111111111 --fromMarketIndex=1 --toMarketIndex=0 --fromAmount=1.5 --swapMode=ExactIn'\n\t);\n\tconsole.log(\n\t\t' ExactOut: ts-node cli.ts swap --userAccount=11111111111111111111111111111111 --fromMarketIndex=1 --toMarketIndex=0 --toAmount=150 --swapMode=ExactOut'\n\t);\n\tconsole.log('');\n\n\tconsole.log('Options:');\n\tconsole.log(' --help, -h Show this help message');\n\tconsole.log('');\n\tconsole.log('Notes:');\n\tconsole.log(\n\t\t' - Amounts are in human-readable format (e.g., 1.5 USDC, 0.1 SOL)'\n\t);\n\tconsole.log(' - Direction can be: long, short, buy, sell');\n\tconsole.log(\n\t\t' - Asset type: base (for native tokens like SOL) or quote (for USDC amounts)'\n\t);\n\tconsole.log(' - Swap modes:');\n\tconsole.log(\n\t\t' * ExactIn: Specify --fromAmount (how much input token to swap)'\n\t);\n\tconsole.log(\n\t\t' * ExactOut: Specify --toAmount (how much output token to receive)'\n\t);\n\tconsole.log(' - Ensure your .env file contains ANCHOR_WALLET and ENDPOINT');\n}\n\n/**\n * CLI Command: editOrder\n */\nasync function editOrderCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst orderId = parseInt(args.orderId as string);\n\tconst newDirection = args.newDirection as string;\n\tconst newBaseAmount = args.newBaseAmount as string;\n\tconst newLimitPrice = args.newLimitPrice as string;\n\tconst newTriggerPrice = args.newTriggerPrice as string;\n\tconst reduceOnly = (args.reduceOnly as string) === 'true';\n\tconst postOnly = (args.postOnly as string) === 'true';\n\n\tif (!userAccount || isNaN(orderId)) {\n\t\tthrow new Error('Required arguments: --userAccount, --orderId');\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst editParams: any = {};\n\n\tif (newDirection) {\n\t\teditParams.newDirection = parseDirection(newDirection);\n\t}\n\n\tif (newBaseAmount) {\n\t\teditParams.newBaseAmount = parseAmount(newBaseAmount, BASE_PRECISION);\n\t}\n\n\tif (newLimitPrice) {\n\t\teditParams.newLimitPrice = parseAmount(newLimitPrice, PRICE_PRECISION);\n\t}\n\n\tif (newTriggerPrice) {\n\t\teditParams.newTriggerPrice = parseAmount(newTriggerPrice, PRICE_PRECISION);\n\t}\n\n\tif (reduceOnly) {\n\t\teditParams.reduceOnly = true;\n\t}\n\n\tif (postOnly) {\n\t\teditParams.postOnly = true;\n\t}\n\n\tconsole.log('--- ✏️ Edit Order ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🆔 Order ID: ${orderId}`);\n\tconsole.log(`📝 Edit Parameters:`, editParams);\n\n\tconst editOrderTxn = await centralServerDrift.getEditOrderTxn(\n\t\tuserAccountPubkey,\n\t\torderId,\n\t\teditParams\n\t);\n\n\tawait executeTransaction(editOrderTxn as VersionedTransaction, 'Edit Order');\n}\n\n/**\n * CLI Command: cancelOrder\n */\nasync function cancelOrderCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst orderIds = args.orderIds as string;\n\n\tif (!userAccount || !orderIds) {\n\t\tthrow new Error('Required arguments: --userAccount, --orderIds');\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst orderIdArray = orderIds.split(',').map((id) => parseInt(id.trim()));\n\n\tconsole.log('--- ❌ Cancel Orders ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🆔 Order IDs: ${orderIdArray.join(', ')}`);\n\n\tconst cancelOrderTxn = await centralServerDrift.getCancelOrdersTxn(\n\t\tuserAccountPubkey,\n\t\torderIdArray\n\t);\n\n\tawait executeTransaction(\n\t\tcancelOrderTxn as VersionedTransaction,\n\t\t'Cancel Orders'\n\t);\n}\n\n/**\n * CLI Command: cancelAllOrders\n */\nasync function cancelAllOrdersCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketType = args.marketType as string;\n\tconst marketIndex = args.marketIndex\n\t\t? parseInt(args.marketIndex as string)\n\t\t: undefined;\n\tconst direction = args.direction as string;\n\n\tif (!userAccount) {\n\t\tthrow new Error('Required arguments: --userAccount');\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tlet marketTypeEnum = undefined;\n\tlet directionEnum = undefined;\n\n\tif (marketType) {\n\t\tmarketTypeEnum =\n\t\t\tmarketType.toLowerCase() === 'perp' ? { perp: {} } : { spot: {} };\n\t}\n\n\tif (direction) {\n\t\tdirectionEnum = parseDirection(direction);\n\t}\n\n\tconsole.log('--- 🧹 Cancel All Orders ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Type Filter: ${marketType || 'none'}`);\n\tconsole.log(\n\t\t`📊 Market Index Filter: ${\n\t\t\tmarketIndex !== undefined ? marketIndex : 'none'\n\t\t}`\n\t);\n\tconsole.log(`📈 Direction Filter: ${direction || 'none'}`);\n\n\tconst cancelAllOrdersTxn = await centralServerDrift.getCancelAllOrdersTxn(\n\t\tuserAccountPubkey,\n\t\tmarketTypeEnum,\n\t\tmarketIndex,\n\t\tdirectionEnum\n\t);\n\n\tawait executeTransaction(\n\t\tcancelAllOrdersTxn as VersionedTransaction,\n\t\t'Cancel All Orders'\n\t);\n}\n\n/**\n * CLI Command: swap\n */\nasync function swapCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst fromMarketIndex = parseInt(args.fromMarketIndex as string);\n\tconst toMarketIndex = parseInt(args.toMarketIndex as string);\n\tconst fromAmount = args.fromAmount as string;\n\tconst toAmount = args.toAmount as string;\n\tconst slippage = args.slippage ? parseInt(args.slippage as string) : 10; // Default 0.1%\n\tconst swapMode = (args.swapMode as string) || 'ExactIn';\n\n\tif (!userAccount || isNaN(fromMarketIndex) || isNaN(toMarketIndex)) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --fromMarketIndex, --toMarketIndex'\n\t\t);\n\t}\n\n\tconst swapModeEnum = parseSwapMode(swapMode);\n\n\t// Validate amount parameters based on swap mode\n\tif (swapModeEnum === 'ExactIn') {\n\t\tif (!fromAmount) {\n\t\t\tthrow new Error('ExactIn swap mode requires --fromAmount');\n\t\t}\n\t\tif (toAmount) {\n\t\t\tconsole.warn(\n\t\t\t\t'⚠️ Warning: --toAmount ignored in ExactIn mode, using --fromAmount'\n\t\t\t);\n\t\t}\n\t} else if (swapModeEnum === 'ExactOut') {\n\t\tif (!toAmount) {\n\t\t\tthrow new Error('ExactOut swap mode requires --toAmount');\n\t\t}\n\t\tif (fromAmount) {\n\t\t\tconsole.warn(\n\t\t\t\t'⚠️ Warning: --fromAmount ignored in ExactOut mode, using --toAmount'\n\t\t\t);\n\t\t}\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\n\t// Use the appropriate amount based on swap mode\n\tconst amount = swapModeEnum === 'ExactIn' ? fromAmount : toAmount;\n\n\t// Determine which market to use for precision (input market for ExactIn, output market for ExactOut)\n\tconst precisionMarketIndex =\n\t\tswapModeEnum === 'ExactIn' ? fromMarketIndex : toMarketIndex;\n\n\t// Get the appropriate precision for the amount based on the market\n\tconst isMainnet = true; // Default to mainnet, could be made configurable\n\tconst precision = getMarketPrecision(precisionMarketIndex, isMainnet);\n\tconst amountBN = parseAmount(amount, precision);\n\n\tconsole.log('--- 🔄 Swap Transaction ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`📤 From Market Index: ${fromMarketIndex}`);\n\tconsole.log(`📥 To Market Index: ${toMarketIndex}`);\n\tconsole.log(`🔄 Swap Mode: ${swapMode}`);\n\tconsole.log(\n\t\t`🎯 Using precision from market ${precisionMarketIndex}: ${precision.toString()}`\n\t);\n\n\tif (swapModeEnum === 'ExactIn') {\n\t\tconsole.log(\n\t\t\t`💰 From Amount: ${fromAmount} (${amountBN.toString()} raw units)`\n\t\t);\n\t\tconsole.log(`💰 To Amount: Will be calculated based on quote`);\n\t} else {\n\t\tconsole.log(`💰 From Amount: Will be calculated based on quote`);\n\t\tconsole.log(`💰 To Amount: ${toAmount} (${amountBN.toString()} raw units)`);\n\t}\n\n\tconsole.log(`📊 Slippage: ${slippage} BPS (${slippage / 100}%)`);\n\n\tconst swapTxn = await centralServerDrift.getSwapTxn(\n\t\tuserAccountPubkey,\n\t\tfromMarketIndex,\n\t\ttoMarketIndex,\n\t\tamountBN,\n\t\t{\n\t\t\tslippageBps: slippage,\n\t\t\tswapMode: swapModeEnum,\n\t\t}\n\t);\n\n\tawait executeTransaction(swapTxn as VersionedTransaction, 'Swap');\n}\n\n/**\n * Main CLI entry point\n */\nasync function main(): Promise<void> {\n\tconst args = process.argv.slice(2);\n\n\tif (\n\t\targs.length === 0 ||\n\t\targs[0] === '--help' ||\n\t\targs[0] === '-h' ||\n\t\targs[0] === 'help'\n\t) {\n\t\tshowUsage();\n\t\treturn;\n\t}\n\n\tconst command = args[0];\n\tconst parsedArgs = parseArgs(args.slice(1));\n\n\t// Initialize the client first\n\tawait initializeCentralServerDrift();\n\n\t// Route to appropriate command\n\tswitch (command) {\n\t\tcase 'deposit':\n\t\t\tawait depositCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'withdraw':\n\t\t\tawait withdrawCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'settleFunding':\n\t\t\tawait settleFundingCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'settlePnl':\n\t\t\tawait settlePnlCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'openPerpMarketOrder':\n\t\t\tawait openPerpMarketOrderCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'openPerpMarketOrderSwift':\n\t\t\tawait openPerpMarketOrderSwiftCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'openPerpNonMarketOrder':\n\t\t\tawait openPerpNonMarketOrderCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'openPerpNonMarketOrderSwift':\n\t\t\tawait openPerpNonMarketOrderSwiftCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'editOrder':\n\t\t\tawait editOrderCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'cancelOrder':\n\t\t\tawait cancelOrderCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'cancelAllOrders':\n\t\t\tawait cancelAllOrdersCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'swap':\n\t\t\tawait swapCommand(parsedArgs);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tconsole.error(`❌ Unknown command: ${command}`);\n\t\t\tconsole.error('');\n\t\t\tshowUsage();\n\t\t\tprocess.exit(1);\n\t}\n}\n\n// Run CLI if this file is executed directly\nif (require.main === module) {\n\tmain()\n\t\t.then(() => {\n\t\t\tconsole.log('\\n✨ Command executed successfully!');\n\t\t\t// Don't exit immediately for Swift orders (they need time to process)\n\t\t\tsetTimeout(() => process.exit(0), 2000);\n\t\t})\n\t\t.catch((error) => {\n\t\t\tconsole.error('\\n💥 Command failed:', error.message || error);\n\t\t\tprocess.exit(1);\n\t\t});\n}\n\nexport { main, parseArgs, parseAmount, parseDirection, parseSwapMode };\n"]}
|
|
1
|
+
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../../src/drift/cli.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0DAA4C;AAC5C,6CAAkE;AAClE,yCAYyB;AACzB,yCAAiC;AACjC,2EAAwE;AAExE,oCAAsC;AACtC,iDAA+C;AAC/C,2CAA6B;AAO7B,4CAA4C;AAC5C,MAAM,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;AACjC,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC;AAEzD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,uBAAuB;AACvB,IAAI,kBAAsC,CAAC;AAC3C,IAAI,MAAqB,CAAC;AAM1B;;GAEG;AACH,SAAS,SAAS,CAAC,IAAc;IAChC,MAAM,MAAM,GAAY,EAAE,CAAC;IAE3B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAA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IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACF,CAAC;AAgBQ,oBAAI;AAdb,4CAA4C;AAC5C,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;IAC7B,IAAI,EAAE;SACJ,IAAI,CAAC,GAAG,EAAE;QACV,OAAO,CAAC,GAAG,CAAC,oCAAoC,CAAC,CAAC;QAClD,sEAAsE;QACtE,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;IACzC,CAAC,CAAC;SACD,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;QAChB,OAAO,CAAC,KAAK,CAAC,sBAAsB,EAAE,KAAK,CAAC,OAAO,IAAI,KAAK,CAAC,CAAC;QAC9D,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACjB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import * as anchor from '@coral-xyz/anchor';\nimport { PublicKey, VersionedTransaction } from '@solana/web3.js';\nimport {\n\tBN,\n\tloadKeypair,\n\tPositionDirection,\n\tOrderType,\n\tPostOnlyParams,\n\tSwapMode,\n\tBASE_PRECISION,\n\tQUOTE_PRECISION,\n\tPRICE_PRECISION,\n\tMainnetSpotMarkets,\n\tDevnetSpotMarkets,\n} from '@drift-labs/sdk';\nimport { sign } from 'tweetnacl';\nimport { CentralServerDrift } from './Drift/clients/CentralServerDrift';\nimport { CentralServerSwiftOrderOptions } from './Drift/clients/CentralServerDrift/types';\nimport { ENUM_UTILS } from '../utils';\nimport { API_URLS } from './constants/apiUrls';\nimport * as path from 'path';\nimport {\n\tNonMarketOrderType,\n\tLimitOrderParamsOrderConfig,\n\tNonMarketOrderParamsConfig,\n} from './base/actions/trade/openPerpOrder/types';\n\n// Load environment variables from .env file\nconst dotenv = require('dotenv');\ndotenv.config({ path: path.resolve(__dirname, '.env') });\n\n/**\n * CLI Tool for CentralServerDrift client\n *\n * This CLI tool allows you to execute various Drift protocol operations via command line\n * with human-readable parameters that are automatically converted to the proper precision.\n *\n * Prerequisites:\n * - Create a .env file in the same directory as this CLI file with:\n * ANCHOR_WALLET=[private key byte array]\n * ENDPOINT=https://your-rpc-endpoint.com\n *\n * Usage Examples:\n * ts-node cli.ts deposit --marketIndex=0 --amount=2 --userAccount=11111111111111111111111111111111\n * ts-node cli.ts withdraw --marketIndex=0 --amount=1.5 --userAccount=11111111111111111111111111111111\n * ts-node cli.ts settleFunding --userAccount=11111111111111111111111111111111\n * ts-node cli.ts settlePnl --marketIndexes=0,1 --userAccount=11111111111111111111111111111111\n * ts-node cli.ts openPerpMarketOrder --marketIndex=0 --direction=long --amount=0.1 --assetType=base --userAccount=11111111111111111111111111111111\n * ts-node cli.ts openPerpMarketOrderSwift --marketIndex=0 --direction=short --amount=100 --assetType=quote --userAccount=11111111111111111111111111111111\n * ts-node cli.ts openPerpNonMarketOrder --marketIndex=0 --direction=long --baseAssetAmount=0.1 --orderType=limit --limitPrice=100 --userAccount=11111111111111111111111111111111\n * ts-node cli.ts openPerpNonMarketOrderSwift --marketIndex=0 --direction=long --baseAssetAmount=0.1 --orderType=limit --limitPrice=99.5 --userAccount=11111111111111111111111111111111\n * ts-node cli.ts editOrder --userAccount=11111111111111111111111111111111 --orderId=123 --newLimitPrice=105.5\n * ts-node cli.ts cancelOrder --userAccount=11111111111111111111111111111111 --orderIds=123,456,789\n * ts-node cli.ts cancelAllOrders --userAccount=11111111111111111111111111111111 --marketType=perp\n * ts-node cli.ts swap --userAccount=11111111111111111111111111111111 --fromMarketIndex=1 --toMarketIndex=0 --fromAmount=1.5 --slippage=100 --swapMode=ExactIn\n * ts-node cli.ts swap --userAccount=11111111111111111111111111111111 --fromMarketIndex=1 --toMarketIndex=0 --toAmount=150 --slippage=100 --swapMode=ExactOut\n */\n\n// Shared configuration\nlet centralServerDrift: CentralServerDrift;\nlet wallet: anchor.Wallet;\n\ninterface CliArgs {\n\t[key: string]: string | string[];\n}\n\n/**\n * Parse command line arguments into a key-value object\n */\nfunction parseArgs(args: string[]): CliArgs {\n\tconst parsed: CliArgs = {};\n\n\tfor (let i = 0; i < args.length; i++) {\n\t\tconst arg = args[i];\n\t\tif (arg.startsWith('--')) {\n\t\t\tconst [key, value] = arg.substring(2).split('=');\n\t\t\tif (value !== undefined) {\n\t\t\t\t// Handle comma-separated arrays\n\t\t\t\tif (value.includes(',')) {\n\t\t\t\t\tparsed[key] = value.split(',');\n\t\t\t\t} else {\n\t\t\t\t\tparsed[key] = value;\n\t\t\t\t}\n\t\t\t} else if (i + 1 < args.length && !args[i + 1].startsWith('--')) {\n\t\t\t\t// Handle space-separated values\n\t\t\t\tconst nextValue = args[i + 1];\n\t\t\t\tif (nextValue.includes(',')) {\n\t\t\t\t\tparsed[key] = nextValue.split(',');\n\t\t\t\t} else {\n\t\t\t\t\tparsed[key] = nextValue;\n\t\t\t\t}\n\t\t\t\ti++; // Skip the next argument as it's the value\n\t\t\t} else {\n\t\t\t\tparsed[key] = 'true'; // Boolean flag\n\t\t\t}\n\t\t}\n\t}\n\n\treturn parsed;\n}\n\n/**\n * Convert human-readable amount to BN with proper precision\n */\nfunction parseAmount(amount: string, precision: BN = QUOTE_PRECISION): BN {\n\tconst floatAmount = parseFloat(amount);\n\tif (isNaN(floatAmount)) {\n\t\tthrow new Error(`Invalid amount: ${amount}`);\n\t}\n\n\t// Convert to the proper precision\n\tconst scaledAmount = Math.floor(floatAmount * precision.toNumber());\n\treturn new BN(scaledAmount);\n}\n\n/**\n * Parse direction string to PositionDirection\n */\nfunction parseDirection(direction: string): PositionDirection {\n\tconst normalized = direction.toLowerCase();\n\tif (normalized === 'long' || normalized === 'buy') {\n\t\treturn PositionDirection.LONG;\n\t} else if (normalized === 'short' || normalized === 'sell') {\n\t\treturn PositionDirection.SHORT;\n\t} else {\n\t\tthrow new Error(\n\t\t\t`Invalid direction: ${direction}. Use 'long', 'short', 'buy', or 'sell'`\n\t\t);\n\t}\n}\n\n/**\n * Parse order type string to OrderType\n */\nfunction _parseOrderType(orderType: string): OrderType {\n\tconst normalized = orderType.toLowerCase();\n\tswitch (normalized) {\n\t\tcase 'limit':\n\t\t\treturn OrderType.LIMIT;\n\t\tcase 'market':\n\t\t\treturn OrderType.MARKET;\n\t\tcase 'oracle':\n\t\t\treturn OrderType.ORACLE;\n\t\tcase 'trigger_market':\n\t\tcase 'stopmarket':\n\t\t\treturn OrderType.TRIGGER_MARKET;\n\t\tcase 'trigger_limit':\n\t\tcase 'stoplimit':\n\t\t\treturn OrderType.TRIGGER_LIMIT;\n\t\tdefault:\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid order type: ${orderType}. Use 'limit', 'market', 'oracle', 'trigger_market', or 'trigger_limit'`\n\t\t\t);\n\t}\n}\n\n/**\n * Parse post only string to PostOnlyParams\n */\nfunction parsePostOnly(postOnly: string): PostOnlyParams {\n\tconst normalized = postOnly.toLowerCase();\n\tswitch (normalized) {\n\t\tcase 'none':\n\t\tcase 'false':\n\t\t\treturn PostOnlyParams.NONE;\n\t\tcase 'must_post_only':\n\t\tcase 'true':\n\t\t\treturn PostOnlyParams.MUST_POST_ONLY;\n\t\tcase 'try_post_only':\n\t\t\treturn PostOnlyParams.TRY_POST_ONLY;\n\t\tcase 'slide':\n\t\t\treturn PostOnlyParams.SLIDE;\n\t\tdefault:\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid post only: ${postOnly}. Use 'none', 'must_post_only', 'try_post_only', or 'slide'`\n\t\t\t);\n\t}\n}\n\n/**\n * Parse swap mode string to SwapMode\n */\nfunction parseSwapMode(swapMode: string): SwapMode {\n\tconst normalized = swapMode.toLowerCase();\n\tswitch (normalized) {\n\t\tcase 'exactin':\n\t\tcase 'exact_in':\n\t\t\treturn 'ExactIn';\n\t\tcase 'exactout':\n\t\tcase 'exact_out':\n\t\t\treturn 'ExactOut';\n\t\tdefault:\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid swap mode: ${swapMode}. Use 'ExactIn' or 'ExactOut'`\n\t\t\t);\n\t}\n}\n\n/**\n * Get the precision for a spot market based on environment and market index\n */\nfunction getMarketPrecision(\n\tmarketIndex: number,\n\tisMainnet: boolean = true\n): BN {\n\tconst markets = isMainnet ? MainnetSpotMarkets : DevnetSpotMarkets;\n\tconst market = markets.find((m) => m.marketIndex === marketIndex);\n\n\tif (!market) {\n\t\tconsole.warn(\n\t\t\t`⚠️ Market ${marketIndex} not found, using QUOTE_PRECISION as fallback`\n\t\t);\n\t\treturn QUOTE_PRECISION;\n\t}\n\n\treturn market.precision;\n}\n\n/**\n * Initialize CentralServerDrift instance\n */\nasync function initializeCentralServerDrift(): Promise<void> {\n\tconsole.log('🚀 Initializing CentralServerDrift...\\n');\n\n\t// Validate required environment variables\n\tif (!process.env.ANCHOR_WALLET) {\n\t\tthrow new Error('ANCHOR_WALLET must be set in .env file');\n\t}\n\n\tif (!process.env.ENDPOINT) {\n\t\tthrow new Error(\n\t\t\t'ENDPOINT environment variable must be set to your Solana RPC endpoint'\n\t\t);\n\t}\n\n\t// Set up the wallet\n\twallet = new anchor.Wallet(loadKeypair(process.env.ANCHOR_WALLET as string));\n\n\tconsole.log(`✅ Wallet Public Key: ${wallet.publicKey.toString()}`);\n\tconsole.log(`✅ RPC Endpoint: ${process.env.ENDPOINT}\\n`);\n\n\t// Initialize CentralServerDrift\n\tconsole.log('🏗️ Initializing CentralServerDrift...');\n\tcentralServerDrift = new CentralServerDrift({\n\t\tsolanaRpcEndpoint: process.env.ENDPOINT as string,\n\t\tdriftEnv: 'mainnet-beta', // Change to 'devnet' for devnet testing\n\t\tadditionalDriftClientConfig: {\n\t\t\ttxVersion: 0,\n\t\t\ttxParams: {\n\t\t\t\tcomputeUnits: 200000,\n\t\t\t\tcomputeUnitsPrice: 1000,\n\t\t\t},\n\t\t},\n\t});\n\n\tconsole.log('✅ CentralServerDrift instance created successfully\\n');\n\n\t// Subscribe to market data\n\tconsole.log('📡 Subscribing to market data...');\n\tawait centralServerDrift.subscribe();\n\tconsole.log('✅ Successfully subscribed to market data\\n');\n}\n\n/**\n * Execute a regular transaction\n */\nasync function executeTransaction(\n\ttxn: VersionedTransaction,\n\ttransactionType: string\n): Promise<void> {\n\tconsole.log(`✅ ${transactionType} transaction created successfully`);\n\tconsole.log('\\n📝 Signing Transaction...');\n\n\ttxn.sign([wallet.payer]);\n\tconsole.log('✅ Transaction signed successfully');\n\n\tconsole.log('\\n🚀 Sending transaction to the network...');\n\tconst { txSig } = await centralServerDrift.sendSignedTransaction(txn);\n\n\tconsole.log('✅ Transaction sent successfully!');\n\tconsole.log(`📋 Transaction Signature: ${txSig?.toString()}`);\n\tconsole.log(`🔍 View on Solscan: https://solscan.io/tx/${txSig?.toString()}`);\n}\n\nconst createSwiftOrderCallbacks = (\n\torderType: string\n): CentralServerSwiftOrderOptions['callbacks'] => {\n\tconst terminalCall = () => {\n\t\tconsole.log('🏁 Order monitoring completed');\n\t};\n\n\treturn {\n\t\tonSigningExpiry: () => {\n\t\t\tconsole.log('Swift order signing expired');\n\t\t},\n\t\tonSigningSuccess: (signedMessage, orderUuid, orderParamsMessage) => {\n\t\t\tconsole.log(\n\t\t\t\t'Swift order signed successfully. Signed message:',\n\t\t\t\tsignedMessage,\n\t\t\t\torderUuid,\n\t\t\t\torderParamsMessage\n\t\t\t);\n\t\t},\n\t\tonSent: () => {\n\t\t\tconsole.log(`✅ ${orderType} Swift order submitted successfully`);\n\t\t},\n\t\tonConfirmed: (event) => {\n\t\t\tconsole.log('✅ Order confirmed!');\n\t\t\tconsole.log(`📋 Order ID: ${event.orderId}`);\n\t\t\tconsole.log(`📋 Hash: ${event.hash}`);\n\t\t\tterminalCall();\n\t\t},\n\t\tonExpired: (event) => {\n\t\t\tconsole.error('⏰ Order expired:', event.message);\n\t\t\tterminalCall();\n\t\t},\n\t\tonErrored: (event) => {\n\t\t\tconsole.error('❌ Order failed:', event.message);\n\t\t\tconsole.error(`📋 Status: ${event.status}`);\n\t\t\tterminalCall();\n\t\t},\n\t};\n};\n\n/**\n * CLI Command: deposit\n */\nasync function depositCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndex = parseInt(args.marketIndex as string);\n\tconst amount = args.amount as string;\n\n\tif (!userAccount || isNaN(marketIndex) || !amount) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndex, --amount'\n\t\t);\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst amountBN = parseAmount(amount, QUOTE_PRECISION); // Most deposits are USDC (quote precision)\n\n\tconsole.log('--- 📥 Deposit Transaction ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Index: ${marketIndex}`);\n\tconsole.log(`💰 Amount: ${amount} (${amountBN.toString()} raw units)`);\n\n\tconst depositTxn = await centralServerDrift.getDepositTxn(\n\t\tuserAccountPubkey,\n\t\tamountBN,\n\t\tmarketIndex\n\t);\n\n\tawait executeTransaction(depositTxn as VersionedTransaction, 'Deposit');\n}\n\n/**\n * CLI Command: withdraw\n */\nasync function withdrawCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndex = parseInt(args.marketIndex as string);\n\tconst amount = args.amount as string;\n\tconst isBorrow = args.isBorrow === 'true';\n\tconst isMax = args.isMax === 'true';\n\n\tif (!userAccount || isNaN(marketIndex) || !amount) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndex, --amount'\n\t\t);\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst amountBN = parseAmount(amount, QUOTE_PRECISION);\n\n\tconsole.log('--- 📤 Withdraw Transaction ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Index: ${marketIndex}`);\n\tconsole.log(`💰 Amount: ${amount} (${amountBN.toString()} raw units)`);\n\tconsole.log(`💳 Is Borrow: ${isBorrow}`);\n\tconsole.log(`📊 Is Max: ${isMax}`);\n\n\tconst withdrawTxn = await centralServerDrift.getWithdrawTxn(\n\t\tuserAccountPubkey,\n\t\tamountBN,\n\t\tmarketIndex,\n\t\t{ isBorrow, isMax }\n\t);\n\n\tawait executeTransaction(withdrawTxn as VersionedTransaction, 'Withdraw');\n}\n\n/**\n * CLI Command: settleFunding\n */\nasync function settleFundingCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\n\tif (!userAccount) {\n\t\tthrow new Error('Required arguments: --userAccount');\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\n\tconsole.log('--- 💰 Settle Funding Transaction ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\n\tconst settleFundingTxn = await centralServerDrift.getSettleFundingTxn(\n\t\tuserAccountPubkey\n\t);\n\n\tawait executeTransaction(\n\t\tsettleFundingTxn as VersionedTransaction,\n\t\t'Settle Funding'\n\t);\n}\n\n/**\n * CLI Command: settlePnl\n */\nasync function settlePnlCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndexesArg = args.marketIndexes;\n\n\tif (!userAccount || !marketIndexesArg) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndexes (comma-separated)'\n\t\t);\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst marketIndexes = Array.isArray(marketIndexesArg)\n\t\t? marketIndexesArg.map((idx) => parseInt(idx))\n\t\t: [parseInt(marketIndexesArg as string)];\n\n\tconsole.log('--- 📈 Settle PnL Transaction ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`📊 Market Indexes: ${marketIndexes.join(', ')}`);\n\n\tconst settlePnlTxn = await centralServerDrift.getSettlePnlTxn(\n\t\tuserAccountPubkey,\n\t\tmarketIndexes\n\t);\n\n\tawait executeTransaction(settlePnlTxn as VersionedTransaction, 'Settle PnL');\n}\n\n/**\n * CLI Command: openPerpMarketOrder (regular transaction)\n */\nasync function openPerpMarketOrderCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndex = parseInt(args.marketIndex as string);\n\tconst direction = args.direction as string;\n\tconst amount = args.amount as string;\n\tconst assetType = (args.assetType as string) || 'base';\n\tconst dlobServerHttpUrl = API_URLS.DLOB;\n\n\tif (!userAccount || isNaN(marketIndex) || !direction || !amount) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndex, --direction, --amount'\n\t\t);\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst directionEnum = parseDirection(direction);\n\tconst precision = assetType === 'base' ? BASE_PRECISION : QUOTE_PRECISION;\n\tconst amountBN = parseAmount(amount, precision);\n\n\tconsole.log('--- 🎯 Open Perp Order Transaction ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Index: ${marketIndex}`);\n\tconsole.log(\n\t\t`📊 Direction: ${direction} (${ENUM_UTILS.toStr(directionEnum)})`\n\t);\n\tconsole.log(`💰 Amount: ${amount} (${amountBN.toString()} raw units)`);\n\tconsole.log(`💱 Asset Type: ${assetType}`);\n\tconsole.log(`🌐 DLOB Server: ${dlobServerHttpUrl}`);\n\n\tconst orderTxn = await centralServerDrift.getOpenPerpMarketOrderTxn({\n\t\tuserAccountPublicKey: userAccountPubkey,\n\t\tassetType: assetType as 'base' | 'quote',\n\t\tmarketIndex,\n\t\tdirection: directionEnum,\n\t\tamount: amountBN,\n\t\tuseSwift: false,\n\t});\n\n\tawait executeTransaction(orderTxn as VersionedTransaction, 'Open Perp Order');\n}\n\n/**\n * CLI Command: openPerpMarketOrderSwift (Swift signed message order)\n */\nasync function openPerpMarketOrderSwiftCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndex = parseInt(args.marketIndex as string);\n\tconst direction = args.direction as string;\n\tconst amount = args.amount as string;\n\tconst assetType = (args.assetType as string) || 'base';\n\tconst dlobServerHttpUrl = API_URLS.DLOB;\n\tconst swiftServerUrl = (args.swiftServerUrl as string) || API_URLS.SWIFT;\n\n\tif (!userAccount || isNaN(marketIndex) || !direction || !amount) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndex, --direction, --amount'\n\t\t);\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst directionEnum = parseDirection(direction);\n\tconst precision = assetType === 'base' ? BASE_PRECISION : QUOTE_PRECISION;\n\tconst amountBN = parseAmount(amount, precision);\n\n\tconsole.log('--- ⚡ Open Perp Order Swift ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Index: ${marketIndex}`);\n\tconsole.log(\n\t\t`📊 Direction: ${direction} (${ENUM_UTILS.toStr(directionEnum)})`\n\t);\n\tconsole.log(`💰 Amount: ${amount} (${amountBN.toString()} raw units)`);\n\tconsole.log(`💱 Asset Type: ${assetType}`);\n\tconsole.log(`🌐 DLOB Server: ${dlobServerHttpUrl}`);\n\tconsole.log(`⚡ Swift Server: ${swiftServerUrl}`);\n\tconsole.log(`🔑 Wallet Public Key: ${wallet.publicKey.toString()}`);\n\n\tconsole.log('\\n👁️ Monitoring order status...');\n\n\ttry {\n\t\tawait centralServerDrift.getOpenPerpMarketOrderTxn({\n\t\t\tuserAccountPublicKey: userAccountPubkey,\n\t\t\tassetType: assetType as 'base' | 'quote',\n\t\t\tmarketIndex,\n\t\t\tdirection: directionEnum,\n\t\t\tamount: amountBN,\n\t\t\tuseSwift: true,\n\t\t\tswiftOptions: {\n\t\t\t\twallet: {\n\t\t\t\t\tsignMessage: async (message: Uint8Array) => {\n\t\t\t\t\t\tconst signature = sign.detached(message, wallet.payer.secretKey);\n\t\t\t\t\t\treturn new Uint8Array(signature);\n\t\t\t\t\t},\n\t\t\t\t\ttakerAuthority: wallet.publicKey,\n\t\t\t\t\tsigningAuthority: wallet.publicKey,\n\t\t\t\t},\n\t\t\t\tcallbacks: createSwiftOrderCallbacks('Open Perp Order'),\n\t\t\t},\n\t\t});\n\t\tconsole.log('✅ [CLI] Swift order finished');\n\t} catch (error) {\n\t\tconsole.error('❌ [CLI] Error creating Swift order:', error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * CLI Command: openPerpNonMarketOrder (regular limit/oracle order)\n */\nasync function openPerpNonMarketOrderCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndex = parseInt(args.marketIndex as string);\n\tconst direction = args.direction as string;\n\tconst amount = args.amount as string;\n\tconst assetType = (args.assetType as string) || 'base';\n\tconst baseAssetAmount = args.baseAssetAmount as string;\n\tconst orderType = args.orderType as NonMarketOrderType;\n\tconst limitPrice = args.limitPrice as string;\n\tconst triggerPrice = args.triggerPrice as string;\n\tconst reduceOnly = (args.reduceOnly as string) === 'true';\n\tconst postOnly = (args.postOnly as string) || 'none';\n\tconst oraclePriceOffset = args.oraclePriceOffset as string;\n\n\tif (!userAccount || isNaN(marketIndex) || !direction || !orderType) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndex, --direction, --orderType'\n\t\t);\n\t}\n\n\tif (!amount && !baseAssetAmount) {\n\t\tthrow new Error('Either --amount or --baseAssetAmount must be provided');\n\t}\n\n\t// Validate price requirements based on order type\n\tif (orderType === 'limit') {\n\t\tif (!limitPrice) {\n\t\t\tthrow new Error(`Order type '${orderType}' requires --limitPrice`);\n\t\t}\n\t} else if (orderType === 'takeProfit' || orderType === 'stopLoss') {\n\t\tif (!triggerPrice) {\n\t\t\tthrow new Error(`Order type '${orderType}' requires --triggerPrice`);\n\t\t}\n\t} else if (orderType === 'oracleLimit') {\n\t\tif (!oraclePriceOffset) {\n\t\t\tthrow new Error(`Order type '${orderType}' requires --oraclePriceOffset`);\n\t\t}\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst directionEnum = parseDirection(direction);\n\tconst postOnlyEnum = parsePostOnly(postOnly);\n\tconst limitPriceBN = limitPrice\n\t\t? parseAmount(limitPrice, PRICE_PRECISION)\n\t\t: undefined;\n\tconst triggerPriceBN = triggerPrice\n\t\t? parseAmount(triggerPrice, PRICE_PRECISION)\n\t\t: undefined;\n\tconst oraclePriceOffsetBN = oraclePriceOffset\n\t\t? parseAmount(oraclePriceOffset, PRICE_PRECISION)\n\t\t: undefined;\n\n\tconst orderConfig: NonMarketOrderParamsConfig['orderConfig'] =\n\t\torderType === 'limit'\n\t\t\t? {\n\t\t\t\t\torderType,\n\t\t\t\t\tlimitPrice: limitPriceBN!,\n\t\t\t }\n\t\t\t: orderType === 'takeProfit' || orderType === 'stopLoss'\n\t\t\t? {\n\t\t\t\t\torderType,\n\t\t\t\t\ttriggerPrice: triggerPriceBN!,\n\t\t\t }\n\t\t\t: {\n\t\t\t\t\torderType,\n\t\t\t\t\toraclePriceOffset: oraclePriceOffsetBN!,\n\t\t\t };\n\n\tconsole.log('--- 📋 Open Perp Non-Market Order ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Index: ${marketIndex}`);\n\tconsole.log(\n\t\t`📊 Direction: ${direction} (${ENUM_UTILS.toStr(directionEnum)})`\n\t);\n\n\tlet amountBN: BN;\n\tif (amount) {\n\t\tconst precision = assetType === 'base' ? BASE_PRECISION : QUOTE_PRECISION;\n\t\tamountBN = parseAmount(amount, precision);\n\t\tconsole.log(`💰 Amount: ${amount} (${amountBN.toString()} raw units)`);\n\t\tconsole.log(`💱 Asset Type: ${assetType}`);\n\t} else {\n\t\tamountBN = parseAmount(baseAssetAmount, BASE_PRECISION);\n\t\tconsole.log(\n\t\t\t`💰 Base Asset Amount: ${baseAssetAmount} (${amountBN.toString()} raw units)`\n\t\t);\n\t}\n\n\tif (limitPriceBN) {\n\t\tconsole.log(\n\t\t\t`💵 Limit Price: ${limitPrice} (${limitPriceBN.toString()} raw units)`\n\t\t);\n\t}\n\tif (triggerPriceBN) {\n\t\tconsole.log(\n\t\t\t`🎯 Trigger Price: ${triggerPrice} (${triggerPriceBN.toString()} raw units)`\n\t\t);\n\t}\n\tconsole.log(`📝 Order Type: ${orderType}`);\n\tconsole.log(`🔄 Reduce Only: ${reduceOnly}`);\n\tconsole.log(`📌 Post Only: ${postOnly} (${ENUM_UTILS.toStr(postOnlyEnum)})`);\n\n\t// Just call the main method - it will handle both approaches internally\n\tconst orderTxn = await centralServerDrift.getOpenPerpNonMarketOrderTxn({\n\t\tuserAccountPublicKey: userAccountPubkey,\n\t\tmarketIndex,\n\t\tdirection: directionEnum,\n\t\torderConfig,\n\t\tuseSwift: false,\n\t\treduceOnly,\n\t\tpostOnly: postOnlyEnum,\n\t\tassetType: assetType as 'base' | 'quote',\n\t\tamount: amountBN,\n\t});\n\n\tawait executeTransaction(\n\t\torderTxn as VersionedTransaction,\n\t\t'Open Perp Non-Market Order'\n\t);\n}\n\n/**\n * CLI Command: openPerpNonMarketOrderSwift (Swift signed message limit order)\n */\nasync function openPerpNonMarketOrderSwiftCommand(\n\targs: CliArgs\n): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndex = parseInt(args.marketIndex as string);\n\tconst direction = args.direction as string;\n\tconst amount = args.amount as string;\n\tconst assetType = (args.assetType as string) || 'base';\n\tconst baseAssetAmount = args.baseAssetAmount as string;\n\tconst orderType = args.orderType as NonMarketOrderType;\n\tconst limitPrice = args.limitPrice as string;\n\tconst reduceOnly = (args.reduceOnly as string) === 'true';\n\tconst postOnly = (args.postOnly as string) || 'none';\n\tconst swiftServerUrl = API_URLS.SWIFT;\n\n\tif (!userAccount || isNaN(marketIndex) || !direction || !orderType) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndex, --direction, --orderType'\n\t\t);\n\t}\n\n\tif (!amount && !baseAssetAmount) {\n\t\tthrow new Error('Either --amount or --baseAssetAmount must be provided');\n\t}\n\n\t// Swift orders only support LIMIT order type\n\tif (orderType.toLowerCase() !== 'limit') {\n\t\tthrow new Error('Swift orders only support LIMIT order type');\n\t}\n\n\t// LIMIT orders require limitPrice\n\tif (!limitPrice) {\n\t\tthrow new Error('LIMIT orders require --limitPrice');\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst directionEnum = parseDirection(direction);\n\tconst postOnlyEnum = parsePostOnly(postOnly);\n\tconst limitPriceBN = parseAmount(limitPrice, PRICE_PRECISION);\n\n\tconst orderConfig: LimitOrderParamsOrderConfig = {\n\t\torderType: 'limit',\n\t\tlimitPrice: limitPriceBN!,\n\t};\n\n\tconsole.log('--- ⚡ Open Perp Non-Market Order Swift ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Index: ${marketIndex}`);\n\tconsole.log(\n\t\t`📊 Direction: ${direction} (${ENUM_UTILS.toStr(directionEnum)})`\n\t);\n\n\tlet amountBN: BN;\n\tif (amount) {\n\t\tconst precision = assetType === 'base' ? BASE_PRECISION : QUOTE_PRECISION;\n\t\tamountBN = parseAmount(amount, precision);\n\t\tconsole.log(`💰 Amount: ${amount} (${amountBN.toString()} raw units)`);\n\t\tconsole.log(`💱 Asset Type: ${assetType}`);\n\t} else {\n\t\tamountBN = parseAmount(baseAssetAmount, BASE_PRECISION);\n\t\tconsole.log(\n\t\t\t`💰 Base Asset Amount: ${baseAssetAmount} (${amountBN.toString()} raw units)`\n\t\t);\n\t}\n\n\tconsole.log(\n\t\t`💵 Limit Price: ${limitPrice} (${limitPriceBN.toString()} raw units)`\n\t);\n\tconsole.log(`📝 Order Type: ${orderType})`);\n\tconsole.log(`🔄 Reduce Only: ${reduceOnly}`);\n\tconsole.log(`📌 Post Only: ${postOnly} (${ENUM_UTILS.toStr(postOnlyEnum)})`);\n\tconsole.log(`⚡ Swift Server: ${swiftServerUrl}`);\n\tconsole.log(`🔑 Wallet Public Key: ${wallet.publicKey.toString()}`);\n\n\ttry {\n\t\tconst swiftOptions: CentralServerSwiftOrderOptions = {\n\t\t\twallet: {\n\t\t\t\tsignMessage: async (message: Uint8Array) => {\n\t\t\t\t\tconst signature = sign.detached(message, wallet.payer.secretKey);\n\t\t\t\t\treturn new Uint8Array(signature);\n\t\t\t\t},\n\t\t\t\ttakerAuthority: wallet.publicKey,\n\t\t\t\tsigningAuthority: wallet.publicKey,\n\t\t\t},\n\t\t\tcallbacks: createSwiftOrderCallbacks('Open Perp Non-Market Order'),\n\t\t};\n\n\t\tconsole.log('\\n👁️ Monitoring order status...');\n\n\t\t// Use the main method - it handles both approaches internally\n\t\tawait centralServerDrift.getOpenPerpNonMarketOrderTxn({\n\t\t\tuserAccountPublicKey: userAccountPubkey,\n\t\t\tmarketIndex,\n\t\t\tdirection: directionEnum,\n\t\t\torderConfig,\n\t\t\treduceOnly,\n\t\t\tpostOnly: postOnlyEnum,\n\t\t\tassetType: assetType as 'base' | 'quote',\n\t\t\tamount: amountBN,\n\t\t\tuseSwift: true,\n\t\t\tswiftOptions,\n\t\t});\n\n\t\tconsole.log('✅ [CLI] Swift order finished');\n\t} catch (error) {\n\t\tconsole.error('❌ [CLI] Error creating Swift non-market order:', error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * Show CLI usage information\n */\nfunction showUsage(): void {\n\tconsole.log('📋 Drift CLI Usage');\n\tconsole.log('');\n\tconsole.log('Available Commands:');\n\tconsole.log('');\n\n\tconsole.log('💰 deposit');\n\tconsole.log(\n\t\t' ts-node cli.ts deposit --userAccount=<pubkey> --marketIndex=<num> --amount=<num>'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts deposit --userAccount=11111111111111111111111111111111 --marketIndex=0 --amount=100'\n\t);\n\tconsole.log('');\n\n\tconsole.log('💸 withdraw');\n\tconsole.log(\n\t\t' ts-node cli.ts withdraw --userAccount=<pubkey> --marketIndex=<num> --amount=<num> [--isBorrow=<bool>] [--isMax=<bool>]'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts withdraw --userAccount=11111111111111111111111111111111 --marketIndex=0 --amount=50'\n\t);\n\tconsole.log('');\n\n\tconsole.log('🏦 settleFunding');\n\tconsole.log(' ts-node cli.ts settleFunding --userAccount=<pubkey>');\n\tconsole.log(\n\t\t' Example: ts-node cli.ts settleFunding --userAccount=11111111111111111111111111111111'\n\t);\n\tconsole.log('');\n\n\tconsole.log('📊 settlePnl');\n\tconsole.log(\n\t\t' ts-node cli.ts settlePnl --userAccount=<pubkey> --marketIndexes=<comma-separated>'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts settlePnl --userAccount=11111111111111111111111111111111 --marketIndexes=0,1'\n\t);\n\tconsole.log('');\n\n\tconsole.log('🎯 openPerpMarketOrder');\n\tconsole.log(\n\t\t' ts-node cli.ts openPerpMarketOrder --userAccount=<pubkey> --marketIndex=<num> --direction=<long|short> --amount=<num> [--assetType=<base|quote>]'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts openPerpMarketOrder --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=long --amount=0.1 --assetType=base'\n\t);\n\tconsole.log('');\n\n\tconsole.log('⚡ openPerpMarketOrderSwift');\n\tconsole.log(\n\t\t' ts-node cli.ts openPerpMarketOrderSwift --userAccount=<pubkey> --marketIndex=<num> --direction=<long|short> --amount=<num> [--assetType=<base|quote>]'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts openPerpMarketOrderSwift --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=short --amount=100 --assetType=quote'\n\t);\n\tconsole.log('');\n\n\tconsole.log('📋 openPerpNonMarketOrder');\n\tconsole.log(\n\t\t' ts-node cli.ts openPerpNonMarketOrder --userAccount=<pubkey> --marketIndex=<num> --direction=<long|short> --amount=<num> [--assetType=<base|quote>] --orderType=<limit|trigger_limit|trigger_market|oracle> [--limitPrice=<num>] [--triggerPrice=<num>] [--reduceOnly=<true|false>] [--postOnly=<none|must_post_only|try_post_only|slide>]'\n\t);\n\tconsole.log(\n\t\t' New LIMIT: ts-node cli.ts openPerpNonMarketOrder --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=long --amount=0.1 --assetType=base --orderType=limit --limitPrice=100'\n\t);\n\tconsole.log(\n\t\t' New QUOTE: ts-node cli.ts openPerpNonMarketOrder --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=long --amount=100 --assetType=quote --orderType=limit --limitPrice=100'\n\t);\n\tconsole.log(\n\t\t' Legacy: ts-node cli.ts openPerpNonMarketOrder --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=long --baseAssetAmount=0.1 --orderType=limit --limitPrice=100'\n\t);\n\tconsole.log('');\n\n\tconsole.log('⚡ openPerpNonMarketOrderSwift');\n\tconsole.log(\n\t\t' ts-node cli.ts openPerpNonMarketOrderSwift --userAccount=<pubkey> --marketIndex=<num> --direction=<long|short> --amount=<num> [--assetType=<base|quote>] --orderType=limit --limitPrice=<num> [--reduceOnly=<true|false>] [--postOnly=<none|must_post_only|try_post_only|slide>]'\n\t);\n\tconsole.log(\n\t\t' New: ts-node cli.ts openPerpNonMarketOrderSwift --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=long --amount=0.1 --assetType=base --orderType=limit --limitPrice=99.5'\n\t);\n\tconsole.log(\n\t\t' Legacy: ts-node cli.ts openPerpNonMarketOrderSwift --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=long --baseAssetAmount=0.1 --orderType=limit --limitPrice=99.5'\n\t);\n\tconsole.log('');\n\n\tconsole.log('✏️ editOrder');\n\tconsole.log(\n\t\t' ts-node cli.ts editOrder --userAccount=<pubkey> --orderId=<num> [--newDirection=<long|short>] [--newBaseAmount=<num>] [--newLimitPrice=<num>] [--newTriggerPrice=<num>] [--reduceOnly=<true|false>] [--postOnly=<true|false>]'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts editOrder --userAccount=11111111111111111111111111111111 --orderId=123 --newLimitPrice=105.5'\n\t);\n\tconsole.log('');\n\n\tconsole.log('❌ cancelOrder');\n\tconsole.log(\n\t\t' ts-node cli.ts cancelOrder --userAccount=<pubkey> --orderIds=<comma-separated-list>'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts cancelOrder --userAccount=11111111111111111111111111111111 --orderIds=123,456,789'\n\t);\n\tconsole.log('');\n\n\tconsole.log('🧹 cancelAllOrders');\n\tconsole.log(\n\t\t' ts-node cli.ts cancelAllOrders --userAccount=<pubkey> [--marketType=<perp|spot>] [--marketIndex=<num>] [--direction=<long|short>]'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts cancelAllOrders --userAccount=11111111111111111111111111111111 --marketType=perp'\n\t);\n\tconsole.log('');\n\n\tconsole.log('🔄 swap');\n\tconsole.log(\n\t\t' ts-node cli.ts swap --userAccount=<pubkey> --fromMarketIndex=<num> --toMarketIndex=<num> [--fromAmount=<num>] [--toAmount=<num>] [--slippage=<bps>] [--swapMode=<ExactIn|ExactOut>]'\n\t);\n\tconsole.log(\n\t\t' ExactIn: ts-node cli.ts swap --userAccount=11111111111111111111111111111111 --fromMarketIndex=1 --toMarketIndex=0 --fromAmount=1.5 --swapMode=ExactIn'\n\t);\n\tconsole.log(\n\t\t' ExactOut: ts-node cli.ts swap --userAccount=11111111111111111111111111111111 --fromMarketIndex=1 --toMarketIndex=0 --toAmount=150 --swapMode=ExactOut'\n\t);\n\tconsole.log('');\n\n\tconsole.log('Options:');\n\tconsole.log(' --help, -h Show this help message');\n\tconsole.log('');\n\tconsole.log('Notes:');\n\tconsole.log(\n\t\t' - Amounts are in human-readable format (e.g., 1.5 USDC, 0.1 SOL)'\n\t);\n\tconsole.log(' - Direction can be: long, short, buy, sell');\n\tconsole.log(\n\t\t' - Asset type: base (for native tokens like SOL) or quote (for USDC amounts)'\n\t);\n\tconsole.log(' - Swap modes:');\n\tconsole.log(\n\t\t' * ExactIn: Specify --fromAmount (how much input token to swap)'\n\t);\n\tconsole.log(\n\t\t' * ExactOut: Specify --toAmount (how much output token to receive)'\n\t);\n\tconsole.log(' - Ensure your .env file contains ANCHOR_WALLET and ENDPOINT');\n}\n\n/**\n * CLI Command: editOrder\n */\nasync function editOrderCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst orderId = parseInt(args.orderId as string);\n\tconst newDirection = args.newDirection as string;\n\tconst newBaseAmount = args.newBaseAmount as string;\n\tconst newLimitPrice = args.newLimitPrice as string;\n\tconst newTriggerPrice = args.newTriggerPrice as string;\n\tconst reduceOnly = (args.reduceOnly as string) === 'true';\n\tconst postOnly = (args.postOnly as string) === 'true';\n\n\tif (!userAccount || isNaN(orderId)) {\n\t\tthrow new Error('Required arguments: --userAccount, --orderId');\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst editParams: any = {};\n\n\tif (newDirection) {\n\t\teditParams.newDirection = parseDirection(newDirection);\n\t}\n\n\tif (newBaseAmount) {\n\t\teditParams.newBaseAmount = parseAmount(newBaseAmount, BASE_PRECISION);\n\t}\n\n\tif (newLimitPrice) {\n\t\teditParams.newLimitPrice = parseAmount(newLimitPrice, PRICE_PRECISION);\n\t}\n\n\tif (newTriggerPrice) {\n\t\teditParams.newTriggerPrice = parseAmount(newTriggerPrice, PRICE_PRECISION);\n\t}\n\n\tif (reduceOnly) {\n\t\teditParams.reduceOnly = true;\n\t}\n\n\tif (postOnly) {\n\t\teditParams.postOnly = true;\n\t}\n\n\tconsole.log('--- ✏️ Edit Order ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🆔 Order ID: ${orderId}`);\n\tconsole.log(`📝 Edit Parameters:`, editParams);\n\n\tconst editOrderTxn = await centralServerDrift.getEditOrderTxn(\n\t\tuserAccountPubkey,\n\t\torderId,\n\t\teditParams\n\t);\n\n\tawait executeTransaction(editOrderTxn as VersionedTransaction, 'Edit Order');\n}\n\n/**\n * CLI Command: cancelOrder\n */\nasync function cancelOrderCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst orderIds = args.orderIds as string;\n\n\tif (!userAccount || !orderIds) {\n\t\tthrow new Error('Required arguments: --userAccount, --orderIds');\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst orderIdArray = orderIds.split(',').map((id) => parseInt(id.trim()));\n\n\tconsole.log('--- ❌ Cancel Orders ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🆔 Order IDs: ${orderIdArray.join(', ')}`);\n\n\tconst cancelOrderTxn = await centralServerDrift.getCancelOrdersTxn(\n\t\tuserAccountPubkey,\n\t\torderIdArray\n\t);\n\n\tawait executeTransaction(\n\t\tcancelOrderTxn as VersionedTransaction,\n\t\t'Cancel Orders'\n\t);\n}\n\n/**\n * CLI Command: cancelAllOrders\n */\nasync function cancelAllOrdersCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketType = args.marketType as string;\n\tconst marketIndex = args.marketIndex\n\t\t? parseInt(args.marketIndex as string)\n\t\t: undefined;\n\tconst direction = args.direction as string;\n\n\tif (!userAccount) {\n\t\tthrow new Error('Required arguments: --userAccount');\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tlet marketTypeEnum = undefined;\n\tlet directionEnum = undefined;\n\n\tif (marketType) {\n\t\tmarketTypeEnum =\n\t\t\tmarketType.toLowerCase() === 'perp' ? { perp: {} } : { spot: {} };\n\t}\n\n\tif (direction) {\n\t\tdirectionEnum = parseDirection(direction);\n\t}\n\n\tconsole.log('--- 🧹 Cancel All Orders ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Type Filter: ${marketType || 'none'}`);\n\tconsole.log(\n\t\t`📊 Market Index Filter: ${\n\t\t\tmarketIndex !== undefined ? marketIndex : 'none'\n\t\t}`\n\t);\n\tconsole.log(`📈 Direction Filter: ${direction || 'none'}`);\n\n\tconst cancelAllOrdersTxn = await centralServerDrift.getCancelAllOrdersTxn(\n\t\tuserAccountPubkey,\n\t\tmarketTypeEnum,\n\t\tmarketIndex,\n\t\tdirectionEnum\n\t);\n\n\tawait executeTransaction(\n\t\tcancelAllOrdersTxn as VersionedTransaction,\n\t\t'Cancel All Orders'\n\t);\n}\n\n/**\n * CLI Command: swap\n */\nasync function swapCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst fromMarketIndex = parseInt(args.fromMarketIndex as string);\n\tconst toMarketIndex = parseInt(args.toMarketIndex as string);\n\tconst fromAmount = args.fromAmount as string;\n\tconst toAmount = args.toAmount as string;\n\tconst slippage = args.slippage ? parseInt(args.slippage as string) : 10; // Default 0.1%\n\tconst swapMode = (args.swapMode as string) || 'ExactIn';\n\n\tif (!userAccount || isNaN(fromMarketIndex) || isNaN(toMarketIndex)) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --fromMarketIndex, --toMarketIndex'\n\t\t);\n\t}\n\n\tconst swapModeEnum = parseSwapMode(swapMode);\n\n\t// Validate amount parameters based on swap mode\n\tif (swapModeEnum === 'ExactIn') {\n\t\tif (!fromAmount) {\n\t\t\tthrow new Error('ExactIn swap mode requires --fromAmount');\n\t\t}\n\t\tif (toAmount) {\n\t\t\tconsole.warn(\n\t\t\t\t'⚠️ Warning: --toAmount ignored in ExactIn mode, using --fromAmount'\n\t\t\t);\n\t\t}\n\t} else if (swapModeEnum === 'ExactOut') {\n\t\tif (!toAmount) {\n\t\t\tthrow new Error('ExactOut swap mode requires --toAmount');\n\t\t}\n\t\tif (fromAmount) {\n\t\t\tconsole.warn(\n\t\t\t\t'⚠️ Warning: --fromAmount ignored in ExactOut mode, using --toAmount'\n\t\t\t);\n\t\t}\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\n\t// Use the appropriate amount based on swap mode\n\tconst amount = swapModeEnum === 'ExactIn' ? fromAmount : toAmount;\n\n\t// Determine which market to use for precision (input market for ExactIn, output market for ExactOut)\n\tconst precisionMarketIndex =\n\t\tswapModeEnum === 'ExactIn' ? fromMarketIndex : toMarketIndex;\n\n\t// Get the appropriate precision for the amount based on the market\n\tconst isMainnet = true; // Default to mainnet, could be made configurable\n\tconst precision = getMarketPrecision(precisionMarketIndex, isMainnet);\n\tconst amountBN = parseAmount(amount, precision);\n\n\tconsole.log('--- 🔄 Swap Transaction ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`📤 From Market Index: ${fromMarketIndex}`);\n\tconsole.log(`📥 To Market Index: ${toMarketIndex}`);\n\tconsole.log(`🔄 Swap Mode: ${swapMode}`);\n\tconsole.log(\n\t\t`🎯 Using precision from market ${precisionMarketIndex}: ${precision.toString()}`\n\t);\n\n\tif (swapModeEnum === 'ExactIn') {\n\t\tconsole.log(\n\t\t\t`💰 From Amount: ${fromAmount} (${amountBN.toString()} raw units)`\n\t\t);\n\t\tconsole.log(`💰 To Amount: Will be calculated based on quote`);\n\t} else {\n\t\tconsole.log(`💰 From Amount: Will be calculated based on quote`);\n\t\tconsole.log(`💰 To Amount: ${toAmount} (${amountBN.toString()} raw units)`);\n\t}\n\n\tconsole.log(`📊 Slippage: ${slippage} BPS (${slippage / 100}%)`);\n\n\tconst swapTxn = await centralServerDrift.getSwapTxn(\n\t\tuserAccountPubkey,\n\t\tfromMarketIndex,\n\t\ttoMarketIndex,\n\t\tamountBN,\n\t\t{\n\t\t\tslippageBps: slippage,\n\t\t\tswapMode: swapModeEnum,\n\t\t}\n\t);\n\n\tawait executeTransaction(swapTxn as VersionedTransaction, 'Swap');\n}\n\n/**\n * Main CLI entry point\n */\nasync function main(): Promise<void> {\n\tconst args = process.argv.slice(2);\n\n\tif (\n\t\targs.length === 0 ||\n\t\targs[0] === '--help' ||\n\t\targs[0] === '-h' ||\n\t\targs[0] === 'help'\n\t) {\n\t\tshowUsage();\n\t\treturn;\n\t}\n\n\tconst command = args[0];\n\tconst parsedArgs = parseArgs(args.slice(1));\n\n\t// Initialize the client first\n\tawait initializeCentralServerDrift();\n\n\t// Route to appropriate command\n\tswitch (command) {\n\t\tcase 'deposit':\n\t\t\tawait depositCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'withdraw':\n\t\t\tawait withdrawCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'settleFunding':\n\t\t\tawait settleFundingCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'settlePnl':\n\t\t\tawait settlePnlCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'openPerpMarketOrder':\n\t\t\tawait openPerpMarketOrderCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'openPerpMarketOrderSwift':\n\t\t\tawait openPerpMarketOrderSwiftCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'openPerpNonMarketOrder':\n\t\t\tawait openPerpNonMarketOrderCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'openPerpNonMarketOrderSwift':\n\t\t\tawait openPerpNonMarketOrderSwiftCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'editOrder':\n\t\t\tawait editOrderCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'cancelOrder':\n\t\t\tawait cancelOrderCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'cancelAllOrders':\n\t\t\tawait cancelAllOrdersCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'swap':\n\t\t\tawait swapCommand(parsedArgs);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tconsole.error(`❌ Unknown command: ${command}`);\n\t\t\tconsole.error('');\n\t\t\tshowUsage();\n\t\t\tprocess.exit(1);\n\t}\n}\n\n// Run CLI if this file is executed directly\nif (require.main === module) {\n\tmain()\n\t\t.then(() => {\n\t\t\tconsole.log('\\n✨ Command executed successfully!');\n\t\t\t// Don't exit immediately for Swift orders (they need time to process)\n\t\t\tsetTimeout(() => process.exit(0), 2000);\n\t\t})\n\t\t.catch((error) => {\n\t\t\tconsole.error('\\n💥 Command failed:', error.message || error);\n\t\t\tprocess.exit(1);\n\t\t});\n}\n\nexport { main, parseArgs, parseAmount, parseDirection, parseSwapMode };\n"]}
|