@drift-labs/common 1.0.4 → 1.0.6

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.
@@ -1,4 +1,4 @@
1
- import { BN, DriftClientConfig, DriftEnv, MarketType, OrderTriggerCondition, PositionDirection, PublicKey, QuoteResponse, SwapMode, UserAccount } from '@drift-labs/sdk';
1
+ import { BN, DriftClientConfig, DriftEnv, MarketType, OrderTriggerCondition, PositionDirection, PublicKey, QuoteResponse, SwapMode, User } from '@drift-labs/sdk';
2
2
  import { Transaction, VersionedTransaction } from '@solana/web3.js';
3
3
  import { MarketId } from '../../../types';
4
4
  import { OpenPerpMarketOrderParams } from '../../base/actions/trade/openPerpOrder/openPerpMarketOrder';
@@ -40,7 +40,14 @@ export declare class CentralServerDrift {
40
40
  * @returns The result of the operation
41
41
  */
42
42
  private driftClientContextWrapper;
43
- getUserAccount(userAccountPublicKey: PublicKey): Promise<UserAccount>;
43
+ /**
44
+ * Returns a User object for a given user account public key. This fetches the user account data once.
45
+ *
46
+ * You may read more about the User object [here](https://github.com/drift-labs/protocol-v2/blob/master/sdk/src/user.ts)
47
+ *
48
+ * @param userAccountPublicKey - The user account public key
49
+ */
50
+ getUser(userAccountPublicKey: PublicKey): Promise<User>;
44
51
  getDepositTxn(userAccountPublicKey: PublicKey, amount: BN, spotMarketIndex: number): Promise<VersionedTransaction | Transaction>;
45
52
  getWithdrawTxn(userAccountPublicKey: PublicKey, amount: BN, spotMarketIndex: number, options?: {
46
53
  isBorrow?: boolean;
@@ -83,6 +83,10 @@ class CentralServerDrift {
83
83
  const user = new sdk_1.User({
84
84
  driftClient: this.driftClient,
85
85
  userAccountPublicKey,
86
+ accountSubscription: {
87
+ type: 'custom',
88
+ userAccountSubscriber: new sdk_1.OneShotUserAccountSubscriber(this.driftClient.program, userAccountPublicKey, undefined, undefined),
89
+ },
86
90
  });
87
91
  // Store original state
88
92
  const originalWallet = this.driftClient.wallet;
@@ -127,10 +131,25 @@ class CentralServerDrift {
127
131
  }
128
132
  }
129
133
  }
130
- async getUserAccount(userAccountPublicKey) {
134
+ /**
135
+ * Returns a User object for a given user account public key. This fetches the user account data once.
136
+ *
137
+ * You may read more about the User object [here](https://github.com/drift-labs/protocol-v2/blob/master/sdk/src/user.ts)
138
+ *
139
+ * @param userAccountPublicKey - The user account public key
140
+ */
141
+ async getUser(userAccountPublicKey) {
131
142
  const oneShotUserAccountSubscriber = new sdk_1.OneShotUserAccountSubscriber(this.driftClient.program, userAccountPublicKey, undefined, undefined);
132
- await oneShotUserAccountSubscriber.subscribe();
133
- return oneShotUserAccountSubscriber.getUserAccountAndSlot().data;
143
+ const user = new sdk_1.User({
144
+ driftClient: this.driftClient,
145
+ userAccountPublicKey,
146
+ accountSubscription: {
147
+ type: 'custom',
148
+ userAccountSubscriber: oneShotUserAccountSubscriber,
149
+ },
150
+ });
151
+ await user.subscribe();
152
+ return user;
134
153
  }
135
154
  async getDepositTxn(userAccountPublicKey, amount, spotMarketIndex) {
136
155
  return this.driftClientContextWrapper(userAccountPublicKey, async (user) => {
@@ -1 +1 @@
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;Q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ACxC,gBAAgB,EAAE,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,gBAAgB,mCAAI,KAAK;iBACpD,CAAC,CAAC;YACJ,CAAC;YAED,MAAM,OAAO,GAAG,MAAM,IAAA,oBAAa,EAAC;gBACnC,WAAW,EAAE,IAAI,CAAC,WAAW;gBAC7B,aAAa;gBACb,IAAI;gBACJ,mBAAmB,EAAE,eAAe;gBACpC,iBAAiB,EAAE,aAAa;gBAChC,MAAM;gBACN,KAAK;gBACL,QAAQ,EAAE;oBACT,wBAAwB,EAAE,IAAI;oBAC9B,4BAA4B,EAAE,GAAG;iBACjC;aACD,CAAC,CAAC;YAEH,OAAO,OAAO,CAAC;QAChB,CAAC,CACD,CAAC;IACH,CAAC;IAEM,KAAK,CAAC,qBAAqB,CAAC,EAAsC;QACxE,OAAO,IAAI,CAAC,WAAW,CAAC,eAAe,CAAC,EAAE,EAAE,SAAS,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;IACzE,CAAC;CACD;AAzdD,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
+ {"version":3,"file":"CentralServerDrift.js","sourceRoot":"","sources":["../../../../src/drift/Drift/clients/CentralServerDrift.ts"],"names":[],"mappings":";;;AAAA,yCAyByB;AACzB,6CAAgF;AAChF,0EAAyE;AACzE,4CAKsB;AAEtB,6DAAmE;AACnE,+DAAqE;AACrE,yEAA+E;AAC/E,iEAAuE;AACvE,oGAGoE;AACpE,0GAGuE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AAC,CAAC;IACzE,CAAC;CACD;AA/eD,gDA+eC","sourcesContent":["import {\n\tBigNum,\n\tBN,\n\tCustomizedCadenceBulkAccountLoader,\n\tDelistedMarketSetting,\n\tDevnetPerpMarkets,\n\tDevnetSpotMarkets,\n\tDRIFT_PROGRAM_ID,\n\tDriftClient,\n\tDriftClientConfig,\n\tDriftEnv,\n\tJupiterClient,\n\tMainnetPerpMarkets,\n\tMainnetSpotMarkets,\n\tMarketType,\n\tOneShotUserAccountSubscriber,\n\tOrderTriggerCondition,\n\tPerpMarketConfig,\n\tPositionDirection,\n\tPublicKey,\n\tQuoteResponse,\n\tSpotMarketConfig,\n\tSwapMode,\n\tUser,\n\tWhileValidTxSender,\n} from '@drift-labs/sdk';\nimport { Connection, Transaction, VersionedTransaction } from '@solana/web3.js';\nimport { COMMON_UI_UTILS } from '../../../common-ui-utils/commonUiUtils';\nimport {\n\tDEFAULT_ACCOUNT_LOADER_COMMITMENT,\n\tDEFAULT_ACCOUNT_LOADER_POLLING_FREQUENCY_MS,\n\tDEFAULT_TX_SENDER_CONFIRMATION_STRATEGY,\n\tDEFAULT_TX_SENDER_RETRY_INTERVAL,\n} from '../constants';\nimport { MarketId } from '../../../types';\nimport { createDepositTxn } from '../../base/actions/spot/deposit';\nimport { createWithdrawTxn } from '../../base/actions/spot/withdraw';\nimport { createSettleFundingTxn } from '../../base/actions/perp/settleFunding';\nimport { createSettlePnlTxn } from '../../base/actions/perp/settlePnl';\nimport {\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\taccountSubscription: {\n\t\t\t\ttype: 'custom',\n\t\t\t\tuserAccountSubscriber: new OneShotUserAccountSubscriber(\n\t\t\t\t\tthis.driftClient.program,\n\t\t\t\t\tuserAccountPublicKey,\n\t\t\t\t\tundefined,\n\t\t\t\t\tundefined\n\t\t\t\t),\n\t\t\t},\n\t\t});\n\n\t\t// Store original state\n\t\tconst originalWallet = this.driftClient.wallet;\n\t\tconst originalAuthority = this.driftClient.authority;\n\n\t\ttry {\n\t\t\t// Setup: Subscribe to user and configure DriftClient\n\t\t\tawait user.subscribe();\n\n\t\t\tconst authority = user.getUserAccount().authority;\n\t\t\tthis.driftClient.authority = authority;\n\n\t\t\tconst success = await this.driftClient.addUser(\n\t\t\t\tuser.getUserAccount().subAccountId,\n\t\t\t\tauthority\n\t\t\t);\n\n\t\t\tif (!success) {\n\t\t\t\tthrow new Error('Failed to add user to DriftClient');\n\t\t\t}\n\n\t\t\t// Replace wallet with user's authority to ensure correct transaction signing\n\t\t\t// This is necessary because DriftClient adds wallet.publicKey to instructions\n\t\t\tconst userWallet = {\n\t\t\t\tpublicKey: authority,\n\t\t\t\tsignTransaction: () =>\n\t\t\t\t\tPromise.reject(\n\t\t\t\t\t\t'This is a placeholder - do not sign with this wallet'\n\t\t\t\t\t),\n\t\t\t\tsignAllTransactions: () =>\n\t\t\t\t\tPromise.reject(\n\t\t\t\t\t\t'This is a placeholder - do not sign with this wallet'\n\t\t\t\t\t),\n\t\t\t};\n\n\t\t\t// Update wallet in all places that reference it\n\t\t\tthis.driftClient.wallet = userWallet;\n\t\t\t//@ts-ignore\n\t\t\tthis.driftClient.provider.wallet = userWallet;\n\t\t\tthis.driftClient.txHandler.updateWallet(userWallet);\n\n\t\t\t// Execute the operation\n\t\t\tconst result = await operation(user);\n\n\t\t\treturn result;\n\t\t} finally {\n\t\t\t// Cleanup: Always restore original state and unsubscribe\n\t\t\tthis.driftClient.wallet = originalWallet;\n\t\t\tthis.driftClient.txHandler.updateWallet(originalWallet);\n\t\t\tthis.driftClient.authority = originalAuthority;\n\n\t\t\ttry {\n\t\t\t\tawait user.unsubscribe();\n\t\t\t\tthis.driftClient.users.clear();\n\t\t\t} catch (cleanupError) {\n\t\t\t\tconsole.warn('Error during cleanup:', cleanupError);\n\t\t\t\t// Don't throw cleanup errors, but log them\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Returns a User object for a given user account public key. This fetches the user account data once.\n\t *\n\t * You may read more about the User object [here](https://github.com/drift-labs/protocol-v2/blob/master/sdk/src/user.ts)\n\t *\n\t * @param userAccountPublicKey - The user account public key\n\t */\n\tpublic async getUser(userAccountPublicKey: PublicKey): Promise<User> {\n\t\tconst oneShotUserAccountSubscriber = new OneShotUserAccountSubscriber(\n\t\t\tthis.driftClient.program,\n\t\t\tuserAccountPublicKey,\n\t\t\tundefined,\n\t\t\tundefined\n\t\t);\n\t\tconst user = new User({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuserAccountPublicKey,\n\t\t\taccountSubscription: {\n\t\t\t\ttype: 'custom',\n\t\t\t\tuserAccountSubscriber: oneShotUserAccountSubscriber,\n\t\t\t},\n\t\t});\n\t\tawait user.subscribe();\n\t\treturn user;\n\t}\n\n\tpublic async getDepositTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tamount: BN,\n\t\tspotMarketIndex: number\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst spotMarketConfig = this.spotMarketConfigs.find(\n\t\t\t\t\t(market) => market.marketIndex === spotMarketIndex\n\t\t\t\t);\n\n\t\t\t\tif (!spotMarketConfig) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Spot market config not found for index ${spotMarketIndex}`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst depositTxn = await createDepositTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tamount: BigNum.from(amount, spotMarketConfig.precisionExp),\n\t\t\t\t\tspotMarketConfig,\n\t\t\t\t});\n\n\t\t\t\treturn depositTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\tpublic async getWithdrawTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tamount: BN,\n\t\tspotMarketIndex: number,\n\t\toptions?: {\n\t\t\tisBorrow?: boolean;\n\t\t\tisMax?: boolean;\n\t\t}\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst spotMarketConfig = this.spotMarketConfigs.find(\n\t\t\t\t\t(market) => market.marketIndex === spotMarketIndex\n\t\t\t\t);\n\n\t\t\t\tif (!spotMarketConfig) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Spot market config not found for index ${spotMarketIndex}`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst withdrawTxn = await createWithdrawTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tamount: BigNum.from(amount, spotMarketConfig.precisionExp),\n\t\t\t\t\tspotMarketConfig,\n\t\t\t\t\tisBorrow: options?.isBorrow,\n\t\t\t\t\tisMax: options?.isMax,\n\t\t\t\t});\n\n\t\t\t\treturn withdrawTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\tpublic async getSettleFundingTxn(\n\t\tuserAccountPublicKey: PublicKey\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst settleFundingTxn = await createSettleFundingTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t});\n\n\t\t\t\treturn settleFundingTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\tpublic async getSettlePnlTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tmarketIndexes: number[]\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst settlePnlTxn = await createSettlePnlTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tmarketIndexes,\n\t\t\t\t});\n\n\t\t\t\treturn settlePnlTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\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"]}
@@ -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":["../../../../../../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;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/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,IAA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,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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drift-labs/common",
3
- "version": "1.0.4",
3
+ "version": "1.0.6",
4
4
  "description": "Common functions for Drift",
5
5
  "main": "./lib/index.js",
6
6
  "types": "./lib/index.d.ts",