@drift-labs/common 1.0.6 → 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/Drift/clients/{CentralServerDrift.d.ts → CentralServerDrift/index.d.ts} +10 -10
- package/lib/drift/Drift/clients/{CentralServerDrift.js → CentralServerDrift/index.js} +71 -27
- package/lib/drift/Drift/clients/CentralServerDrift/index.js.map +1 -0
- package/lib/drift/Drift/clients/CentralServerDrift/types.d.ts +12 -0
- package/lib/drift/Drift/clients/CentralServerDrift/types.js +3 -0
- package/lib/drift/Drift/clients/CentralServerDrift/types.js.map +1 -0
- package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.d.ts +9 -5
- 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.d.ts +7 -4
- 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 -7
- package/lib/drift/cli.js.map +1 -1
- package/package.json +1 -1
- package/lib/drift/Drift/clients/CentralServerDrift.js.map +0 -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,EACz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7C,iBAAiB,EAAE,KAAM;IACzB,wBAAwB,EAAE,IAAI;IAC9B,4BAA4B,EAAE,GAAG;CACjC,CAAC;AAEc,uCAAuB,GAAG,IAAI,GAAG,EAAE,GAAG,OAAS,CAAC,CAAC,+GAA+G;AA4oBjL;;;;;;;;;;;GAWG","sourcesContent":["import {\n\tBigNum,\n\tDriftClient,\n\tJupiterClient,\n\tMarketType,\n\tMAX_LEVERAGE_ORDER_SIZE,\n\tQuoteResponse,\n\tSwapMode,\n\tTxParams,\n\tUser,\n\tZERO,\n} from '@drift-labs/sdk';\nimport { TransactionSignature } from '@solana/web3.js';\nimport { MARKET_UTILS } from '../../../../../common-ui-utils/market';\nimport { MAIN_POOL_ID } from '../../../../../constants';\nimport { TRADING_UTILS } from '../../../../../common-ui-utils/trading';\nimport { UserAccountCache } from '../../../stores/UserAccountCache';\nimport { createDepositTxn } from '../../../../base/actions/spot/deposit';\nimport { createUserAndDepositCollateralBaseTxn } from '../../../../base/actions/user/create';\nimport { createWithdrawTxn } from '../../../../base/actions/spot/withdraw';\nimport { deleteUserTxn } from '../../../../base/actions/user/delete';\nimport { createSettlePnlTxn } from '../../../../base/actions/perp/settlePnl';\nimport {\n\tCreateUserAndDepositParams,\n\tDepositParams,\n\tWithdrawParams,\n\tPerpOrderParams,\n\tSwapParams,\n\tSettleAccountPnlParams,\n\tCancelOrdersParams,\n} from './types';\nimport { createCancelOrdersTxn } from '../../../../base/actions/trade/cancelOrder';\nimport {\n\tcreateOpenPerpMarketOrder,\n\tOpenPerpMarketOrderParams,\n} from '../../../../base/actions/trade/openPerpOrder/openPerpMarketOrder';\nimport { createSwapTxn } from '../../../../base/actions/trade/swap';\nimport { createOpenPerpNonMarketOrder } from '../../../../base/actions/trade/openPerpOrder/openPerpNonMarketOrder';\n\n/**\n * Handles majority of the relevant operations on the Drift program including deposits,\n * withdrawals, position management, and trading operations.\n *\n * This class encapsulates the trading logic and provides a clean API for\n * executing various trading operations while handling common patterns like\n * token address resolution and transaction preparation.\n */\nexport class DriftOperations {\n\tstatic readonly DEFAULT_TX_PARAMS: TxParams = {\n\t\tcomputeUnitsPrice: 50_000,\n\t\tuseSimulatedComputeUnits: true,\n\t\tcomputeUnitsBufferMultiplier: 1.3,\n\t};\n\n\tstatic readonly MAX_COMPUTE_UNITS_PRICE = 1e15 / 10 / 1_400_000; // 1e15 = 1 SOL worth of micro lamports; 1e15 / 10 = 0.1 SOL worth of micro lamports; 1.4M = max compute units;\n\n\t/**\n\t * Creates a new DriftOperations instance.\n\t *\n\t * @param driftClient - The DriftClient instance for executing transactions\n\t * @param getUserAccountCache - Function to get the user account cache. We lazily load the user account cache, so that we always get the latest user account data.\n\t * @param getPriorityFee - Function to get current priority fee in micro lamports\n\t */\n\tconstructor(\n\t\tprivate driftClient: DriftClient,\n\t\tprivate getUserAccountCache: () => UserAccountCache,\n\t\tprivate dlobServerHttpUrl: string,\n\t\tprivate swiftServerUrl: string,\n\t\tprivate getPriorityFee: () => number\n\t) {}\n\n\t/**\n\t * Gets transaction parameters with dynamic priority fees.\n\t * Falls back to default if priority fee function is not available.\n\t */\n\tprivate getTxParams(overrides?: Partial<TxParams>): TxParams {\n\t\tconst unsafePriorityFee = Math.floor(\n\t\t\tthis.getPriorityFee() ??\n\t\t\t\tDriftOperations.DEFAULT_TX_PARAMS.computeUnitsPrice\n\t\t);\n\n\t\tconst safePriorityFee = Math.min(\n\t\t\tunsafePriorityFee,\n\t\t\tDriftOperations.MAX_COMPUTE_UNITS_PRICE\n\t\t);\n\n\t\treturn {\n\t\t\t...DriftOperations.DEFAULT_TX_PARAMS,\n\t\t\tcomputeUnitsPrice: safePriorityFee,\n\t\t\t...overrides,\n\t\t};\n\t}\n\n\t/**\n\t * Creates a new user account and deposits initial collateral.\n\t *\n\t * This method handles the complete onboarding flow for new users including:\n\t * - Validating that the subaccount doesn't already exist\n\t * - Resolving referrer information if provided\n\t * - Getting the correct token address for deposits\n\t * - Creating the user account with custom leverage settings\n\t * - Subscribing to the new user's account updates\n\t *\n\t * @param params - The parameters for user creation and initial deposit\n\t * @returns Promise resolving to transaction signature and user account public key\n\t *\n\t * @throws Error if subaccount already exists\n\t *\n\t * @example\n\t * ```typescript\n\t * const result = await tradingOps.createUserAndDeposit({\n\t * depositAmount: new BigNum(100),\n\t * depositSpotMarketIndex: 0, // USDC\n\t * name: \"Trading Account\",\n\t * maxLeverage: 5,\n\t * subAccountId: 0\n\t * });\n\t * ```\n\t */\n\tasync createUserAndDeposit(params: CreateUserAndDepositParams): Promise<{\n\t\ttxSig: TransactionSignature;\n\t\tuser: User;\n\t}> {\n\t\tconst {\n\t\t\tdepositAmount,\n\t\t\tdepositSpotMarketIndex,\n\t\t\tnewAccountName,\n\t\t\tmaxLeverage,\n\t\t\tpoolId = MAIN_POOL_ID,\n\t\t\treferrerName,\n\t\t} = params;\n\n\t\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tdepositSpotMarketIndex\n\t\t);\n\n\t\tconst customMaxMarginRatio = TRADING_UTILS.convertLeverageToMarginRatio(\n\t\t\tmaxLeverage ?? 0\n\t\t);\n\n\t\tconst { transaction, subAccountId } =\n\t\t\tawait createUserAndDepositCollateralBaseTxn({\n\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\tamount: depositAmount.val,\n\t\t\t\tspotMarketConfig: spotMarketConfig,\n\t\t\t\tauthority: this.driftClient.wallet.publicKey,\n\t\t\t\tuserStatsAccount: this.driftClient.userStats?.getAccount(),\n\t\t\t\taccountName: newAccountName,\n\t\t\t\treferrerName,\n\t\t\t\tcustomMaxMarginRatio,\n\t\t\t\tpoolId,\n\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(transaction);\n\n\t\tawait this.driftClient.addUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t); // adds user to driftclient's user map, subscribes to user account data\n\t\tconst user = this.driftClient.getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tuser.eventEmitter.on('update', () => {\n\t\t\tthis.getUserAccountCache().updateUserAccount(user);\n\t\t});\n\n\t\treturn {\n\t\t\ttxSig,\n\t\t\tuser,\n\t\t};\n\t}\n\n\t/**\n\t * Deletes a user account.\n\t *\n\t * This method removes a user's sub-account from the Drift.\n\t *\n\t * @param subAccountId - The ID of the sub-account to delete\n\t * @returns A promise that resolves to the transaction signature of the deletion\n\t *\n\t * @throws {Error} When the user account is not found in the cache\n\t *\n\t * @example\n\t * ```typescript\n\t * // Delete user sub-account with ID 0\n\t * const txSignature = await tradingOps.deleteUser(0);\n\t * console.log('User deleted with transaction:', txSignature);\n\t * ```\n\t */\n\tasync deleteUser(subAccountId: number): Promise<TransactionSignature> {\n\t\tconst user = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!user) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst deleteTxn = await deleteUserTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuser: user.userClient,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(deleteTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Deposits collateral into a user's spot market position.\n\t *\n\t * This method handles depositing tokens into a user's account, with optional\n\t * support for max borrow repayment scenarios where the deposit amount may be\n\t * over-estimated to ensure complete repayment of borrowed funds.\n\t *\n\t * @param params - The deposit parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.deposit({\n\t * subAccountId: 0,\n\t * amount: new BigNum(50),\n\t * spotMarketIndex: 0, // USDC\n\t * isMaxBorrowRepayment: false\n\t * });\n\t * ```\n\t */\n\tasync deposit(params: DepositParams): Promise<TransactionSignature> {\n\t\tconst { subAccountId, amount, spotMarketIndex, isMaxBorrowRepayment } =\n\t\t\tparams;\n\n\t\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tspotMarketIndex\n\t\t);\n\n\t\tconst user = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!user) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst depositTxn = await createDepositTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuser: user.userClient,\n\t\t\tamount: amount,\n\t\t\tspotMarketConfig: spotMarketConfig,\n\t\t\tisMaxBorrowRepayment,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(depositTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Withdraws collateral from a user's spot market position.\n\t *\n\t * This method handles withdrawing tokens from a user's account with options\n\t * for borrowing (if allowBorrow is true) or reduce-only withdrawals. For max\n\t * withdrawals with reduce-only, the amount is over-estimated to ensure\n\t * complete withdrawal.\n\t *\n\t * @param params - The withdrawal parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.withdraw({\n\t * subAccountId: 0,\n\t * amount: new BigNum(25),\n\t * spotMarketIndex: 0, // USDC\n\t * allowBorrow: false,\n\t * isMax: false\n\t * });\n\t * ```\n\t */\n\tasync withdraw(params: WithdrawParams): Promise<TransactionSignature> {\n\t\tconst {\n\t\t\tsubAccountId,\n\t\t\tamount,\n\t\t\tspotMarketIndex,\n\t\t\tisBorrow = false,\n\t\t\tisMax = false,\n\t\t} = params;\n\n\t\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tspotMarketIndex\n\t\t);\n\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst withdrawTxn = await createWithdrawTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tamount,\n\t\t\tspotMarketConfig,\n\t\t\tuser: accountData.userClient,\n\t\t\tisBorrow,\n\t\t\tisMax,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(withdrawTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Opens a perpetual market order (placeholder for future implementation).\n\t *\n\t * This method will handle opening long or short positions in perpetual markets\n\t * with support for market and limit orders, reduce-only orders, and post-only orders.\n\t *\n\t * @param params - The perp order parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.openPerpMarketOrder({\n\t * marketIndex: 0, // SOL-PERP\n\t * direction: 'long',\n\t * baseAssetAmount: new BigNum(1), // 1 SOL\n\t * orderType: 'market',\n\t * subAccountId: 0\n\t * });\n\t * ```\n\t */\n\tasync openPerpOrder(\n\t\tparams: PerpOrderParams\n\t): Promise<TransactionSignature | void> {\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tparams.subAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst user = accountData.userClient;\n\n\t\tconst processBracketOrders = (bracketOrdersInput?: {\n\t\t\ttakeProfitPrice?: BigNum;\n\t\t\tstopLossPrice?: BigNum;\n\t\t}) => {\n\t\t\tconst bracketOrders: OpenPerpMarketOrderParams['bracketOrders'] = {};\n\n\t\t\tif (bracketOrdersInput?.takeProfitPrice) {\n\t\t\t\tbracketOrders.takeProfit = {\n\t\t\t\t\ttriggerPrice: bracketOrdersInput.takeProfitPrice.val,\n\t\t\t\t\tbaseAssetAmount: params.size.val,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (bracketOrdersInput?.stopLossPrice) {\n\t\t\t\tbracketOrders.stopLoss = {\n\t\t\t\t\ttriggerPrice: bracketOrdersInput.stopLossPrice.val,\n\t\t\t\t\tbaseAssetAmount: params.size.val,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn bracketOrders;\n\t\t};\n\n\t\tconst amountBN = params.isMaxLeverage\n\t\t\t? MAX_LEVERAGE_ORDER_SIZE\n\t\t\t: params.size.val;\n\n\t\tswitch (params.orderConfig.orderType) {\n\t\t\tcase 'market': {\n\t\t\t\tconst useSwift = !params.orderConfig.disableSwift;\n\n\t\t\t\tconst bracketOrders = processBracketOrders(\n\t\t\t\t\tparams.orderConfig.bracketOrders\n\t\t\t\t);\n\n\t\t\t\t// we split the logic for SWIFT and non-SWIFT orders to achieve better type inference\n\t\t\t\tif (useSwift) {\n\t\t\t\t\tconst swiftOrderResult = await createOpenPerpMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\tuseSwift: true,\n\t\t\t\t\t\tswiftOptions: {\n\t\t\t\t\t\t\t// @ts-ignore TODO: we might want to add signMessage to the IWallet interface\n\t\t\t\t\t\t\twallet: this.driftClient.wallet,\n\t\t\t\t\t\t\tswiftServerUrl: this.swiftServerUrl,\n\t\t\t\t\t\t\t...params.orderConfig.swiftOptions,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\tdlobServerHttpUrl: this.dlobServerHttpUrl,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\toptionalAuctionParamsInputs:\n\t\t\t\t\t\t\tparams.orderConfig.optionalAuctionParamsInputs,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn swiftOrderResult;\n\t\t\t\t} else {\n\t\t\t\t\tconst result = await createOpenPerpMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\toptionalAuctionParamsInputs:\n\t\t\t\t\t\t\tparams.orderConfig.optionalAuctionParamsInputs,\n\t\t\t\t\t\tdlobServerHttpUrl: this.dlobServerHttpUrl,\n\t\t\t\t\t\tuseSwift: false,\n\t\t\t\t\t});\n\n\t\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(result);\n\n\t\t\t\t\treturn txSig;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcase 'limit': {\n\t\t\t\tconst useSwift = !params.orderConfig.disableSwift;\n\n\t\t\t\tconst bracketOrders = processBracketOrders(\n\t\t\t\t\tparams.orderConfig.bracketOrders\n\t\t\t\t);\n\n\t\t\t\t// we split the logic for SWIFT and non-SWIFT orders to achieve better type inference\n\t\t\t\tif (useSwift) {\n\t\t\t\t\tconst swiftOrderResult = await createOpenPerpNonMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\torderConfig: {\n\t\t\t\t\t\t\torderType: 'limit',\n\t\t\t\t\t\t\tlimitPrice: params.orderConfig.limitPrice.val,\n\t\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\t},\n\t\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\t\tpostOnly: params.postOnly,\n\t\t\t\t\t\tuseSwift: true,\n\t\t\t\t\t\tswiftOptions: {\n\t\t\t\t\t\t\t// @ts-ignore TODO: we might want to add signMessage to the IWallet interface\n\t\t\t\t\t\t\twallet: this.driftClient.wallet,\n\t\t\t\t\t\t\tswiftServerUrl: this.swiftServerUrl,\n\t\t\t\t\t\t\t...params.orderConfig.swiftOptions,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\n\t\t\t\t\treturn swiftOrderResult;\n\t\t\t\t} else {\n\t\t\t\t\tconst txn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\torderConfig: {\n\t\t\t\t\t\t\torderType: 'limit',\n\t\t\t\t\t\t\tlimitPrice: params.orderConfig.limitPrice.val,\n\t\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\t},\n\t\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\t\tpostOnly: params.postOnly,\n\t\t\t\t\t\tuseSwift: false,\n\t\t\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t\t\t});\n\n\t\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\t\t\t\treturn txSig;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcase 'takeProfit':\n\t\t\tcase 'stopLoss': {\n\t\t\t\tconst txn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\tamount: amountBN,\n\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\torderConfig: {\n\t\t\t\t\t\torderType: params.orderConfig.orderType,\n\t\t\t\t\t\ttriggerPrice: params.orderConfig.triggerPrice.val,\n\t\t\t\t\t\tlimitPrice: params.orderConfig.limitPrice?.val ?? ZERO,\n\t\t\t\t\t},\n\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\tuseSwift: false,\n\t\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t\t});\n\n\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\t\t\treturn txSig;\n\t\t\t}\n\t\t\tcase 'oracleLimit': {\n\t\t\t\tconst txn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\tamount: amountBN,\n\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\torderConfig: {\n\t\t\t\t\t\torderType: 'oracleLimit',\n\t\t\t\t\t\toraclePriceOffset: params.orderConfig.oraclePriceOffset.val,\n\t\t\t\t\t},\n\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\tuseSwift: false,\n\t\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t\t});\n\n\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\t\t\treturn txSig;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tconst _exhaustiveCheck: never = params.orderConfig;\n\t\t\t\tthrow new Error('Invalid order type');\n\t\t\t}\n\t\t}\n\t}\n\n\tasync getSwapQuote(\n\t\tparams: Omit<SwapParams, 'jupiterQuote'> & {\n\t\t\tslippageBps?: number;\n\t\t\tswapMode?: SwapMode;\n\t\t\tonlyDirectRoutes?: boolean;\n\t\t}\n\t): Promise<QuoteResponse> {\n\t\tconst jupiterClient = new JupiterClient({\n\t\t\tconnection: this.driftClient.connection,\n\t\t});\n\n\t\tconst inputMint = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tparams.fromMarketIndex\n\t\t).mint;\n\t\tconst outputMint = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tparams.toMarketIndex\n\t\t).mint;\n\n\t\tconst jupiterQuote = await jupiterClient.getQuote({\n\t\t\tinputMint,\n\t\t\toutputMint,\n\t\t\tamount: params.amount.val,\n\t\t\tslippageBps: params.slippageBps,\n\t\t\tswapMode: params.swapMode,\n\t\t\tonlyDirectRoutes: params.onlyDirectRoutes,\n\t\t});\n\n\t\treturn jupiterQuote;\n\t}\n\n\t/**\n\t * Executes a swap between two spot markets (placeholder for future implementation).\n\t *\n\t * This method will handle swapping between different spot markets through\n\t * the Drift protocol's swap functionality.\n\t *\n\t * @param params - The swap parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.executeSwap({\n\t * fromMarketIndex: 0, // USDC\n\t * toMarketIndex: 1, // SOL\n\t * amount: new BigNum(100),\n\t * subAccountId: 0,\n\t * minReceiveAmount: new BigNum(0.5)\n\t * });\n\t * ```\n\t */\n\tasync swap(params: SwapParams): Promise<TransactionSignature> {\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tparams.subAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst jupiterClient = new JupiterClient({\n\t\t\tconnection: this.driftClient.connection,\n\t\t});\n\n\t\tconst jupiterQuote = params.jupiterQuote\n\t\t\t? params.jupiterQuote\n\t\t\t: await this.getSwapQuote(params);\n\n\t\tconst swapTxn = await createSwapTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tjupiterClient,\n\t\t\tuser: accountData.userClient,\n\t\t\tswapFromMarketIndex: params.fromMarketIndex,\n\t\t\tswapToMarketIndex: params.toMarketIndex,\n\t\t\tamount: params.amount.val,\n\t\t\tquote: jupiterQuote,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(swapTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Settles P&L and funding for all perp position.\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.settlePnl({\n\t * subAccountId: 0,\n\t * marketIndex: 0, // SOL-PERP\n\t * counterpartySubAccountId: 1\n\t * });\n\t * ```\n\t */\n\tasync settleAccountPnl(\n\t\tparams: SettleAccountPnlParams\n\t): Promise<TransactionSignature> {\n\t\tconst { subAccountId } = params;\n\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst marketIndexes = accountData.openPerpPositions.map(\n\t\t\t(position) => position.marketIndex\n\t\t);\n\n\t\tconst settlePnlTxn = await createSettlePnlTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuser: accountData.userClient,\n\t\t\tmarketIndexes,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(settlePnlTxn);\n\n\t\treturn txSig;\n\t}\n\n\tasync cancelOrders(\n\t\tparams: CancelOrdersParams\n\t): Promise<TransactionSignature> {\n\t\tconst { subAccountId, orderIds } = params;\n\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst cancelOrdersTxn = await createCancelOrdersTxn(\n\t\t\tthis.driftClient,\n\t\t\taccountData.userClient,\n\t\t\torderIds,\n\t\t\tthis.getTxParams()\n\t\t);\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(cancelOrdersTxn);\n\n\t\treturn txSig;\n\t}\n}\n\n/**\n * TODO:\n * - transfer between subaccounts\n * - close position?\n * - close multiple positions\n * - edit open order\n * - create user only\n *\n * - open spot order\n * - rename subaccount\n * - withdraw dust positions\n */\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/drift/Drift/clients/AuthorityDrift/DriftOperations/index.ts"],"names":[],"mappings":";;;AAAA,yCAYyB;AAEzB,kEAAqE;AACrE,wDAAwD;AACxD,oEAAuE;AAEvE,mEAAyE;AACzE,iEAA6F;AAC7F,qEAA2E;AAC3E,iEAAqE;AACrE,uEAA6E;AAU7E,4EAAmF;AACnF,0GAG0E;AAC1E,8DAAoE;AACpE,gHAAmH;AAEnH;;;;;;;GAOG;AACH,MAAa,eAAe;IAS3B;;;;;;OAMG;IACH,YACS,WAAwB,EACxB,mBAA2C,EAC3C,iBAAyB,EACzB,cAAsB,EACtB,cAA4B;QAJ5B,gBAAW,GAAX,WAAW,CAAa;QACxB,wBAAmB,GAAnB,mBAAmB,CAAwB;QAC3C,sBAAiB,GAAjB,iBAAiB,CAAQ;QACzB,mBAAc,GAAd,cAAc,CAAQ;QACtB,mBAAc,GAAd,cAAc,CAAc;IAClC,CAAC;IAEJ;;;OAGG;IACK,WAAW,CAAC,SAA6B;;QAChD,MAAM,iBAAiB,GAAG,IAAI,CAAC,KAAK,CACnC,MAAA,IAAI,CAAC,cAAc,EAAE,mCACpB,eAAe,CAAC,iBAAiB,CAAC,iBAAiB,CACpD,CAAC;QAEF,MAAM,eAAe,GAAG,IAAI,CAAC,GAAG,CAC/B,iBAAiB,EACjB,eAAe,CAAC,uBAAuB,CACvC,CAAC;QAEF,OAAO;YACN,GAAG,eAAe,CAAC,iBAAiB;YACpC,iBAAiB,EAAE,eAAe;YAClC,GAAG,SAAS;SACZ,CAAC;IACH,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;;;;;OAyBG;IACH,KAAK,CAAC,oBAAoB,CAAC,MAAkC;;QAI5D,MAAM,EACL,aAAa,EACb,sBAAsB,EACtB,cAAc,EACd,WAAW,EACX,MAAM,GAAG,wBAAY,EACrB,YAAY,GACZ,GAAG,MAAM,CAAC;QAEX,MAAM,gBAAgB,GAAG,qBAAY,CAAC,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QAE1C,MAAM,WAAW,GAAG,IAAI,CAAC,mBAAmB,EAAE,CAAC,OAAO,CACrD,YAAY,EACZ,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,SAAS,CACjC,CAAC;QAEF,IAAI,CAAC,WAAW,EAAE,CAAC;YAClB,MAAM,IAAI,KAAK,CAAC,gBAAgB,CAAC,CAAC;QACnC,CAAC;QAED,MAAM,eAAe,GAAG,MAAM,IAAA,mCAAqB,EAClD,IAAI,CAAC,WAAW,EAChB,WAAW,CAAC,UAAU,EACtB,QAAQ,EACR,IAAI,CAAC,WAAW,EAAE,CAClB,CAAC;QAEF,MAAM,EAAE,KAAK,EAAE,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,eAAe,CAAC,eAAe,CAAC,CAAC;QAE1E,OAAO,KAAK,CAAC;IACd,CAAC;;AAxpBF,0CAypBC;AAxpBgB,iCAAiB,GAAa;IAC7C,iBAAiB,EAAE,KAAM;IACzB,wBAAwB,EAAE,IAAI;IAC9B,4BAA4B,EAAE,GAAG;CACjC,CAAC;AAEc,uCAAuB,GAAG,IAAI,GAAG,EAAE,GAAG,OAAS,CAAC,CAAC,+GAA+G;AAopBjL;;;;;;;;;;;GAWG","sourcesContent":["import {\n\tBigNum,\n\tDriftClient,\n\tJupiterClient,\n\tMarketType,\n\tMAX_LEVERAGE_ORDER_SIZE,\n\tQuoteResponse,\n\tSwapMode,\n\tTxParams,\n\tUser,\n\tUserStatsAccount,\n\tZERO,\n} from '@drift-labs/sdk';\nimport { TransactionSignature } from '@solana/web3.js';\nimport { MARKET_UTILS } from '../../../../../common-ui-utils/market';\nimport { MAIN_POOL_ID } from '../../../../../constants';\nimport { TRADING_UTILS } from '../../../../../common-ui-utils/trading';\nimport { UserAccountCache } from '../../../stores/UserAccountCache';\nimport { createDepositTxn } from '../../../../base/actions/spot/deposit';\nimport { createUserAndDepositCollateralBaseTxn } from '../../../../base/actions/user/create';\nimport { createWithdrawTxn } from '../../../../base/actions/spot/withdraw';\nimport { deleteUserTxn } from '../../../../base/actions/user/delete';\nimport { createSettlePnlTxn } from '../../../../base/actions/perp/settlePnl';\nimport {\n\tCreateUserAndDepositParams,\n\tDepositParams,\n\tWithdrawParams,\n\tPerpOrderParams,\n\tSwapParams,\n\tSettleAccountPnlParams,\n\tCancelOrdersParams,\n} from './types';\nimport { createCancelOrdersTxn } from '../../../../base/actions/trade/cancelOrder';\nimport {\n\tcreateOpenPerpMarketOrder,\n\tOpenPerpMarketOrderParams,\n} from '../../../../base/actions/trade/openPerpOrder/openPerpMarketOrder';\nimport { createSwapTxn } from '../../../../base/actions/trade/swap';\nimport { createOpenPerpNonMarketOrder } from '../../../../base/actions/trade/openPerpOrder/openPerpNonMarketOrder';\n\n/**\n * Handles majority of the relevant operations on the Drift program including deposits,\n * withdrawals, position management, and trading operations.\n *\n * This class encapsulates the trading logic and provides a clean API for\n * executing various trading operations while handling common patterns like\n * token address resolution and transaction preparation.\n */\nexport class DriftOperations {\n\tstatic readonly DEFAULT_TX_PARAMS: TxParams = {\n\t\tcomputeUnitsPrice: 50_000,\n\t\tuseSimulatedComputeUnits: true,\n\t\tcomputeUnitsBufferMultiplier: 1.3,\n\t};\n\n\tstatic readonly MAX_COMPUTE_UNITS_PRICE = 1e15 / 10 / 1_400_000; // 1e15 = 1 SOL worth of micro lamports; 1e15 / 10 = 0.1 SOL worth of micro lamports; 1.4M = max compute units;\n\n\t/**\n\t * Creates a new DriftOperations instance.\n\t *\n\t * @param driftClient - The DriftClient instance for executing transactions\n\t * @param getUserAccountCache - Function to get the user account cache. We lazily load the user account cache, so that we always get the latest user account data.\n\t * @param getPriorityFee - Function to get current priority fee in micro lamports\n\t */\n\tconstructor(\n\t\tprivate driftClient: DriftClient,\n\t\tprivate getUserAccountCache: () => UserAccountCache,\n\t\tprivate dlobServerHttpUrl: string,\n\t\tprivate swiftServerUrl: string,\n\t\tprivate getPriorityFee: () => number\n\t) {}\n\n\t/**\n\t * Gets transaction parameters with dynamic priority fees.\n\t * Falls back to default if priority fee function is not available.\n\t */\n\tprivate getTxParams(overrides?: Partial<TxParams>): TxParams {\n\t\tconst unsafePriorityFee = Math.floor(\n\t\t\tthis.getPriorityFee() ??\n\t\t\t\tDriftOperations.DEFAULT_TX_PARAMS.computeUnitsPrice\n\t\t);\n\n\t\tconst safePriorityFee = Math.min(\n\t\t\tunsafePriorityFee,\n\t\t\tDriftOperations.MAX_COMPUTE_UNITS_PRICE\n\t\t);\n\n\t\treturn {\n\t\t\t...DriftOperations.DEFAULT_TX_PARAMS,\n\t\t\tcomputeUnitsPrice: safePriorityFee,\n\t\t\t...overrides,\n\t\t};\n\t}\n\n\t/**\n\t * Creates a new user account and deposits initial collateral.\n\t *\n\t * This method handles the complete onboarding flow for new users including:\n\t * - Validating that the subaccount doesn't already exist\n\t * - Resolving referrer information if provided\n\t * - Getting the correct token address for deposits\n\t * - Creating the user account with custom leverage settings\n\t * - Subscribing to the new user's account updates\n\t *\n\t * @param params - The parameters for user creation and initial deposit\n\t * @returns Promise resolving to transaction signature and user account public key\n\t *\n\t * @throws Error if subaccount already exists\n\t *\n\t * @example\n\t * ```typescript\n\t * const result = await tradingOps.createUserAndDeposit({\n\t * depositAmount: new BigNum(100),\n\t * depositSpotMarketIndex: 0, // USDC\n\t * name: \"Trading Account\",\n\t * maxLeverage: 5,\n\t * subAccountId: 0\n\t * });\n\t * ```\n\t */\n\tasync createUserAndDeposit(params: CreateUserAndDepositParams): Promise<{\n\t\ttxSig: TransactionSignature;\n\t\tuser: User;\n\t}> {\n\t\tconst {\n\t\t\tdepositAmount,\n\t\t\tdepositSpotMarketIndex,\n\t\t\tnewAccountName,\n\t\t\tmaxLeverage,\n\t\t\tpoolId = MAIN_POOL_ID,\n\t\t\treferrerName,\n\t\t} = params;\n\n\t\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tdepositSpotMarketIndex\n\t\t);\n\n\t\tconst customMaxMarginRatio = TRADING_UTILS.convertLeverageToMarginRatio(\n\t\t\tmaxLeverage ?? 0\n\t\t);\n\n\t\tlet userStatsAccount: UserStatsAccount | undefined = undefined;\n\n\t\ttry {\n\t\t\tuserStatsAccount = this.driftClient.userStats?.getAccount();\n\t\t} catch (error) {\n\t\t\t// ignore\n\t\t}\n\n\t\tconst { transaction, subAccountId } =\n\t\t\tawait createUserAndDepositCollateralBaseTxn({\n\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\tamount: depositAmount.val,\n\t\t\t\tspotMarketConfig: spotMarketConfig,\n\t\t\t\tauthority: this.driftClient.wallet.publicKey,\n\t\t\t\tuserStatsAccount: userStatsAccount,\n\t\t\t\taccountName: newAccountName,\n\t\t\t\treferrerName,\n\t\t\t\tcustomMaxMarginRatio,\n\t\t\t\tpoolId,\n\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(transaction);\n\n\t\tawait this.driftClient.addUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t); // adds user to driftclient's user map, subscribes to user account data\n\t\tconst user = this.driftClient.getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tuser.eventEmitter.on('update', () => {\n\t\t\tthis.getUserAccountCache().updateUserAccount(user);\n\t\t});\n\n\t\treturn {\n\t\t\ttxSig,\n\t\t\tuser,\n\t\t};\n\t}\n\n\t/**\n\t * Deletes a user account.\n\t *\n\t * This method removes a user's sub-account from the Drift.\n\t *\n\t * @param subAccountId - The ID of the sub-account to delete\n\t * @returns A promise that resolves to the transaction signature of the deletion\n\t *\n\t * @throws {Error} When the user account is not found in the cache\n\t *\n\t * @example\n\t * ```typescript\n\t * // Delete user sub-account with ID 0\n\t * const txSignature = await tradingOps.deleteUser(0);\n\t * console.log('User deleted with transaction:', txSignature);\n\t * ```\n\t */\n\tasync deleteUser(subAccountId: number): Promise<TransactionSignature> {\n\t\tconst user = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!user) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst deleteTxn = await deleteUserTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\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,9 +1,7 @@
|
|
|
1
1
|
import { BN, DriftClientConfig, DriftEnv, MarketType, OrderTriggerCondition, PositionDirection, PublicKey, QuoteResponse, SwapMode, User } from '@drift-labs/sdk';
|
|
2
2
|
import { Transaction, VersionedTransaction } from '@solana/web3.js';
|
|
3
|
-
import { MarketId } from '
|
|
4
|
-
import {
|
|
5
|
-
import { OpenPerpNonMarketOrderParams } from '../../base/actions/trade/openPerpOrder/openPerpNonMarketOrder';
|
|
6
|
-
import { TxnOrSwiftResult, WithTxnParams } from '../../base/actions/trade/openPerpOrder/types';
|
|
3
|
+
import { MarketId } from '../../../../types';
|
|
4
|
+
import { CentralServerGetOpenPerpMarketOrderTxnParams, CentralServerGetOpenPerpNonMarketOrderTxnParams } from './types';
|
|
7
5
|
/**
|
|
8
6
|
* A Drift client that fetches user data on-demand, while market data is continuously subscribed to.
|
|
9
7
|
*
|
|
@@ -13,6 +11,10 @@ export declare class CentralServerDrift {
|
|
|
13
11
|
private driftClient;
|
|
14
12
|
private _perpMarketConfigs;
|
|
15
13
|
private spotMarketConfigs;
|
|
14
|
+
/**
|
|
15
|
+
* The public endpoints that can be used to retrieve Drift data / interact with the Drift program.
|
|
16
|
+
*/
|
|
17
|
+
private _driftEndpoints;
|
|
16
18
|
/**
|
|
17
19
|
* @param solanaRpcEndpoint - The Solana RPC endpoint to use for reading RPC data.
|
|
18
20
|
* @param driftEnv - The drift environment to use for the drift client.
|
|
@@ -55,15 +57,13 @@ export declare class CentralServerDrift {
|
|
|
55
57
|
}): Promise<VersionedTransaction | Transaction>;
|
|
56
58
|
getSettleFundingTxn(userAccountPublicKey: PublicKey): Promise<VersionedTransaction | Transaction>;
|
|
57
59
|
getSettlePnlTxn(userAccountPublicKey: PublicKey, marketIndexes: number[]): Promise<VersionedTransaction | Transaction>;
|
|
58
|
-
getOpenPerpMarketOrderTxn<
|
|
59
|
-
|
|
60
|
-
}): Promise<TxnOrSwiftResult<T>>;
|
|
60
|
+
getOpenPerpMarketOrderTxn(params: CentralServerGetOpenPerpMarketOrderTxnParams<true>): Promise<void>;
|
|
61
|
+
getOpenPerpMarketOrderTxn(params: CentralServerGetOpenPerpMarketOrderTxnParams<false>): Promise<Transaction | VersionedTransaction>;
|
|
61
62
|
/**
|
|
62
63
|
* Create a perp non-market order with amount and asset type
|
|
63
64
|
*/
|
|
64
|
-
getOpenPerpNonMarketOrderTxn(
|
|
65
|
-
|
|
66
|
-
}): Promise<VersionedTransaction | Transaction | void>;
|
|
65
|
+
getOpenPerpNonMarketOrderTxn(params: CentralServerGetOpenPerpNonMarketOrderTxnParams<true>): Promise<void>;
|
|
66
|
+
getOpenPerpNonMarketOrderTxn(params: CentralServerGetOpenPerpNonMarketOrderTxnParams<false>): Promise<Transaction | VersionedTransaction>;
|
|
67
67
|
/**
|
|
68
68
|
* Create a transaction to edit an existing order
|
|
69
69
|
*/
|
|
@@ -3,17 +3,18 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.CentralServerDrift = void 0;
|
|
4
4
|
const sdk_1 = require("@drift-labs/sdk");
|
|
5
5
|
const web3_js_1 = require("@solana/web3.js");
|
|
6
|
-
const commonUiUtils_1 = require("
|
|
7
|
-
const constants_1 = require("
|
|
8
|
-
const deposit_1 = require("
|
|
9
|
-
const withdraw_1 = require("
|
|
10
|
-
const settleFunding_1 = require("
|
|
11
|
-
const settlePnl_1 = require("
|
|
12
|
-
const openPerpMarketOrder_1 = require("
|
|
13
|
-
const openPerpNonMarketOrder_1 = require("
|
|
14
|
-
const editOrder_1 = require("
|
|
15
|
-
const cancelOrder_1 = require("
|
|
16
|
-
const swap_1 = require("
|
|
6
|
+
const commonUiUtils_1 = require("../../../../common-ui-utils/commonUiUtils");
|
|
7
|
+
const constants_1 = require("../../constants");
|
|
8
|
+
const deposit_1 = require("../../../base/actions/spot/deposit");
|
|
9
|
+
const withdraw_1 = require("../../../base/actions/spot/withdraw");
|
|
10
|
+
const settleFunding_1 = require("../../../base/actions/perp/settleFunding");
|
|
11
|
+
const settlePnl_1 = require("../../../base/actions/perp/settlePnl");
|
|
12
|
+
const openPerpMarketOrder_1 = require("../../../base/actions/trade/openPerpOrder/openPerpMarketOrder");
|
|
13
|
+
const openPerpNonMarketOrder_1 = require("../../../base/actions/trade/openPerpOrder/openPerpNonMarketOrder");
|
|
14
|
+
const editOrder_1 = require("../../../base/actions/trade/editOrder");
|
|
15
|
+
const cancelOrder_1 = require("../../../base/actions/trade/cancelOrder");
|
|
16
|
+
const swap_1 = require("../../../base/actions/trade/swap");
|
|
17
|
+
const EnvironmentConstants_1 = require("../../../../EnvironmentConstants");
|
|
17
18
|
/**
|
|
18
19
|
* A Drift client that fetches user data on-demand, while market data is continuously subscribed to.
|
|
19
20
|
*
|
|
@@ -63,6 +64,13 @@ class CentralServerDrift {
|
|
|
63
64
|
driftEnv === 'devnet' ? sdk_1.DevnetPerpMarkets : sdk_1.MainnetPerpMarkets;
|
|
64
65
|
this.spotMarketConfigs =
|
|
65
66
|
driftEnv === 'devnet' ? sdk_1.DevnetSpotMarkets : sdk_1.MainnetSpotMarkets;
|
|
67
|
+
// set up Drift endpoints
|
|
68
|
+
const driftDlobServerHttpUrlToUse = EnvironmentConstants_1.EnvironmentConstants.dlobServerHttpUrl[config.driftEnv === 'devnet' ? 'dev' : 'mainnet'];
|
|
69
|
+
const swiftServerUrlToUse = EnvironmentConstants_1.EnvironmentConstants.swiftServerUrl[config.driftEnv === 'devnet' ? 'staging' : 'mainnet'];
|
|
70
|
+
this._driftEndpoints = {
|
|
71
|
+
dlobServerHttpUrl: driftDlobServerHttpUrlToUse,
|
|
72
|
+
swiftServerUrl: swiftServerUrlToUse,
|
|
73
|
+
};
|
|
66
74
|
}
|
|
67
75
|
async subscribe() {
|
|
68
76
|
await this.driftClient.subscribe();
|
|
@@ -204,25 +212,61 @@ class CentralServerDrift {
|
|
|
204
212
|
}
|
|
205
213
|
async getOpenPerpMarketOrderTxn({ userAccountPublicKey, ...rest }) {
|
|
206
214
|
return this.driftClientContextWrapper(userAccountPublicKey, async (user) => {
|
|
207
|
-
const
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
215
|
+
const { useSwift, swiftOptions, placeAndTake, ...otherProps } = rest;
|
|
216
|
+
if (useSwift) {
|
|
217
|
+
const swiftOrderResult = await (0, openPerpMarketOrder_1.createOpenPerpMarketOrder)({
|
|
218
|
+
...otherProps,
|
|
219
|
+
useSwift: true,
|
|
220
|
+
swiftOptions: {
|
|
221
|
+
...swiftOptions,
|
|
222
|
+
swiftServerUrl: this._driftEndpoints.swiftServerUrl,
|
|
223
|
+
},
|
|
224
|
+
driftClient: this.driftClient,
|
|
225
|
+
user,
|
|
226
|
+
dlobServerHttpUrl: this._driftEndpoints.dlobServerHttpUrl,
|
|
227
|
+
});
|
|
228
|
+
return swiftOrderResult;
|
|
229
|
+
}
|
|
230
|
+
else {
|
|
231
|
+
const openPerpMarketOrderTxn = await (0, openPerpMarketOrder_1.createOpenPerpMarketOrder)({
|
|
232
|
+
...otherProps,
|
|
233
|
+
placeAndTake,
|
|
234
|
+
useSwift: false,
|
|
235
|
+
driftClient: this.driftClient,
|
|
236
|
+
user,
|
|
237
|
+
dlobServerHttpUrl: this._driftEndpoints.dlobServerHttpUrl,
|
|
238
|
+
});
|
|
239
|
+
return openPerpMarketOrderTxn;
|
|
240
|
+
}
|
|
213
241
|
});
|
|
214
242
|
}
|
|
215
|
-
/**
|
|
216
|
-
* Create a perp non-market order with amount and asset type
|
|
217
|
-
*/
|
|
218
243
|
async getOpenPerpNonMarketOrderTxn({ userAccountPublicKey, ...rest }) {
|
|
219
244
|
return this.driftClientContextWrapper(userAccountPublicKey, async (user) => {
|
|
220
|
-
const
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
245
|
+
const { useSwift, swiftOptions, ...otherProps } = rest;
|
|
246
|
+
if (useSwift) {
|
|
247
|
+
const swiftOrderResult = await (0, openPerpNonMarketOrder_1.createOpenPerpNonMarketOrder)({
|
|
248
|
+
...otherProps,
|
|
249
|
+
useSwift: true,
|
|
250
|
+
swiftOptions: {
|
|
251
|
+
...swiftOptions,
|
|
252
|
+
swiftServerUrl: this._driftEndpoints.swiftServerUrl,
|
|
253
|
+
},
|
|
254
|
+
driftClient: this.driftClient,
|
|
255
|
+
user,
|
|
256
|
+
dlobServerHttpUrl: this._driftEndpoints.dlobServerHttpUrl,
|
|
257
|
+
});
|
|
258
|
+
return swiftOrderResult;
|
|
259
|
+
}
|
|
260
|
+
else {
|
|
261
|
+
const openPerpNonMarketOrderTxn = await (0, openPerpNonMarketOrder_1.createOpenPerpNonMarketOrder)({
|
|
262
|
+
...otherProps,
|
|
263
|
+
useSwift: false,
|
|
264
|
+
driftClient: this.driftClient,
|
|
265
|
+
user,
|
|
266
|
+
dlobServerHttpUrl: this._driftEndpoints.dlobServerHttpUrl,
|
|
267
|
+
});
|
|
268
|
+
return openPerpNonMarketOrderTxn;
|
|
269
|
+
}
|
|
226
270
|
});
|
|
227
271
|
}
|
|
228
272
|
/**
|
|
@@ -304,4 +348,4 @@ class CentralServerDrift {
|
|
|
304
348
|
}
|
|
305
349
|
}
|
|
306
350
|
exports.CentralServerDrift = CentralServerDrift;
|
|
307
|
-
//# sourceMappingURL=
|
|
351
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/drift/Drift/clients/CentralServerDrift/index.ts"],"names":[],"mappings":";;;AAAA,yCAyByB;AACzB,6CAAgF;AAChF,6EAA4E;AAC5E,+CAKyB;AAEzB,gEAAsE;AACtE,kEAAwE;AACxE,4EAAkF;AAClF,oEAA0E;AAC1E,uGAA0G;AAC1G,6GAG0E;AAC1E,qEAA2E;AAC3E,yEAAgF;AAChF,2DAAiE;AAKjE,2EAAwE;AAMxE;;;;GAIG;AACH,MAAa,kBAAkB;IAY9B;;;;;OAKG;IACH,YAAY,MAMX;QACA,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;QAEjC,MAAM,UAAU,GAAG,IAAI,oBAAU,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAC;QAC5D,MAAM,cAAc,GAAG,IAAI,eAAS,CAAC,sBAAgB,CAAC,CAAC;QACvD,MAAM,aAAa,GAAG,IAAI,wCAAkC,CAC3D,UAAU,EACV,6CAAiC,EACjC,uDAA2C,CAC3C,CAAC;QAEF,MAAM,MAAM,GAAG,+BAAe,CAAC,wBAAwB,EAAE,CAAC,CAAC,4DAA4D;QAEvH,MAAM,iBAAiB,GAAsB;YAC5C,GAAG,EAAE,QAAQ;YACb,UAAU;YACV,MAAM;YACN,SAAS,EAAE,cAAc;YACzB,mBAAmB,EAAE,KAAK;YAC1B,mBAAmB,EAAE;gBACpB,IAAI,EAAE,SAAS;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C;gBACZ,KAAK,GAAG,MAAM,aAAa,CAAC,QAAQ,CAAC;oBACpC,SAAS,EAAE,oBAAoB,CAAC,IAAI;oBACpC,UAAU,EAAE,kBAAkB,CAAC,IAAI;oBACnC,MAAM;oBACN,WAAW,EAAE,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,WAAW,mCAAI,EAAE,EAAE,eAAe;oBACxD,QAAQ,EAAE,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,QAAQ,mCAAI,SAAS;oBACxC,gBAAgB,EAAE,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,gBAAgB,mCAAI,KAAK;iBACpD,CAAC,CAAC;YACJ,CAAC;YAED,MAAM,OAAO,GAAG,MAAM,IAAA,oBAAa,EAAC;gBACnC,WAAW,EAAE,IAAI,CAAC,WAAW;gBAC7B,aAAa;gBACb,IAAI;gBACJ,mBAAmB,EAAE,eAAe;gBACpC,iBAAiB,EAAE,aAAa;gBAChC,MAAM;gBACN,KAAK;gBACL,QAAQ,EAAE;oBACT,wBAAwB,EAAE,IAAI;oBAC9B,4BAA4B,EAAE,GAAG;iBACjC;aACD,CAAC,CAAC;YAEH,OAAO,OAAO,CAAC;QAChB,CAAC,CACD,CAAC;IACH,CAAC;IAEM,KAAK,CAAC,qBAAqB,CAAC,EAAsC;QACxE,OAAO,IAAI,CAAC,WAAW,CAAC,eAAe,CAAC,EAAE,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;IACzE,CAAC;CACD;AAnjBD,gDAmjBC","sourcesContent":["import {\n\tBigNum,\n\tBN,\n\tCustomizedCadenceBulkAccountLoader,\n\tDelistedMarketSetting,\n\tDevnetPerpMarkets,\n\tDevnetSpotMarkets,\n\tDRIFT_PROGRAM_ID,\n\tDriftClient,\n\tDriftClientConfig,\n\tDriftEnv,\n\tJupiterClient,\n\tMainnetPerpMarkets,\n\tMainnetSpotMarkets,\n\tMarketType,\n\tOneShotUserAccountSubscriber,\n\tOrderTriggerCondition,\n\tPerpMarketConfig,\n\tPositionDirection,\n\tPublicKey,\n\tQuoteResponse,\n\tSpotMarketConfig,\n\tSwapMode,\n\tUser,\n\tWhileValidTxSender,\n} from '@drift-labs/sdk';\nimport { Connection, Transaction, VersionedTransaction } from '@solana/web3.js';\nimport { COMMON_UI_UTILS } from '../../../../common-ui-utils/commonUiUtils';\nimport {\n\tDEFAULT_ACCOUNT_LOADER_COMMITMENT,\n\tDEFAULT_ACCOUNT_LOADER_POLLING_FREQUENCY_MS,\n\tDEFAULT_TX_SENDER_CONFIRMATION_STRATEGY,\n\tDEFAULT_TX_SENDER_RETRY_INTERVAL,\n} from '../../constants';\nimport { MarketId } from '../../../../types';\nimport { createDepositTxn } from '../../../base/actions/spot/deposit';\nimport { createWithdrawTxn } from '../../../base/actions/spot/withdraw';\nimport { createSettleFundingTxn } from '../../../base/actions/perp/settleFunding';\nimport { createSettlePnlTxn } from '../../../base/actions/perp/settlePnl';\nimport { createOpenPerpMarketOrder } from '../../../base/actions/trade/openPerpOrder/openPerpMarketOrder';\nimport {\n\tcreateOpenPerpNonMarketOrder,\n\tOpenPerpNonMarketOrderParams,\n} from '../../../base/actions/trade/openPerpOrder/openPerpNonMarketOrder';\nimport { createEditOrderTxn } from '../../../base/actions/trade/editOrder';\nimport { createCancelOrdersTxn } from '../../../base/actions/trade/cancelOrder';\nimport { createSwapTxn } from '../../../base/actions/trade/swap';\nimport {\n\tTxnOrSwiftResult,\n\tWithTxnParams,\n} from '../../../base/actions/trade/openPerpOrder/types';\nimport { EnvironmentConstants } from '../../../../EnvironmentConstants';\nimport {\n\tCentralServerGetOpenPerpMarketOrderTxnParams,\n\tCentralServerGetOpenPerpNonMarketOrderTxnParams,\n} from './types';\n\n/**\n * A Drift client that fetches user data on-demand, while market data is continuously subscribed to.\n *\n * This is useful for an API server that fetches user data on-demand, and return transaction messages specific to a given user\n */\nexport class CentralServerDrift {\n\tprivate driftClient: DriftClient;\n\tprivate _perpMarketConfigs: PerpMarketConfig[];\n\tprivate spotMarketConfigs: SpotMarketConfig[];\n\t/**\n\t * The public endpoints that can be used to retrieve Drift data / interact with the Drift program.\n\t */\n\tprivate _driftEndpoints: {\n\t\tdlobServerHttpUrl: string;\n\t\tswiftServerUrl: string;\n\t};\n\n\t/**\n\t * @param solanaRpcEndpoint - The Solana RPC endpoint to use for reading RPC data.\n\t * @param driftEnv - The drift environment to use for the drift client.\n\t * @param activeTradeMarket - The active trade market to use for the drift client. This is used to subscribe to the market account, oracle data and mark price more frequently compared to the other markets.\n\t * @param additionalDriftClientConfig - Additional DriftClient config to use for the DriftClient.\n\t */\n\tconstructor(config: {\n\t\tsolanaRpcEndpoint: string;\n\t\tdriftEnv: DriftEnv;\n\t\tadditionalDriftClientConfig?: Partial<Omit<DriftClientConfig, 'env'>>;\n\t\tactiveTradeMarket?: MarketId;\n\t\tmarketsToSubscribe?: MarketId[];\n\t}) {\n\t\tconst driftEnv = config.driftEnv;\n\n\t\tconst connection = new Connection(config.solanaRpcEndpoint);\n\t\tconst driftProgramID = new PublicKey(DRIFT_PROGRAM_ID);\n\t\tconst accountLoader = new CustomizedCadenceBulkAccountLoader(\n\t\t\tconnection,\n\t\t\tDEFAULT_ACCOUNT_LOADER_COMMITMENT,\n\t\t\tDEFAULT_ACCOUNT_LOADER_POLLING_FREQUENCY_MS\n\t\t);\n\n\t\tconst wallet = COMMON_UI_UTILS.createPlaceholderIWallet(); // use random wallet to initialize a central-server instance\n\n\t\tconst driftClientConfig: DriftClientConfig = {\n\t\t\tenv: driftEnv,\n\t\t\tconnection,\n\t\t\twallet,\n\t\t\tprogramID: driftProgramID,\n\t\t\tenableMetricsEvents: false,\n\t\t\taccountSubscription: {\n\t\t\t\ttype: 'polling',\n\t\t\t\taccountLoader,\n\t\t\t},\n\t\t\tuserStats: false,\n\t\t\tincludeDelegates: false,\n\t\t\tskipLoadUsers: true,\n\t\t\tdelistedMarketSetting: DelistedMarketSetting.Unsubscribe,\n\t\t\t...config.additionalDriftClientConfig,\n\t\t};\n\t\tthis.driftClient = new DriftClient(driftClientConfig);\n\n\t\tconst txSender = new WhileValidTxSender({\n\t\t\tconnection,\n\t\t\twallet,\n\t\t\tadditionalConnections: [],\n\t\t\tadditionalTxSenderCallbacks: [],\n\t\t\ttxHandler: this.driftClient.txHandler,\n\t\t\tconfirmationStrategy: DEFAULT_TX_SENDER_CONFIRMATION_STRATEGY,\n\t\t\tretrySleep: DEFAULT_TX_SENDER_RETRY_INTERVAL,\n\t\t});\n\n\t\tthis.driftClient.txSender = txSender;\n\t\tthis._perpMarketConfigs =\n\t\t\tdriftEnv === 'devnet' ? DevnetPerpMarkets : MainnetPerpMarkets;\n\t\tthis.spotMarketConfigs =\n\t\t\tdriftEnv === 'devnet' ? DevnetSpotMarkets : MainnetSpotMarkets;\n\n\t\t// set up Drift endpoints\n\t\tconst driftDlobServerHttpUrlToUse =\n\t\t\tEnvironmentConstants.dlobServerHttpUrl[\n\t\t\t\tconfig.driftEnv === 'devnet' ? 'dev' : 'mainnet'\n\t\t\t];\n\t\tconst swiftServerUrlToUse =\n\t\t\tEnvironmentConstants.swiftServerUrl[\n\t\t\t\tconfig.driftEnv === 'devnet' ? 'staging' : 'mainnet'\n\t\t\t];\n\t\tthis._driftEndpoints = {\n\t\t\tdlobServerHttpUrl: driftDlobServerHttpUrlToUse,\n\t\t\tswiftServerUrl: swiftServerUrlToUse,\n\t\t};\n\t}\n\n\tpublic async subscribe() {\n\t\tawait this.driftClient.subscribe();\n\t}\n\n\t/**\n\t * Manages DriftClient state for transaction creation with proper setup and cleanup.\n\t * This abstraction handles:\n\t * - User creation and subscription\n\t * - Authority management\n\t * - Wallet replacement for correct transaction signing\n\t * - Cleanup and state restoration\n\t *\n\t * @param userAccountPublicKey - The user account public key\n\t * @param operation - The transaction creation operation to execute\n\t * @returns The result of the operation\n\t */\n\tprivate async driftClientContextWrapper<T>(\n\t\tuserAccountPublicKey: PublicKey,\n\t\toperation: (user: User) => Promise<T>\n\t): Promise<T> {\n\t\tconst user = new User({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuserAccountPublicKey,\n\t\t\taccountSubscription: {\n\t\t\t\ttype: 'custom',\n\t\t\t\tuserAccountSubscriber: new OneShotUserAccountSubscriber(\n\t\t\t\t\tthis.driftClient.program,\n\t\t\t\t\tuserAccountPublicKey,\n\t\t\t\t\tundefined,\n\t\t\t\t\tundefined\n\t\t\t\t),\n\t\t\t},\n\t\t});\n\n\t\t// Store original state\n\t\tconst originalWallet = this.driftClient.wallet;\n\t\tconst originalAuthority = this.driftClient.authority;\n\n\t\ttry {\n\t\t\t// Setup: Subscribe to user and configure DriftClient\n\t\t\tawait user.subscribe();\n\n\t\t\tconst authority = user.getUserAccount().authority;\n\t\t\tthis.driftClient.authority = authority;\n\n\t\t\tconst success = await this.driftClient.addUser(\n\t\t\t\tuser.getUserAccount().subAccountId,\n\t\t\t\tauthority\n\t\t\t);\n\n\t\t\tif (!success) {\n\t\t\t\tthrow new Error('Failed to add user to DriftClient');\n\t\t\t}\n\n\t\t\t// Replace wallet with user's authority to ensure correct transaction signing\n\t\t\t// This is necessary because DriftClient adds wallet.publicKey to instructions\n\t\t\tconst userWallet = {\n\t\t\t\tpublicKey: authority,\n\t\t\t\tsignTransaction: () =>\n\t\t\t\t\tPromise.reject(\n\t\t\t\t\t\t'This is a placeholder - do not sign with this wallet'\n\t\t\t\t\t),\n\t\t\t\tsignAllTransactions: () =>\n\t\t\t\t\tPromise.reject(\n\t\t\t\t\t\t'This is a placeholder - do not sign with this wallet'\n\t\t\t\t\t),\n\t\t\t};\n\n\t\t\t// Update wallet in all places that reference it\n\t\t\tthis.driftClient.wallet = userWallet;\n\t\t\t//@ts-ignore\n\t\t\tthis.driftClient.provider.wallet = userWallet;\n\t\t\tthis.driftClient.txHandler.updateWallet(userWallet);\n\n\t\t\t// Execute the operation\n\t\t\tconst result = await operation(user);\n\n\t\t\treturn result;\n\t\t} finally {\n\t\t\t// Cleanup: Always restore original state and unsubscribe\n\t\t\tthis.driftClient.wallet = originalWallet;\n\t\t\tthis.driftClient.txHandler.updateWallet(originalWallet);\n\t\t\tthis.driftClient.authority = originalAuthority;\n\n\t\t\ttry {\n\t\t\t\tawait user.unsubscribe();\n\t\t\t\tthis.driftClient.users.clear();\n\t\t\t} catch (cleanupError) {\n\t\t\t\tconsole.warn('Error during cleanup:', cleanupError);\n\t\t\t\t// Don't throw cleanup errors, but log them\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Returns a User object for a given user account public key. This fetches the user account data once.\n\t *\n\t * You may read more about the User object [here](https://github.com/drift-labs/protocol-v2/blob/master/sdk/src/user.ts)\n\t *\n\t * @param userAccountPublicKey - The user account public key\n\t */\n\tpublic async getUser(userAccountPublicKey: PublicKey): Promise<User> {\n\t\tconst oneShotUserAccountSubscriber = new OneShotUserAccountSubscriber(\n\t\t\tthis.driftClient.program,\n\t\t\tuserAccountPublicKey,\n\t\t\tundefined,\n\t\t\tundefined\n\t\t);\n\t\tconst user = new User({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuserAccountPublicKey,\n\t\t\taccountSubscription: {\n\t\t\t\ttype: 'custom',\n\t\t\t\tuserAccountSubscriber: oneShotUserAccountSubscriber,\n\t\t\t},\n\t\t});\n\t\tawait user.subscribe();\n\t\treturn user;\n\t}\n\n\tpublic async getDepositTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tamount: BN,\n\t\tspotMarketIndex: number\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst spotMarketConfig = this.spotMarketConfigs.find(\n\t\t\t\t\t(market) => market.marketIndex === spotMarketIndex\n\t\t\t\t);\n\n\t\t\t\tif (!spotMarketConfig) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Spot market config not found for index ${spotMarketIndex}`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst depositTxn = await createDepositTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tamount: BigNum.from(amount, spotMarketConfig.precisionExp),\n\t\t\t\t\tspotMarketConfig,\n\t\t\t\t});\n\n\t\t\t\treturn depositTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\tpublic async getWithdrawTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tamount: BN,\n\t\tspotMarketIndex: number,\n\t\toptions?: {\n\t\t\tisBorrow?: boolean;\n\t\t\tisMax?: boolean;\n\t\t}\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst spotMarketConfig = this.spotMarketConfigs.find(\n\t\t\t\t\t(market) => market.marketIndex === spotMarketIndex\n\t\t\t\t);\n\n\t\t\t\tif (!spotMarketConfig) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Spot market config not found for index ${spotMarketIndex}`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst withdrawTxn = await createWithdrawTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tamount: BigNum.from(amount, spotMarketConfig.precisionExp),\n\t\t\t\t\tspotMarketConfig,\n\t\t\t\t\tisBorrow: options?.isBorrow,\n\t\t\t\t\tisMax: options?.isMax,\n\t\t\t\t});\n\n\t\t\t\treturn withdrawTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\tpublic async getSettleFundingTxn(\n\t\tuserAccountPublicKey: PublicKey\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst settleFundingTxn = await createSettleFundingTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t});\n\n\t\t\t\treturn settleFundingTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\tpublic async getSettlePnlTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tmarketIndexes: number[]\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst settlePnlTxn = await createSettlePnlTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tmarketIndexes,\n\t\t\t\t});\n\n\t\t\t\treturn settlePnlTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\t// overloads for better type inference\n\tpublic async getOpenPerpMarketOrderTxn(\n\t\tparams: CentralServerGetOpenPerpMarketOrderTxnParams<true>\n\t): Promise<void>;\n\tpublic async getOpenPerpMarketOrderTxn(\n\t\tparams: CentralServerGetOpenPerpMarketOrderTxnParams<false>\n\t): Promise<Transaction | VersionedTransaction>;\n\tpublic async getOpenPerpMarketOrderTxn<T extends boolean>({\n\t\tuserAccountPublicKey,\n\t\t...rest\n\t}: CentralServerGetOpenPerpMarketOrderTxnParams<T>): Promise<\n\t\tTxnOrSwiftResult<T>\n\t> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user): Promise<TxnOrSwiftResult<T>> => {\n\t\t\t\tconst { useSwift, swiftOptions, placeAndTake, ...otherProps } = rest;\n\n\t\t\t\tif (useSwift) {\n\t\t\t\t\tconst swiftOrderResult = await createOpenPerpMarketOrder({\n\t\t\t\t\t\t...otherProps,\n\t\t\t\t\t\tuseSwift: true,\n\t\t\t\t\t\tswiftOptions: {\n\t\t\t\t\t\t\t...swiftOptions,\n\t\t\t\t\t\t\tswiftServerUrl: this._driftEndpoints.swiftServerUrl,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdlobServerHttpUrl: this._driftEndpoints.dlobServerHttpUrl,\n\t\t\t\t\t});\n\t\t\t\t\treturn swiftOrderResult as TxnOrSwiftResult<T>;\n\t\t\t\t} else {\n\t\t\t\t\tconst openPerpMarketOrderTxn = await createOpenPerpMarketOrder({\n\t\t\t\t\t\t...otherProps,\n\t\t\t\t\t\tplaceAndTake,\n\t\t\t\t\t\tuseSwift: false,\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdlobServerHttpUrl: this._driftEndpoints.dlobServerHttpUrl,\n\t\t\t\t\t});\n\t\t\t\t\treturn openPerpMarketOrderTxn as TxnOrSwiftResult<T>;\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a perp non-market order with amount and asset type\n\t */\n\tpublic async getOpenPerpNonMarketOrderTxn(\n\t\tparams: CentralServerGetOpenPerpNonMarketOrderTxnParams<true>\n\t): Promise<void>;\n\tpublic async getOpenPerpNonMarketOrderTxn(\n\t\tparams: CentralServerGetOpenPerpNonMarketOrderTxnParams<false>\n\t): Promise<Transaction | VersionedTransaction>;\n\tpublic async getOpenPerpNonMarketOrderTxn<T extends boolean>({\n\t\tuserAccountPublicKey,\n\t\t...rest\n\t}: WithTxnParams<\n\t\tOmit<OpenPerpNonMarketOrderParams<T>, 'driftClient' | 'user'>\n\t> & {\n\t\tuserAccountPublicKey: PublicKey;\n\t}): Promise<TxnOrSwiftResult<T>> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst { useSwift, swiftOptions, ...otherProps } = rest;\n\n\t\t\t\tif (useSwift) {\n\t\t\t\t\tconst swiftOrderResult = await createOpenPerpNonMarketOrder({\n\t\t\t\t\t\t...otherProps,\n\t\t\t\t\t\tuseSwift: true,\n\t\t\t\t\t\tswiftOptions: {\n\t\t\t\t\t\t\t...swiftOptions,\n\t\t\t\t\t\t\tswiftServerUrl: this._driftEndpoints.swiftServerUrl,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdlobServerHttpUrl: this._driftEndpoints.dlobServerHttpUrl,\n\t\t\t\t\t});\n\t\t\t\t\treturn swiftOrderResult as TxnOrSwiftResult<T>;\n\t\t\t\t} else {\n\t\t\t\t\tconst openPerpNonMarketOrderTxn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\t\t...otherProps,\n\t\t\t\t\t\tuseSwift: false,\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdlobServerHttpUrl: this._driftEndpoints.dlobServerHttpUrl,\n\t\t\t\t\t});\n\t\t\t\t\treturn openPerpNonMarketOrderTxn as TxnOrSwiftResult<T>;\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a transaction to edit an existing order\n\t */\n\tpublic async getEditOrderTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\torderId: number,\n\t\teditOrderParams: {\n\t\t\tnewDirection?: PositionDirection;\n\t\t\tnewBaseAmount?: BN;\n\t\t\tnewLimitPrice?: BN;\n\t\t\tnewOraclePriceOffset?: number;\n\t\t\tnewTriggerPrice?: BN;\n\t\t\tnewTriggerCondition?: OrderTriggerCondition;\n\t\t\tauctionDuration?: number;\n\t\t\tauctionStartPrice?: BN;\n\t\t\tauctionEndPrice?: BN;\n\t\t\treduceOnly?: boolean;\n\t\t\tpostOnly?: boolean;\n\t\t\tbitFlags?: number;\n\t\t\tmaxTs?: BN;\n\t\t\tpolicy?: number;\n\t\t}\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst editOrderTxn = await createEditOrderTxn(\n\t\t\t\t\tthis.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\torderId,\n\t\t\t\t\teditOrderParams\n\t\t\t\t);\n\n\t\t\t\treturn editOrderTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a transaction to cancel specific orders by their IDs\n\t */\n\tpublic async getCancelOrdersTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\torderIds: number[]\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst cancelOrdersTxn = await createCancelOrdersTxn(\n\t\t\t\t\tthis.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\torderIds\n\t\t\t\t);\n\n\t\t\t\treturn cancelOrdersTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a transaction to cancel all orders for a user\n\t */\n\tpublic async getCancelAllOrdersTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tmarketType?: MarketType,\n\t\tmarketIndex?: number,\n\t\tdirection?: PositionDirection\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst ix = await this.driftClient.getCancelOrdersIx(\n\t\t\t\t\tmarketType ?? null,\n\t\t\t\t\tmarketIndex ?? null,\n\t\t\t\t\tdirection ?? null,\n\t\t\t\t\tuser.getUserAccount().subAccountId\n\t\t\t\t);\n\n\t\t\t\tconst cancelAllOrdersTxn = await this.driftClient.buildTransaction(ix);\n\n\t\t\t\treturn cancelAllOrdersTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a swap transaction between two spot markets using Jupiter\n\t */\n\tpublic async getSwapTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tfromMarketIndex: number,\n\t\ttoMarketIndex: number,\n\t\tamount: BN,\n\t\toptions?: {\n\t\t\tslippageBps?: number;\n\t\t\tswapMode?: SwapMode;\n\t\t\tonlyDirectRoutes?: boolean;\n\t\t\tquote?: QuoteResponse;\n\t\t}\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst fromSpotMarketConfig = this.spotMarketConfigs.find(\n\t\t\t\t\t(market) => market.marketIndex === fromMarketIndex\n\t\t\t\t);\n\t\t\t\tconst toSpotMarketConfig = this.spotMarketConfigs.find(\n\t\t\t\t\t(market) => market.marketIndex === toMarketIndex\n\t\t\t\t);\n\n\t\t\t\tif (!fromSpotMarketConfig) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`From spot market config not found for index ${fromMarketIndex}`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tif (!toSpotMarketConfig) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`To spot market config not found for index ${toMarketIndex}`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Initialize Jupiter client\n\t\t\t\tconst jupiterClient = new JupiterClient({\n\t\t\t\t\tconnection: this.driftClient.connection,\n\t\t\t\t});\n\n\t\t\t\t// Get quote if not provided\n\t\t\t\tlet quote = options?.quote;\n\t\t\t\tif (!quote) {\n\t\t\t\t\tquote = await jupiterClient.getQuote({\n\t\t\t\t\t\tinputMint: fromSpotMarketConfig.mint,\n\t\t\t\t\t\toutputMint: toSpotMarketConfig.mint,\n\t\t\t\t\t\tamount,\n\t\t\t\t\t\tslippageBps: options?.slippageBps ?? 10, // Default 0.1%\n\t\t\t\t\t\tswapMode: options?.swapMode ?? 'ExactIn',\n\t\t\t\t\t\tonlyDirectRoutes: options?.onlyDirectRoutes ?? false,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tconst swapTxn = await createSwapTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tjupiterClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tswapFromMarketIndex: fromMarketIndex,\n\t\t\t\t\tswapToMarketIndex: toMarketIndex,\n\t\t\t\t\tamount,\n\t\t\t\t\tquote,\n\t\t\t\t\ttxParams: {\n\t\t\t\t\t\tuseSimulatedComputeUnits: true,\n\t\t\t\t\t\tcomputeUnitsBufferMultiplier: 1.5,\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\treturn swapTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\tpublic async sendSignedTransaction(tx: VersionedTransaction | Transaction) {\n\t\treturn this.driftClient.sendTransaction(tx, undefined, undefined, true);\n\t}\n}\n"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { SwiftOrderOptions } from '../../../base/actions/trade/openPerpOrder/openSwiftOrder';
|
|
2
|
+
import { WithTxnParams } from '../../../base/actions/trade/openPerpOrder/types';
|
|
3
|
+
import { OpenPerpMarketOrderParams } from '../../../base/actions/trade/openPerpOrder/openPerpMarketOrder';
|
|
4
|
+
import { OpenPerpNonMarketOrderParams } from '../../../base/actions/trade/openPerpOrder/openPerpNonMarketOrder';
|
|
5
|
+
import { PublicKey } from '@solana/web3.js';
|
|
6
|
+
export type CentralServerSwiftOrderOptions = Omit<SwiftOrderOptions, 'swiftServerUrl'>;
|
|
7
|
+
export type CentralServerGetOpenPerpMarketOrderTxnParams<T extends boolean = boolean> = WithTxnParams<Omit<OpenPerpMarketOrderParams<T, CentralServerSwiftOrderOptions>, 'driftClient' | 'user' | 'dlobServerHttpUrl'>> & {
|
|
8
|
+
userAccountPublicKey: PublicKey;
|
|
9
|
+
};
|
|
10
|
+
export type CentralServerGetOpenPerpNonMarketOrderTxnParams<T extends boolean = boolean> = WithTxnParams<Omit<OpenPerpNonMarketOrderParams<T, CentralServerSwiftOrderOptions>, 'driftClient' | 'user' | 'dlobServerHttpUrl'>> & {
|
|
11
|
+
userAccountPublicKey: PublicKey;
|
|
12
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/drift/Drift/clients/CentralServerDrift/types.ts"],"names":[],"mappings":"","sourcesContent":["import { SwiftOrderOptions } from '../../../base/actions/trade/openPerpOrder/openSwiftOrder';\nimport { WithTxnParams } from '../../../base/actions/trade/openPerpOrder/types';\nimport { OpenPerpMarketOrderParams } from '../../../base/actions/trade/openPerpOrder/openPerpMarketOrder';\nimport { OpenPerpNonMarketOrderParams } from '../../../base/actions/trade/openPerpOrder/openPerpNonMarketOrder';\nimport { PublicKey } from '@solana/web3.js';\n\nexport type CentralServerSwiftOrderOptions = Omit<\n\tSwiftOrderOptions,\n\t'swiftServerUrl'\n>;\n\nexport type CentralServerGetOpenPerpMarketOrderTxnParams<\n\tT extends boolean = boolean\n> = WithTxnParams<\n\tOmit<\n\t\tOpenPerpMarketOrderParams<T, CentralServerSwiftOrderOptions>,\n\t\t'driftClient' | 'user' | 'dlobServerHttpUrl'\n\t>\n> & {\n\tuserAccountPublicKey: PublicKey;\n};\n\nexport type CentralServerGetOpenPerpNonMarketOrderTxnParams<\n\tT extends boolean = boolean\n> = WithTxnParams<\n\tOmit<\n\t\tOpenPerpNonMarketOrderParams<T, CentralServerSwiftOrderOptions>,\n\t\t'driftClient' | 'user' | 'dlobServerHttpUrl'\n\t>\n> & {\n\tuserAccountPublicKey: PublicKey;\n};\n"]}
|
|
@@ -97,7 +97,7 @@ async function fetchAuctionOrderParamsFromDlob({ marketIndex, marketType = sdk_1
|
|
|
97
97
|
? amount
|
|
98
98
|
: (() => {
|
|
99
99
|
const oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;
|
|
100
|
-
return amount.mul(
|
|
100
|
+
return amount.mul(sdk_1.BASE_PRECISION).div(oraclePrice);
|
|
101
101
|
})();
|
|
102
102
|
// Build URL parameters for server request
|
|
103
103
|
const urlParamsObject = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/dlobServer/index.ts"],"names":[],"mappings":";;;;;;AAAA,yCAYyB;AACzB,mDAAqD;AACrD,kGAI0D;AAC1D,yDAAkE;AAClE,mDAAqE;AACrE,iEAO2C;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O,YAAY,CAAC;IACrB,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACZ,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACjB,OAAO,EAAE,CAAC;IACX,CAAC;AACF,CAAC;AA3CD,wCA2CC","sourcesContent":["import {\n\tDriftClient,\n\tUser,\n\tBN,\n\tPositionDirection,\n\tOptionalOrderParams,\n\tMarketType,\n\tUserAccount,\n\tPublicKey,\n\tdecodeUser,\n\tDefaultOrderParams,\n\tPRICE_PRECISION,\n} from '@drift-labs/sdk';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport {\n\tmapAuctionParamsResponse,\n\tServerAuctionParamsResponse,\n\tMappedAuctionParams,\n} from '../../../../../utils/auctionParamsResponseMapper';\nimport { encodeQueryParams } from '../../../../../../utils/fetch';\nimport { MarketId, TradeOffsetPrice } from '../../../../../../types';\nimport {\n\tconvertToL2OrderBook,\n\tdeserializeL2Response,\n\tL2WithOracleAndMarketData,\n\tRawL2Output,\n\tcalculateDynamicSlippageFromL2,\n\tDynamicSlippageConfig,\n} from '../../../../../../utils/orderbook';\nimport { PollingSequenceGuard } from '../../../../../../utils/pollingSequenceGuard';\nimport { calculatePriceImpactFromL2 } from '../../../../../../utils/priceImpact';\nimport { COMMON_UI_UTILS } from '../../../../../../common-ui-utils';\nimport invariant from 'tiny-invariant';\n\nexport interface OptionalAuctionParamsRequestInputs {\n\t// Optional parameters that can override defaults or provide additional configuration\n\tmaxLeverageSelected?: boolean;\n\tmaxLeverageOrderSize?: BN;\n\treduceOnly?: boolean;\n\tauctionDuration?: number;\n\tauctionStartPriceOffset?: number;\n\tauctionEndPriceOffset?: number;\n\tauctionStartPriceOffsetFrom?: TradeOffsetPrice;\n\tauctionEndPriceOffsetFrom?: TradeOffsetPrice;\n\tslippageTolerance?: number | 'dynamic';\n\tauctionPriceCaps?: {\n\t\tmin: BN;\n\t\tmax: BN;\n\t};\n\tisOracleOrder?: boolean;\n\tadditionalEndPriceBuffer?: BN;\n\tforceUpToSlippage?: boolean;\n\torderType?: 'market' | 'oracle';\n}\n\ninterface RegularOrderParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tassetType: 'base' | 'quote';\n\tmarketType?: MarketType;\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\tamount: BN;\n\toptionalAuctionParamsInputs?: OptionalAuctionParamsRequestInputs;\n\tdlobServerHttpUrl: string;\n\tdynamicSlippageConfig?: DynamicSlippageConfig;\n}\n\nexport interface BulkL2FetchingQueryParams {\n\tmarketIndex: number;\n\tmarketType: string;\n\tdepth: number;\n\tincludeVamm: boolean;\n\tincludePhoenix: boolean;\n\tincludeOpenbook: boolean;\n\tincludeSerum: boolean;\n\tincludeOracle: boolean;\n\tincludeIndicative: boolean;\n}\n\nexport interface BulkL2FetchingParams {\n\tmarkets: BulkL2FetchingQueryParams[];\n\tgrouping?: number;\n}\n\nconst BACKGROUND_L2_POLLING_KEY = Symbol('BACKGROUND_L2_POLLING_KEY');\n\n/**\n * Fetches the L2 data for the given markets and their depth\n */\nexport function fetchBulkMarketsDlobL2Data(\n\tdlobServerHttpUrl: string,\n\tmarkets: {\n\t\tmarketId: MarketId;\n\t\tdepth: number;\n\t}[],\n\tgroupingSize?: number,\n\texcludeIndicativeLiquidity = false\n): Promise<L2WithOracleAndMarketData[]> {\n\tconst params: BulkL2FetchingParams = {\n\t\tmarkets: markets.map((m) => ({\n\t\t\tmarketIndex: m.marketId.marketIndex,\n\t\t\tmarketType: m.marketId.marketTypeStr,\n\t\t\tdepth: m.depth,\n\t\t\tincludeVamm: m.marketId.isPerp,\n\t\t\tincludePhoenix: m.marketId.isSpot,\n\t\t\tincludeSerum: m.marketId.isSpot,\n\t\t\tincludeOpenbook: m.marketId.isSpot,\n\t\t\tincludeOracle: true,\n\t\t\tincludeIndicative: !excludeIndicativeLiquidity,\n\t\t})),\n\t\tgrouping: groupingSize,\n\t};\n\n\tconst queryParamsMap: {\n\t\t[K in keyof BulkL2FetchingQueryParams]: string;\n\t} & {\n\t\tgrouping?: string;\n\t} = {\n\t\tmarketType: params.markets.map((market) => market.marketType).join(','),\n\t\tmarketIndex: params.markets.map((market) => market.marketIndex).join(','),\n\t\tdepth: params.markets.map((market) => market.depth).join(','),\n\t\tincludeVamm: params.markets.map((market) => market.includeVamm).join(','),\n\t\tincludePhoenix: params.markets\n\t\t\t.map((market) => market.includePhoenix)\n\t\t\t.join(','),\n\t\tincludeOpenbook: params.markets\n\t\t\t.map((market) => market.includeOpenbook)\n\t\t\t.join(','),\n\t\tincludeSerum: params.markets.map((market) => market.includeSerum).join(','),\n\t\tgrouping: params.grouping\n\t\t\t? params.markets.map(() => params.grouping).join(',')\n\t\t\t: undefined,\n\t\tincludeOracle: params.markets\n\t\t\t.map((market) => market.includeOracle)\n\t\t\t.join(','),\n\t\tincludeIndicative: params.markets\n\t\t\t.map((market) => market.includeIndicative)\n\t\t\t.join(','),\n\t};\n\n\tconst queryParams = encodeQueryParams(queryParamsMap);\n\n\t// Use cached endpoint when exclusively fetching background markets\n\tconst useCachedEndpoint = !params.markets.some(\n\t\t(market) => market.depth !== 1\n\t);\n\n\tconst endpoint = useCachedEndpoint\n\t\t? `${dlobServerHttpUrl}/batchL2Cache`\n\t\t: `${dlobServerHttpUrl}/batchL2`;\n\n\treturn new Promise<L2WithOracleAndMarketData[]>((resolve, reject) => {\n\t\tPollingSequenceGuard.fetch(BACKGROUND_L2_POLLING_KEY, () => {\n\t\t\treturn fetch(`${endpoint}?${queryParams}`);\n\t\t})\n\t\t\t.then(async (response) => {\n\t\t\t\tconst responseData = await response.json();\n\t\t\t\tconst resultsArray = responseData.l2s as RawL2Output[];\n\t\t\t\tconst deserializedL2 = resultsArray.map(deserializeL2Response);\n\t\t\t\tresolve(deserializedL2);\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\treject(error);\n\t\t\t});\n\t});\n}\n\nexport async function fetchAuctionOrderParams(params: RegularOrderParams) {\n\ttry {\n\t\treturn await fetchAuctionOrderParamsFromDlob(params);\n\t} catch (error) {\n\t\tconsole.error(error);\n\t\tconsole.log('Falling back to L2 data');\n\t\treturn await fetchAuctionOrderParamsFromL2(params);\n\t}\n}\n\n/**\n * Fetches auction order parameters from the auction params endpoint\n */\nexport async function fetchAuctionOrderParamsFromDlob({\n\tmarketIndex,\n\tmarketType = MarketType.PERP,\n\tdirection,\n\tamount,\n\tdlobServerHttpUrl,\n\tassetType,\n\tdriftClient,\n\toptionalAuctionParamsInputs = {},\n}: RegularOrderParams): Promise<OptionalOrderParams> {\n\tconst baseAmount =\n\t\tassetType === 'base'\n\t\t\t? amount\n\t\t\t: (() => {\n\t\t\t\t\tconst oraclePrice =\n\t\t\t\t\t\tdriftClient.getOracleDataForPerpMarket(marketIndex).price;\n\t\t\t\t\treturn amount.mul(oraclePrice).div(PRICE_PRECISION);\n\t\t\t })();\n\n\t// Build URL parameters for server request\n\tconst urlParamsObject: Record<string, string> = {\n\t\t// Required fields\n\t\tassetType: 'base',\n\t\tmarketType: ENUM_UTILS.toStr(marketType),\n\t\tmarketIndex: marketIndex.toString(),\n\t\tdirection: ENUM_UTILS.toStr(direction),\n\t\tamount: baseAmount.toString(),\n\t};\n\n\t// Add defined optional parameters\n\tObject.entries(optionalAuctionParamsInputs).forEach(([key, value]) => {\n\t\tif (value !== undefined) {\n\t\t\turlParamsObject[key] = value.toString();\n\t\t}\n\t});\n\n\tconst urlParams = encodeQueryParams(urlParamsObject);\n\n\t// Get order params from server\n\tconst requestUrl = `${dlobServerHttpUrl}/auctionParams?${urlParams.toString()}`;\n\tconst response = await fetch(requestUrl);\n\n\tif (!response.ok) {\n\t\tthrow new Error(\n\t\t\t`Server responded with ${response.status}: ${response.statusText}`\n\t\t);\n\t}\n\n\tconst serverResponse: ServerAuctionParamsResponse = await response.json();\n\tconst serverAuctionParams = serverResponse?.data?.params;\n\tinvariant(serverAuctionParams, 'Server auction params are required');\n\tconst mappedParams: MappedAuctionParams =\n\t\tmapAuctionParamsResponse(serverAuctionParams);\n\n\t// Convert MappedAuctionParams to OptionalOrderParams\n\treturn {\n\t\torderType: mappedParams.orderType,\n\t\tmarketType: mappedParams.marketType,\n\t\tuserOrderId: mappedParams.userOrderId,\n\t\tdirection: mappedParams.direction,\n\t\tbaseAssetAmount: mappedParams.baseAssetAmount,\n\t\tmarketIndex: mappedParams.marketIndex,\n\t\treduceOnly: mappedParams.reduceOnly,\n\t\tpostOnly: mappedParams.postOnly ?? DefaultOrderParams.postOnly,\n\t\ttriggerPrice: mappedParams.triggerPrice || null,\n\t\ttriggerCondition:\n\t\t\tmappedParams.triggerCondition ?? DefaultOrderParams.triggerCondition,\n\t\toraclePriceOffset: mappedParams.oraclePriceOffset?.toNumber() || null,\n\t\tauctionDuration: mappedParams.auctionDuration || null,\n\t\tmaxTs: mappedParams.maxTs,\n\t\tauctionStartPrice: mappedParams.auctionStartPrice || null,\n\t\tauctionEndPrice: mappedParams.auctionEndPrice || null,\n\t\t// no price, because market orders don't need a price\n\t};\n}\n\nconst DEFAULT_L2_DEPTH_FOR_AUCTION_ORDER_PARAMS = 100;\n\n/**\n * Fetches auction order parameters from the L2 data\n */\nexport async function fetchAuctionOrderParamsFromL2({\n\tdlobServerHttpUrl,\n\tmarketIndex,\n\tmarketType,\n\tdirection,\n\tassetType,\n\tamount,\n\toptionalAuctionParamsInputs,\n\tdriftClient,\n\tdynamicSlippageConfig,\n}: RegularOrderParams): Promise<OptionalOrderParams> {\n\tconst marketId = new MarketId(marketIndex, marketType);\n\tconst baseAmount =\n\t\tassetType === 'base'\n\t\t\t? amount\n\t\t\t: (() => {\n\t\t\t\t\tconst oraclePrice =\n\t\t\t\t\t\tdriftClient.getOracleDataForPerpMarket(marketIndex).price;\n\t\t\t\t\treturn amount.mul(oraclePrice).div(PRICE_PRECISION);\n\t\t\t })();\n\n\tconst l2DataResponse = await fetchBulkMarketsDlobL2Data(dlobServerHttpUrl, [\n\t\t{\n\t\t\tmarketId,\n\t\t\tdepth: DEFAULT_L2_DEPTH_FOR_AUCTION_ORDER_PARAMS,\n\t\t},\n\t]);\n\tconst oraclePriceData = l2DataResponse[0].oracleData;\n\tconst oraclePriceBn = oraclePriceData?.price;\n\tconst markPriceBn = l2DataResponse[0].markPrice;\n\tconst l2Data = convertToL2OrderBook(l2DataResponse);\n\n\tconst priceImpactData = calculatePriceImpactFromL2(\n\t\tmarketId,\n\t\tdirection,\n\t\tbaseAmount,\n\t\tl2Data,\n\t\toraclePriceBn\n\t);\n\n\tconst startPrices = COMMON_UI_UTILS.getPriceObject({\n\t\toraclePrice: oraclePriceBn,\n\t\tbestOffer: priceImpactData.bestPrice,\n\t\tentryPrice: priceImpactData.entryPrice,\n\t\tworstPrice: priceImpactData.worstPrice,\n\t\tmarkPrice: markPriceBn,\n\t\tdirection: direction,\n\t});\n\tconst slippageToleranceInput = optionalAuctionParamsInputs.slippageTolerance;\n\tconst derivedSlippage =\n\t\tslippageToleranceInput === 'dynamic'\n\t\t\t? calculateDynamicSlippageFromL2({\n\t\t\t\t\tl2Data,\n\t\t\t\t\tmarketId,\n\t\t\t\t\tstartPrice:\n\t\t\t\t\t\tstartPrices[\n\t\t\t\t\t\t\toptionalAuctionParamsInputs.auctionStartPriceOffsetFrom as keyof typeof startPrices\n\t\t\t\t\t\t],\n\t\t\t\t\tworstPrice: priceImpactData.worstPrice,\n\t\t\t\t\toraclePrice: oraclePriceBn,\n\t\t\t\t\tdynamicSlippageConfig,\n\t\t\t })\n\t\t\t: typeof slippageToleranceInput === 'number'\n\t\t\t? slippageToleranceInput\n\t\t\t: 0.005;\n\n\tconst auctionOrderParams = COMMON_UI_UTILS.deriveMarketOrderParams({\n\t\tmarketType: marketType,\n\t\tmarketIndex: marketIndex,\n\t\tdirection: direction,\n\t\tmaxLeverageSelected: optionalAuctionParamsInputs.maxLeverageSelected,\n\t\tmaxLeverageOrderSize: optionalAuctionParamsInputs.maxLeverageOrderSize,\n\t\tbaseAmount: baseAmount,\n\t\treduceOnly: optionalAuctionParamsInputs.reduceOnly,\n\t\tallowInfSlippage: false,\n\t\toraclePrice: oraclePriceBn,\n\t\tbestPrice: priceImpactData.bestPrice,\n\t\tentryPrice: priceImpactData.entryPrice,\n\t\tworstPrice: priceImpactData.worstPrice,\n\t\tmarkPrice: markPriceBn,\n\t\tauctionDuration: optionalAuctionParamsInputs.auctionDuration,\n\t\tauctionStartPriceOffset:\n\t\t\toptionalAuctionParamsInputs.auctionStartPriceOffset,\n\t\tauctionEndPriceOffset: optionalAuctionParamsInputs.auctionEndPriceOffset,\n\t\tauctionStartPriceOffsetFrom:\n\t\t\toptionalAuctionParamsInputs.auctionStartPriceOffsetFrom,\n\t\tauctionEndPriceOffsetFrom:\n\t\t\toptionalAuctionParamsInputs.auctionEndPriceOffsetFrom,\n\t\tslippageTolerance: derivedSlippage,\n\t\tisOracleOrder: optionalAuctionParamsInputs.isOracleOrder,\n\t\tadditionalEndPriceBuffer:\n\t\t\toptionalAuctionParamsInputs.additionalEndPriceBuffer,\n\t\tforceUpToSlippage: optionalAuctionParamsInputs.forceUpToSlippage,\n\t});\n\n\tif (!auctionOrderParams) {\n\t\tthrow new Error('Failed to derive auction params from L2');\n\t}\n\n\treturn auctionOrderParams;\n}\n\ntype FetchTopMakersParams = {\n\tdlobServerHttpUrl: string;\n\tmarketIndex: number;\n\tmarketType: MarketType;\n\tside: 'bid' | 'ask';\n\tlimit: number;\n};\n\n/**\n * Fetches the top makers information, for use as inputs in placeAndTake market orders.\n * The side of the request should be opposite of the side of the placeAndTake market order.\n */\nexport async function fetchTopMakers(params: FetchTopMakersParams): Promise<\n\t{\n\t\tuserAccountPubKey: PublicKey;\n\t\tuserAccount: UserAccount;\n\t}[]\n> {\n\ttry {\n\t\tconst { dlobServerHttpUrl, marketIndex, marketType, side, limit } = params;\n\n\t\tconst urlParams = encodeQueryParams({\n\t\t\tmarketIndex: marketIndex.toString(),\n\t\t\tmarketType: ENUM_UTILS.toStr(marketType),\n\t\t\tside,\n\t\t\tlimit: limit.toString(),\n\t\t\tincludeAccounts: 'true',\n\t\t});\n\n\t\tconst requestUrl = `${dlobServerHttpUrl}/topMakers?${urlParams}`;\n\t\tconst response = await fetch(requestUrl);\n\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(\n\t\t\t\t`Server responded with ${response.status}: ${response.statusText}`\n\t\t\t);\n\t\t}\n\n\t\tconst serverResponse: {\n\t\t\tuserAccountPubKey: string;\n\t\t\taccountBase64: string;\n\t\t}[] = await response.json();\n\t\tconst mappedParams: {\n\t\t\tuserAccountPubKey: PublicKey;\n\t\t\tuserAccount: UserAccount;\n\t\t}[] = serverResponse.map((value) => ({\n\t\t\tuserAccountPubKey: new PublicKey(value.userAccountPubKey),\n\t\t\tuserAccount: decodeUser(Buffer.from(value.accountBase64, 'base64')),\n\t\t}));\n\n\t\treturn mappedParams;\n\t} catch (e) {\n\t\tconsole.error(e);\n\t\treturn [];\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/dlobServer/index.ts"],"names":[],"mappings":";;;;;;AAAA,yCAayB;AACzB,mDAAqD;AACrD,kGAI0D;AAC1D,yDAAkE;AAClE,mDAAqE;AACrE,iEAO2C;AAC3C,uFAAoF;AACpF,qEAAiF;AACjF,uEAAoE;AACpE,oEAAuC;AAqDvC,MAAM,yBAAyB,GAAG,MAAM,CAAC,2BAA2B,CAAC,CAAC;AAEtE;;GAEG;AACH,SAAgB,0BAA0B,CACzC,iBAAyB,EACzB,OAGG,EACH,YAAqB,EACrB,0BAA0B,GAAG,KAAK;IAElC,MAAM,MAAM,GAAyB;QACpC,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;YAC5B,WAAW,EAAE,CAAC,CAAC,QAAQ,CAAC,WAAW;YACnC,UAAU,EAAE,CAAC,CAAC,QAAQ,CAAC,aAAa;YACpC,KAAK,EAAE,CAAC,CAAC,KAAK;YACd,WAAW,EAAE,CAAC,CAAC,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AU,CAAC;YACxC,IAAI;YACJ,KAAK,EAAE,KAAK,CAAC,QAAQ,EAAE;YACvB,eAAe,EAAE,MAAM;SACvB,CAAC,CAAC;QAEH,MAAM,UAAU,GAAG,GAAG,iBAAiB,cAAc,SAAS,EAAE,CAAC;QACjE,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,UAAU,CAAC,CAAC;QAEzC,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YAClB,MAAM,IAAI,KAAK,CACd,yBAAyB,QAAQ,CAAC,MAAM,KAAK,QAAQ,CAAC,UAAU,EAAE,CAClE,CAAC;QACH,CAAC;QAED,MAAM,cAAc,GAGd,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QAC5B,MAAM,YAAY,GAGZ,cAAc,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;YACpC,iBAAiB,EAAE,IAAI,eAAS,CAAC,KAAK,CAAC,iBAAiB,CAAC;YACzD,WAAW,EAAE,IAAA,gBAAU,EAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAC;SACnE,CAAC,CAAC,CAAC;QAEJ,OAAO,YAAY,CAAC;IACrB,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACZ,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACjB,OAAO,EAAE,CAAC;IACX,CAAC;AACF,CAAC;AA3CD,wCA2CC","sourcesContent":["import {\n\tDriftClient,\n\tUser,\n\tBN,\n\tPositionDirection,\n\tOptionalOrderParams,\n\tMarketType,\n\tUserAccount,\n\tPublicKey,\n\tdecodeUser,\n\tDefaultOrderParams,\n\tPRICE_PRECISION,\n\tBASE_PRECISION,\n} from '@drift-labs/sdk';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport {\n\tmapAuctionParamsResponse,\n\tServerAuctionParamsResponse,\n\tMappedAuctionParams,\n} from '../../../../../utils/auctionParamsResponseMapper';\nimport { encodeQueryParams } from '../../../../../../utils/fetch';\nimport { MarketId, TradeOffsetPrice } from '../../../../../../types';\nimport {\n\tconvertToL2OrderBook,\n\tdeserializeL2Response,\n\tL2WithOracleAndMarketData,\n\tRawL2Output,\n\tcalculateDynamicSlippageFromL2,\n\tDynamicSlippageConfig,\n} from '../../../../../../utils/orderbook';\nimport { PollingSequenceGuard } from '../../../../../../utils/pollingSequenceGuard';\nimport { calculatePriceImpactFromL2 } from '../../../../../../utils/priceImpact';\nimport { COMMON_UI_UTILS } from '../../../../../../common-ui-utils';\nimport invariant from 'tiny-invariant';\n\nexport interface OptionalAuctionParamsRequestInputs {\n\t// Optional parameters that can override defaults or provide additional configuration\n\tmaxLeverageSelected?: boolean;\n\tmaxLeverageOrderSize?: BN;\n\treduceOnly?: boolean;\n\tauctionDuration?: number;\n\tauctionStartPriceOffset?: number;\n\tauctionEndPriceOffset?: number;\n\tauctionStartPriceOffsetFrom?: TradeOffsetPrice;\n\tauctionEndPriceOffsetFrom?: TradeOffsetPrice;\n\tslippageTolerance?: number | 'dynamic';\n\tauctionPriceCaps?: {\n\t\tmin: BN;\n\t\tmax: BN;\n\t};\n\tisOracleOrder?: boolean;\n\tadditionalEndPriceBuffer?: BN;\n\tforceUpToSlippage?: boolean;\n\torderType?: 'market' | 'oracle';\n}\n\ninterface RegularOrderParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tassetType: 'base' | 'quote';\n\tmarketType?: MarketType;\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\tamount: BN;\n\toptionalAuctionParamsInputs?: OptionalAuctionParamsRequestInputs;\n\tdlobServerHttpUrl: string;\n\tdynamicSlippageConfig?: DynamicSlippageConfig;\n}\n\nexport interface BulkL2FetchingQueryParams {\n\tmarketIndex: number;\n\tmarketType: string;\n\tdepth: number;\n\tincludeVamm: boolean;\n\tincludePhoenix: boolean;\n\tincludeOpenbook: boolean;\n\tincludeSerum: boolean;\n\tincludeOracle: boolean;\n\tincludeIndicative: boolean;\n}\n\nexport interface BulkL2FetchingParams {\n\tmarkets: BulkL2FetchingQueryParams[];\n\tgrouping?: number;\n}\n\nconst BACKGROUND_L2_POLLING_KEY = Symbol('BACKGROUND_L2_POLLING_KEY');\n\n/**\n * Fetches the L2 data for the given markets and their depth\n */\nexport function fetchBulkMarketsDlobL2Data(\n\tdlobServerHttpUrl: string,\n\tmarkets: {\n\t\tmarketId: MarketId;\n\t\tdepth: number;\n\t}[],\n\tgroupingSize?: number,\n\texcludeIndicativeLiquidity = false\n): Promise<L2WithOracleAndMarketData[]> {\n\tconst params: BulkL2FetchingParams = {\n\t\tmarkets: markets.map((m) => ({\n\t\t\tmarketIndex: m.marketId.marketIndex,\n\t\t\tmarketType: m.marketId.marketTypeStr,\n\t\t\tdepth: m.depth,\n\t\t\tincludeVamm: m.marketId.isPerp,\n\t\t\tincludePhoenix: m.marketId.isSpot,\n\t\t\tincludeSerum: m.marketId.isSpot,\n\t\t\tincludeOpenbook: m.marketId.isSpot,\n\t\t\tincludeOracle: true,\n\t\t\tincludeIndicative: !excludeIndicativeLiquidity,\n\t\t})),\n\t\tgrouping: groupingSize,\n\t};\n\n\tconst queryParamsMap: {\n\t\t[K in keyof BulkL2FetchingQueryParams]: string;\n\t} & {\n\t\tgrouping?: string;\n\t} = {\n\t\tmarketType: params.markets.map((market) => market.marketType).join(','),\n\t\tmarketIndex: params.markets.map((market) => market.marketIndex).join(','),\n\t\tdepth: params.markets.map((market) => market.depth).join(','),\n\t\tincludeVamm: params.markets.map((market) => market.includeVamm).join(','),\n\t\tincludePhoenix: params.markets\n\t\t\t.map((market) => market.includePhoenix)\n\t\t\t.join(','),\n\t\tincludeOpenbook: params.markets\n\t\t\t.map((market) => market.includeOpenbook)\n\t\t\t.join(','),\n\t\tincludeSerum: params.markets.map((market) => market.includeSerum).join(','),\n\t\tgrouping: params.grouping\n\t\t\t? params.markets.map(() => params.grouping).join(',')\n\t\t\t: undefined,\n\t\tincludeOracle: params.markets\n\t\t\t.map((market) => market.includeOracle)\n\t\t\t.join(','),\n\t\tincludeIndicative: params.markets\n\t\t\t.map((market) => market.includeIndicative)\n\t\t\t.join(','),\n\t};\n\n\tconst queryParams = encodeQueryParams(queryParamsMap);\n\n\t// Use cached endpoint when exclusively fetching background markets\n\tconst useCachedEndpoint = !params.markets.some(\n\t\t(market) => market.depth !== 1\n\t);\n\n\tconst endpoint = useCachedEndpoint\n\t\t? `${dlobServerHttpUrl}/batchL2Cache`\n\t\t: `${dlobServerHttpUrl}/batchL2`;\n\n\treturn new Promise<L2WithOracleAndMarketData[]>((resolve, reject) => {\n\t\tPollingSequenceGuard.fetch(BACKGROUND_L2_POLLING_KEY, () => {\n\t\t\treturn fetch(`${endpoint}?${queryParams}`);\n\t\t})\n\t\t\t.then(async (response) => {\n\t\t\t\tconst responseData = await response.json();\n\t\t\t\tconst resultsArray = responseData.l2s as RawL2Output[];\n\t\t\t\tconst deserializedL2 = resultsArray.map(deserializeL2Response);\n\t\t\t\tresolve(deserializedL2);\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\treject(error);\n\t\t\t});\n\t});\n}\n\nexport async function fetchAuctionOrderParams(params: RegularOrderParams) {\n\ttry {\n\t\treturn await fetchAuctionOrderParamsFromDlob(params);\n\t} catch (error) {\n\t\tconsole.error(error);\n\t\tconsole.log('Falling back to L2 data');\n\t\treturn await fetchAuctionOrderParamsFromL2(params);\n\t}\n}\n\n/**\n * Fetches auction order parameters from the auction params endpoint\n */\nexport async function fetchAuctionOrderParamsFromDlob({\n\tmarketIndex,\n\tmarketType = MarketType.PERP,\n\tdirection,\n\tamount,\n\tdlobServerHttpUrl,\n\tassetType,\n\tdriftClient,\n\toptionalAuctionParamsInputs = {},\n}: RegularOrderParams): Promise<OptionalOrderParams> {\n\tconst baseAmount =\n\t\tassetType === 'base'\n\t\t\t? amount\n\t\t\t: (() => {\n\t\t\t\t\tconst oraclePrice =\n\t\t\t\t\t\tdriftClient.getOracleDataForPerpMarket(marketIndex).price;\n\t\t\t\t\treturn amount.mul(BASE_PRECISION).div(oraclePrice);\n\t\t\t })();\n\n\t// Build URL parameters for server request\n\tconst urlParamsObject: Record<string, string> = {\n\t\t// Required fields\n\t\tassetType: 'base',\n\t\tmarketType: ENUM_UTILS.toStr(marketType),\n\t\tmarketIndex: marketIndex.toString(),\n\t\tdirection: ENUM_UTILS.toStr(direction),\n\t\tamount: baseAmount.toString(),\n\t};\n\n\t// Add defined optional parameters\n\tObject.entries(optionalAuctionParamsInputs).forEach(([key, value]) => {\n\t\tif (value !== undefined) {\n\t\t\turlParamsObject[key] = value.toString();\n\t\t}\n\t});\n\n\tconst urlParams = encodeQueryParams(urlParamsObject);\n\n\t// Get order params from server\n\tconst requestUrl = `${dlobServerHttpUrl}/auctionParams?${urlParams.toString()}`;\n\tconst response = await fetch(requestUrl);\n\n\tif (!response.ok) {\n\t\tthrow new Error(\n\t\t\t`Server responded with ${response.status}: ${response.statusText}`\n\t\t);\n\t}\n\n\tconst serverResponse: ServerAuctionParamsResponse = await response.json();\n\tconst serverAuctionParams = serverResponse?.data?.params;\n\tinvariant(serverAuctionParams, 'Server auction params are required');\n\tconst mappedParams: MappedAuctionParams =\n\t\tmapAuctionParamsResponse(serverAuctionParams);\n\n\t// Convert MappedAuctionParams to OptionalOrderParams\n\treturn {\n\t\torderType: mappedParams.orderType,\n\t\tmarketType: mappedParams.marketType,\n\t\tuserOrderId: mappedParams.userOrderId,\n\t\tdirection: mappedParams.direction,\n\t\tbaseAssetAmount: mappedParams.baseAssetAmount,\n\t\tmarketIndex: mappedParams.marketIndex,\n\t\treduceOnly: mappedParams.reduceOnly,\n\t\tpostOnly: mappedParams.postOnly ?? DefaultOrderParams.postOnly,\n\t\ttriggerPrice: mappedParams.triggerPrice || null,\n\t\ttriggerCondition:\n\t\t\tmappedParams.triggerCondition ?? DefaultOrderParams.triggerCondition,\n\t\toraclePriceOffset: mappedParams.oraclePriceOffset?.toNumber() || null,\n\t\tauctionDuration: mappedParams.auctionDuration || null,\n\t\tmaxTs: mappedParams.maxTs,\n\t\tauctionStartPrice: mappedParams.auctionStartPrice || null,\n\t\tauctionEndPrice: mappedParams.auctionEndPrice || null,\n\t\t// no price, because market orders don't need a price\n\t};\n}\n\nconst DEFAULT_L2_DEPTH_FOR_AUCTION_ORDER_PARAMS = 100;\n\n/**\n * Fetches auction order parameters from the L2 data\n */\nexport async function fetchAuctionOrderParamsFromL2({\n\tdlobServerHttpUrl,\n\tmarketIndex,\n\tmarketType,\n\tdirection,\n\tassetType,\n\tamount,\n\toptionalAuctionParamsInputs,\n\tdriftClient,\n\tdynamicSlippageConfig,\n}: RegularOrderParams): Promise<OptionalOrderParams> {\n\tconst marketId = new MarketId(marketIndex, marketType);\n\tconst baseAmount =\n\t\tassetType === 'base'\n\t\t\t? amount\n\t\t\t: (() => {\n\t\t\t\t\tconst oraclePrice =\n\t\t\t\t\t\tdriftClient.getOracleDataForPerpMarket(marketIndex).price;\n\t\t\t\t\treturn amount.mul(oraclePrice).div(PRICE_PRECISION);\n\t\t\t })();\n\n\tconst l2DataResponse = await fetchBulkMarketsDlobL2Data(dlobServerHttpUrl, [\n\t\t{\n\t\t\tmarketId,\n\t\t\tdepth: DEFAULT_L2_DEPTH_FOR_AUCTION_ORDER_PARAMS,\n\t\t},\n\t]);\n\tconst oraclePriceData = l2DataResponse[0].oracleData;\n\tconst oraclePriceBn = oraclePriceData?.price;\n\tconst markPriceBn = l2DataResponse[0].markPrice;\n\tconst l2Data = convertToL2OrderBook(l2DataResponse);\n\n\tconst priceImpactData = calculatePriceImpactFromL2(\n\t\tmarketId,\n\t\tdirection,\n\t\tbaseAmount,\n\t\tl2Data,\n\t\toraclePriceBn\n\t);\n\n\tconst startPrices = COMMON_UI_UTILS.getPriceObject({\n\t\toraclePrice: oraclePriceBn,\n\t\tbestOffer: priceImpactData.bestPrice,\n\t\tentryPrice: priceImpactData.entryPrice,\n\t\tworstPrice: priceImpactData.worstPrice,\n\t\tmarkPrice: markPriceBn,\n\t\tdirection: direction,\n\t});\n\tconst slippageToleranceInput = optionalAuctionParamsInputs.slippageTolerance;\n\tconst derivedSlippage =\n\t\tslippageToleranceInput === 'dynamic'\n\t\t\t? calculateDynamicSlippageFromL2({\n\t\t\t\t\tl2Data,\n\t\t\t\t\tmarketId,\n\t\t\t\t\tstartPrice:\n\t\t\t\t\t\tstartPrices[\n\t\t\t\t\t\t\toptionalAuctionParamsInputs.auctionStartPriceOffsetFrom as keyof typeof startPrices\n\t\t\t\t\t\t],\n\t\t\t\t\tworstPrice: priceImpactData.worstPrice,\n\t\t\t\t\toraclePrice: oraclePriceBn,\n\t\t\t\t\tdynamicSlippageConfig,\n\t\t\t })\n\t\t\t: typeof slippageToleranceInput === 'number'\n\t\t\t? slippageToleranceInput\n\t\t\t: 0.005;\n\n\tconst auctionOrderParams = COMMON_UI_UTILS.deriveMarketOrderParams({\n\t\tmarketType: marketType,\n\t\tmarketIndex: marketIndex,\n\t\tdirection: direction,\n\t\tmaxLeverageSelected: optionalAuctionParamsInputs.maxLeverageSelected,\n\t\tmaxLeverageOrderSize: optionalAuctionParamsInputs.maxLeverageOrderSize,\n\t\tbaseAmount: baseAmount,\n\t\treduceOnly: optionalAuctionParamsInputs.reduceOnly,\n\t\tallowInfSlippage: false,\n\t\toraclePrice: oraclePriceBn,\n\t\tbestPrice: priceImpactData.bestPrice,\n\t\tentryPrice: priceImpactData.entryPrice,\n\t\tworstPrice: priceImpactData.worstPrice,\n\t\tmarkPrice: markPriceBn,\n\t\tauctionDuration: optionalAuctionParamsInputs.auctionDuration,\n\t\tauctionStartPriceOffset:\n\t\t\toptionalAuctionParamsInputs.auctionStartPriceOffset,\n\t\tauctionEndPriceOffset: optionalAuctionParamsInputs.auctionEndPriceOffset,\n\t\tauctionStartPriceOffsetFrom:\n\t\t\toptionalAuctionParamsInputs.auctionStartPriceOffsetFrom,\n\t\tauctionEndPriceOffsetFrom:\n\t\t\toptionalAuctionParamsInputs.auctionEndPriceOffsetFrom,\n\t\tslippageTolerance: derivedSlippage,\n\t\tisOracleOrder: optionalAuctionParamsInputs.isOracleOrder,\n\t\tadditionalEndPriceBuffer:\n\t\t\toptionalAuctionParamsInputs.additionalEndPriceBuffer,\n\t\tforceUpToSlippage: optionalAuctionParamsInputs.forceUpToSlippage,\n\t});\n\n\tif (!auctionOrderParams) {\n\t\tthrow new Error('Failed to derive auction params from L2');\n\t}\n\n\treturn auctionOrderParams;\n}\n\ntype FetchTopMakersParams = {\n\tdlobServerHttpUrl: string;\n\tmarketIndex: number;\n\tmarketType: MarketType;\n\tside: 'bid' | 'ask';\n\tlimit: number;\n};\n\n/**\n * Fetches the top makers information, for use as inputs in placeAndTake market orders.\n * The side of the request should be opposite of the side of the placeAndTake market order.\n */\nexport async function fetchTopMakers(params: FetchTopMakersParams): Promise<\n\t{\n\t\tuserAccountPubKey: PublicKey;\n\t\tuserAccount: UserAccount;\n\t}[]\n> {\n\ttry {\n\t\tconst { dlobServerHttpUrl, marketIndex, marketType, side, limit } = params;\n\n\t\tconst urlParams = encodeQueryParams({\n\t\t\tmarketIndex: marketIndex.toString(),\n\t\t\tmarketType: ENUM_UTILS.toStr(marketType),\n\t\t\tside,\n\t\t\tlimit: limit.toString(),\n\t\t\tincludeAccounts: 'true',\n\t\t});\n\n\t\tconst requestUrl = `${dlobServerHttpUrl}/topMakers?${urlParams}`;\n\t\tconst response = await fetch(requestUrl);\n\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(\n\t\t\t\t`Server responded with ${response.status}: ${response.statusText}`\n\t\t\t);\n\t\t}\n\n\t\tconst serverResponse: {\n\t\t\tuserAccountPubKey: string;\n\t\t\taccountBase64: string;\n\t\t}[] = await response.json();\n\t\tconst mappedParams: {\n\t\t\tuserAccountPubKey: PublicKey;\n\t\t\tuserAccount: UserAccount;\n\t\t}[] = serverResponse.map((value) => ({\n\t\t\tuserAccountPubKey: new PublicKey(value.userAccountPubKey),\n\t\t\tuserAccount: decodeUser(Buffer.from(value.accountBase64, 'base64')),\n\t\t}));\n\n\t\treturn mappedParams;\n\t} catch (e) {\n\t\tconsole.error(e);\n\t\treturn [];\n\t}\n}\n"]}
|