@drift-labs/common 1.0.3 → 1.0.5
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/clients/redisClient.d.ts +1 -0
- package/lib/clients/swiftClient.d.ts +1 -0
- package/lib/common-ui-utils/commonUiUtils.d.ts +2 -0
- package/lib/common-ui-utils/order.d.ts +1 -0
- package/lib/common-ui-utils/trading.d.ts +1 -0
- package/lib/drift/Drift/clients/AuthorityDrift/DriftL2OrderbookManager.d.ts +6 -5
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js +2 -0
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js.map +1 -1
- package/lib/drift/Drift/clients/CentralServerDrift.d.ts +3 -1
- package/lib/drift/Drift/clients/CentralServerDrift.js +5 -0
- package/lib/drift/Drift/clients/CentralServerDrift.js.map +1 -1
- package/lib/drift/Drift/stores/MarkPriceCache.d.ts +1 -0
- package/lib/drift/Drift/stores/OraclePriceCache.d.ts +1 -0
- package/lib/drift/base/actions/trade/editOrder.d.ts +1 -0
- package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.d.ts +1 -0
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.d.ts +1 -0
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.d.ts +1 -0
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js +19 -8
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/types.d.ts +1 -0
- package/lib/drift/base/actions/trade/swap.d.ts +1 -0
- package/lib/drift/base/actions/user/create.d.ts +1 -0
- package/lib/drift/cli.d.ts +1 -0
- package/lib/drift/utils/auctionParamsResponseMapper.d.ts +1 -0
- package/lib/drift/utils/orderParams.d.ts +1 -0
- package/lib/serializableTypes.d.ts +1 -0
- package/lib/types/UIMarket.d.ts +3 -2
- package/lib/types/leaderboard.d.ts +1 -0
- package/lib/types/trade.d.ts +1 -0
- package/lib/types/user.d.ts +1 -0
- package/lib/utils/NumLib.d.ts +1 -0
- package/lib/utils/candles/Candle.d.ts +1 -0
- package/lib/utils/index.d.ts +2 -0
- package/lib/utils/math.d.ts +1 -0
- package/lib/utils/orderbook/index.d.ts +1 -0
- package/package.json +1 -1
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
/// <reference types="node" />
|
|
2
|
+
/// <reference types="node" />
|
|
2
3
|
import { AccountInfo, Connection, PublicKey } from '@solana/web3.js';
|
|
3
4
|
import { DriftClient, MarketType, OrderType, SignedMsgOrderParamsDelegateMessage, SignedMsgOrderParamsMessage } from '@drift-labs/sdk';
|
|
4
5
|
import { Observable, Subscriber } from 'rxjs';
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
/// <reference types="bn.js" />
|
|
2
|
+
/// <reference types="node" />
|
|
1
3
|
/// <reference types="node" />
|
|
2
4
|
import { BN, BigNum, DriftClient, IWallet, MarketType, OptionalOrderParams, OrderType, PositionDirection, PublicKey, SpotMarketConfig, User, UserAccount } from '@drift-labs/sdk';
|
|
3
5
|
import { AccountInfo, Connection, ParsedAccountData } from '@solana/web3.js';
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
/// <reference types="bn.js" />
|
|
1
2
|
import { Subscription } from 'rxjs';
|
|
2
3
|
import { MarketId } from '../../../../types';
|
|
3
4
|
import { L2WithOracleAndMarketData } from '../../../../utils/orderbook';
|
|
@@ -24,11 +25,11 @@ export declare class DriftL2OrderbookManager {
|
|
|
24
25
|
marketName: string;
|
|
25
26
|
marketType?: import("../../../../../../protocol/sdk/lib/node").MarketType;
|
|
26
27
|
oracleData: import("../../../../../../protocol/sdk/lib/node").OraclePriceData;
|
|
27
|
-
markPrice: import("
|
|
28
|
-
bestBidPrice: import("
|
|
29
|
-
bestAskPrice: import("
|
|
30
|
-
spreadPct: import("
|
|
31
|
-
spreadQuote: import("
|
|
28
|
+
markPrice: import("@coral-xyz/anchor").BN;
|
|
29
|
+
bestBidPrice: import("@coral-xyz/anchor").BN;
|
|
30
|
+
bestAskPrice: import("@coral-xyz/anchor").BN;
|
|
31
|
+
spreadPct: import("@coral-xyz/anchor").BN;
|
|
32
|
+
spreadQuote: import("@coral-xyz/anchor").BN;
|
|
32
33
|
mmOracleData?: import("../../../../../../protocol/sdk/lib/node").MMOraclePriceData;
|
|
33
34
|
asks: import("../../../../../../protocol/sdk/lib/node").L2Level[];
|
|
34
35
|
bids: import("../../../../../../protocol/sdk/lib/node").L2Level[];
|
|
@@ -275,6 +275,7 @@ class DriftOperations {
|
|
|
275
275
|
// @ts-ignore TODO: we might want to add signMessage to the IWallet interface
|
|
276
276
|
wallet: this.driftClient.wallet,
|
|
277
277
|
swiftServerUrl: this.swiftServerUrl,
|
|
278
|
+
...params.orderConfig.swiftOptions,
|
|
278
279
|
},
|
|
279
280
|
direction: params.direction,
|
|
280
281
|
amount: amountBN,
|
|
@@ -326,6 +327,7 @@ class DriftOperations {
|
|
|
326
327
|
// @ts-ignore TODO: we might want to add signMessage to the IWallet interface
|
|
327
328
|
wallet: this.driftClient.wallet,
|
|
328
329
|
swiftServerUrl: this.swiftServerUrl,
|
|
330
|
+
...params.orderConfig.swiftOptions,
|
|
329
331
|
},
|
|
330
332
|
});
|
|
331
333
|
return swiftOrderResult;
|
|
@@ -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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AK,CAAC;IACd,CAAC;;AA9oBF,0CA+oBC;AA9oBgB,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;AA0oBjL;;;;;;;;;;;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},\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},\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,yCAWyB;AAEzB,kEAAqE;AACrE,wDAAwD;AACxD,oEAAuE;AAEvE,mEAAyE;AACzE,iEAA6F;AAC7F,qEAA2E;AAC3E,iEAAqE;AACrE,uEAA6E;AAU7E,4EAAmF;AACnF,0GAG0E;AAC1E,8DAAoE;AACpE,gHAAmH;AAEnH;;;;;;;GAOG;AACH,MAAa,eAAe;IAS3B;;;;;;OAMG;IACH,YACS,WAAwB,EACxB,mBAA2C,EAC3C,iBAAyB,EACzB,cAAsB,EACtB,cAA4B;QAJ5B,gBAAW,GAAX,WAAW,CAAa;QACxB,wBAAmB,GAAnB,mBAAmB,CAAwB;QAC3C,sBAAiB,GAAjB,iBAAiB,CAAQ;QACzB,mBAAc,GAAd,cAAc,CAAQ;QACtB,mBAAc,GAAd,cAAc,CAAc;IAClC,CAAC;IAEJ;;;OAGG;IACK,WAAW,CAAC,SAA6B;;QAChD,MAAM,iBAAiB,GAAG,IAAI,CAAC,KAAK,CACnC,MAAA,IAAI,CAAC,cAAc,EAAE,mCACpB,eAAe,CAAC,iBAAiB,CAAC,iBAAiB,CACpD,CAAC;QAEF,MAAM,eAAe,GAAG,IAAI,CAAC,GAAG,CAC/B,iBAAiB,EACjB,eAAe,CAAC,uBAAuB,CACvC,CAAC;QAEF,OAAO;YACN,GAAG,eAAe,CAAC,iBAAiB;YACpC,iBAAiB,EAAE,eAAe;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,eAAe,CACp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AAC;YAClB,MAAM,IAAI,KAAK,CAAC,gBAAgB,CAAC,CAAC;QACnC,CAAC;QAED,MAAM,eAAe,GAAG,MAAM,IAAA,mCAAqB,EAClD,IAAI,CAAC,WAAW,EAChB,WAAW,CAAC,UAAU,EACtB,QAAQ,EACR,IAAI,CAAC,WAAW,EAAE,CAClB,CAAC;QAEF,MAAM,EAAE,KAAK,EAAE,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,eAAe,CAAC,eAAe,CAAC,CAAC;QAE1E,OAAO,KAAK,CAAC;IACd,CAAC;;AAhpBF,0CAipBC;AAhpBgB,iCAAiB,GAAa;IAC7C,iBAAiB,EAAE,KAAM;IACzB,wBAAwB,EAAE,IAAI;IAC9B,4BAA4B,EAAE,GAAG;CACjC,CAAC;AAEc,uCAAuB,GAAG,IAAI,GAAG,EAAE,GAAG,OAAS,CAAC,CAAC,+GAA+G;AA4oBjL;;;;;;;;;;;GAWG","sourcesContent":["import {\n\tBigNum,\n\tDriftClient,\n\tJupiterClient,\n\tMarketType,\n\tMAX_LEVERAGE_ORDER_SIZE,\n\tQuoteResponse,\n\tSwapMode,\n\tTxParams,\n\tUser,\n\tZERO,\n} from '@drift-labs/sdk';\nimport { TransactionSignature } from '@solana/web3.js';\nimport { MARKET_UTILS } from '../../../../../common-ui-utils/market';\nimport { MAIN_POOL_ID } from '../../../../../constants';\nimport { TRADING_UTILS } from '../../../../../common-ui-utils/trading';\nimport { UserAccountCache } from '../../../stores/UserAccountCache';\nimport { createDepositTxn } from '../../../../base/actions/spot/deposit';\nimport { createUserAndDepositCollateralBaseTxn } from '../../../../base/actions/user/create';\nimport { createWithdrawTxn } from '../../../../base/actions/spot/withdraw';\nimport { deleteUserTxn } from '../../../../base/actions/user/delete';\nimport { createSettlePnlTxn } from '../../../../base/actions/perp/settlePnl';\nimport {\n\tCreateUserAndDepositParams,\n\tDepositParams,\n\tWithdrawParams,\n\tPerpOrderParams,\n\tSwapParams,\n\tSettleAccountPnlParams,\n\tCancelOrdersParams,\n} from './types';\nimport { createCancelOrdersTxn } from '../../../../base/actions/trade/cancelOrder';\nimport {\n\tcreateOpenPerpMarketOrder,\n\tOpenPerpMarketOrderParams,\n} from '../../../../base/actions/trade/openPerpOrder/openPerpMarketOrder';\nimport { createSwapTxn } from '../../../../base/actions/trade/swap';\nimport { createOpenPerpNonMarketOrder } from '../../../../base/actions/trade/openPerpOrder/openPerpNonMarketOrder';\n\n/**\n * Handles majority of the relevant operations on the Drift program including deposits,\n * withdrawals, position management, and trading operations.\n *\n * This class encapsulates the trading logic and provides a clean API for\n * executing various trading operations while handling common patterns like\n * token address resolution and transaction preparation.\n */\nexport class DriftOperations {\n\tstatic readonly DEFAULT_TX_PARAMS: TxParams = {\n\t\tcomputeUnitsPrice: 50_000,\n\t\tuseSimulatedComputeUnits: true,\n\t\tcomputeUnitsBufferMultiplier: 1.3,\n\t};\n\n\tstatic readonly MAX_COMPUTE_UNITS_PRICE = 1e15 / 10 / 1_400_000; // 1e15 = 1 SOL worth of micro lamports; 1e15 / 10 = 0.1 SOL worth of micro lamports; 1.4M = max compute units;\n\n\t/**\n\t * Creates a new DriftOperations instance.\n\t *\n\t * @param driftClient - The DriftClient instance for executing transactions\n\t * @param getUserAccountCache - Function to get the user account cache. We lazily load the user account cache, so that we always get the latest user account data.\n\t * @param getPriorityFee - Function to get current priority fee in micro lamports\n\t */\n\tconstructor(\n\t\tprivate driftClient: DriftClient,\n\t\tprivate getUserAccountCache: () => UserAccountCache,\n\t\tprivate dlobServerHttpUrl: string,\n\t\tprivate swiftServerUrl: string,\n\t\tprivate getPriorityFee: () => number\n\t) {}\n\n\t/**\n\t * Gets transaction parameters with dynamic priority fees.\n\t * Falls back to default if priority fee function is not available.\n\t */\n\tprivate getTxParams(overrides?: Partial<TxParams>): TxParams {\n\t\tconst unsafePriorityFee = Math.floor(\n\t\t\tthis.getPriorityFee() ??\n\t\t\t\tDriftOperations.DEFAULT_TX_PARAMS.computeUnitsPrice\n\t\t);\n\n\t\tconst safePriorityFee = Math.min(\n\t\t\tunsafePriorityFee,\n\t\t\tDriftOperations.MAX_COMPUTE_UNITS_PRICE\n\t\t);\n\n\t\treturn {\n\t\t\t...DriftOperations.DEFAULT_TX_PARAMS,\n\t\t\tcomputeUnitsPrice: safePriorityFee,\n\t\t\t...overrides,\n\t\t};\n\t}\n\n\t/**\n\t * Creates a new user account and deposits initial collateral.\n\t *\n\t * This method handles the complete onboarding flow for new users including:\n\t * - Validating that the subaccount doesn't already exist\n\t * - Resolving referrer information if provided\n\t * - Getting the correct token address for deposits\n\t * - Creating the user account with custom leverage settings\n\t * - Subscribing to the new user's account updates\n\t *\n\t * @param params - The parameters for user creation and initial deposit\n\t * @returns Promise resolving to transaction signature and user account public key\n\t *\n\t * @throws Error if subaccount already exists\n\t *\n\t * @example\n\t * ```typescript\n\t * const result = await tradingOps.createUserAndDeposit({\n\t * depositAmount: new BigNum(100),\n\t * depositSpotMarketIndex: 0, // USDC\n\t * name: \"Trading Account\",\n\t * maxLeverage: 5,\n\t * subAccountId: 0\n\t * });\n\t * ```\n\t */\n\tasync createUserAndDeposit(params: CreateUserAndDepositParams): Promise<{\n\t\ttxSig: TransactionSignature;\n\t\tuser: User;\n\t}> {\n\t\tconst {\n\t\t\tdepositAmount,\n\t\t\tdepositSpotMarketIndex,\n\t\t\tnewAccountName,\n\t\t\tmaxLeverage,\n\t\t\tpoolId = MAIN_POOL_ID,\n\t\t\treferrerName,\n\t\t} = params;\n\n\t\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tdepositSpotMarketIndex\n\t\t);\n\n\t\tconst customMaxMarginRatio = TRADING_UTILS.convertLeverageToMarginRatio(\n\t\t\tmaxLeverage ?? 0\n\t\t);\n\n\t\tconst { transaction, subAccountId } =\n\t\t\tawait createUserAndDepositCollateralBaseTxn({\n\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\tamount: depositAmount.val,\n\t\t\t\tspotMarketConfig: spotMarketConfig,\n\t\t\t\tauthority: this.driftClient.wallet.publicKey,\n\t\t\t\tuserStatsAccount: this.driftClient.userStats?.getAccount(),\n\t\t\t\taccountName: newAccountName,\n\t\t\t\treferrerName,\n\t\t\t\tcustomMaxMarginRatio,\n\t\t\t\tpoolId,\n\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(transaction);\n\n\t\tawait this.driftClient.addUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t); // adds user to driftclient's user map, subscribes to user account data\n\t\tconst user = this.driftClient.getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tuser.eventEmitter.on('update', () => {\n\t\t\tthis.getUserAccountCache().updateUserAccount(user);\n\t\t});\n\n\t\treturn {\n\t\t\ttxSig,\n\t\t\tuser,\n\t\t};\n\t}\n\n\t/**\n\t * Deletes a user account.\n\t *\n\t * This method removes a user's sub-account from the Drift.\n\t *\n\t * @param subAccountId - The ID of the sub-account to delete\n\t * @returns A promise that resolves to the transaction signature of the deletion\n\t *\n\t * @throws {Error} When the user account is not found in the cache\n\t *\n\t * @example\n\t * ```typescript\n\t * // Delete user sub-account with ID 0\n\t * const txSignature = await tradingOps.deleteUser(0);\n\t * console.log('User deleted with transaction:', txSignature);\n\t * ```\n\t */\n\tasync deleteUser(subAccountId: number): Promise<TransactionSignature> {\n\t\tconst user = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!user) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst deleteTxn = await deleteUserTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuser: user.userClient,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(deleteTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Deposits collateral into a user's spot market position.\n\t *\n\t * This method handles depositing tokens into a user's account, with optional\n\t * support for max borrow repayment scenarios where the deposit amount may be\n\t * over-estimated to ensure complete repayment of borrowed funds.\n\t *\n\t * @param params - The deposit parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.deposit({\n\t * subAccountId: 0,\n\t * amount: new BigNum(50),\n\t * spotMarketIndex: 0, // USDC\n\t * isMaxBorrowRepayment: false\n\t * });\n\t * ```\n\t */\n\tasync deposit(params: DepositParams): Promise<TransactionSignature> {\n\t\tconst { subAccountId, amount, spotMarketIndex, isMaxBorrowRepayment } =\n\t\t\tparams;\n\n\t\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tspotMarketIndex\n\t\t);\n\n\t\tconst user = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!user) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst depositTxn = await createDepositTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuser: user.userClient,\n\t\t\tamount: amount,\n\t\t\tspotMarketConfig: spotMarketConfig,\n\t\t\tisMaxBorrowRepayment,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(depositTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Withdraws collateral from a user's spot market position.\n\t *\n\t * This method handles withdrawing tokens from a user's account with options\n\t * for borrowing (if allowBorrow is true) or reduce-only withdrawals. For max\n\t * withdrawals with reduce-only, the amount is over-estimated to ensure\n\t * complete withdrawal.\n\t *\n\t * @param params - The withdrawal parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.withdraw({\n\t * subAccountId: 0,\n\t * amount: new BigNum(25),\n\t * spotMarketIndex: 0, // USDC\n\t * allowBorrow: false,\n\t * isMax: false\n\t * });\n\t * ```\n\t */\n\tasync withdraw(params: WithdrawParams): Promise<TransactionSignature> {\n\t\tconst {\n\t\t\tsubAccountId,\n\t\t\tamount,\n\t\t\tspotMarketIndex,\n\t\t\tisBorrow = false,\n\t\t\tisMax = false,\n\t\t} = params;\n\n\t\tconst spotMarketConfig = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tspotMarketIndex\n\t\t);\n\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst withdrawTxn = await createWithdrawTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tamount,\n\t\t\tspotMarketConfig,\n\t\t\tuser: accountData.userClient,\n\t\t\tisBorrow,\n\t\t\tisMax,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(withdrawTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Opens a perpetual market order (placeholder for future implementation).\n\t *\n\t * This method will handle opening long or short positions in perpetual markets\n\t * with support for market and limit orders, reduce-only orders, and post-only orders.\n\t *\n\t * @param params - The perp order parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.openPerpMarketOrder({\n\t * marketIndex: 0, // SOL-PERP\n\t * direction: 'long',\n\t * baseAssetAmount: new BigNum(1), // 1 SOL\n\t * orderType: 'market',\n\t * subAccountId: 0\n\t * });\n\t * ```\n\t */\n\tasync openPerpOrder(\n\t\tparams: PerpOrderParams\n\t): Promise<TransactionSignature | void> {\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tparams.subAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst user = accountData.userClient;\n\n\t\tconst processBracketOrders = (bracketOrdersInput?: {\n\t\t\ttakeProfitPrice?: BigNum;\n\t\t\tstopLossPrice?: BigNum;\n\t\t}) => {\n\t\t\tconst bracketOrders: OpenPerpMarketOrderParams['bracketOrders'] = {};\n\n\t\t\tif (bracketOrdersInput?.takeProfitPrice) {\n\t\t\t\tbracketOrders.takeProfit = {\n\t\t\t\t\ttriggerPrice: bracketOrdersInput.takeProfitPrice.val,\n\t\t\t\t\tbaseAssetAmount: params.size.val,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (bracketOrdersInput?.stopLossPrice) {\n\t\t\t\tbracketOrders.stopLoss = {\n\t\t\t\t\ttriggerPrice: bracketOrdersInput.stopLossPrice.val,\n\t\t\t\t\tbaseAssetAmount: params.size.val,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn bracketOrders;\n\t\t};\n\n\t\tconst amountBN = params.isMaxLeverage\n\t\t\t? MAX_LEVERAGE_ORDER_SIZE\n\t\t\t: params.size.val;\n\n\t\tswitch (params.orderConfig.orderType) {\n\t\t\tcase 'market': {\n\t\t\t\tconst useSwift = !params.orderConfig.disableSwift;\n\n\t\t\t\tconst bracketOrders = processBracketOrders(\n\t\t\t\t\tparams.orderConfig.bracketOrders\n\t\t\t\t);\n\n\t\t\t\t// we split the logic for SWIFT and non-SWIFT orders to achieve better type inference\n\t\t\t\tif (useSwift) {\n\t\t\t\t\tconst swiftOrderResult = await createOpenPerpMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\tuseSwift: true,\n\t\t\t\t\t\tswiftOptions: {\n\t\t\t\t\t\t\t// @ts-ignore TODO: we might want to add signMessage to the IWallet interface\n\t\t\t\t\t\t\twallet: this.driftClient.wallet,\n\t\t\t\t\t\t\tswiftServerUrl: this.swiftServerUrl,\n\t\t\t\t\t\t\t...params.orderConfig.swiftOptions,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\tdlobServerHttpUrl: this.dlobServerHttpUrl,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\toptionalAuctionParamsInputs:\n\t\t\t\t\t\t\tparams.orderConfig.optionalAuctionParamsInputs,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn swiftOrderResult;\n\t\t\t\t} else {\n\t\t\t\t\tconst result = await createOpenPerpMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\toptionalAuctionParamsInputs:\n\t\t\t\t\t\t\tparams.orderConfig.optionalAuctionParamsInputs,\n\t\t\t\t\t\tdlobServerHttpUrl: this.dlobServerHttpUrl,\n\t\t\t\t\t\tuseSwift: false,\n\t\t\t\t\t});\n\n\t\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(result);\n\n\t\t\t\t\treturn txSig;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcase 'limit': {\n\t\t\t\tconst useSwift = !params.orderConfig.disableSwift;\n\n\t\t\t\tconst bracketOrders = processBracketOrders(\n\t\t\t\t\tparams.orderConfig.bracketOrders\n\t\t\t\t);\n\n\t\t\t\t// we split the logic for SWIFT and non-SWIFT orders to achieve better type inference\n\t\t\t\tif (useSwift) {\n\t\t\t\t\tconst swiftOrderResult = await createOpenPerpNonMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\torderConfig: {\n\t\t\t\t\t\t\torderType: 'limit',\n\t\t\t\t\t\t\tlimitPrice: params.orderConfig.limitPrice.val,\n\t\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\t},\n\t\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\t\tpostOnly: params.postOnly,\n\t\t\t\t\t\tuseSwift: true,\n\t\t\t\t\t\tswiftOptions: {\n\t\t\t\t\t\t\t// @ts-ignore TODO: we might want to add signMessage to the IWallet interface\n\t\t\t\t\t\t\twallet: this.driftClient.wallet,\n\t\t\t\t\t\t\tswiftServerUrl: this.swiftServerUrl,\n\t\t\t\t\t\t\t...params.orderConfig.swiftOptions,\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\n\t\t\t\t\treturn swiftOrderResult;\n\t\t\t\t} else {\n\t\t\t\t\tconst txn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\t\tamount: amountBN,\n\t\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\t\torderConfig: {\n\t\t\t\t\t\t\torderType: 'limit',\n\t\t\t\t\t\t\tlimitPrice: params.orderConfig.limitPrice.val,\n\t\t\t\t\t\t\tbracketOrders,\n\t\t\t\t\t\t},\n\t\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\t\tpostOnly: params.postOnly,\n\t\t\t\t\t\tuseSwift: false,\n\t\t\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t\t\t});\n\n\t\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\t\t\t\treturn txSig;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcase 'takeProfit':\n\t\t\tcase 'stopLoss': {\n\t\t\t\tconst txn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\tamount: amountBN,\n\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\torderConfig: {\n\t\t\t\t\t\torderType: params.orderConfig.orderType,\n\t\t\t\t\t\ttriggerPrice: params.orderConfig.triggerPrice.val,\n\t\t\t\t\t\tlimitPrice: params.orderConfig.limitPrice?.val ?? ZERO,\n\t\t\t\t\t},\n\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\tuseSwift: false,\n\t\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t\t});\n\n\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\t\t\treturn txSig;\n\t\t\t}\n\t\t\tcase 'oracleLimit': {\n\t\t\t\tconst txn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tdirection: params.direction,\n\t\t\t\t\tmarketIndex: params.marketIndex,\n\t\t\t\t\tamount: amountBN,\n\t\t\t\t\tassetType: params.assetType,\n\t\t\t\t\torderConfig: {\n\t\t\t\t\t\torderType: 'oracleLimit',\n\t\t\t\t\t\toraclePriceOffset: params.orderConfig.oraclePriceOffset.val,\n\t\t\t\t\t},\n\t\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\t\tuseSwift: false,\n\t\t\t\t\ttxParams: this.getTxParams(),\n\t\t\t\t});\n\n\t\t\t\tconst { txSig } = await this.driftClient.sendTransaction(txn);\n\n\t\t\t\treturn txSig;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tconst _exhaustiveCheck: never = params.orderConfig;\n\t\t\t\tthrow new Error('Invalid order type');\n\t\t\t}\n\t\t}\n\t}\n\n\tasync getSwapQuote(\n\t\tparams: Omit<SwapParams, 'jupiterQuote'> & {\n\t\t\tslippageBps?: number;\n\t\t\tswapMode?: SwapMode;\n\t\t\tonlyDirectRoutes?: boolean;\n\t\t}\n\t): Promise<QuoteResponse> {\n\t\tconst jupiterClient = new JupiterClient({\n\t\t\tconnection: this.driftClient.connection,\n\t\t});\n\n\t\tconst inputMint = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tparams.fromMarketIndex\n\t\t).mint;\n\t\tconst outputMint = MARKET_UTILS.getMarketConfig(\n\t\t\tthis.driftClient.env,\n\t\t\tMarketType.SPOT,\n\t\t\tparams.toMarketIndex\n\t\t).mint;\n\n\t\tconst jupiterQuote = await jupiterClient.getQuote({\n\t\t\tinputMint,\n\t\t\toutputMint,\n\t\t\tamount: params.amount.val,\n\t\t\tslippageBps: params.slippageBps,\n\t\t\tswapMode: params.swapMode,\n\t\t\tonlyDirectRoutes: params.onlyDirectRoutes,\n\t\t});\n\n\t\treturn jupiterQuote;\n\t}\n\n\t/**\n\t * Executes a swap between two spot markets (placeholder for future implementation).\n\t *\n\t * This method will handle swapping between different spot markets through\n\t * the Drift protocol's swap functionality.\n\t *\n\t * @param params - The swap parameters\n\t * @returns Promise resolving to the transaction signature\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.executeSwap({\n\t * fromMarketIndex: 0, // USDC\n\t * toMarketIndex: 1, // SOL\n\t * amount: new BigNum(100),\n\t * subAccountId: 0,\n\t * minReceiveAmount: new BigNum(0.5)\n\t * });\n\t * ```\n\t */\n\tasync swap(params: SwapParams): Promise<TransactionSignature> {\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tparams.subAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst jupiterClient = new JupiterClient({\n\t\t\tconnection: this.driftClient.connection,\n\t\t});\n\n\t\tconst jupiterQuote = params.jupiterQuote\n\t\t\t? params.jupiterQuote\n\t\t\t: await this.getSwapQuote(params);\n\n\t\tconst swapTxn = await createSwapTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tjupiterClient,\n\t\t\tuser: accountData.userClient,\n\t\t\tswapFromMarketIndex: params.fromMarketIndex,\n\t\t\tswapToMarketIndex: params.toMarketIndex,\n\t\t\tamount: params.amount.val,\n\t\t\tquote: jupiterQuote,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(swapTxn);\n\n\t\treturn txSig;\n\t}\n\n\t/**\n\t * Settles P&L and funding for all perp position.\n\t *\n\t * @example\n\t * ```typescript\n\t * const txSig = await tradingOps.settlePnl({\n\t * subAccountId: 0,\n\t * marketIndex: 0, // SOL-PERP\n\t * counterpartySubAccountId: 1\n\t * });\n\t * ```\n\t */\n\tasync settleAccountPnl(\n\t\tparams: SettleAccountPnlParams\n\t): Promise<TransactionSignature> {\n\t\tconst { subAccountId } = params;\n\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst marketIndexes = accountData.openPerpPositions.map(\n\t\t\t(position) => position.marketIndex\n\t\t);\n\n\t\tconst settlePnlTxn = await createSettlePnlTxn({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuser: accountData.userClient,\n\t\t\tmarketIndexes,\n\t\t\ttxParams: this.getTxParams(),\n\t\t});\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(settlePnlTxn);\n\n\t\treturn txSig;\n\t}\n\n\tasync cancelOrders(\n\t\tparams: CancelOrdersParams\n\t): Promise<TransactionSignature> {\n\t\tconst { subAccountId, orderIds } = params;\n\n\t\tconst accountData = this.getUserAccountCache().getUser(\n\t\t\tsubAccountId,\n\t\t\tthis.driftClient.wallet.publicKey\n\t\t);\n\n\t\tif (!accountData) {\n\t\t\tthrow new Error('User not found');\n\t\t}\n\n\t\tconst cancelOrdersTxn = await createCancelOrdersTxn(\n\t\t\tthis.driftClient,\n\t\t\taccountData.userClient,\n\t\t\torderIds,\n\t\t\tthis.getTxParams()\n\t\t);\n\n\t\tconst { txSig } = await this.driftClient.sendTransaction(cancelOrdersTxn);\n\n\t\treturn txSig;\n\t}\n}\n\n/**\n * TODO:\n * - transfer between subaccounts\n * - close position?\n * - close multiple positions\n * - edit open order\n * - create user only\n *\n * - open spot order\n * - rename subaccount\n * - withdraw dust positions\n */\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
|
|
1
|
+
/// <reference types="bn.js" />
|
|
2
|
+
import { BN, DriftClientConfig, DriftEnv, MarketType, OrderTriggerCondition, PositionDirection, PublicKey, QuoteResponse, SwapMode, UserAccount } from '@drift-labs/sdk';
|
|
2
3
|
import { Transaction, VersionedTransaction } from '@solana/web3.js';
|
|
3
4
|
import { MarketId } from '../../../types';
|
|
4
5
|
import { OpenPerpMarketOrderParams } from '../../base/actions/trade/openPerpOrder/openPerpMarketOrder';
|
|
@@ -40,6 +41,7 @@ export declare class CentralServerDrift {
|
|
|
40
41
|
* @returns The result of the operation
|
|
41
42
|
*/
|
|
42
43
|
private driftClientContextWrapper;
|
|
44
|
+
getUserAccount(userAccountPublicKey: PublicKey): Promise<UserAccount>;
|
|
43
45
|
getDepositTxn(userAccountPublicKey: PublicKey, amount: BN, spotMarketIndex: number): Promise<VersionedTransaction | Transaction>;
|
|
44
46
|
getWithdrawTxn(userAccountPublicKey: PublicKey, amount: BN, spotMarketIndex: number, options?: {
|
|
45
47
|
isBorrow?: boolean;
|
|
@@ -127,6 +127,11 @@ class CentralServerDrift {
|
|
|
127
127
|
}
|
|
128
128
|
}
|
|
129
129
|
}
|
|
130
|
+
async getUserAccount(userAccountPublicKey) {
|
|
131
|
+
const oneShotUserAccountSubscriber = new sdk_1.OneShotUserAccountSubscriber(this.driftClient.program, userAccountPublicKey, undefined, undefined);
|
|
132
|
+
await oneShotUserAccountSubscriber.subscribe();
|
|
133
|
+
return oneShotUserAccountSubscriber.getUserAccountAndSlot().data;
|
|
134
|
+
}
|
|
130
135
|
async getDepositTxn(userAccountPublicKey, amount, spotMarketIndex) {
|
|
131
136
|
return this.driftClientContextWrapper(userAccountPublicKey, async (user) => {
|
|
132
137
|
const spotMarketConfig = this.spotMarketConfigs.find((market) => market.marketIndex === spotMarketIndex);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CentralServerDrift.js","sourceRoot":"","sources":["../../../../src/drift/Drift/clients/CentralServerDrift.ts"],"names":[],"mappings":";;;AAAA,yCAwByB;AACzB,6CAAgF;AAChF,0EAAyE;AACzE,4CAKsB;AAEtB,6DAAmE;AACnE,+DAAqE;AACrE,yEAA+E;AAC/E,iEAAuE;AACvE,oGAGoE;AACpE,0GAGuE;AACvE,kEAAwE;AACxE,sEAA6E;AAC7E,wDAA8D;AAM9D;;;;GAIG;AACH,MAAa,kBAAkB;IAK9B;;;;;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;gBACf,aAAa;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gDA4cC","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\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 {\n\tcreateOpenPerpMarketOrder,\n\tOpenPerpMarketOrderParams,\n} from '../../base/actions/trade/openPerpOrder/openPerpMarketOrder';\nimport {\n\tcreateOpenPerpNonMarketOrderTxn,\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';\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\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\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});\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\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\tpublic async getOpenPerpMarketOrderTxn<T extends boolean>({\n\t\tuserAccountPublicKey,\n\t\t...rest\n\t}: WithTxnParams<\n\t\tOmit<OpenPerpMarketOrderParams<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 openPerpMarketOrderTxn = await createOpenPerpMarketOrder({\n\t\t\t\t\t...rest,\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t});\n\t\t\t\treturn openPerpMarketOrderTxn;\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\tuserAccountPublicKey,\n\t\t...rest\n\t}: WithTxnParams<\n\t\tOmit<OpenPerpNonMarketOrderParams, 'driftClient' | 'user'>\n\t> & {\n\t\tuserAccountPublicKey: PublicKey;\n\t}): Promise<VersionedTransaction | Transaction | void> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst openPerpNonMarketOrderTxn = await createOpenPerpNonMarketOrderTxn(\n\t\t\t\t\t{\n\t\t\t\t\t\t...rest,\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t}\n\t\t\t\t);\n\n\t\t\t\treturn openPerpNonMarketOrderTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a transaction to edit an existing order\n\t */\n\tpublic async getEditOrderTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\torderId: number,\n\t\teditOrderParams: {\n\t\t\tnewDirection?: PositionDirection;\n\t\t\tnewBaseAmount?: BN;\n\t\t\tnewLimitPrice?: BN;\n\t\t\tnewOraclePriceOffset?: number;\n\t\t\tnewTriggerPrice?: BN;\n\t\t\tnewTriggerCondition?: OrderTriggerCondition;\n\t\t\tauctionDuration?: number;\n\t\t\tauctionStartPrice?: BN;\n\t\t\tauctionEndPrice?: BN;\n\t\t\treduceOnly?: boolean;\n\t\t\tpostOnly?: boolean;\n\t\t\tbitFlags?: number;\n\t\t\tmaxTs?: BN;\n\t\t\tpolicy?: number;\n\t\t}\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst editOrderTxn = await createEditOrderTxn(\n\t\t\t\t\tthis.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\torderId,\n\t\t\t\t\teditOrderParams\n\t\t\t\t);\n\n\t\t\t\treturn editOrderTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a transaction to cancel specific orders by their IDs\n\t */\n\tpublic async getCancelOrdersTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\torderIds: number[]\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst cancelOrdersTxn = await createCancelOrdersTxn(\n\t\t\t\t\tthis.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\torderIds\n\t\t\t\t);\n\n\t\t\t\treturn cancelOrdersTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a transaction to cancel all orders for a user\n\t */\n\tpublic async getCancelAllOrdersTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tmarketType?: MarketType,\n\t\tmarketIndex?: number,\n\t\tdirection?: PositionDirection\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst ix = await this.driftClient.getCancelOrdersIx(\n\t\t\t\t\tmarketType ?? null,\n\t\t\t\t\tmarketIndex ?? null,\n\t\t\t\t\tdirection ?? null,\n\t\t\t\t\tuser.getUserAccount().subAccountId\n\t\t\t\t);\n\n\t\t\t\tconst cancelAllOrdersTxn = await this.driftClient.buildTransaction(ix);\n\n\t\t\t\treturn cancelAllOrdersTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a swap transaction between two spot markets using Jupiter\n\t */\n\tpublic async getSwapTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tfromMarketIndex: number,\n\t\ttoMarketIndex: number,\n\t\tamount: BN,\n\t\toptions?: {\n\t\t\tslippageBps?: number;\n\t\t\tswapMode?: SwapMode;\n\t\t\tonlyDirectRoutes?: boolean;\n\t\t\tquote?: QuoteResponse;\n\t\t}\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst fromSpotMarketConfig = this.spotMarketConfigs.find(\n\t\t\t\t\t(market) => market.marketIndex === fromMarketIndex\n\t\t\t\t);\n\t\t\t\tconst toSpotMarketConfig = this.spotMarketConfigs.find(\n\t\t\t\t\t(market) => market.marketIndex === toMarketIndex\n\t\t\t\t);\n\n\t\t\t\tif (!fromSpotMarketConfig) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`From spot market config not found for index ${fromMarketIndex}`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tif (!toSpotMarketConfig) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`To spot market config not found for index ${toMarketIndex}`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Initialize Jupiter client\n\t\t\t\tconst jupiterClient = new JupiterClient({\n\t\t\t\t\tconnection: this.driftClient.connection,\n\t\t\t\t});\n\n\t\t\t\t// Get quote if not provided\n\t\t\t\tlet quote = options?.quote;\n\t\t\t\tif (!quote) {\n\t\t\t\t\tquote = await jupiterClient.getQuote({\n\t\t\t\t\t\tinputMint: fromSpotMarketConfig.mint,\n\t\t\t\t\t\toutputMint: toSpotMarketConfig.mint,\n\t\t\t\t\t\tamount,\n\t\t\t\t\t\tslippageBps: options?.slippageBps ?? 10, // Default 0.1%\n\t\t\t\t\t\tswapMode: options?.swapMode ?? 'ExactIn',\n\t\t\t\t\t\tonlyDirectRoutes: options?.onlyDirectRoutes ?? false,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tconst swapTxn = await createSwapTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tjupiterClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tswapFromMarketIndex: fromMarketIndex,\n\t\t\t\t\tswapToMarketIndex: toMarketIndex,\n\t\t\t\t\tamount,\n\t\t\t\t\tquote,\n\t\t\t\t\ttxParams: {\n\t\t\t\t\t\tuseSimulatedComputeUnits: true,\n\t\t\t\t\t\tcomputeUnitsBufferMultiplier: 1.5,\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\treturn swapTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\tpublic async sendSignedTransaction(tx: VersionedTransaction | Transaction) {\n\t\treturn this.driftClient.sendTransaction(tx, undefined, undefined, true);\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"CentralServerDrift.js","sourceRoot":"","sources":["../../../../src/drift/Drift/clients/CentralServerDrift.ts"],"names":[],"mappings":";;;AAAA,yCA0ByB;AACzB,6CAAgF;AAChF,0EAAyE;AACzE,4CAKsB;AAEtB,6DAAmE;AACnE,+DAAqE;AACrE,yEAA+E;AAC/E,iEAAuE;AACvE,oGAGoE;AACpE,0GAGuE;AACvE,kEAAwE;AACxE,sEAA6E;AAC7E,wDAA8D;AAM9D;;;;GAIG;AACH,MAAa,kBAAkB;IAK9B;;;;;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;gBACf,aAAa;aACb;YACD,SAAS,EAAE,KAAK;YAChB,gBAAgB,EAAE,KAAK;YACvB,aAAa,EAAE,IAAI;YACnB,qBAAqB,EAAE,2BAAqB,CAAC,WAAW;YACxD,GAAG,MAAM,CAAC,2BAA2B;SACrC,CAAC;QACF,IAAI,CAAC,WAAW,GAAG,IAAI,iBAAW,CAAC,iBAAiB,CAAC,CAAC;QAEtD,MAAM,QAAQ,GAAG,IAAI,wBAAkB,CAA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zdD,gDAydC","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\tUserAccount,\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 {\n\tcreateOpenPerpMarketOrder,\n\tOpenPerpMarketOrderParams,\n} from '../../base/actions/trade/openPerpOrder/openPerpMarketOrder';\nimport {\n\tcreateOpenPerpNonMarketOrderTxn,\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';\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\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\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});\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\tpublic async getUserAccount(\n\t\tuserAccountPublicKey: PublicKey\n\t): Promise<UserAccount> {\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\tawait oneShotUserAccountSubscriber.subscribe();\n\t\treturn oneShotUserAccountSubscriber.getUserAccountAndSlot().data;\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\tpublic async getOpenPerpMarketOrderTxn<T extends boolean>({\n\t\tuserAccountPublicKey,\n\t\t...rest\n\t}: WithTxnParams<\n\t\tOmit<OpenPerpMarketOrderParams<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 openPerpMarketOrderTxn = await createOpenPerpMarketOrder({\n\t\t\t\t\t...rest,\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t});\n\t\t\t\treturn openPerpMarketOrderTxn;\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\tuserAccountPublicKey,\n\t\t...rest\n\t}: WithTxnParams<\n\t\tOmit<OpenPerpNonMarketOrderParams, 'driftClient' | 'user'>\n\t> & {\n\t\tuserAccountPublicKey: PublicKey;\n\t}): Promise<VersionedTransaction | Transaction | void> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst openPerpNonMarketOrderTxn = await createOpenPerpNonMarketOrderTxn(\n\t\t\t\t\t{\n\t\t\t\t\t\t...rest,\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t}\n\t\t\t\t);\n\n\t\t\t\treturn openPerpNonMarketOrderTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a transaction to edit an existing order\n\t */\n\tpublic async getEditOrderTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\torderId: number,\n\t\teditOrderParams: {\n\t\t\tnewDirection?: PositionDirection;\n\t\t\tnewBaseAmount?: BN;\n\t\t\tnewLimitPrice?: BN;\n\t\t\tnewOraclePriceOffset?: number;\n\t\t\tnewTriggerPrice?: BN;\n\t\t\tnewTriggerCondition?: OrderTriggerCondition;\n\t\t\tauctionDuration?: number;\n\t\t\tauctionStartPrice?: BN;\n\t\t\tauctionEndPrice?: BN;\n\t\t\treduceOnly?: boolean;\n\t\t\tpostOnly?: boolean;\n\t\t\tbitFlags?: number;\n\t\t\tmaxTs?: BN;\n\t\t\tpolicy?: number;\n\t\t}\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst editOrderTxn = await createEditOrderTxn(\n\t\t\t\t\tthis.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\torderId,\n\t\t\t\t\teditOrderParams\n\t\t\t\t);\n\n\t\t\t\treturn editOrderTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a transaction to cancel specific orders by their IDs\n\t */\n\tpublic async getCancelOrdersTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\torderIds: number[]\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst cancelOrdersTxn = await createCancelOrdersTxn(\n\t\t\t\t\tthis.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\torderIds\n\t\t\t\t);\n\n\t\t\t\treturn cancelOrdersTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a transaction to cancel all orders for a user\n\t */\n\tpublic async getCancelAllOrdersTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tmarketType?: MarketType,\n\t\tmarketIndex?: number,\n\t\tdirection?: PositionDirection\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst ix = await this.driftClient.getCancelOrdersIx(\n\t\t\t\t\tmarketType ?? null,\n\t\t\t\t\tmarketIndex ?? null,\n\t\t\t\t\tdirection ?? null,\n\t\t\t\t\tuser.getUserAccount().subAccountId\n\t\t\t\t);\n\n\t\t\t\tconst cancelAllOrdersTxn = await this.driftClient.buildTransaction(ix);\n\n\t\t\t\treturn cancelAllOrdersTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a swap transaction between two spot markets using Jupiter\n\t */\n\tpublic async getSwapTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tfromMarketIndex: number,\n\t\ttoMarketIndex: number,\n\t\tamount: BN,\n\t\toptions?: {\n\t\t\tslippageBps?: number;\n\t\t\tswapMode?: SwapMode;\n\t\t\tonlyDirectRoutes?: boolean;\n\t\t\tquote?: QuoteResponse;\n\t\t}\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst fromSpotMarketConfig = this.spotMarketConfigs.find(\n\t\t\t\t\t(market) => market.marketIndex === fromMarketIndex\n\t\t\t\t);\n\t\t\t\tconst toSpotMarketConfig = this.spotMarketConfigs.find(\n\t\t\t\t\t(market) => market.marketIndex === toMarketIndex\n\t\t\t\t);\n\n\t\t\t\tif (!fromSpotMarketConfig) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`From spot market config not found for index ${fromMarketIndex}`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tif (!toSpotMarketConfig) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`To spot market config not found for index ${toMarketIndex}`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Initialize Jupiter client\n\t\t\t\tconst jupiterClient = new JupiterClient({\n\t\t\t\t\tconnection: this.driftClient.connection,\n\t\t\t\t});\n\n\t\t\t\t// Get quote if not provided\n\t\t\t\tlet quote = options?.quote;\n\t\t\t\tif (!quote) {\n\t\t\t\t\tquote = await jupiterClient.getQuote({\n\t\t\t\t\t\tinputMint: fromSpotMarketConfig.mint,\n\t\t\t\t\t\toutputMint: toSpotMarketConfig.mint,\n\t\t\t\t\t\tamount,\n\t\t\t\t\t\tslippageBps: options?.slippageBps ?? 10, // Default 0.1%\n\t\t\t\t\t\tswapMode: options?.swapMode ?? 'ExactIn',\n\t\t\t\t\t\tonlyDirectRoutes: options?.onlyDirectRoutes ?? false,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tconst swapTxn = await createSwapTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tjupiterClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tswapFromMarketIndex: fromMarketIndex,\n\t\t\t\t\tswapToMarketIndex: toMarketIndex,\n\t\t\t\t\tamount,\n\t\t\t\t\tquote,\n\t\t\t\t\ttxParams: {\n\t\t\t\t\t\tuseSimulatedComputeUnits: true,\n\t\t\t\t\t\tcomputeUnitsBufferMultiplier: 1.5,\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\treturn swapTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\tpublic async sendSignedTransaction(tx: VersionedTransaction | Transaction) {\n\t\treturn this.driftClient.sendTransaction(tx, undefined, undefined, true);\n\t}\n}\n"]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
/// <reference types="bn.js" />
|
|
1
2
|
import { DriftClient, User, BN, PositionDirection, OptionalOrderParams, MarketType, UserAccount, PublicKey } from '@drift-labs/sdk';
|
|
2
3
|
import { MarketId, TradeOffsetPrice } from '../../../../../../types';
|
|
3
4
|
import { L2WithOracleAndMarketData, DynamicSlippageConfig } from '../../../../../../utils/orderbook';
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
/// <reference types="bn.js" />
|
|
1
2
|
import { DriftClient, User, BN, PositionDirection, ReferrerInfo } from '@drift-labs/sdk';
|
|
2
3
|
import { Transaction, TransactionInstruction, VersionedTransaction } from '@solana/web3.js';
|
|
3
4
|
import { SwiftOrderOptions } from '../openSwiftOrder';
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
/// <reference types="bn.js" />
|
|
1
2
|
import { DriftClient, User, BN, PostOnlyParams, PositionDirection } from '@drift-labs/sdk';
|
|
2
3
|
import { Transaction, TransactionInstruction, VersionedTransaction } from '@solana/web3.js';
|
|
3
4
|
import { SwiftOrderOptions } from '../openSwiftOrder';
|
|
@@ -202,7 +202,7 @@ const createOpenPerpNonMarketOrderIxs = async (params) => {
|
|
|
202
202
|
exports.createOpenPerpNonMarketOrderIxs = createOpenPerpNonMarketOrderIxs;
|
|
203
203
|
exports.MINIMUM_SWIFT_LIMIT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 35;
|
|
204
204
|
const createSwiftLimitOrder = async (params) => {
|
|
205
|
-
var _a, _b;
|
|
205
|
+
var _a, _b, _c;
|
|
206
206
|
const { driftClient, user, marketIndex, swiftOptions, orderConfig } = params;
|
|
207
207
|
const limitPrice = orderConfig.limitPrice;
|
|
208
208
|
if (limitPrice.isZero()) {
|
|
@@ -215,11 +215,22 @@ const createSwiftLimitOrder = async (params) => {
|
|
|
215
215
|
baseAssetAmount: 'baseAssetAmount' in params ? params.baseAssetAmount : undefined,
|
|
216
216
|
limitPrice,
|
|
217
217
|
});
|
|
218
|
-
const orderParams =
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
218
|
+
const orderParams = ((_a = orderConfig.limitAuction) === null || _a === void 0 ? void 0 : _a.enable)
|
|
219
|
+
? await getLimitAuctionOrderParams({
|
|
220
|
+
...params,
|
|
221
|
+
baseAssetAmount: finalBaseAssetAmount,
|
|
222
|
+
orderConfig: orderConfig,
|
|
223
|
+
})
|
|
224
|
+
: (0, orderParams_1.buildNonMarketOrderParams)({
|
|
225
|
+
marketIndex,
|
|
226
|
+
marketType: sdk_1.MarketType.PERP,
|
|
227
|
+
direction: params.direction,
|
|
228
|
+
baseAssetAmount: finalBaseAssetAmount,
|
|
229
|
+
orderConfig,
|
|
230
|
+
reduceOnly: params.reduceOnly,
|
|
231
|
+
postOnly: params.postOnly,
|
|
232
|
+
userOrderId: params.userOrderId,
|
|
233
|
+
});
|
|
223
234
|
const userAccount = user.getUserAccount();
|
|
224
235
|
const slotBuffer = Math.max((swiftOptions.signedMessageOrderSlotBuffer || 0) +
|
|
225
236
|
(orderParams.auctionDuration || 0), exports.MINIMUM_SWIFT_LIMIT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS); // limit orders require a much larger buffer, to replace the auction duration usually found in market orders
|
|
@@ -231,8 +242,8 @@ const createSwiftLimitOrder = async (params) => {
|
|
|
231
242
|
swiftOptions,
|
|
232
243
|
orderParams: {
|
|
233
244
|
main: orderParams,
|
|
234
|
-
takeProfit: (
|
|
235
|
-
stopLoss: (
|
|
245
|
+
takeProfit: (_b = orderConfig.bracketOrders) === null || _b === void 0 ? void 0 : _b.takeProfit,
|
|
246
|
+
stopLoss: (_c = orderConfig.bracketOrders) === null || _c === void 0 ? void 0 : _c.stopLoss,
|
|
236
247
|
},
|
|
237
248
|
});
|
|
238
249
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.ts"],"names":[],"mappings":";;;;;;AAAA,yCAcyB;AAMzB,sDAG2B;AAC3B,kEAG0C;AAC1C,mDAAqD;AACrD,8CAAwD;AACxD,uEAG2C;AAC3C,gEAA6E;AAC7E,oEAAuC;AAoCvC,MAAM,0BAA0B,GAAG,KAAK,EAAE,EACzC,WAAW,EACX,IAAI,EACJ,WAAW,EACX,SAAS,EACT,eAAe,EACf,WAAW,GAAG,CAAC,EACf,UAAU,GAAG,KAAK,EAClB,QAAQ,GAAG,oBAAc,CAAC,IAAI,EAC9B,WAAW,GAMX,EAAgC,EAAE;IAClC,MAAM,WAAW,GAAG,MAAM,IAAA,oCAAuB,EAAC;QACjD,WAAW;QACX,IAAI;QACJ,SAAS,EAAE,MAAM;QACjB,WAAW;QACX,UAAU,EAAE,gBAAU,CAAC,IAAI;QAC3B,SAAS;QACT,MAAM,EAAE,eAAe;QACvB,iBAAiB,EAAE,WAAW,CAAC,YAAY,CAAC,iBAAiB;QAC7D,2BAA2B,EAC1B,WAAW,CAAC,YAAY,CAAC,0BAA0B;KACpD,CAAC,CAAC;IAEH,MAAM,iBAAiB,GAAG,WAAW,CAAC,oBAAoB,CAAC,WAAW,CAAC,CAAC;IAExE,IAAA,wBAAS,EAAC,iBAAiB,EAAE,+BAA+B,CAAC,CAAC;IAC9D,IAAA,wBAAS,EAAC,WAAW,CAAC,YAAY,CAAC,WA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AAC;YACnB,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;QACnE,CAAC;QAED,IACC,MAAM,CAAC,QAAQ;YACf,CAAC,kBAAU,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,EAAE,oBAAc,CAAC,IAAI,CAAC,EACtD,CAAC;YACF,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;QAClE,CAAC;QAED,MAAM,gBAAgB,GAAG,MAAM,IAAA,6BAAqB,EAAC;YACpD,GAAG,MAAM;YACT,YAAY;YACZ,WAAW;SACX,CAAC,CAAC;QAEH,OAAO,gBAAuC,CAAC;IAChD,CAAC;IAED,MAAM,cAAc,GAAG,MAAM,IAAA,uCAA+B,EAAC,MAAM,CAAC,CAAC;IAErE,OAAO,cAAqC,CAAC;AAC9C,CAAC,CAAC;AAlCW,QAAA,4BAA4B,gCAkCvC","sourcesContent":["import {\n\tDriftClient,\n\tUser,\n\tBN,\n\tMarketType,\n\tPostOnlyParams,\n\tgetLimitOrderParams,\n\tOptionalOrderParams,\n\tPRICE_PRECISION_EXP,\n\tBigNum,\n\toraclePriceBands as getOraclePriceBands,\n\tPositionDirection,\n\tOrderParamsBitFlag,\n\tPRICE_PRECISION,\n} from '@drift-labs/sdk';\nimport {\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport {\n\tprepSignAndSendSwiftOrder,\n\tSwiftOrderOptions,\n} from '../openSwiftOrder';\nimport {\n\tbuildNonMarketOrderParams,\n\tresolveBaseAssetAmount,\n} from '../../../../../utils/orderParams';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport { fetchAuctionOrderParams } from '../dlobServer';\nimport {\n\tCOMMON_UI_UTILS,\n\tORDER_COMMON_UTILS,\n} from '../../../../../../common-ui-utils';\nimport { createPlaceAndTakePerpMarketOrderIx } from '../openPerpMarketOrder';\nimport invariant from 'tiny-invariant';\nimport {\n\tTxnOrSwiftResult,\n\tLimitAuctionConfig,\n\tLimitOrderParamsOrderConfig,\n\tNonMarketOrderParamsConfig,\n\tWithTxnParams,\n} from '../types';\n\nexport interface OpenPerpNonMarketOrderBaseParams\n\textends Omit<NonMarketOrderParamsConfig, 'marketType' | 'baseAssetAmount'> {\n\tdriftClient: DriftClient;\n\tuser: User;\n\t// Either new approach\n\tamount?: BN;\n\tassetType?: 'base' | 'quote';\n\t// Or legacy approach\n\tbaseAssetAmount?: BN;\n\t// Common optional params\n\treduceOnly?: boolean;\n\tpostOnly?: PostOnlyParams;\n\tuserOrderId?: number;\n\tautoEnterHighLeverageModeBufferPct?: number;\n}\n\nexport interface OpenPerpNonMarketOrderParamsWithSwift\n\textends OpenPerpNonMarketOrderBaseParams {\n\tswiftOptions: SwiftOrderOptions;\n}\n\nexport interface OpenPerpNonMarketOrderParams<T extends boolean = boolean>\n\textends OpenPerpNonMarketOrderBaseParams {\n\tuseSwift: T;\n\tswiftOptions?: T extends true ? SwiftOrderOptions : never;\n}\n\nconst getLimitAuctionOrderParams = async ({\n\tdriftClient,\n\tuser,\n\tmarketIndex,\n\tdirection,\n\tbaseAssetAmount,\n\tuserOrderId = 0,\n\treduceOnly = false,\n\tpostOnly = PostOnlyParams.NONE,\n\torderConfig,\n}: OpenPerpNonMarketOrderBaseParams & {\n\tbaseAssetAmount: BN;\n\torderConfig: LimitOrderParamsOrderConfig & {\n\t\tlimitAuction: LimitAuctionConfig;\n\t};\n}): Promise<OptionalOrderParams> => {\n\tconst orderParams = await fetchAuctionOrderParams({\n\t\tdriftClient,\n\t\tuser,\n\t\tassetType: 'base',\n\t\tmarketIndex,\n\t\tmarketType: MarketType.PERP,\n\t\tdirection,\n\t\tamount: baseAssetAmount,\n\t\tdlobServerHttpUrl: orderConfig.limitAuction.dlobServerHttpUrl,\n\t\toptionalAuctionParamsInputs:\n\t\t\torderConfig.limitAuction.optionalLimitAuctionParams,\n\t});\n\n\tconst perpMarketAccount = driftClient.getPerpMarketAccount(marketIndex);\n\n\tinvariant(perpMarketAccount, 'Perp market account not found');\n\tinvariant(orderConfig.limitAuction.oraclePrice, 'Oracle price not found');\n\tinvariant(orderParams.auctionStartPrice, 'Auction start price not found');\n\n\tconst oraclePriceBands = orderConfig.limitAuction.oraclePrice\n\t\t? getOraclePriceBands(perpMarketAccount, {\n\t\t\t\tprice: orderConfig.limitAuction.oraclePrice,\n\t\t })\n\t\t: undefined;\n\tconst auctionDuration = ORDER_COMMON_UTILS.getPerpAuctionDuration(\n\t\torderConfig.limitPrice.sub(orderParams.auctionStartPrice).abs(),\n\t\torderConfig.limitAuction.oraclePrice,\n\t\tperpMarketAccount.contractTier\n\t);\n\tconst limitAuctionParams = COMMON_UI_UTILS.getLimitAuctionParams({\n\t\tdirection,\n\t\tinputPrice: BigNum.from(orderConfig.limitPrice, PRICE_PRECISION_EXP),\n\t\tstartPriceFromSettings: orderParams.auctionStartPrice,\n\t\tduration: auctionDuration,\n\t\tauctionStartPriceOffset: orderConfig.limitAuction.auctionStartPriceOffset,\n\t\toraclePriceBands,\n\t});\n\n\tconst limitAuctionOrderParams = getLimitOrderParams({\n\t\tmarketIndex,\n\t\tmarketType: MarketType.PERP,\n\t\tdirection,\n\t\tbaseAssetAmount,\n\t\treduceOnly,\n\t\tpostOnly,\n\t\tprice: orderConfig.limitPrice,\n\t\tuserOrderId,\n\t\t...limitAuctionParams,\n\t});\n\n\tconst oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;\n\tconst totalQuoteAmount = baseAssetAmount\n\t\t.mul(oraclePrice)\n\t\t.div(PRICE_PRECISION);\n\n\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\tmarketIndex,\n\t\tdriftClient,\n\t\tuser,\n\t\ttotalQuoteAmount,\n\t\tdirection\n\t);\n\n\treturn {\n\t\t...limitAuctionOrderParams,\n\t\tbitFlags,\n\t};\n};\n\n/**\n * Creates a transaction instruction to open multiple non-market orders.\n */\nexport const createMultipleOpenPerpNonMarketOrderIx = async (params: {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\torderParamsConfigs: NonMarketOrderParamsConfig[];\n\tenterHighLeverageMode?: boolean;\n}): Promise<TransactionInstruction> => {\n\tconst { driftClient, orderParamsConfigs } = params;\n\n\tconst orderParams = orderParamsConfigs.map(buildNonMarketOrderParams);\n\n\tif (params.enterHighLeverageMode && orderParams.length > 0) {\n\t\torderParams[0].bitFlags = OrderParamsBitFlag.UpdateHighLeverageMode;\n\t}\n\n\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(orderParams);\n\treturn placeOrderIx;\n};\n\n/**\n * Creates a transaction instruction to open a non-market order.\n * Allows for bracket orders to be opened in the same transaction.\n *\n * If `limitAuction` is enabled, a placeAndTake order is created to simulate a market auction order,\n * with the end price being the limit price.\n */\nexport const createOpenPerpNonMarketOrderIxs = async (\n\tparams: OpenPerpNonMarketOrderBaseParams\n): Promise<TransactionInstruction[]> => {\n\tconst {\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\tdirection,\n\t\treduceOnly = false,\n\t\tpostOnly = PostOnlyParams.NONE,\n\t\torderConfig,\n\t\tuserOrderId = 0,\n\t} = params;\n\t// Support both new (amount + assetType) and legacy (baseAssetAmount) approaches\n\tconst finalBaseAssetAmount = resolveBaseAssetAmount({\n\t\tamount: 'amount' in params ? params.amount : undefined,\n\t\tassetType: 'assetType' in params ? params.assetType : undefined,\n\t\tbaseAssetAmount:\n\t\t\t'baseAssetAmount' in params ? params.baseAssetAmount : undefined,\n\t\tlimitPrice:\n\t\t\t'limitPrice' in params.orderConfig\n\t\t\t\t? params.orderConfig.limitPrice\n\t\t\t\t: undefined,\n\t});\n\n\tif (!finalBaseAssetAmount || finalBaseAssetAmount.isZero()) {\n\t\tthrow new Error('Final base asset amount must be greater than zero');\n\t}\n\n\tconst allOrders: OptionalOrderParams[] = [];\n\tconst allIxs: TransactionInstruction[] = [];\n\n\t// handle limit auction\n\tif (orderConfig.orderType === 'limit' && orderConfig.limitAuction?.enable) {\n\t\tconst limitAuctionOrderParams = await getLimitAuctionOrderParams({\n\t\t\t...params,\n\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\torderConfig: orderConfig as LimitOrderParamsOrderConfig & {\n\t\t\t\tlimitAuction: LimitAuctionConfig;\n\t\t\t},\n\t\t});\n\n\t\tlet createdPlaceAndTakeIx = false;\n\n\t\t// if it is a limit auction order, we create a placeAndTake order to simulate a market order.\n\t\t// this is useful when a limit order is crossing, and we want to achieve the best fill price through a placeAndTake.\n\t\t// falls back to limit order with auction params if the placeAndTake order creation fails\n\t\tif (\n\t\t\tlimitAuctionOrderParams.auctionDuration &&\n\t\t\tlimitAuctionOrderParams.auctionDuration > 0 &&\n\t\t\torderConfig.limitAuction?.usePlaceAndTake?.enable\n\t\t) {\n\t\t\ttry {\n\t\t\t\tconst placeAndTakeIx = await createPlaceAndTakePerpMarketOrderIx({\n\t\t\t\t\tassetType: 'base',\n\t\t\t\t\tamount: finalBaseAssetAmount,\n\t\t\t\t\tdirection,\n\t\t\t\t\tdlobServerHttpUrl: orderConfig.limitAuction.dlobServerHttpUrl,\n\t\t\t\t\tmarketIndex,\n\t\t\t\t\tdriftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tuserOrderId,\n\t\t\t\t\toptionalAuctionParamsInputs:\n\t\t\t\t\t\torderConfig.limitAuction.optionalLimitAuctionParams,\n\t\t\t\t\tauctionDurationPercentage:\n\t\t\t\t\t\torderConfig.limitAuction.usePlaceAndTake.auctionDurationPercentage,\n\t\t\t\t\treferrerInfo: orderConfig.limitAuction.usePlaceAndTake.referrerInfo,\n\t\t\t\t});\n\t\t\t\tallIxs.push(placeAndTakeIx);\n\t\t\t\tcreatedPlaceAndTakeIx = true;\n\t\t\t} catch (e) {\n\t\t\t\tconsole.error(\n\t\t\t\t\t'Failed to create placeAndTake order for limit auction order',\n\t\t\t\t\te\n\t\t\t\t);\n\t\t\t\tcreatedPlaceAndTakeIx = false;\n\t\t\t}\n\t\t}\n\n\t\t// fallback to normal limit order with auction params\n\t\tif (!createdPlaceAndTakeIx) {\n\t\t\tallOrders.push(limitAuctionOrderParams);\n\t\t}\n\t} else {\n\t\tconst orderParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\torderConfig,\n\t\t\treduceOnly,\n\t\t\tpostOnly,\n\t\t\tuserOrderId,\n\t\t});\n\n\t\tconst oraclePrice =\n\t\t\tdriftClient.getOracleDataForPerpMarket(marketIndex).price;\n\t\tconst totalQuoteAmount = finalBaseAssetAmount\n\t\t\t.mul(oraclePrice)\n\t\t\t.div(PRICE_PRECISION);\n\n\t\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\t\tmarketIndex,\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\ttotalQuoteAmount,\n\t\t\tdirection\n\t\t);\n\t\torderParams.bitFlags = bitFlags;\n\n\t\tallOrders.push(orderParams);\n\t}\n\n\tconst bracketOrdersDirection = ENUM_UTILS.match(\n\t\tdirection,\n\t\tPositionDirection.LONG\n\t)\n\t\t? PositionDirection.SHORT\n\t\t: PositionDirection.LONG;\n\n\tif ('bracketOrders' in orderConfig && orderConfig.bracketOrders?.takeProfit) {\n\t\tconst takeProfitParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount:\n\t\t\t\torderConfig.bracketOrders.takeProfit.baseAssetAmount ??\n\t\t\t\tfinalBaseAssetAmount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'takeProfit',\n\t\t\t\ttriggerPrice: orderConfig.bracketOrders.takeProfit.triggerPrice,\n\t\t\t\tlimitPrice: orderConfig.bracketOrders.takeProfit.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: orderConfig.bracketOrders.takeProfit.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(takeProfitParams);\n\t}\n\n\tif ('bracketOrders' in orderConfig && orderConfig.bracketOrders?.stopLoss) {\n\t\tconst stopLossParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount:\n\t\t\t\torderConfig.bracketOrders.stopLoss.baseAssetAmount ??\n\t\t\t\tfinalBaseAssetAmount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'stopLoss',\n\t\t\t\ttriggerPrice: orderConfig.bracketOrders.stopLoss.triggerPrice,\n\t\t\t\tlimitPrice: orderConfig.bracketOrders.stopLoss.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: orderConfig.bracketOrders.stopLoss.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(stopLossParams);\n\t}\n\n\tif (allOrders.length > 0) {\n\t\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(allOrders);\n\t\tallIxs.push(placeOrderIx);\n\t}\n\n\treturn allIxs;\n};\n\nexport const MINIMUM_SWIFT_LIMIT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 35;\n\nexport const createSwiftLimitOrder = async (\n\tparams: OpenPerpNonMarketOrderParamsWithSwift & {\n\t\torderConfig: LimitOrderParamsOrderConfig;\n\t}\n): Promise<void> => {\n\tconst { driftClient, user, marketIndex, swiftOptions, orderConfig } = params;\n\n\tconst limitPrice = orderConfig.limitPrice;\n\n\tif (limitPrice.isZero()) {\n\t\tthrow new Error('LIMIT orders require limitPrice');\n\t}\n\n\t// Support both new (amount + assetType) and legacy (baseAssetAmount) approaches\n\tconst finalBaseAssetAmount = resolveBaseAssetAmount({\n\t\tamount: 'amount' in params ? params.amount : undefined,\n\t\tassetType: 'assetType' in params ? params.assetType : undefined,\n\t\tbaseAssetAmount:\n\t\t\t'baseAssetAmount' in params ? params.baseAssetAmount : undefined,\n\t\tlimitPrice,\n\t});\n\n\tconst orderParams = await getLimitAuctionOrderParams({\n\t\t...params,\n\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\torderConfig: orderConfig as LimitOrderParamsOrderConfig & {\n\t\t\tlimitAuction: LimitAuctionConfig;\n\t\t},\n\t});\n\n\tconst userAccount = user.getUserAccount();\n\tconst slotBuffer = Math.max(\n\t\t(swiftOptions.signedMessageOrderSlotBuffer || 0) +\n\t\t\t(orderParams.auctionDuration || 0),\n\t\tMINIMUM_SWIFT_LIMIT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS\n\t); // limit orders require a much larger buffer, to replace the auction duration usually found in market orders\n\n\tawait prepSignAndSendSwiftOrder({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tmarketIndex,\n\t\tslotBuffer,\n\t\tswiftOptions,\n\t\torderParams: {\n\t\t\tmain: orderParams,\n\t\t\ttakeProfit: orderConfig.bracketOrders?.takeProfit,\n\t\t\tstopLoss: orderConfig.bracketOrders?.stopLoss,\n\t\t},\n\t});\n};\n\nexport const createOpenPerpNonMarketOrderTxn = async (\n\tparams: WithTxnParams<OpenPerpNonMarketOrderBaseParams>\n): Promise<Transaction | VersionedTransaction> => {\n\tconst { driftClient } = params;\n\n\tconst instructions = await createOpenPerpNonMarketOrderIxs(params);\n\n\tconst openPerpNonMarketOrderTxn = await driftClient.buildTransaction(\n\t\tinstructions,\n\t\tparams.txParams\n\t);\n\n\treturn openPerpNonMarketOrderTxn;\n};\n\nexport const createOpenPerpNonMarketOrder = async <T extends boolean>(\n\tparams: WithTxnParams<OpenPerpNonMarketOrderParams<T>>\n): Promise<TxnOrSwiftResult<T>> => {\n\tconst { swiftOptions, useSwift, orderConfig } = params;\n\n\t// If useSwift is true, return the Swift result directly\n\tif (useSwift) {\n\t\tif (orderConfig.orderType !== 'limit') {\n\t\t\tthrow new Error('Only limit orders are supported with Swift');\n\t\t}\n\n\t\tif (!swiftOptions) {\n\t\t\tthrow new Error('swiftOptions is required when useSwift is true');\n\t\t}\n\n\t\tif (\n\t\t\tparams.postOnly &&\n\t\t\t!ENUM_UTILS.match(params.postOnly, PostOnlyParams.NONE)\n\t\t) {\n\t\t\tthrow new Error('Post only orders are not supported with Swift');\n\t\t}\n\n\t\tconst swiftOrderResult = await createSwiftLimitOrder({\n\t\t\t...params,\n\t\t\tswiftOptions,\n\t\t\torderConfig,\n\t\t});\n\n\t\treturn swiftOrderResult as TxnOrSwiftResult<T>;\n\t}\n\n\tconst marketOrderTxn = await createOpenPerpNonMarketOrderTxn(params);\n\n\treturn marketOrderTxn as TxnOrSwiftResult<T>;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.ts"],"names":[],"mappings":";;;;;;AAAA,yCAcyB;AAMzB,sDAG2B;AAC3B,kEAG0C;AAC1C,mDAAqD;AACrD,8CAAwD;AACxD,uEAG2C;AAC3C,gEAA6E;AAC7E,oEAAuC;AAoCvC,MAAM,0BAA0B,GAAG,KAAK,EAAE,EACzC,WAAW,EACX,IAAI,EACJ,WAAW,EACX,SAAS,EACT,eAAe,EACf,WAAW,GAAG,CAAC,EACf,UAAU,GAAG,KAAK,EAClB,QAAQ,GAAG,oBAAc,CAAC,IAAI,EAC9B,WAAW,GAMX,EAAgC,EAAE;IAClC,MAAM,WAAW,GAAG,MAAM,IAAA,oCAAuB,EAAC;QACjD,WAAW;QACX,IAAI;QACJ,SAAS,EAAE,MAAM;QACjB,WAAW;QACX,UAAU,EAAE,gBAAU,CAAC,IAAI;QAC3B,SAAS;QACT,MAAM,EAAE,eAAe;QACvB,iBAAiB,EAAE,WAAW,CAAC,YAAY,CAAC,iBAAiB;QAC7D,2BAA2B,EAC1B,WAAW,CAAC,YAAY,CAAC,0BAA0B;KACpD,CAAC,CAAC;IAEH,MAAM,iBAAiB,GAAG,WAAW,CAAC,oBAAoB,CAAC,WAAW,CAAC,CAA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AAW,CAAC,gBAAgB,CACnE,YAAY,EACZ,MAAM,CAAC,QAAQ,CACf,CAAC;IAEF,OAAO,yBAAyB,CAAC;AAClC,CAAC,CAAC;AAbW,QAAA,+BAA+B,mCAa1C;AAEK,MAAM,4BAA4B,GAAG,KAAK,EAChD,MAAsD,EACvB,EAAE;IACjC,MAAM,EAAE,YAAY,EAAE,QAAQ,EAAE,WAAW,EAAE,GAAG,MAAM,CAAC;IAEvD,wDAAwD;IACxD,IAAI,QAAQ,EAAE,CAAC;QACd,IAAI,WAAW,CAAC,SAAS,KAAK,OAAO,EAAE,CAAC;YACvC,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;QAC/D,CAAC;QAED,IAAI,CAAC,YAAY,EAAE,CAAC;YACnB,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;QACnE,CAAC;QAED,IACC,MAAM,CAAC,QAAQ;YACf,CAAC,kBAAU,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,EAAE,oBAAc,CAAC,IAAI,CAAC,EACtD,CAAC;YACF,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;QAClE,CAAC;QAED,MAAM,gBAAgB,GAAG,MAAM,IAAA,6BAAqB,EAAC;YACpD,GAAG,MAAM;YACT,YAAY;YACZ,WAAW;SACX,CAAC,CAAC;QAEH,OAAO,gBAAuC,CAAC;IAChD,CAAC;IAED,MAAM,cAAc,GAAG,MAAM,IAAA,uCAA+B,EAAC,MAAM,CAAC,CAAC;IAErE,OAAO,cAAqC,CAAC;AAC9C,CAAC,CAAC;AAlCW,QAAA,4BAA4B,gCAkCvC","sourcesContent":["import {\n\tDriftClient,\n\tUser,\n\tBN,\n\tMarketType,\n\tPostOnlyParams,\n\tgetLimitOrderParams,\n\tOptionalOrderParams,\n\tPRICE_PRECISION_EXP,\n\tBigNum,\n\toraclePriceBands as getOraclePriceBands,\n\tPositionDirection,\n\tOrderParamsBitFlag,\n\tPRICE_PRECISION,\n} from '@drift-labs/sdk';\nimport {\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport {\n\tprepSignAndSendSwiftOrder,\n\tSwiftOrderOptions,\n} from '../openSwiftOrder';\nimport {\n\tbuildNonMarketOrderParams,\n\tresolveBaseAssetAmount,\n} from '../../../../../utils/orderParams';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport { fetchAuctionOrderParams } from '../dlobServer';\nimport {\n\tCOMMON_UI_UTILS,\n\tORDER_COMMON_UTILS,\n} from '../../../../../../common-ui-utils';\nimport { createPlaceAndTakePerpMarketOrderIx } from '../openPerpMarketOrder';\nimport invariant from 'tiny-invariant';\nimport {\n\tTxnOrSwiftResult,\n\tLimitAuctionConfig,\n\tLimitOrderParamsOrderConfig,\n\tNonMarketOrderParamsConfig,\n\tWithTxnParams,\n} from '../types';\n\nexport interface OpenPerpNonMarketOrderBaseParams\n\textends Omit<NonMarketOrderParamsConfig, 'marketType' | 'baseAssetAmount'> {\n\tdriftClient: DriftClient;\n\tuser: User;\n\t// Either new approach\n\tamount?: BN;\n\tassetType?: 'base' | 'quote';\n\t// Or legacy approach\n\tbaseAssetAmount?: BN;\n\t// Common optional params\n\treduceOnly?: boolean;\n\tpostOnly?: PostOnlyParams;\n\tuserOrderId?: number;\n\tautoEnterHighLeverageModeBufferPct?: number;\n}\n\nexport interface OpenPerpNonMarketOrderParamsWithSwift\n\textends OpenPerpNonMarketOrderBaseParams {\n\tswiftOptions: SwiftOrderOptions;\n}\n\nexport interface OpenPerpNonMarketOrderParams<T extends boolean = boolean>\n\textends OpenPerpNonMarketOrderBaseParams {\n\tuseSwift: T;\n\tswiftOptions?: T extends true ? SwiftOrderOptions : never;\n}\n\nconst getLimitAuctionOrderParams = async ({\n\tdriftClient,\n\tuser,\n\tmarketIndex,\n\tdirection,\n\tbaseAssetAmount,\n\tuserOrderId = 0,\n\treduceOnly = false,\n\tpostOnly = PostOnlyParams.NONE,\n\torderConfig,\n}: OpenPerpNonMarketOrderBaseParams & {\n\tbaseAssetAmount: BN;\n\torderConfig: LimitOrderParamsOrderConfig & {\n\t\tlimitAuction: LimitAuctionConfig;\n\t};\n}): Promise<OptionalOrderParams> => {\n\tconst orderParams = await fetchAuctionOrderParams({\n\t\tdriftClient,\n\t\tuser,\n\t\tassetType: 'base',\n\t\tmarketIndex,\n\t\tmarketType: MarketType.PERP,\n\t\tdirection,\n\t\tamount: baseAssetAmount,\n\t\tdlobServerHttpUrl: orderConfig.limitAuction.dlobServerHttpUrl,\n\t\toptionalAuctionParamsInputs:\n\t\t\torderConfig.limitAuction.optionalLimitAuctionParams,\n\t});\n\n\tconst perpMarketAccount = driftClient.getPerpMarketAccount(marketIndex);\n\n\tinvariant(perpMarketAccount, 'Perp market account not found');\n\tinvariant(orderConfig.limitAuction.oraclePrice, 'Oracle price not found');\n\tinvariant(orderParams.auctionStartPrice, 'Auction start price not found');\n\n\tconst oraclePriceBands = orderConfig.limitAuction.oraclePrice\n\t\t? getOraclePriceBands(perpMarketAccount, {\n\t\t\t\tprice: orderConfig.limitAuction.oraclePrice,\n\t\t })\n\t\t: undefined;\n\tconst auctionDuration = ORDER_COMMON_UTILS.getPerpAuctionDuration(\n\t\torderConfig.limitPrice.sub(orderParams.auctionStartPrice).abs(),\n\t\torderConfig.limitAuction.oraclePrice,\n\t\tperpMarketAccount.contractTier\n\t);\n\tconst limitAuctionParams = COMMON_UI_UTILS.getLimitAuctionParams({\n\t\tdirection,\n\t\tinputPrice: BigNum.from(orderConfig.limitPrice, PRICE_PRECISION_EXP),\n\t\tstartPriceFromSettings: orderParams.auctionStartPrice,\n\t\tduration: auctionDuration,\n\t\tauctionStartPriceOffset: orderConfig.limitAuction.auctionStartPriceOffset,\n\t\toraclePriceBands,\n\t});\n\n\tconst limitAuctionOrderParams = getLimitOrderParams({\n\t\tmarketIndex,\n\t\tmarketType: MarketType.PERP,\n\t\tdirection,\n\t\tbaseAssetAmount,\n\t\treduceOnly,\n\t\tpostOnly,\n\t\tprice: orderConfig.limitPrice,\n\t\tuserOrderId,\n\t\t...limitAuctionParams,\n\t});\n\n\tconst oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;\n\tconst totalQuoteAmount = baseAssetAmount\n\t\t.mul(oraclePrice)\n\t\t.div(PRICE_PRECISION);\n\n\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\tmarketIndex,\n\t\tdriftClient,\n\t\tuser,\n\t\ttotalQuoteAmount,\n\t\tdirection\n\t);\n\n\treturn {\n\t\t...limitAuctionOrderParams,\n\t\tbitFlags,\n\t};\n};\n\n/**\n * Creates a transaction instruction to open multiple non-market orders.\n */\nexport const createMultipleOpenPerpNonMarketOrderIx = async (params: {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\torderParamsConfigs: NonMarketOrderParamsConfig[];\n\tenterHighLeverageMode?: boolean;\n}): Promise<TransactionInstruction> => {\n\tconst { driftClient, orderParamsConfigs } = params;\n\n\tconst orderParams = orderParamsConfigs.map(buildNonMarketOrderParams);\n\n\tif (params.enterHighLeverageMode && orderParams.length > 0) {\n\t\torderParams[0].bitFlags = OrderParamsBitFlag.UpdateHighLeverageMode;\n\t}\n\n\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(orderParams);\n\treturn placeOrderIx;\n};\n\n/**\n * Creates a transaction instruction to open a non-market order.\n * Allows for bracket orders to be opened in the same transaction.\n *\n * If `limitAuction` is enabled, a placeAndTake order is created to simulate a market auction order,\n * with the end price being the limit price.\n */\nexport const createOpenPerpNonMarketOrderIxs = async (\n\tparams: OpenPerpNonMarketOrderBaseParams\n): Promise<TransactionInstruction[]> => {\n\tconst {\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\tdirection,\n\t\treduceOnly = false,\n\t\tpostOnly = PostOnlyParams.NONE,\n\t\torderConfig,\n\t\tuserOrderId = 0,\n\t} = params;\n\t// Support both new (amount + assetType) and legacy (baseAssetAmount) approaches\n\tconst finalBaseAssetAmount = resolveBaseAssetAmount({\n\t\tamount: 'amount' in params ? params.amount : undefined,\n\t\tassetType: 'assetType' in params ? params.assetType : undefined,\n\t\tbaseAssetAmount:\n\t\t\t'baseAssetAmount' in params ? params.baseAssetAmount : undefined,\n\t\tlimitPrice:\n\t\t\t'limitPrice' in params.orderConfig\n\t\t\t\t? params.orderConfig.limitPrice\n\t\t\t\t: undefined,\n\t});\n\n\tif (!finalBaseAssetAmount || finalBaseAssetAmount.isZero()) {\n\t\tthrow new Error('Final base asset amount must be greater than zero');\n\t}\n\n\tconst allOrders: OptionalOrderParams[] = [];\n\tconst allIxs: TransactionInstruction[] = [];\n\n\t// handle limit auction\n\tif (orderConfig.orderType === 'limit' && orderConfig.limitAuction?.enable) {\n\t\tconst limitAuctionOrderParams = await getLimitAuctionOrderParams({\n\t\t\t...params,\n\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\torderConfig: orderConfig as LimitOrderParamsOrderConfig & {\n\t\t\t\tlimitAuction: LimitAuctionConfig;\n\t\t\t},\n\t\t});\n\n\t\tlet createdPlaceAndTakeIx = false;\n\n\t\t// if it is a limit auction order, we create a placeAndTake order to simulate a market order.\n\t\t// this is useful when a limit order is crossing, and we want to achieve the best fill price through a placeAndTake.\n\t\t// falls back to limit order with auction params if the placeAndTake order creation fails\n\t\tif (\n\t\t\tlimitAuctionOrderParams.auctionDuration &&\n\t\t\tlimitAuctionOrderParams.auctionDuration > 0 &&\n\t\t\torderConfig.limitAuction?.usePlaceAndTake?.enable\n\t\t) {\n\t\t\ttry {\n\t\t\t\tconst placeAndTakeIx = await createPlaceAndTakePerpMarketOrderIx({\n\t\t\t\t\tassetType: 'base',\n\t\t\t\t\tamount: finalBaseAssetAmount,\n\t\t\t\t\tdirection,\n\t\t\t\t\tdlobServerHttpUrl: orderConfig.limitAuction.dlobServerHttpUrl,\n\t\t\t\t\tmarketIndex,\n\t\t\t\t\tdriftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tuserOrderId,\n\t\t\t\t\toptionalAuctionParamsInputs:\n\t\t\t\t\t\torderConfig.limitAuction.optionalLimitAuctionParams,\n\t\t\t\t\tauctionDurationPercentage:\n\t\t\t\t\t\torderConfig.limitAuction.usePlaceAndTake.auctionDurationPercentage,\n\t\t\t\t\treferrerInfo: orderConfig.limitAuction.usePlaceAndTake.referrerInfo,\n\t\t\t\t});\n\t\t\t\tallIxs.push(placeAndTakeIx);\n\t\t\t\tcreatedPlaceAndTakeIx = true;\n\t\t\t} catch (e) {\n\t\t\t\tconsole.error(\n\t\t\t\t\t'Failed to create placeAndTake order for limit auction order',\n\t\t\t\t\te\n\t\t\t\t);\n\t\t\t\tcreatedPlaceAndTakeIx = false;\n\t\t\t}\n\t\t}\n\n\t\t// fallback to normal limit order with auction params\n\t\tif (!createdPlaceAndTakeIx) {\n\t\t\tallOrders.push(limitAuctionOrderParams);\n\t\t}\n\t} else {\n\t\tconst orderParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\torderConfig,\n\t\t\treduceOnly,\n\t\t\tpostOnly,\n\t\t\tuserOrderId,\n\t\t});\n\n\t\tconst oraclePrice =\n\t\t\tdriftClient.getOracleDataForPerpMarket(marketIndex).price;\n\t\tconst totalQuoteAmount = finalBaseAssetAmount\n\t\t\t.mul(oraclePrice)\n\t\t\t.div(PRICE_PRECISION);\n\n\t\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\t\tmarketIndex,\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\ttotalQuoteAmount,\n\t\t\tdirection\n\t\t);\n\t\torderParams.bitFlags = bitFlags;\n\n\t\tallOrders.push(orderParams);\n\t}\n\n\tconst bracketOrdersDirection = ENUM_UTILS.match(\n\t\tdirection,\n\t\tPositionDirection.LONG\n\t)\n\t\t? PositionDirection.SHORT\n\t\t: PositionDirection.LONG;\n\n\tif ('bracketOrders' in orderConfig && orderConfig.bracketOrders?.takeProfit) {\n\t\tconst takeProfitParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount:\n\t\t\t\torderConfig.bracketOrders.takeProfit.baseAssetAmount ??\n\t\t\t\tfinalBaseAssetAmount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'takeProfit',\n\t\t\t\ttriggerPrice: orderConfig.bracketOrders.takeProfit.triggerPrice,\n\t\t\t\tlimitPrice: orderConfig.bracketOrders.takeProfit.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: orderConfig.bracketOrders.takeProfit.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(takeProfitParams);\n\t}\n\n\tif ('bracketOrders' in orderConfig && orderConfig.bracketOrders?.stopLoss) {\n\t\tconst stopLossParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount:\n\t\t\t\torderConfig.bracketOrders.stopLoss.baseAssetAmount ??\n\t\t\t\tfinalBaseAssetAmount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'stopLoss',\n\t\t\t\ttriggerPrice: orderConfig.bracketOrders.stopLoss.triggerPrice,\n\t\t\t\tlimitPrice: orderConfig.bracketOrders.stopLoss.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: orderConfig.bracketOrders.stopLoss.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(stopLossParams);\n\t}\n\n\tif (allOrders.length > 0) {\n\t\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(allOrders);\n\t\tallIxs.push(placeOrderIx);\n\t}\n\n\treturn allIxs;\n};\n\nexport const MINIMUM_SWIFT_LIMIT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 35;\n\nexport const createSwiftLimitOrder = async (\n\tparams: OpenPerpNonMarketOrderParamsWithSwift & {\n\t\torderConfig: LimitOrderParamsOrderConfig;\n\t}\n): Promise<void> => {\n\tconst { driftClient, user, marketIndex, swiftOptions, orderConfig } = params;\n\n\tconst limitPrice = orderConfig.limitPrice;\n\n\tif (limitPrice.isZero()) {\n\t\tthrow new Error('LIMIT orders require limitPrice');\n\t}\n\n\t// Support both new (amount + assetType) and legacy (baseAssetAmount) approaches\n\tconst finalBaseAssetAmount = resolveBaseAssetAmount({\n\t\tamount: 'amount' in params ? params.amount : undefined,\n\t\tassetType: 'assetType' in params ? params.assetType : undefined,\n\t\tbaseAssetAmount:\n\t\t\t'baseAssetAmount' in params ? params.baseAssetAmount : undefined,\n\t\tlimitPrice,\n\t});\n\n\tconst orderParams = orderConfig.limitAuction?.enable\n\t\t? await getLimitAuctionOrderParams({\n\t\t\t\t...params,\n\t\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\t\torderConfig: orderConfig as LimitOrderParamsOrderConfig & {\n\t\t\t\t\tlimitAuction: LimitAuctionConfig;\n\t\t\t\t},\n\t\t })\n\t\t: buildNonMarketOrderParams({\n\t\t\t\tmarketIndex,\n\t\t\t\tmarketType: MarketType.PERP,\n\t\t\t\tdirection: params.direction,\n\t\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\t\torderConfig,\n\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\tpostOnly: params.postOnly,\n\t\t\t\tuserOrderId: params.userOrderId,\n\t\t });\n\n\tconst userAccount = user.getUserAccount();\n\tconst slotBuffer = Math.max(\n\t\t(swiftOptions.signedMessageOrderSlotBuffer || 0) +\n\t\t\t(orderParams.auctionDuration || 0),\n\t\tMINIMUM_SWIFT_LIMIT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS\n\t); // limit orders require a much larger buffer, to replace the auction duration usually found in market orders\n\n\tawait prepSignAndSendSwiftOrder({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tmarketIndex,\n\t\tslotBuffer,\n\t\tswiftOptions,\n\t\torderParams: {\n\t\t\tmain: orderParams,\n\t\t\ttakeProfit: orderConfig.bracketOrders?.takeProfit,\n\t\t\tstopLoss: orderConfig.bracketOrders?.stopLoss,\n\t\t},\n\t});\n};\n\nexport const createOpenPerpNonMarketOrderTxn = async (\n\tparams: WithTxnParams<OpenPerpNonMarketOrderBaseParams>\n): Promise<Transaction | VersionedTransaction> => {\n\tconst { driftClient } = params;\n\n\tconst instructions = await createOpenPerpNonMarketOrderIxs(params);\n\n\tconst openPerpNonMarketOrderTxn = await driftClient.buildTransaction(\n\t\tinstructions,\n\t\tparams.txParams\n\t);\n\n\treturn openPerpNonMarketOrderTxn;\n};\n\nexport const createOpenPerpNonMarketOrder = async <T extends boolean>(\n\tparams: WithTxnParams<OpenPerpNonMarketOrderParams<T>>\n): Promise<TxnOrSwiftResult<T>> => {\n\tconst { swiftOptions, useSwift, orderConfig } = params;\n\n\t// If useSwift is true, return the Swift result directly\n\tif (useSwift) {\n\t\tif (orderConfig.orderType !== 'limit') {\n\t\t\tthrow new Error('Only limit orders are supported with Swift');\n\t\t}\n\n\t\tif (!swiftOptions) {\n\t\t\tthrow new Error('swiftOptions is required when useSwift is true');\n\t\t}\n\n\t\tif (\n\t\t\tparams.postOnly &&\n\t\t\t!ENUM_UTILS.match(params.postOnly, PostOnlyParams.NONE)\n\t\t) {\n\t\t\tthrow new Error('Post only orders are not supported with Swift');\n\t\t}\n\n\t\tconst swiftOrderResult = await createSwiftLimitOrder({\n\t\t\t...params,\n\t\t\tswiftOptions,\n\t\t\torderConfig,\n\t\t});\n\n\t\treturn swiftOrderResult as TxnOrSwiftResult<T>;\n\t}\n\n\tconst marketOrderTxn = await createOpenPerpNonMarketOrderTxn(params);\n\n\treturn marketOrderTxn as TxnOrSwiftResult<T>;\n};\n"]}
|
|
@@ -159,7 +159,7 @@ exports.sendSwiftOrder = sendSwiftOrder;
|
|
|
159
159
|
*/
|
|
160
160
|
const prepSignAndSendSwiftOrder = async ({ driftClient, subAccountId, marketIndex, slotBuffer, swiftOptions, orderParams, }) => {
|
|
161
161
|
var _a, _b, _c, _d;
|
|
162
|
-
const currentSlot = await driftClient.connection.getSlot();
|
|
162
|
+
const currentSlot = await driftClient.connection.getSlot('confirmed');
|
|
163
163
|
const { hexEncodedSwiftOrderMessage, signedMsgOrderUuid, signedMsgOrderParamsMessage, } = (0, exports.prepSwiftOrder)({
|
|
164
164
|
driftClient,
|
|
165
165
|
takerUserAccount: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.ts"],"names":[],"mappings":";;;AAAA,yCAKyB;AACzB,yCAOyB;AACzB,uEAO+C;AAC/C,mDAAmD;AAItC,QAAA,2CAA2C,GAAG,CAAC,CAAC;AAChD,QAAA,mDAAmD,GAAG,CAAC,CAAC;AAyErE;;;;;;;;;;;;;;;;GAgBG;AACI,MAAM,cAAc,GAAG,CAAC,EAC9B,WAAW,EACX,gBAAgB,EAChB,WAAW,EACX,UAAU,EACV,WAAW,EACX,UAAU,GAAG,EAAE,GACO,EAUrB,EAAE;IACH,MAAM,eAAe,GAAG,IAAA,oBAAc,EAAC;QACtC,GAAG,WAAW,CAAC,IAAI;QACnB,eAAe,EAAE,WAAW,CAAC,IAAI,CAAC,eAAe,IAAI,IAAI,EAAE,6EAA6E;KACxI,CAAC,CAAC;IAEH,gFAAgF;IAChF,MAAM,gBAAgB,GAAG,IAAI,QAAE,CAAC,WAAW,GAAG,UAAU,CAAC,CAAC;IAE1D,MAAM,kBAAkB,GAAG,IAAA,2BAAqB,GAAE,CAAC;IAEnD,MAAM,+BAA+B,GAAG;QACvC,oBAAoB,EAAE,eAAe;QACrC,IAAI,EAAE,kBAAkB;QACxB,IAAI,EAAE,gBAAgB;QACtB,mBAAmB,EAAE,WAAW,CAAC,QAAQ;YACxC,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M,YAAY,GAAG,oBAAoB,CAAC,SAAS,CAAC,CAAC,eAAe,EAAE,EAAE;;QACvE,IAAI,eAAe,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YACrC,MAAA,MAAA,YAAY,CAAC,SAAS,0CAAE,MAAM,mDAAG,mBAAmB,CAAC,eAAe,CAAC,CAAC,CAAC;QACxE,CAAC;QACD,IAAI,eAAe,CAAC,IAAI,KAAK,WAAW,EAAE,CAAC;YAC1C,MAAA,MAAA,YAAY,CAAC,SAAS,0CAAE,WAAW,mDAClC,mBAAmB,CAAC,eAAe,CAAC,CACpC,CAAC;YACF,mBAAmB,CAAC,YAAY,CAAC,CAAC;QACnC,CAAC;QACD,IAAI,eAAe,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YACxC,MAAA,MAAA,YAAY,CAAC,SAAS,0CAAE,SAAS,mDAAG,mBAAmB,CAAC,eAAe,CAAC,CAAC,CAAC;YAC1E,mBAAmB,CAAC,YAAY,CAAC,CAAC;QACnC,CAAC;QACD,IAAI,eAAe,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YACxC,MAAA,MAAA,YAAY,CAAC,SAAS,0CAAE,SAAS,mDAAG,mBAAmB,CAAC,eAAe,CAAC,CAAC,CAAC;YAC1E,mBAAmB,CAAC,YAAY,CAAC,CAAC;QACnC,CAAC;IACF,CAAC,CAAC,CAAC;IAEH,OAAO,OAAO,CAAC;AAChB,CAAC,CAAC;AA7GW,QAAA,yBAAyB,6BA6GpC","sourcesContent":["import {\n\tgetSignedMsgUserAccountPublicKey,\n\tSignedMsgOrderParamsDelegateMessage,\n\tSignedMsgOrderParamsMessage,\n\tSLOT_TIME_ESTIMATE_MS,\n} from '@drift-labs/sdk';\nimport {\n\tBN,\n\tDriftClient,\n\tgenerateSignedMsgUuid,\n\tgetOrderParams,\n\tOptionalOrderParams,\n\tPublicKey,\n} from '@drift-labs/sdk';\nimport {\n\tSwiftClient,\n\tSwiftOrderConfirmedEvent,\n\tSwiftOrderErroredEvent,\n\tSwiftOrderEvent,\n\tSwiftOrderEventWithParams,\n\tSwiftOrderSentEvent,\n} from '../../../../../../clients/swiftClient';\nimport { MarketId } from '../../../../../../types';\nimport { Observable, Subscription } from 'rxjs';\nimport { OptionalTriggerOrderParams } from '../types';\n\nexport const SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 5;\nexport const MINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 5;\n\nexport interface SwiftOrderOptions {\n\twallet: {\n\t\tsignMessage: (message: Uint8Array) => Promise<Uint8Array>;\n\t\tpublicKey: PublicKey;\n\t};\n\tswiftServerUrl: string;\n\tsignedMessageOrderSlotBuffer?: number;\n\tisDelegate?: boolean;\n\tcallbacks?: {\n\t\tonOrderParamsMessagePrepped?: (\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSigningExpiry?: (\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSigningSuccess?: (\n\t\t\tsignedMessage: Uint8Array,\n\t\t\t// we add the following here, because the onSigningSuccess callback is called before the order is sent to the swift server\n\t\t\torderUuid: Uint8Array,\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSent?: (\n\t\t\tswiftSentEvent: SwiftOrderEventWithParams<SwiftOrderSentEvent>\n\t\t) => void;\n\t\tonConfirmed?: (\n\t\t\tswiftConfirmedEvent: SwiftOrderEventWithParams<SwiftOrderConfirmedEvent>\n\t\t) => void;\n\t\tonExpired?: (\n\t\t\tswiftExpiredEvent: SwiftOrderEventWithParams<SwiftOrderErroredEvent>\n\t\t) => void;\n\t\tonErrored?: (\n\t\t\tswiftErroredEvent: SwiftOrderEventWithParams<SwiftOrderErroredEvent>\n\t\t) => void;\n\t};\n}\n\nexport type SwiftOrderObservable = Observable<SwiftOrderEvent>;\n\ninterface PrepSwiftOrderParams {\n\t/** The Drift client instance */\n\tdriftClient: DriftClient;\n\t/** The taker user account information */\n\ttakerUserAccount: {\n\t\t/** Public key of the user account */\n\t\tpubKey: PublicKey;\n\t\t/** User account ID */\n\t\tsubAccountId: number;\n\t};\n\t/** Current blockchain slot number */\n\tcurrentSlot: number;\n\t/** Whether this is a delegate order */\n\tisDelegate: boolean;\n\t/** Order parameters including main order and optional stop loss/take profit */\n\torderParams: {\n\t\t/** Main order parameters */\n\t\tmain: OptionalOrderParams;\n\t\t/** Optional stop loss order parameters */\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t\t/** Optional take profit order parameters */\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t};\n\t/** Buffer slots to account for signing time (default: 2 slots ~1 second). If a user is required to manually sign the message, this should be a higher number. */\n\tslotBuffer?: number;\n}\n\n/**\n * Prepares a swift order by encoding the order parameters into a message format\n * suitable for signing and sending to the Swift server.\n *\n * @param driftClient - The Drift client instance\n * @param takerUserAccount - The taker user account information\n * @param currentSlot - Current blockchain slot number\n * @param isDelegate - Whether this is a delegate order\n * @param orderParams - Order parameters including main order and optional stop loss/take profit\n * @param slotBuffer - Buffer slots to account for signing time (default: 35 slots ~14 seconds). Use this default value if it is not an auction order, else used an estimate number of slots to sign the message.\n *\n * @returns An object containing:\n * - `hexEncodedSwiftOrderMessage`: The encoded order message in both Uint8Array and string formats. The Uint8Array format is for a wallet to sign, while the string format is used to send to the SWIFT server.\n * - `signedMsgOrderParamsMessage`: The signed message order parameters\n * - `slotForSignedMsg`: The slot number for the signed message\n * - `signedMsgOrderUuid`: Unique identifier for the signed message order\n */\nexport const prepSwiftOrder = ({\n\tdriftClient,\n\ttakerUserAccount,\n\tcurrentSlot,\n\tisDelegate,\n\torderParams,\n\tslotBuffer = 35,\n}: PrepSwiftOrderParams): {\n\thexEncodedSwiftOrderMessage: {\n\t\tuInt8Array: Uint8Array;\n\t\tstring: string;\n\t};\n\tsignedMsgOrderParamsMessage:\n\t\t| SignedMsgOrderParamsMessage\n\t\t| SignedMsgOrderParamsDelegateMessage;\n\tslotForSignedMsg: BN;\n\tsignedMsgOrderUuid: Uint8Array;\n} => {\n\tconst mainOrderParams = getOrderParams({\n\t\t...orderParams.main,\n\t\tauctionDuration: orderParams.main.auctionDuration || null, // swift server expects auctionDuration to be null if not set, won't handle 0\n\t});\n\n\t// buffer for time the user takes to sign a message and send to the swift server\n\tconst slotForSignedMsg = new BN(currentSlot + slotBuffer);\n\n\tconst signedMsgOrderUuid = generateSignedMsgUuid();\n\n\tconst baseSignedMsgOrderParamsMessage = {\n\t\tsignedMsgOrderParams: mainOrderParams,\n\t\tuuid: signedMsgOrderUuid,\n\t\tslot: slotForSignedMsg,\n\t\tstopLossOrderParams: orderParams.stopLoss\n\t\t\t? {\n\t\t\t\t\tbaseAssetAmount: orderParams.stopLoss.baseAssetAmount,\n\t\t\t\t\ttriggerPrice: orderParams.stopLoss.triggerPrice,\n\t\t\t }\n\t\t\t: null,\n\t\ttakeProfitOrderParams: orderParams.takeProfit\n\t\t\t? {\n\t\t\t\t\tbaseAssetAmount: orderParams.takeProfit.baseAssetAmount,\n\t\t\t\t\ttriggerPrice: orderParams.takeProfit.triggerPrice,\n\t\t\t }\n\t\t\t: null,\n\t};\n\n\tconst signedMsgOrderParamsMessage:\n\t\t| SignedMsgOrderParamsMessage\n\t\t| SignedMsgOrderParamsDelegateMessage = isDelegate\n\t\t? {\n\t\t\t\t...baseSignedMsgOrderParamsMessage,\n\t\t\t\ttakerPubkey: takerUserAccount.pubKey,\n\t\t }\n\t\t: {\n\t\t\t\t...baseSignedMsgOrderParamsMessage,\n\t\t\t\tsubAccountId: takerUserAccount.subAccountId,\n\t\t };\n\n\tconst encodedOrderMessage = driftClient.encodeSignedMsgOrderParamsMessage(\n\t\tsignedMsgOrderParamsMessage,\n\t\tisDelegate\n\t);\n\tconst hexEncodedSwiftOrderMessage = Buffer.from(\n\t\tencodedOrderMessage.toString('hex')\n\t);\n\n\treturn {\n\t\thexEncodedSwiftOrderMessage: {\n\t\t\tuInt8Array: new Uint8Array(hexEncodedSwiftOrderMessage),\n\t\t\tstring: hexEncodedSwiftOrderMessage.toString(),\n\t\t},\n\t\tsignedMsgOrderParamsMessage,\n\t\tslotForSignedMsg,\n\t\tsignedMsgOrderUuid,\n\t};\n};\n\n/**\n * Error thrown when an auction slot has expired\n */\nexport class AuctionSlotExpiredError extends Error {\n\tname = 'AuctionSlotExpiredError';\n\n\t/**\n\t * Creates an instance of AuctionSlotExpiredError\n\t * @param message - Error message (default: 'Auction slot expired')\n\t */\n\tconstructor(message: string = 'Auction slot expired') {\n\t\tsuper(message);\n\t\tif (Error.captureStackTrace) {\n\t\t\tError.captureStackTrace(this, AuctionSlotExpiredError);\n\t\t}\n\t}\n}\n\ninterface SignOrderMsgParams {\n\t/** Wallet instance with message signing capability */\n\twallet: {\n\t\t/** Function to sign a message */\n\t\tsignMessage: (message: Uint8Array) => Promise<Uint8Array>;\n\t};\n\t/** Hex-encoded swift order message to sign */\n\thexEncodedSwiftOrderMessage: Uint8Array;\n\t/** Time in milliseconds till the auction expires */\n\texpirationTimeMs: number;\n\t/** Callback function called when the auction expires */\n\tonExpired?: () => void;\n}\n\n/**\n * Signs a swift order message with slot expiration monitoring.\n * Continuously monitors the current slot and rejects with AuctionSlotExpiredError\n * if the auction slot expires before signing is complete.\n *\n * @param wallet - Wallet instance with message signing capability\n * @param hexEncodedSwiftOrderMessage - Hex-encoded swift order message to sign\n * @param expirationTimeMs - Time in milliseconds till the auction expires\n * @param onExpired - Callback function called when the auction expires\n *\n * @returns Promise resolving to the signed message as Uint8Array\n * @throws {AuctionSlotExpiredError} When the auction slot expires before signing completes\n */\nexport const signSwiftOrderMsg = async ({\n\twallet,\n\thexEncodedSwiftOrderMessage,\n\texpirationTimeMs,\n\tonExpired,\n}: SignOrderMsgParams): Promise<Uint8Array> => {\n\tlet timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n\ttry {\n\t\t// Sign the message\n\t\tconst signedMessagePromise = wallet.signMessage(\n\t\t\thexEncodedSwiftOrderMessage\n\t\t);\n\n\t\tconst signingExpiredPromise = new Promise<never>((_resolve, reject) => {\n\t\t\ttimeoutId = setTimeout(() => {\n\t\t\t\tonExpired?.();\n\t\t\t\treject(new AuctionSlotExpiredError());\n\t\t\t}, expirationTimeMs);\n\t\t});\n\n\t\t// Ensure that the user signs the message before the expiration time\n\t\tconst signedMessage = await Promise.race([\n\t\t\tsignedMessagePromise,\n\t\t\tsigningExpiredPromise,\n\t\t]);\n\n\t\treturn signedMessage;\n\t} finally {\n\t\tif (timeoutId) {\n\t\t\tclearTimeout(timeoutId);\n\t\t}\n\t}\n};\n\n/**\n * Parameters for sending a swift order to the Swift server\n * @interface SendSwiftOrderParams\n */\ninterface SendSwiftOrderParams {\n\t/** The Drift client instance */\n\tdriftClient: DriftClient;\n\t/** Market identifier for the order */\n\tmarketId: MarketId;\n\t/** Hex-encoded swift order message as string */\n\thexEncodedSwiftOrderMessageString: string;\n\t/** The signed message from the wallet */\n\tsignedMessage: Uint8Array;\n\t/** Unique identifier for the signed message order */\n\tsignedMsgOrderUuid: Uint8Array;\n\t/** Public key of the taker authority */\n\ttakerAuthority: PublicKey;\n\t/** Public key of the signing authority */\n\tsigningAuthority: PublicKey;\n\t/** Duration of the auction in slots (optional) */\n\tauctionDuration?: number;\n}\n\n/**\n * Sends a swift order to the Swift server and handles the response.\n * Monitors the order status and calls appropriate callback functions based on the response type.\n *\n * @param driftClient - The Drift client instance\n * @param marketId - Market identifier for the order\n * @param hexEncodedSwiftOrderMessageString - Hex-encoded swift order message as string\n * @param signedMessage - The signed message from the wallet\n * @param signedMsgOrderUuid - Unique identifier for the signed message order\n * @param takerAuthority - Public key of the taker authority\n * @param signingAuthority - Public key of the signing authority\n * @param auctionDurationSlot - Duration of the auction in slots (optional)\n * @param swiftConfirmationSlotBuffer - Slot buffer for swift server confirmation time (default: 15)\n * @param onExpired - Callback function called when the order expires\n * @param onErrored - Callback function called when the order encounters an error\n * @param onConfirmed - Callback function called when the order is confirmed\n *\n * @returns Promise that resolves when the order processing is complete\n *\n */\nexport const sendSwiftOrder = ({\n\tdriftClient,\n\tmarketId,\n\thexEncodedSwiftOrderMessageString,\n\tsignedMessage,\n\tsignedMsgOrderUuid,\n\ttakerAuthority,\n\tsigningAuthority,\n\tauctionDuration,\n}: SendSwiftOrderParams): SwiftOrderObservable => {\n\tconst signedMsgUserOrdersAccountPubkey = getSignedMsgUserAccountPublicKey(\n\t\tdriftClient.program.programId,\n\t\ttakerAuthority\n\t);\n\n\tconst swiftOrderObservable = SwiftClient.sendAndConfirmSwiftOrderWS(\n\t\tdriftClient.connection,\n\t\tdriftClient,\n\t\tmarketId.marketIndex,\n\t\tmarketId.marketType,\n\t\thexEncodedSwiftOrderMessageString,\n\t\tBuffer.from(signedMessage),\n\t\ttakerAuthority,\n\t\tsignedMsgUserOrdersAccountPubkey,\n\t\tsignedMsgOrderUuid,\n\t\t((auctionDuration ?? 0) + 15) * SLOT_TIME_ESTIMATE_MS,\n\t\tsigningAuthority\n\t);\n\n\treturn swiftOrderObservable;\n};\n\ntype PrepSignAndSendSwiftOrderParams = {\n\tdriftClient: DriftClient;\n\tsubAccountId: number;\n\tmarketIndex: number;\n\tslotBuffer: number;\n\tswiftOptions: SwiftOrderOptions;\n\torderParams: {\n\t\tmain: OptionalOrderParams;\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t};\n};\n\n/**\n * Handles the full flow of the swift order, from preparing to signing and sending to the Swift server.\n * Callbacks can be provided to handle the events of the Swift order.\n * Returns a promise that resolves when the Swift order has reached a terminal state (i.e. confirmed, expired, or errored).\n */\nexport const prepSignAndSendSwiftOrder = async ({\n\tdriftClient,\n\tsubAccountId,\n\tmarketIndex,\n\tslotBuffer,\n\tswiftOptions,\n\torderParams,\n}: PrepSignAndSendSwiftOrderParams): Promise<void> => {\n\tconst currentSlot = await driftClient.connection.getSlot();\n\n\tconst {\n\t\thexEncodedSwiftOrderMessage,\n\t\tsignedMsgOrderUuid,\n\t\tsignedMsgOrderParamsMessage,\n\t} = prepSwiftOrder({\n\t\tdriftClient,\n\t\ttakerUserAccount: {\n\t\t\tpubKey: swiftOptions.wallet.publicKey,\n\t\t\tsubAccountId: subAccountId,\n\t\t},\n\t\tcurrentSlot,\n\t\tisDelegate: swiftOptions.isDelegate || false,\n\t\torderParams,\n\t\tslotBuffer,\n\t});\n\n\tswiftOptions.callbacks?.onOrderParamsMessagePrepped?.(\n\t\tsignedMsgOrderParamsMessage\n\t);\n\n\tconst expirationTimeMs =\n\t\tMath.max(\n\t\t\tslotBuffer +\n\t\t\t\t(orderParams.main.auctionDuration || 0) -\n\t\t\t\tSWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS,\n\t\t\tMINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS\n\t\t) * SLOT_TIME_ESTIMATE_MS;\n\n\t// Ensure that the user signs the message before the expiration time\n\tconst signedMessage = await signSwiftOrderMsg({\n\t\twallet: swiftOptions.wallet,\n\t\thexEncodedSwiftOrderMessage: hexEncodedSwiftOrderMessage.uInt8Array,\n\t\texpirationTimeMs,\n\t\tonExpired: () =>\n\t\t\tswiftOptions.callbacks?.onSigningExpiry?.(signedMsgOrderParamsMessage),\n\t});\n\n\tswiftOptions.callbacks?.onSigningSuccess?.(\n\t\tsignedMessage,\n\t\tsignedMsgOrderUuid,\n\t\tsignedMsgOrderParamsMessage\n\t);\n\n\t// Initialize SwiftClient (required before using sendSwiftOrder)\n\tSwiftClient.init(swiftOptions.swiftServerUrl);\n\n\t// Create a promise-based wrapper for the sendSwiftOrder callback-based API\n\tconst swiftOrderObservable = sendSwiftOrder({\n\t\tdriftClient,\n\t\tmarketId: MarketId.createPerpMarket(marketIndex),\n\t\thexEncodedSwiftOrderMessageString: hexEncodedSwiftOrderMessage.string,\n\t\tsignedMessage,\n\t\tsignedMsgOrderUuid,\n\t\ttakerAuthority: swiftOptions.wallet.publicKey,\n\t\tsigningAuthority: swiftOptions.wallet.publicKey,\n\t\tauctionDuration: orderParams.main.auctionDuration || undefined,\n\t});\n\n\tconst wrapSwiftOrderEvent = <T extends SwiftOrderEvent>(\n\t\tswiftOrderEvent: T\n\t) => {\n\t\treturn {\n\t\t\t...swiftOrderEvent,\n\t\t\tswiftOrderUuid: signedMsgOrderUuid,\n\t\t\torderParamsMessage: signedMsgOrderParamsMessage,\n\t\t};\n\t};\n\n\tlet promiseResolver: (value: void | PromiseLike<void>) => void;\n\tconst promise = new Promise<void>((resolve) => {\n\t\tpromiseResolver = resolve;\n\t});\n\n\tconst handleTerminalEvent = (subscription: Subscription) => {\n\t\tsubscription.unsubscribe();\n\t\tpromiseResolver();\n\t};\n\n\tconst subscription = swiftOrderObservable.subscribe((swiftOrderEvent) => {\n\t\tif (swiftOrderEvent.type === 'sent') {\n\t\t\tswiftOptions.callbacks?.onSent?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t}\n\t\tif (swiftOrderEvent.type === 'confirmed') {\n\t\t\tswiftOptions.callbacks?.onConfirmed?.(\n\t\t\t\twrapSwiftOrderEvent(swiftOrderEvent)\n\t\t\t);\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t\tif (swiftOrderEvent.type === 'expired') {\n\t\t\tswiftOptions.callbacks?.onExpired?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t\tif (swiftOrderEvent.type === 'errored') {\n\t\t\tswiftOptions.callbacks?.onErrored?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t});\n\n\treturn promise;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base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AAC;QACnC,CAAC;QACD,IAAI,eAAe,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YACxC,MAAA,MAAA,YAAY,CAAC,SAAS,0CAAE,SAAS,mDAAG,mBAAmB,CAAC,eAAe,CAAC,CAAC,CAAC;YAC1E,mBAAmB,CAAC,YAAY,CAAC,CAAC;QACnC,CAAC;QACD,IAAI,eAAe,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YACxC,MAAA,MAAA,YAAY,CAAC,SAAS,0CAAE,SAAS,mDAAG,mBAAmB,CAAC,eAAe,CAAC,CAAC,CAAC;YAC1E,mBAAmB,CAAC,YAAY,CAAC,CAAC;QACnC,CAAC;IACF,CAAC,CAAC,CAAC;IAEH,OAAO,OAAO,CAAC;AAChB,CAAC,CAAC;AA7GW,QAAA,yBAAyB,6BA6GpC","sourcesContent":["import {\n\tgetSignedMsgUserAccountPublicKey,\n\tSignedMsgOrderParamsDelegateMessage,\n\tSignedMsgOrderParamsMessage,\n\tSLOT_TIME_ESTIMATE_MS,\n} from '@drift-labs/sdk';\nimport {\n\tBN,\n\tDriftClient,\n\tgenerateSignedMsgUuid,\n\tgetOrderParams,\n\tOptionalOrderParams,\n\tPublicKey,\n} from '@drift-labs/sdk';\nimport {\n\tSwiftClient,\n\tSwiftOrderConfirmedEvent,\n\tSwiftOrderErroredEvent,\n\tSwiftOrderEvent,\n\tSwiftOrderEventWithParams,\n\tSwiftOrderSentEvent,\n} from '../../../../../../clients/swiftClient';\nimport { MarketId } from '../../../../../../types';\nimport { Observable, Subscription } from 'rxjs';\nimport { OptionalTriggerOrderParams } from '../types';\n\nexport const SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 5;\nexport const MINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 5;\n\nexport interface SwiftOrderOptions {\n\twallet: {\n\t\tsignMessage: (message: Uint8Array) => Promise<Uint8Array>;\n\t\tpublicKey: PublicKey;\n\t};\n\tswiftServerUrl: string;\n\tsignedMessageOrderSlotBuffer?: number;\n\tisDelegate?: boolean;\n\tcallbacks?: {\n\t\tonOrderParamsMessagePrepped?: (\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSigningExpiry?: (\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSigningSuccess?: (\n\t\t\tsignedMessage: Uint8Array,\n\t\t\t// we add the following here, because the onSigningSuccess callback is called before the order is sent to the swift server\n\t\t\torderUuid: Uint8Array,\n\t\t\torderParamsMessage:\n\t\t\t\t| SignedMsgOrderParamsMessage\n\t\t\t\t| SignedMsgOrderParamsDelegateMessage\n\t\t) => void;\n\t\tonSent?: (\n\t\t\tswiftSentEvent: SwiftOrderEventWithParams<SwiftOrderSentEvent>\n\t\t) => void;\n\t\tonConfirmed?: (\n\t\t\tswiftConfirmedEvent: SwiftOrderEventWithParams<SwiftOrderConfirmedEvent>\n\t\t) => void;\n\t\tonExpired?: (\n\t\t\tswiftExpiredEvent: SwiftOrderEventWithParams<SwiftOrderErroredEvent>\n\t\t) => void;\n\t\tonErrored?: (\n\t\t\tswiftErroredEvent: SwiftOrderEventWithParams<SwiftOrderErroredEvent>\n\t\t) => void;\n\t};\n}\n\nexport type SwiftOrderObservable = Observable<SwiftOrderEvent>;\n\ninterface PrepSwiftOrderParams {\n\t/** The Drift client instance */\n\tdriftClient: DriftClient;\n\t/** The taker user account information */\n\ttakerUserAccount: {\n\t\t/** Public key of the user account */\n\t\tpubKey: PublicKey;\n\t\t/** User account ID */\n\t\tsubAccountId: number;\n\t};\n\t/** Current blockchain slot number */\n\tcurrentSlot: number;\n\t/** Whether this is a delegate order */\n\tisDelegate: boolean;\n\t/** Order parameters including main order and optional stop loss/take profit */\n\torderParams: {\n\t\t/** Main order parameters */\n\t\tmain: OptionalOrderParams;\n\t\t/** Optional stop loss order parameters */\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t\t/** Optional take profit order parameters */\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t};\n\t/** Buffer slots to account for signing time (default: 2 slots ~1 second). If a user is required to manually sign the message, this should be a higher number. */\n\tslotBuffer?: number;\n}\n\n/**\n * Prepares a swift order by encoding the order parameters into a message format\n * suitable for signing and sending to the Swift server.\n *\n * @param driftClient - The Drift client instance\n * @param takerUserAccount - The taker user account information\n * @param currentSlot - Current blockchain slot number\n * @param isDelegate - Whether this is a delegate order\n * @param orderParams - Order parameters including main order and optional stop loss/take profit\n * @param slotBuffer - Buffer slots to account for signing time (default: 35 slots ~14 seconds). Use this default value if it is not an auction order, else used an estimate number of slots to sign the message.\n *\n * @returns An object containing:\n * - `hexEncodedSwiftOrderMessage`: The encoded order message in both Uint8Array and string formats. The Uint8Array format is for a wallet to sign, while the string format is used to send to the SWIFT server.\n * - `signedMsgOrderParamsMessage`: The signed message order parameters\n * - `slotForSignedMsg`: The slot number for the signed message\n * - `signedMsgOrderUuid`: Unique identifier for the signed message order\n */\nexport const prepSwiftOrder = ({\n\tdriftClient,\n\ttakerUserAccount,\n\tcurrentSlot,\n\tisDelegate,\n\torderParams,\n\tslotBuffer = 35,\n}: PrepSwiftOrderParams): {\n\thexEncodedSwiftOrderMessage: {\n\t\tuInt8Array: Uint8Array;\n\t\tstring: string;\n\t};\n\tsignedMsgOrderParamsMessage:\n\t\t| SignedMsgOrderParamsMessage\n\t\t| SignedMsgOrderParamsDelegateMessage;\n\tslotForSignedMsg: BN;\n\tsignedMsgOrderUuid: Uint8Array;\n} => {\n\tconst mainOrderParams = getOrderParams({\n\t\t...orderParams.main,\n\t\tauctionDuration: orderParams.main.auctionDuration || null, // swift server expects auctionDuration to be null if not set, won't handle 0\n\t});\n\n\t// buffer for time the user takes to sign a message and send to the swift server\n\tconst slotForSignedMsg = new BN(currentSlot + slotBuffer);\n\n\tconst signedMsgOrderUuid = generateSignedMsgUuid();\n\n\tconst baseSignedMsgOrderParamsMessage = {\n\t\tsignedMsgOrderParams: mainOrderParams,\n\t\tuuid: signedMsgOrderUuid,\n\t\tslot: slotForSignedMsg,\n\t\tstopLossOrderParams: orderParams.stopLoss\n\t\t\t? {\n\t\t\t\t\tbaseAssetAmount: orderParams.stopLoss.baseAssetAmount,\n\t\t\t\t\ttriggerPrice: orderParams.stopLoss.triggerPrice,\n\t\t\t }\n\t\t\t: null,\n\t\ttakeProfitOrderParams: orderParams.takeProfit\n\t\t\t? {\n\t\t\t\t\tbaseAssetAmount: orderParams.takeProfit.baseAssetAmount,\n\t\t\t\t\ttriggerPrice: orderParams.takeProfit.triggerPrice,\n\t\t\t }\n\t\t\t: null,\n\t};\n\n\tconst signedMsgOrderParamsMessage:\n\t\t| SignedMsgOrderParamsMessage\n\t\t| SignedMsgOrderParamsDelegateMessage = isDelegate\n\t\t? {\n\t\t\t\t...baseSignedMsgOrderParamsMessage,\n\t\t\t\ttakerPubkey: takerUserAccount.pubKey,\n\t\t }\n\t\t: {\n\t\t\t\t...baseSignedMsgOrderParamsMessage,\n\t\t\t\tsubAccountId: takerUserAccount.subAccountId,\n\t\t };\n\n\tconst encodedOrderMessage = driftClient.encodeSignedMsgOrderParamsMessage(\n\t\tsignedMsgOrderParamsMessage,\n\t\tisDelegate\n\t);\n\tconst hexEncodedSwiftOrderMessage = Buffer.from(\n\t\tencodedOrderMessage.toString('hex')\n\t);\n\n\treturn {\n\t\thexEncodedSwiftOrderMessage: {\n\t\t\tuInt8Array: new Uint8Array(hexEncodedSwiftOrderMessage),\n\t\t\tstring: hexEncodedSwiftOrderMessage.toString(),\n\t\t},\n\t\tsignedMsgOrderParamsMessage,\n\t\tslotForSignedMsg,\n\t\tsignedMsgOrderUuid,\n\t};\n};\n\n/**\n * Error thrown when an auction slot has expired\n */\nexport class AuctionSlotExpiredError extends Error {\n\tname = 'AuctionSlotExpiredError';\n\n\t/**\n\t * Creates an instance of AuctionSlotExpiredError\n\t * @param message - Error message (default: 'Auction slot expired')\n\t */\n\tconstructor(message: string = 'Auction slot expired') {\n\t\tsuper(message);\n\t\tif (Error.captureStackTrace) {\n\t\t\tError.captureStackTrace(this, AuctionSlotExpiredError);\n\t\t}\n\t}\n}\n\ninterface SignOrderMsgParams {\n\t/** Wallet instance with message signing capability */\n\twallet: {\n\t\t/** Function to sign a message */\n\t\tsignMessage: (message: Uint8Array) => Promise<Uint8Array>;\n\t};\n\t/** Hex-encoded swift order message to sign */\n\thexEncodedSwiftOrderMessage: Uint8Array;\n\t/** Time in milliseconds till the auction expires */\n\texpirationTimeMs: number;\n\t/** Callback function called when the auction expires */\n\tonExpired?: () => void;\n}\n\n/**\n * Signs a swift order message with slot expiration monitoring.\n * Continuously monitors the current slot and rejects with AuctionSlotExpiredError\n * if the auction slot expires before signing is complete.\n *\n * @param wallet - Wallet instance with message signing capability\n * @param hexEncodedSwiftOrderMessage - Hex-encoded swift order message to sign\n * @param expirationTimeMs - Time in milliseconds till the auction expires\n * @param onExpired - Callback function called when the auction expires\n *\n * @returns Promise resolving to the signed message as Uint8Array\n * @throws {AuctionSlotExpiredError} When the auction slot expires before signing completes\n */\nexport const signSwiftOrderMsg = async ({\n\twallet,\n\thexEncodedSwiftOrderMessage,\n\texpirationTimeMs,\n\tonExpired,\n}: SignOrderMsgParams): Promise<Uint8Array> => {\n\tlet timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n\ttry {\n\t\t// Sign the message\n\t\tconst signedMessagePromise = wallet.signMessage(\n\t\t\thexEncodedSwiftOrderMessage\n\t\t);\n\n\t\tconst signingExpiredPromise = new Promise<never>((_resolve, reject) => {\n\t\t\ttimeoutId = setTimeout(() => {\n\t\t\t\tonExpired?.();\n\t\t\t\treject(new AuctionSlotExpiredError());\n\t\t\t}, expirationTimeMs);\n\t\t});\n\n\t\t// Ensure that the user signs the message before the expiration time\n\t\tconst signedMessage = await Promise.race([\n\t\t\tsignedMessagePromise,\n\t\t\tsigningExpiredPromise,\n\t\t]);\n\n\t\treturn signedMessage;\n\t} finally {\n\t\tif (timeoutId) {\n\t\t\tclearTimeout(timeoutId);\n\t\t}\n\t}\n};\n\n/**\n * Parameters for sending a swift order to the Swift server\n * @interface SendSwiftOrderParams\n */\ninterface SendSwiftOrderParams {\n\t/** The Drift client instance */\n\tdriftClient: DriftClient;\n\t/** Market identifier for the order */\n\tmarketId: MarketId;\n\t/** Hex-encoded swift order message as string */\n\thexEncodedSwiftOrderMessageString: string;\n\t/** The signed message from the wallet */\n\tsignedMessage: Uint8Array;\n\t/** Unique identifier for the signed message order */\n\tsignedMsgOrderUuid: Uint8Array;\n\t/** Public key of the taker authority */\n\ttakerAuthority: PublicKey;\n\t/** Public key of the signing authority */\n\tsigningAuthority: PublicKey;\n\t/** Duration of the auction in slots (optional) */\n\tauctionDuration?: number;\n}\n\n/**\n * Sends a swift order to the Swift server and handles the response.\n * Monitors the order status and calls appropriate callback functions based on the response type.\n *\n * @param driftClient - The Drift client instance\n * @param marketId - Market identifier for the order\n * @param hexEncodedSwiftOrderMessageString - Hex-encoded swift order message as string\n * @param signedMessage - The signed message from the wallet\n * @param signedMsgOrderUuid - Unique identifier for the signed message order\n * @param takerAuthority - Public key of the taker authority\n * @param signingAuthority - Public key of the signing authority\n * @param auctionDurationSlot - Duration of the auction in slots (optional)\n * @param swiftConfirmationSlotBuffer - Slot buffer for swift server confirmation time (default: 15)\n * @param onExpired - Callback function called when the order expires\n * @param onErrored - Callback function called when the order encounters an error\n * @param onConfirmed - Callback function called when the order is confirmed\n *\n * @returns Promise that resolves when the order processing is complete\n *\n */\nexport const sendSwiftOrder = ({\n\tdriftClient,\n\tmarketId,\n\thexEncodedSwiftOrderMessageString,\n\tsignedMessage,\n\tsignedMsgOrderUuid,\n\ttakerAuthority,\n\tsigningAuthority,\n\tauctionDuration,\n}: SendSwiftOrderParams): SwiftOrderObservable => {\n\tconst signedMsgUserOrdersAccountPubkey = getSignedMsgUserAccountPublicKey(\n\t\tdriftClient.program.programId,\n\t\ttakerAuthority\n\t);\n\n\tconst swiftOrderObservable = SwiftClient.sendAndConfirmSwiftOrderWS(\n\t\tdriftClient.connection,\n\t\tdriftClient,\n\t\tmarketId.marketIndex,\n\t\tmarketId.marketType,\n\t\thexEncodedSwiftOrderMessageString,\n\t\tBuffer.from(signedMessage),\n\t\ttakerAuthority,\n\t\tsignedMsgUserOrdersAccountPubkey,\n\t\tsignedMsgOrderUuid,\n\t\t((auctionDuration ?? 0) + 15) * SLOT_TIME_ESTIMATE_MS,\n\t\tsigningAuthority\n\t);\n\n\treturn swiftOrderObservable;\n};\n\ntype PrepSignAndSendSwiftOrderParams = {\n\tdriftClient: DriftClient;\n\tsubAccountId: number;\n\tmarketIndex: number;\n\tslotBuffer: number;\n\tswiftOptions: SwiftOrderOptions;\n\torderParams: {\n\t\tmain: OptionalOrderParams;\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t};\n};\n\n/**\n * Handles the full flow of the swift order, from preparing to signing and sending to the Swift server.\n * Callbacks can be provided to handle the events of the Swift order.\n * Returns a promise that resolves when the Swift order has reached a terminal state (i.e. confirmed, expired, or errored).\n */\nexport const prepSignAndSendSwiftOrder = async ({\n\tdriftClient,\n\tsubAccountId,\n\tmarketIndex,\n\tslotBuffer,\n\tswiftOptions,\n\torderParams,\n}: PrepSignAndSendSwiftOrderParams): Promise<void> => {\n\tconst currentSlot = await driftClient.connection.getSlot('confirmed');\n\n\tconst {\n\t\thexEncodedSwiftOrderMessage,\n\t\tsignedMsgOrderUuid,\n\t\tsignedMsgOrderParamsMessage,\n\t} = prepSwiftOrder({\n\t\tdriftClient,\n\t\ttakerUserAccount: {\n\t\t\tpubKey: swiftOptions.wallet.publicKey,\n\t\t\tsubAccountId: subAccountId,\n\t\t},\n\t\tcurrentSlot,\n\t\tisDelegate: swiftOptions.isDelegate || false,\n\t\torderParams,\n\t\tslotBuffer,\n\t});\n\n\tswiftOptions.callbacks?.onOrderParamsMessagePrepped?.(\n\t\tsignedMsgOrderParamsMessage\n\t);\n\n\tconst expirationTimeMs =\n\t\tMath.max(\n\t\t\tslotBuffer +\n\t\t\t\t(orderParams.main.auctionDuration || 0) -\n\t\t\t\tSWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS,\n\t\t\tMINIMUM_SWIFT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS\n\t\t) * SLOT_TIME_ESTIMATE_MS;\n\n\t// Ensure that the user signs the message before the expiration time\n\tconst signedMessage = await signSwiftOrderMsg({\n\t\twallet: swiftOptions.wallet,\n\t\thexEncodedSwiftOrderMessage: hexEncodedSwiftOrderMessage.uInt8Array,\n\t\texpirationTimeMs,\n\t\tonExpired: () =>\n\t\t\tswiftOptions.callbacks?.onSigningExpiry?.(signedMsgOrderParamsMessage),\n\t});\n\n\tswiftOptions.callbacks?.onSigningSuccess?.(\n\t\tsignedMessage,\n\t\tsignedMsgOrderUuid,\n\t\tsignedMsgOrderParamsMessage\n\t);\n\n\t// Initialize SwiftClient (required before using sendSwiftOrder)\n\tSwiftClient.init(swiftOptions.swiftServerUrl);\n\n\t// Create a promise-based wrapper for the sendSwiftOrder callback-based API\n\tconst swiftOrderObservable = sendSwiftOrder({\n\t\tdriftClient,\n\t\tmarketId: MarketId.createPerpMarket(marketIndex),\n\t\thexEncodedSwiftOrderMessageString: hexEncodedSwiftOrderMessage.string,\n\t\tsignedMessage,\n\t\tsignedMsgOrderUuid,\n\t\ttakerAuthority: swiftOptions.wallet.publicKey,\n\t\tsigningAuthority: swiftOptions.wallet.publicKey,\n\t\tauctionDuration: orderParams.main.auctionDuration || undefined,\n\t});\n\n\tconst wrapSwiftOrderEvent = <T extends SwiftOrderEvent>(\n\t\tswiftOrderEvent: T\n\t) => {\n\t\treturn {\n\t\t\t...swiftOrderEvent,\n\t\t\tswiftOrderUuid: signedMsgOrderUuid,\n\t\t\torderParamsMessage: signedMsgOrderParamsMessage,\n\t\t};\n\t};\n\n\tlet promiseResolver: (value: void | PromiseLike<void>) => void;\n\tconst promise = new Promise<void>((resolve) => {\n\t\tpromiseResolver = resolve;\n\t});\n\n\tconst handleTerminalEvent = (subscription: Subscription) => {\n\t\tsubscription.unsubscribe();\n\t\tpromiseResolver();\n\t};\n\n\tconst subscription = swiftOrderObservable.subscribe((swiftOrderEvent) => {\n\t\tif (swiftOrderEvent.type === 'sent') {\n\t\t\tswiftOptions.callbacks?.onSent?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t}\n\t\tif (swiftOrderEvent.type === 'confirmed') {\n\t\t\tswiftOptions.callbacks?.onConfirmed?.(\n\t\t\t\twrapSwiftOrderEvent(swiftOrderEvent)\n\t\t\t);\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t\tif (swiftOrderEvent.type === 'expired') {\n\t\t\tswiftOptions.callbacks?.onExpired?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t\tif (swiftOrderEvent.type === 'errored') {\n\t\t\tswiftOptions.callbacks?.onErrored?.(wrapSwiftOrderEvent(swiftOrderEvent));\n\t\t\thandleTerminalEvent(subscription);\n\t\t}\n\t});\n\n\treturn promise;\n};\n"]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
/// <reference types="bn.js" />
|
|
1
2
|
import { BN, MarketType, PositionDirection, PostOnlyParams, ReferrerInfo, TxParams } from '@drift-labs/sdk';
|
|
2
3
|
import { Transaction, VersionedTransaction } from '@solana/web3.js';
|
|
3
4
|
import { OptionalAuctionParamsRequestInputs } from './dlobServer';
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
/// <reference types="bn.js" />
|
|
1
2
|
import { BN, DriftClient, PublicKey, SpotMarketConfig, TxParams, UserStatsAccount } from '@drift-labs/sdk';
|
|
2
3
|
import { Transaction, TransactionInstruction, VersionedTransaction } from '@solana/web3.js';
|
|
3
4
|
interface CreateUserAndDepositCollateralBaseIxsParams {
|
package/lib/drift/cli.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
/// <reference types="bn.js" />
|
|
1
2
|
import { BigNum, BN, CandleResolution, CurveRecord, DepositExplanation, DepositRecord, Event, FundingPaymentRecord, FundingRateRecord, InsuranceFundRecord, InsuranceFundStakeRecord, LiquidateBorrowForPerpPnlRecord, LiquidatePerpPnlForDepositRecord, LiquidatePerpRecord, LiquidateSpotRecord, LiquidationRecord, LiquidationType, LPAction, LPRecord, MarketType, NewUserRecord, Order, OrderAction, OrderActionExplanation, OrderStatus, OrderTriggerCondition, OrderType, PerpBankruptcyRecord, PositionDirection, PublicKey, SettlePnlExplanation, SettlePnlRecord, SpotBalanceType, SpotBankruptcyRecord, SpotInterestRecord, StakeAction, SwapRecord, WrappedEvent } from '@drift-labs/sdk';
|
|
2
3
|
import { JsonObject } from 'cerializr';
|
|
3
4
|
import { AccountSnapshot, LeaderboardResult, LeaderBoardResultRow, PnlHistoryDataPoint, PnlSnapshotOrderOption, RollingPnlData, SnapshotEpochResolution, UIAccountSnapshot, UserPerpPositionSnapshot, UserSnapshotRecord, UserSpotPositionSnapshot } from './types/leaderboard';
|
package/lib/types/UIMarket.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
/// <reference types="bn.js" />
|
|
1
2
|
import { MarketType, PerpMarketConfig, SpotMarketConfig } from '@drift-labs/sdk';
|
|
2
3
|
import { MarketId } from './MarketId';
|
|
3
4
|
import { Opaque } from './utility';
|
|
@@ -81,8 +82,8 @@ export declare class UIMarket {
|
|
|
81
82
|
get isUsdcMarket(): boolean;
|
|
82
83
|
get isStableCoinMarket(): boolean;
|
|
83
84
|
get isPredictionMarket(): boolean;
|
|
84
|
-
get precision(): import("
|
|
85
|
-
get precisionExp(): import("
|
|
85
|
+
get precision(): import("@drift-labs/sdk").BN;
|
|
86
|
+
get precisionExp(): import("@drift-labs/sdk").BN;
|
|
86
87
|
equals(other: UIMarket): boolean;
|
|
87
88
|
baseAssetSymbol(removePrefix?: boolean): string;
|
|
88
89
|
protected setUiSymbols(): void;
|
package/lib/types/trade.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
/// <reference types="bn.js" />
|
|
1
2
|
import { BN, OrderType } from '@drift-labs/sdk';
|
|
2
3
|
export type TradeOffsetPrice = 'worst' | 'best' | 'oracle' | 'mark' | 'entry' | 'bestOffer';
|
|
3
4
|
export type UIOrderType = 'market' | 'limit' | 'stopMarket' | 'stopLimit' | 'takeProfitMarket' | 'takeProfitLimit' | 'oracle' | 'oracleLimit' | 'scaledOrders';
|
package/lib/types/user.d.ts
CHANGED
package/lib/utils/NumLib.d.ts
CHANGED
package/lib/utils/index.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
/// <reference types="bn.js" />
|
|
2
|
+
/// <reference types="node" />
|
|
1
3
|
/// <reference types="node" />
|
|
2
4
|
import { BN, Event, OrderActionRecord, OrderRecord, PublicKey, BigNum, MarketType, DriftClient, SpotMarketConfig } from '@drift-labs/sdk';
|
|
3
5
|
import { UIMatchedOrderRecordAndAction, UISerializableOrderActionRecord } from '../serializableTypes';
|
package/lib/utils/math.d.ts
CHANGED