@drift-labs/common 1.0.6 → 1.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/drift/Drift/clients/{CentralServerDrift.d.ts → CentralServerDrift/index.d.ts} +10 -10
- package/lib/drift/Drift/clients/{CentralServerDrift.js → CentralServerDrift/index.js} +71 -27
- package/lib/drift/Drift/clients/CentralServerDrift/index.js.map +1 -0
- package/lib/drift/Drift/clients/CentralServerDrift/types.d.ts +12 -0
- package/lib/drift/Drift/clients/CentralServerDrift/types.js +3 -0
- package/lib/drift/Drift/clients/CentralServerDrift/types.js.map +1 -0
- package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/dlobServer/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.d.ts +9 -5
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.d.ts +7 -4
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js.map +1 -1
- package/lib/drift/cli.js +0 -5
- package/lib/drift/cli.js.map +1 -1
- package/package.json +1 -1
- package/lib/drift/Drift/clients/CentralServerDrift.js.map +0 -1
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
import { BN, DriftClientConfig, DriftEnv, MarketType, OrderTriggerCondition, PositionDirection, PublicKey, QuoteResponse, SwapMode, User } from '@drift-labs/sdk';
|
|
2
2
|
import { Transaction, VersionedTransaction } from '@solana/web3.js';
|
|
3
|
-
import { MarketId } from '
|
|
4
|
-
import {
|
|
5
|
-
import { OpenPerpNonMarketOrderParams } from '../../base/actions/trade/openPerpOrder/openPerpNonMarketOrder';
|
|
6
|
-
import { TxnOrSwiftResult, WithTxnParams } from '../../base/actions/trade/openPerpOrder/types';
|
|
3
|
+
import { MarketId } from '../../../../types';
|
|
4
|
+
import { CentralServerGetOpenPerpMarketOrderTxnParams, CentralServerGetOpenPerpNonMarketOrderTxnParams } from './types';
|
|
7
5
|
/**
|
|
8
6
|
* A Drift client that fetches user data on-demand, while market data is continuously subscribed to.
|
|
9
7
|
*
|
|
@@ -13,6 +11,10 @@ export declare class CentralServerDrift {
|
|
|
13
11
|
private driftClient;
|
|
14
12
|
private _perpMarketConfigs;
|
|
15
13
|
private spotMarketConfigs;
|
|
14
|
+
/**
|
|
15
|
+
* The public endpoints that can be used to retrieve Drift data / interact with the Drift program.
|
|
16
|
+
*/
|
|
17
|
+
private _driftEndpoints;
|
|
16
18
|
/**
|
|
17
19
|
* @param solanaRpcEndpoint - The Solana RPC endpoint to use for reading RPC data.
|
|
18
20
|
* @param driftEnv - The drift environment to use for the drift client.
|
|
@@ -55,15 +57,13 @@ export declare class CentralServerDrift {
|
|
|
55
57
|
}): Promise<VersionedTransaction | Transaction>;
|
|
56
58
|
getSettleFundingTxn(userAccountPublicKey: PublicKey): Promise<VersionedTransaction | Transaction>;
|
|
57
59
|
getSettlePnlTxn(userAccountPublicKey: PublicKey, marketIndexes: number[]): Promise<VersionedTransaction | Transaction>;
|
|
58
|
-
getOpenPerpMarketOrderTxn<
|
|
59
|
-
|
|
60
|
-
}): Promise<TxnOrSwiftResult<T>>;
|
|
60
|
+
getOpenPerpMarketOrderTxn(params: CentralServerGetOpenPerpMarketOrderTxnParams<true>): Promise<void>;
|
|
61
|
+
getOpenPerpMarketOrderTxn(params: CentralServerGetOpenPerpMarketOrderTxnParams<false>): Promise<Transaction | VersionedTransaction>;
|
|
61
62
|
/**
|
|
62
63
|
* Create a perp non-market order with amount and asset type
|
|
63
64
|
*/
|
|
64
|
-
getOpenPerpNonMarketOrderTxn(
|
|
65
|
-
|
|
66
|
-
}): Promise<VersionedTransaction | Transaction | void>;
|
|
65
|
+
getOpenPerpNonMarketOrderTxn(params: CentralServerGetOpenPerpNonMarketOrderTxnParams<true>): Promise<void>;
|
|
66
|
+
getOpenPerpNonMarketOrderTxn(params: CentralServerGetOpenPerpNonMarketOrderTxnParams<false>): Promise<Transaction | VersionedTransaction>;
|
|
67
67
|
/**
|
|
68
68
|
* Create a transaction to edit an existing order
|
|
69
69
|
*/
|
|
@@ -3,17 +3,18 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.CentralServerDrift = void 0;
|
|
4
4
|
const sdk_1 = require("@drift-labs/sdk");
|
|
5
5
|
const web3_js_1 = require("@solana/web3.js");
|
|
6
|
-
const commonUiUtils_1 = require("
|
|
7
|
-
const constants_1 = require("
|
|
8
|
-
const deposit_1 = require("
|
|
9
|
-
const withdraw_1 = require("
|
|
10
|
-
const settleFunding_1 = require("
|
|
11
|
-
const settlePnl_1 = require("
|
|
12
|
-
const openPerpMarketOrder_1 = require("
|
|
13
|
-
const openPerpNonMarketOrder_1 = require("
|
|
14
|
-
const editOrder_1 = require("
|
|
15
|
-
const cancelOrder_1 = require("
|
|
16
|
-
const swap_1 = require("
|
|
6
|
+
const commonUiUtils_1 = require("../../../../common-ui-utils/commonUiUtils");
|
|
7
|
+
const constants_1 = require("../../constants");
|
|
8
|
+
const deposit_1 = require("../../../base/actions/spot/deposit");
|
|
9
|
+
const withdraw_1 = require("../../../base/actions/spot/withdraw");
|
|
10
|
+
const settleFunding_1 = require("../../../base/actions/perp/settleFunding");
|
|
11
|
+
const settlePnl_1 = require("../../../base/actions/perp/settlePnl");
|
|
12
|
+
const openPerpMarketOrder_1 = require("../../../base/actions/trade/openPerpOrder/openPerpMarketOrder");
|
|
13
|
+
const openPerpNonMarketOrder_1 = require("../../../base/actions/trade/openPerpOrder/openPerpNonMarketOrder");
|
|
14
|
+
const editOrder_1 = require("../../../base/actions/trade/editOrder");
|
|
15
|
+
const cancelOrder_1 = require("../../../base/actions/trade/cancelOrder");
|
|
16
|
+
const swap_1 = require("../../../base/actions/trade/swap");
|
|
17
|
+
const EnvironmentConstants_1 = require("../../../../EnvironmentConstants");
|
|
17
18
|
/**
|
|
18
19
|
* A Drift client that fetches user data on-demand, while market data is continuously subscribed to.
|
|
19
20
|
*
|
|
@@ -63,6 +64,13 @@ class CentralServerDrift {
|
|
|
63
64
|
driftEnv === 'devnet' ? sdk_1.DevnetPerpMarkets : sdk_1.MainnetPerpMarkets;
|
|
64
65
|
this.spotMarketConfigs =
|
|
65
66
|
driftEnv === 'devnet' ? sdk_1.DevnetSpotMarkets : sdk_1.MainnetSpotMarkets;
|
|
67
|
+
// set up Drift endpoints
|
|
68
|
+
const driftDlobServerHttpUrlToUse = EnvironmentConstants_1.EnvironmentConstants.dlobServerHttpUrl[config.driftEnv === 'devnet' ? 'dev' : 'mainnet'];
|
|
69
|
+
const swiftServerUrlToUse = EnvironmentConstants_1.EnvironmentConstants.swiftServerUrl[config.driftEnv === 'devnet' ? 'staging' : 'mainnet'];
|
|
70
|
+
this._driftEndpoints = {
|
|
71
|
+
dlobServerHttpUrl: driftDlobServerHttpUrlToUse,
|
|
72
|
+
swiftServerUrl: swiftServerUrlToUse,
|
|
73
|
+
};
|
|
66
74
|
}
|
|
67
75
|
async subscribe() {
|
|
68
76
|
await this.driftClient.subscribe();
|
|
@@ -204,25 +212,61 @@ class CentralServerDrift {
|
|
|
204
212
|
}
|
|
205
213
|
async getOpenPerpMarketOrderTxn({ userAccountPublicKey, ...rest }) {
|
|
206
214
|
return this.driftClientContextWrapper(userAccountPublicKey, async (user) => {
|
|
207
|
-
const
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
215
|
+
const { useSwift, swiftOptions, placeAndTake, ...otherProps } = rest;
|
|
216
|
+
if (useSwift) {
|
|
217
|
+
const swiftOrderResult = await (0, openPerpMarketOrder_1.createOpenPerpMarketOrder)({
|
|
218
|
+
...otherProps,
|
|
219
|
+
useSwift: true,
|
|
220
|
+
swiftOptions: {
|
|
221
|
+
...swiftOptions,
|
|
222
|
+
swiftServerUrl: this._driftEndpoints.swiftServerUrl,
|
|
223
|
+
},
|
|
224
|
+
driftClient: this.driftClient,
|
|
225
|
+
user,
|
|
226
|
+
dlobServerHttpUrl: this._driftEndpoints.dlobServerHttpUrl,
|
|
227
|
+
});
|
|
228
|
+
return swiftOrderResult;
|
|
229
|
+
}
|
|
230
|
+
else {
|
|
231
|
+
const openPerpMarketOrderTxn = await (0, openPerpMarketOrder_1.createOpenPerpMarketOrder)({
|
|
232
|
+
...otherProps,
|
|
233
|
+
placeAndTake,
|
|
234
|
+
useSwift: false,
|
|
235
|
+
driftClient: this.driftClient,
|
|
236
|
+
user,
|
|
237
|
+
dlobServerHttpUrl: this._driftEndpoints.dlobServerHttpUrl,
|
|
238
|
+
});
|
|
239
|
+
return openPerpMarketOrderTxn;
|
|
240
|
+
}
|
|
213
241
|
});
|
|
214
242
|
}
|
|
215
|
-
/**
|
|
216
|
-
* Create a perp non-market order with amount and asset type
|
|
217
|
-
*/
|
|
218
243
|
async getOpenPerpNonMarketOrderTxn({ userAccountPublicKey, ...rest }) {
|
|
219
244
|
return this.driftClientContextWrapper(userAccountPublicKey, async (user) => {
|
|
220
|
-
const
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
245
|
+
const { useSwift, swiftOptions, ...otherProps } = rest;
|
|
246
|
+
if (useSwift) {
|
|
247
|
+
const swiftOrderResult = await (0, openPerpNonMarketOrder_1.createOpenPerpNonMarketOrder)({
|
|
248
|
+
...otherProps,
|
|
249
|
+
useSwift: true,
|
|
250
|
+
swiftOptions: {
|
|
251
|
+
...swiftOptions,
|
|
252
|
+
swiftServerUrl: this._driftEndpoints.swiftServerUrl,
|
|
253
|
+
},
|
|
254
|
+
driftClient: this.driftClient,
|
|
255
|
+
user,
|
|
256
|
+
dlobServerHttpUrl: this._driftEndpoints.dlobServerHttpUrl,
|
|
257
|
+
});
|
|
258
|
+
return swiftOrderResult;
|
|
259
|
+
}
|
|
260
|
+
else {
|
|
261
|
+
const openPerpNonMarketOrderTxn = await (0, openPerpNonMarketOrder_1.createOpenPerpNonMarketOrder)({
|
|
262
|
+
...otherProps,
|
|
263
|
+
useSwift: false,
|
|
264
|
+
driftClient: this.driftClient,
|
|
265
|
+
user,
|
|
266
|
+
dlobServerHttpUrl: this._driftEndpoints.dlobServerHttpUrl,
|
|
267
|
+
});
|
|
268
|
+
return openPerpNonMarketOrderTxn;
|
|
269
|
+
}
|
|
226
270
|
});
|
|
227
271
|
}
|
|
228
272
|
/**
|
|
@@ -304,4 +348,4 @@ class CentralServerDrift {
|
|
|
304
348
|
}
|
|
305
349
|
}
|
|
306
350
|
exports.CentralServerDrift = CentralServerDrift;
|
|
307
|
-
//# sourceMappingURL=
|
|
351
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/drift/Drift/clients/CentralServerDrift/index.ts"],"names":[],"mappings":";;;AAAA,yCAyByB;AACzB,6CAAgF;AAChF,6EAA4E;AAC5E,+CAKyB;AAEzB,gEAAsE;AACtE,kEAAwE;AACxE,4EAAkF;AAClF,oEAA0E;AAC1E,uGAA0G;AAC1G,6GAG0E;AAC1E,qEAA2E;AAC3E,yEAAgF;AAChF,2DAAiE;AAKjE,2EAAwE;AAMxE;;;;GAIG;AACH,MAAa,kBAAkB;IAY9B;;;;;OAKG;IACH,YAAY,MAMX;QACA,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;QAEjC,MAAM,UAAU,GAAG,IAAI,oBAAU,CAAC,MAAM,CAAC,iBAAiB,CAAC,CAAC;QAC5D,MAAM,cAAc,GAAG,IAAI,eAAS,CAAC,sBAAgB,CAAC,CAAC;QACvD,MAAM,aAAa,GAAG,IAAI,wCAAkC,CAC3D,UAAU,EACV,6CAAiC,EACjC,uDAA2C,CAC3C,CAAC;QAEF,MAAM,MAAM,GAAG,+BAAe,CAAC,wBAAwB,EAAE,CAAC,CAAC,4DAA4D;QAEvH,MAAM,iBAAiB,G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\n\tDRIFT_PROGRAM_ID,\n\tDriftClient,\n\tDriftClientConfig,\n\tDriftEnv,\n\tJupiterClient,\n\tMainnetPerpMarkets,\n\tMainnetSpotMarkets,\n\tMarketType,\n\tOneShotUserAccountSubscriber,\n\tOrderTriggerCondition,\n\tPerpMarketConfig,\n\tPositionDirection,\n\tPublicKey,\n\tQuoteResponse,\n\tSpotMarketConfig,\n\tSwapMode,\n\tUser,\n\tWhileValidTxSender,\n} from '@drift-labs/sdk';\nimport { Connection, Transaction, VersionedTransaction } from '@solana/web3.js';\nimport { COMMON_UI_UTILS } from '../../../../common-ui-utils/commonUiUtils';\nimport {\n\tDEFAULT_ACCOUNT_LOADER_COMMITMENT,\n\tDEFAULT_ACCOUNT_LOADER_POLLING_FREQUENCY_MS,\n\tDEFAULT_TX_SENDER_CONFIRMATION_STRATEGY,\n\tDEFAULT_TX_SENDER_RETRY_INTERVAL,\n} from '../../constants';\nimport { MarketId } from '../../../../types';\nimport { createDepositTxn } from '../../../base/actions/spot/deposit';\nimport { createWithdrawTxn } from '../../../base/actions/spot/withdraw';\nimport { createSettleFundingTxn } from '../../../base/actions/perp/settleFunding';\nimport { createSettlePnlTxn } from '../../../base/actions/perp/settlePnl';\nimport { createOpenPerpMarketOrder } from '../../../base/actions/trade/openPerpOrder/openPerpMarketOrder';\nimport {\n\tcreateOpenPerpNonMarketOrder,\n\tOpenPerpNonMarketOrderParams,\n} from '../../../base/actions/trade/openPerpOrder/openPerpNonMarketOrder';\nimport { createEditOrderTxn } from '../../../base/actions/trade/editOrder';\nimport { createCancelOrdersTxn } from '../../../base/actions/trade/cancelOrder';\nimport { createSwapTxn } from '../../../base/actions/trade/swap';\nimport {\n\tTxnOrSwiftResult,\n\tWithTxnParams,\n} from '../../../base/actions/trade/openPerpOrder/types';\nimport { EnvironmentConstants } from '../../../../EnvironmentConstants';\nimport {\n\tCentralServerGetOpenPerpMarketOrderTxnParams,\n\tCentralServerGetOpenPerpNonMarketOrderTxnParams,\n} from './types';\n\n/**\n * A Drift client that fetches user data on-demand, while market data is continuously subscribed to.\n *\n * This is useful for an API server that fetches user data on-demand, and return transaction messages specific to a given user\n */\nexport class CentralServerDrift {\n\tprivate driftClient: DriftClient;\n\tprivate _perpMarketConfigs: PerpMarketConfig[];\n\tprivate spotMarketConfigs: SpotMarketConfig[];\n\t/**\n\t * The public endpoints that can be used to retrieve Drift data / interact with the Drift program.\n\t */\n\tprivate _driftEndpoints: {\n\t\tdlobServerHttpUrl: string;\n\t\tswiftServerUrl: string;\n\t};\n\n\t/**\n\t * @param solanaRpcEndpoint - The Solana RPC endpoint to use for reading RPC data.\n\t * @param driftEnv - The drift environment to use for the drift client.\n\t * @param activeTradeMarket - The active trade market to use for the drift client. This is used to subscribe to the market account, oracle data and mark price more frequently compared to the other markets.\n\t * @param additionalDriftClientConfig - Additional DriftClient config to use for the DriftClient.\n\t */\n\tconstructor(config: {\n\t\tsolanaRpcEndpoint: string;\n\t\tdriftEnv: DriftEnv;\n\t\tadditionalDriftClientConfig?: Partial<Omit<DriftClientConfig, 'env'>>;\n\t\tactiveTradeMarket?: MarketId;\n\t\tmarketsToSubscribe?: MarketId[];\n\t}) {\n\t\tconst driftEnv = config.driftEnv;\n\n\t\tconst connection = new Connection(config.solanaRpcEndpoint);\n\t\tconst driftProgramID = new PublicKey(DRIFT_PROGRAM_ID);\n\t\tconst accountLoader = new CustomizedCadenceBulkAccountLoader(\n\t\t\tconnection,\n\t\t\tDEFAULT_ACCOUNT_LOADER_COMMITMENT,\n\t\t\tDEFAULT_ACCOUNT_LOADER_POLLING_FREQUENCY_MS\n\t\t);\n\n\t\tconst wallet = COMMON_UI_UTILS.createPlaceholderIWallet(); // use random wallet to initialize a central-server instance\n\n\t\tconst driftClientConfig: DriftClientConfig = {\n\t\t\tenv: driftEnv,\n\t\t\tconnection,\n\t\t\twallet,\n\t\t\tprogramID: driftProgramID,\n\t\t\tenableMetricsEvents: false,\n\t\t\taccountSubscription: {\n\t\t\t\ttype: 'polling',\n\t\t\t\taccountLoader,\n\t\t\t},\n\t\t\tuserStats: false,\n\t\t\tincludeDelegates: false,\n\t\t\tskipLoadUsers: true,\n\t\t\tdelistedMarketSetting: DelistedMarketSetting.Unsubscribe,\n\t\t\t...config.additionalDriftClientConfig,\n\t\t};\n\t\tthis.driftClient = new DriftClient(driftClientConfig);\n\n\t\tconst txSender = new WhileValidTxSender({\n\t\t\tconnection,\n\t\t\twallet,\n\t\t\tadditionalConnections: [],\n\t\t\tadditionalTxSenderCallbacks: [],\n\t\t\ttxHandler: this.driftClient.txHandler,\n\t\t\tconfirmationStrategy: DEFAULT_TX_SENDER_CONFIRMATION_STRATEGY,\n\t\t\tretrySleep: DEFAULT_TX_SENDER_RETRY_INTERVAL,\n\t\t});\n\n\t\tthis.driftClient.txSender = txSender;\n\t\tthis._perpMarketConfigs =\n\t\t\tdriftEnv === 'devnet' ? DevnetPerpMarkets : MainnetPerpMarkets;\n\t\tthis.spotMarketConfigs =\n\t\t\tdriftEnv === 'devnet' ? DevnetSpotMarkets : MainnetSpotMarkets;\n\n\t\t// set up Drift endpoints\n\t\tconst driftDlobServerHttpUrlToUse =\n\t\t\tEnvironmentConstants.dlobServerHttpUrl[\n\t\t\t\tconfig.driftEnv === 'devnet' ? 'dev' : 'mainnet'\n\t\t\t];\n\t\tconst swiftServerUrlToUse =\n\t\t\tEnvironmentConstants.swiftServerUrl[\n\t\t\t\tconfig.driftEnv === 'devnet' ? 'staging' : 'mainnet'\n\t\t\t];\n\t\tthis._driftEndpoints = {\n\t\t\tdlobServerHttpUrl: driftDlobServerHttpUrlToUse,\n\t\t\tswiftServerUrl: swiftServerUrlToUse,\n\t\t};\n\t}\n\n\tpublic async subscribe() {\n\t\tawait this.driftClient.subscribe();\n\t}\n\n\t/**\n\t * Manages DriftClient state for transaction creation with proper setup and cleanup.\n\t * This abstraction handles:\n\t * - User creation and subscription\n\t * - Authority management\n\t * - Wallet replacement for correct transaction signing\n\t * - Cleanup and state restoration\n\t *\n\t * @param userAccountPublicKey - The user account public key\n\t * @param operation - The transaction creation operation to execute\n\t * @returns The result of the operation\n\t */\n\tprivate async driftClientContextWrapper<T>(\n\t\tuserAccountPublicKey: PublicKey,\n\t\toperation: (user: User) => Promise<T>\n\t): Promise<T> {\n\t\tconst user = new User({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuserAccountPublicKey,\n\t\t\taccountSubscription: {\n\t\t\t\ttype: 'custom',\n\t\t\t\tuserAccountSubscriber: new OneShotUserAccountSubscriber(\n\t\t\t\t\tthis.driftClient.program,\n\t\t\t\t\tuserAccountPublicKey,\n\t\t\t\t\tundefined,\n\t\t\t\t\tundefined\n\t\t\t\t),\n\t\t\t},\n\t\t});\n\n\t\t// Store original state\n\t\tconst originalWallet = this.driftClient.wallet;\n\t\tconst originalAuthority = this.driftClient.authority;\n\n\t\ttry {\n\t\t\t// Setup: Subscribe to user and configure DriftClient\n\t\t\tawait user.subscribe();\n\n\t\t\tconst authority = user.getUserAccount().authority;\n\t\t\tthis.driftClient.authority = authority;\n\n\t\t\tconst success = await this.driftClient.addUser(\n\t\t\t\tuser.getUserAccount().subAccountId,\n\t\t\t\tauthority\n\t\t\t);\n\n\t\t\tif (!success) {\n\t\t\t\tthrow new Error('Failed to add user to DriftClient');\n\t\t\t}\n\n\t\t\t// Replace wallet with user's authority to ensure correct transaction signing\n\t\t\t// This is necessary because DriftClient adds wallet.publicKey to instructions\n\t\t\tconst userWallet = {\n\t\t\t\tpublicKey: authority,\n\t\t\t\tsignTransaction: () =>\n\t\t\t\t\tPromise.reject(\n\t\t\t\t\t\t'This is a placeholder - do not sign with this wallet'\n\t\t\t\t\t),\n\t\t\t\tsignAllTransactions: () =>\n\t\t\t\t\tPromise.reject(\n\t\t\t\t\t\t'This is a placeholder - do not sign with this wallet'\n\t\t\t\t\t),\n\t\t\t};\n\n\t\t\t// Update wallet in all places that reference it\n\t\t\tthis.driftClient.wallet = userWallet;\n\t\t\t//@ts-ignore\n\t\t\tthis.driftClient.provider.wallet = userWallet;\n\t\t\tthis.driftClient.txHandler.updateWallet(userWallet);\n\n\t\t\t// Execute the operation\n\t\t\tconst result = await operation(user);\n\n\t\t\treturn result;\n\t\t} finally {\n\t\t\t// Cleanup: Always restore original state and unsubscribe\n\t\t\tthis.driftClient.wallet = originalWallet;\n\t\t\tthis.driftClient.txHandler.updateWallet(originalWallet);\n\t\t\tthis.driftClient.authority = originalAuthority;\n\n\t\t\ttry {\n\t\t\t\tawait user.unsubscribe();\n\t\t\t\tthis.driftClient.users.clear();\n\t\t\t} catch (cleanupError) {\n\t\t\t\tconsole.warn('Error during cleanup:', cleanupError);\n\t\t\t\t// Don't throw cleanup errors, but log them\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Returns a User object for a given user account public key. This fetches the user account data once.\n\t *\n\t * You may read more about the User object [here](https://github.com/drift-labs/protocol-v2/blob/master/sdk/src/user.ts)\n\t *\n\t * @param userAccountPublicKey - The user account public key\n\t */\n\tpublic async getUser(userAccountPublicKey: PublicKey): Promise<User> {\n\t\tconst oneShotUserAccountSubscriber = new OneShotUserAccountSubscriber(\n\t\t\tthis.driftClient.program,\n\t\t\tuserAccountPublicKey,\n\t\t\tundefined,\n\t\t\tundefined\n\t\t);\n\t\tconst user = new User({\n\t\t\tdriftClient: this.driftClient,\n\t\t\tuserAccountPublicKey,\n\t\t\taccountSubscription: {\n\t\t\t\ttype: 'custom',\n\t\t\t\tuserAccountSubscriber: oneShotUserAccountSubscriber,\n\t\t\t},\n\t\t});\n\t\tawait user.subscribe();\n\t\treturn user;\n\t}\n\n\tpublic async getDepositTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tamount: BN,\n\t\tspotMarketIndex: number\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst spotMarketConfig = this.spotMarketConfigs.find(\n\t\t\t\t\t(market) => market.marketIndex === spotMarketIndex\n\t\t\t\t);\n\n\t\t\t\tif (!spotMarketConfig) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Spot market config not found for index ${spotMarketIndex}`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst depositTxn = await createDepositTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tamount: BigNum.from(amount, spotMarketConfig.precisionExp),\n\t\t\t\t\tspotMarketConfig,\n\t\t\t\t});\n\n\t\t\t\treturn depositTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\tpublic async getWithdrawTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tamount: BN,\n\t\tspotMarketIndex: number,\n\t\toptions?: {\n\t\t\tisBorrow?: boolean;\n\t\t\tisMax?: boolean;\n\t\t}\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst spotMarketConfig = this.spotMarketConfigs.find(\n\t\t\t\t\t(market) => market.marketIndex === spotMarketIndex\n\t\t\t\t);\n\n\t\t\t\tif (!spotMarketConfig) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Spot market config not found for index ${spotMarketIndex}`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst withdrawTxn = await createWithdrawTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tamount: BigNum.from(amount, spotMarketConfig.precisionExp),\n\t\t\t\t\tspotMarketConfig,\n\t\t\t\t\tisBorrow: options?.isBorrow,\n\t\t\t\t\tisMax: options?.isMax,\n\t\t\t\t});\n\n\t\t\t\treturn withdrawTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\tpublic async getSettleFundingTxn(\n\t\tuserAccountPublicKey: PublicKey\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst settleFundingTxn = await createSettleFundingTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t});\n\n\t\t\t\treturn settleFundingTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\tpublic async getSettlePnlTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tmarketIndexes: number[]\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst settlePnlTxn = await createSettlePnlTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tmarketIndexes,\n\t\t\t\t});\n\n\t\t\t\treturn settlePnlTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\t// overloads for better type inference\n\tpublic async getOpenPerpMarketOrderTxn(\n\t\tparams: CentralServerGetOpenPerpMarketOrderTxnParams<true>\n\t): Promise<void>;\n\tpublic async getOpenPerpMarketOrderTxn(\n\t\tparams: CentralServerGetOpenPerpMarketOrderTxnParams<false>\n\t): Promise<Transaction | VersionedTransaction>;\n\tpublic async getOpenPerpMarketOrderTxn<T extends boolean>({\n\t\tuserAccountPublicKey,\n\t\t...rest\n\t}: CentralServerGetOpenPerpMarketOrderTxnParams<T>): Promise<\n\t\tTxnOrSwiftResult<T>\n\t> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user): Promise<TxnOrSwiftResult<T>> => {\n\t\t\t\tconst { useSwift, swiftOptions, placeAndTake, ...otherProps } = rest;\n\n\t\t\t\tif (useSwift) {\n\t\t\t\t\tconst swiftOrderResult = await createOpenPerpMarketOrder({\n\t\t\t\t\t\t...otherProps,\n\t\t\t\t\t\tuseSwift: true,\n\t\t\t\t\t\tswiftOptions: {\n\t\t\t\t\t\t\t...swiftOptions,\n\t\t\t\t\t\t\tswiftServerUrl: this._driftEndpoints.swiftServerUrl,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdlobServerHttpUrl: this._driftEndpoints.dlobServerHttpUrl,\n\t\t\t\t\t});\n\t\t\t\t\treturn swiftOrderResult as TxnOrSwiftResult<T>;\n\t\t\t\t} else {\n\t\t\t\t\tconst openPerpMarketOrderTxn = await createOpenPerpMarketOrder({\n\t\t\t\t\t\t...otherProps,\n\t\t\t\t\t\tplaceAndTake,\n\t\t\t\t\t\tuseSwift: false,\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdlobServerHttpUrl: this._driftEndpoints.dlobServerHttpUrl,\n\t\t\t\t\t});\n\t\t\t\t\treturn openPerpMarketOrderTxn as TxnOrSwiftResult<T>;\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a perp non-market order with amount and asset type\n\t */\n\tpublic async getOpenPerpNonMarketOrderTxn(\n\t\tparams: CentralServerGetOpenPerpNonMarketOrderTxnParams<true>\n\t): Promise<void>;\n\tpublic async getOpenPerpNonMarketOrderTxn(\n\t\tparams: CentralServerGetOpenPerpNonMarketOrderTxnParams<false>\n\t): Promise<Transaction | VersionedTransaction>;\n\tpublic async getOpenPerpNonMarketOrderTxn<T extends boolean>({\n\t\tuserAccountPublicKey,\n\t\t...rest\n\t}: WithTxnParams<\n\t\tOmit<OpenPerpNonMarketOrderParams<T>, 'driftClient' | 'user'>\n\t> & {\n\t\tuserAccountPublicKey: PublicKey;\n\t}): Promise<TxnOrSwiftResult<T>> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst { useSwift, swiftOptions, ...otherProps } = rest;\n\n\t\t\t\tif (useSwift) {\n\t\t\t\t\tconst swiftOrderResult = await createOpenPerpNonMarketOrder({\n\t\t\t\t\t\t...otherProps,\n\t\t\t\t\t\tuseSwift: true,\n\t\t\t\t\t\tswiftOptions: {\n\t\t\t\t\t\t\t...swiftOptions,\n\t\t\t\t\t\t\tswiftServerUrl: this._driftEndpoints.swiftServerUrl,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdlobServerHttpUrl: this._driftEndpoints.dlobServerHttpUrl,\n\t\t\t\t\t});\n\t\t\t\t\treturn swiftOrderResult as TxnOrSwiftResult<T>;\n\t\t\t\t} else {\n\t\t\t\t\tconst openPerpNonMarketOrderTxn = await createOpenPerpNonMarketOrder({\n\t\t\t\t\t\t...otherProps,\n\t\t\t\t\t\tuseSwift: false,\n\t\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\t\tuser,\n\t\t\t\t\t\tdlobServerHttpUrl: this._driftEndpoints.dlobServerHttpUrl,\n\t\t\t\t\t});\n\t\t\t\t\treturn openPerpNonMarketOrderTxn as TxnOrSwiftResult<T>;\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a transaction to edit an existing order\n\t */\n\tpublic async getEditOrderTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\torderId: number,\n\t\teditOrderParams: {\n\t\t\tnewDirection?: PositionDirection;\n\t\t\tnewBaseAmount?: BN;\n\t\t\tnewLimitPrice?: BN;\n\t\t\tnewOraclePriceOffset?: number;\n\t\t\tnewTriggerPrice?: BN;\n\t\t\tnewTriggerCondition?: OrderTriggerCondition;\n\t\t\tauctionDuration?: number;\n\t\t\tauctionStartPrice?: BN;\n\t\t\tauctionEndPrice?: BN;\n\t\t\treduceOnly?: boolean;\n\t\t\tpostOnly?: boolean;\n\t\t\tbitFlags?: number;\n\t\t\tmaxTs?: BN;\n\t\t\tpolicy?: number;\n\t\t}\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst editOrderTxn = await createEditOrderTxn(\n\t\t\t\t\tthis.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\torderId,\n\t\t\t\t\teditOrderParams\n\t\t\t\t);\n\n\t\t\t\treturn editOrderTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a transaction to cancel specific orders by their IDs\n\t */\n\tpublic async getCancelOrdersTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\torderIds: number[]\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst cancelOrdersTxn = await createCancelOrdersTxn(\n\t\t\t\t\tthis.driftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\torderIds\n\t\t\t\t);\n\n\t\t\t\treturn cancelOrdersTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a transaction to cancel all orders for a user\n\t */\n\tpublic async getCancelAllOrdersTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tmarketType?: MarketType,\n\t\tmarketIndex?: number,\n\t\tdirection?: PositionDirection\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst ix = await this.driftClient.getCancelOrdersIx(\n\t\t\t\t\tmarketType ?? null,\n\t\t\t\t\tmarketIndex ?? null,\n\t\t\t\t\tdirection ?? null,\n\t\t\t\t\tuser.getUserAccount().subAccountId\n\t\t\t\t);\n\n\t\t\t\tconst cancelAllOrdersTxn = await this.driftClient.buildTransaction(ix);\n\n\t\t\t\treturn cancelAllOrdersTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\t/**\n\t * Create a swap transaction between two spot markets using Jupiter\n\t */\n\tpublic async getSwapTxn(\n\t\tuserAccountPublicKey: PublicKey,\n\t\tfromMarketIndex: number,\n\t\ttoMarketIndex: number,\n\t\tamount: BN,\n\t\toptions?: {\n\t\t\tslippageBps?: number;\n\t\t\tswapMode?: SwapMode;\n\t\t\tonlyDirectRoutes?: boolean;\n\t\t\tquote?: QuoteResponse;\n\t\t}\n\t): Promise<VersionedTransaction | Transaction> {\n\t\treturn this.driftClientContextWrapper(\n\t\t\tuserAccountPublicKey,\n\t\t\tasync (user) => {\n\t\t\t\tconst fromSpotMarketConfig = this.spotMarketConfigs.find(\n\t\t\t\t\t(market) => market.marketIndex === fromMarketIndex\n\t\t\t\t);\n\t\t\t\tconst toSpotMarketConfig = this.spotMarketConfigs.find(\n\t\t\t\t\t(market) => market.marketIndex === toMarketIndex\n\t\t\t\t);\n\n\t\t\t\tif (!fromSpotMarketConfig) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`From spot market config not found for index ${fromMarketIndex}`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tif (!toSpotMarketConfig) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`To spot market config not found for index ${toMarketIndex}`\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Initialize Jupiter client\n\t\t\t\tconst jupiterClient = new JupiterClient({\n\t\t\t\t\tconnection: this.driftClient.connection,\n\t\t\t\t});\n\n\t\t\t\t// Get quote if not provided\n\t\t\t\tlet quote = options?.quote;\n\t\t\t\tif (!quote) {\n\t\t\t\t\tquote = await jupiterClient.getQuote({\n\t\t\t\t\t\tinputMint: fromSpotMarketConfig.mint,\n\t\t\t\t\t\toutputMint: toSpotMarketConfig.mint,\n\t\t\t\t\t\tamount,\n\t\t\t\t\t\tslippageBps: options?.slippageBps ?? 10, // Default 0.1%\n\t\t\t\t\t\tswapMode: options?.swapMode ?? 'ExactIn',\n\t\t\t\t\t\tonlyDirectRoutes: options?.onlyDirectRoutes ?? false,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tconst swapTxn = await createSwapTxn({\n\t\t\t\t\tdriftClient: this.driftClient,\n\t\t\t\t\tjupiterClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tswapFromMarketIndex: fromMarketIndex,\n\t\t\t\t\tswapToMarketIndex: toMarketIndex,\n\t\t\t\t\tamount,\n\t\t\t\t\tquote,\n\t\t\t\t\ttxParams: {\n\t\t\t\t\t\tuseSimulatedComputeUnits: true,\n\t\t\t\t\t\tcomputeUnitsBufferMultiplier: 1.5,\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\treturn swapTxn;\n\t\t\t}\n\t\t);\n\t}\n\n\tpublic async sendSignedTransaction(tx: VersionedTransaction | Transaction) {\n\t\treturn this.driftClient.sendTransaction(tx, undefined, undefined, true);\n\t}\n}\n"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { SwiftOrderOptions } from '../../../base/actions/trade/openPerpOrder/openSwiftOrder';
|
|
2
|
+
import { WithTxnParams } from '../../../base/actions/trade/openPerpOrder/types';
|
|
3
|
+
import { OpenPerpMarketOrderParams } from '../../../base/actions/trade/openPerpOrder/openPerpMarketOrder';
|
|
4
|
+
import { OpenPerpNonMarketOrderParams } from '../../../base/actions/trade/openPerpOrder/openPerpNonMarketOrder';
|
|
5
|
+
import { PublicKey } from '@solana/web3.js';
|
|
6
|
+
export type CentralServerSwiftOrderOptions = Omit<SwiftOrderOptions, 'swiftServerUrl'>;
|
|
7
|
+
export type CentralServerGetOpenPerpMarketOrderTxnParams<T extends boolean = boolean> = WithTxnParams<Omit<OpenPerpMarketOrderParams<T, CentralServerSwiftOrderOptions>, 'driftClient' | 'user' | 'dlobServerHttpUrl'>> & {
|
|
8
|
+
userAccountPublicKey: PublicKey;
|
|
9
|
+
};
|
|
10
|
+
export type CentralServerGetOpenPerpNonMarketOrderTxnParams<T extends boolean = boolean> = WithTxnParams<Omit<OpenPerpNonMarketOrderParams<T, CentralServerSwiftOrderOptions>, 'driftClient' | 'user' | 'dlobServerHttpUrl'>> & {
|
|
11
|
+
userAccountPublicKey: PublicKey;
|
|
12
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/drift/Drift/clients/CentralServerDrift/types.ts"],"names":[],"mappings":"","sourcesContent":["import { SwiftOrderOptions } from '../../../base/actions/trade/openPerpOrder/openSwiftOrder';\nimport { WithTxnParams } from '../../../base/actions/trade/openPerpOrder/types';\nimport { OpenPerpMarketOrderParams } from '../../../base/actions/trade/openPerpOrder/openPerpMarketOrder';\nimport { OpenPerpNonMarketOrderParams } from '../../../base/actions/trade/openPerpOrder/openPerpNonMarketOrder';\nimport { PublicKey } from '@solana/web3.js';\n\nexport type CentralServerSwiftOrderOptions = Omit<\n\tSwiftOrderOptions,\n\t'swiftServerUrl'\n>;\n\nexport type CentralServerGetOpenPerpMarketOrderTxnParams<\n\tT extends boolean = boolean\n> = WithTxnParams<\n\tOmit<\n\t\tOpenPerpMarketOrderParams<T, CentralServerSwiftOrderOptions>,\n\t\t'driftClient' | 'user' | 'dlobServerHttpUrl'\n\t>\n> & {\n\tuserAccountPublicKey: PublicKey;\n};\n\nexport type CentralServerGetOpenPerpNonMarketOrderTxnParams<\n\tT extends boolean = boolean\n> = WithTxnParams<\n\tOmit<\n\t\tOpenPerpNonMarketOrderParams<T, CentralServerSwiftOrderOptions>,\n\t\t'driftClient' | 'user' | 'dlobServerHttpUrl'\n\t>\n> & {\n\tuserAccountPublicKey: PublicKey;\n};\n"]}
|
|
@@ -97,7 +97,7 @@ async function fetchAuctionOrderParamsFromDlob({ marketIndex, marketType = sdk_1
|
|
|
97
97
|
? amount
|
|
98
98
|
: (() => {
|
|
99
99
|
const oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;
|
|
100
|
-
return amount.mul(
|
|
100
|
+
return amount.mul(sdk_1.BASE_PRECISION).div(oraclePrice);
|
|
101
101
|
})();
|
|
102
102
|
// Build URL parameters for server request
|
|
103
103
|
const urlParamsObject = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../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AiB,CAAC;YACzD,WAAW,EAAE,IAAA,gBAAU,EAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAC;SACnE,CAAC,CAAC,CAAC;QAEJ,OAAO,YAAY,CAAC;IACrB,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACZ,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACjB,OAAO,EAAE,CAAC;IACX,CAAC;AACF,CAAC;AA3CD,wCA2CC","sourcesContent":["import {\n\tDriftClient,\n\tUser,\n\tBN,\n\tPositionDirection,\n\tOptionalOrderParams,\n\tMarketType,\n\tUserAccount,\n\tPublicKey,\n\tdecodeUser,\n\tDefaultOrderParams,\n\tPRICE_PRECISION,\n} from '@drift-labs/sdk';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport {\n\tmapAuctionParamsResponse,\n\tServerAuctionParamsResponse,\n\tMappedAuctionParams,\n} from '../../../../../utils/auctionParamsResponseMapper';\nimport { encodeQueryParams } from '../../../../../../utils/fetch';\nimport { MarketId, TradeOffsetPrice } from '../../../../../../types';\nimport {\n\tconvertToL2OrderBook,\n\tdeserializeL2Response,\n\tL2WithOracleAndMarketData,\n\tRawL2Output,\n\tcalculateDynamicSlippageFromL2,\n\tDynamicSlippageConfig,\n} from '../../../../../../utils/orderbook';\nimport { PollingSequenceGuard } from '../../../../../../utils/pollingSequenceGuard';\nimport { calculatePriceImpactFromL2 } from '../../../../../../utils/priceImpact';\nimport { COMMON_UI_UTILS } from '../../../../../../common-ui-utils';\nimport invariant from 'tiny-invariant';\n\nexport interface OptionalAuctionParamsRequestInputs {\n\t// Optional parameters that can override defaults or provide additional configuration\n\tmaxLeverageSelected?: boolean;\n\tmaxLeverageOrderSize?: BN;\n\treduceOnly?: boolean;\n\tauctionDuration?: number;\n\tauctionStartPriceOffset?: number;\n\tauctionEndPriceOffset?: number;\n\tauctionStartPriceOffsetFrom?: TradeOffsetPrice;\n\tauctionEndPriceOffsetFrom?: TradeOffsetPrice;\n\tslippageTolerance?: number | 'dynamic';\n\tauctionPriceCaps?: {\n\t\tmin: BN;\n\t\tmax: BN;\n\t};\n\tisOracleOrder?: boolean;\n\tadditionalEndPriceBuffer?: BN;\n\tforceUpToSlippage?: boolean;\n\torderType?: 'market' | 'oracle';\n}\n\ninterface RegularOrderParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tassetType: 'base' | 'quote';\n\tmarketType?: MarketType;\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\tamount: BN;\n\toptionalAuctionParamsInputs?: OptionalAuctionParamsRequestInputs;\n\tdlobServerHttpUrl: string;\n\tdynamicSlippageConfig?: DynamicSlippageConfig;\n}\n\nexport interface BulkL2FetchingQueryParams {\n\tmarketIndex: number;\n\tmarketType: string;\n\tdepth: number;\n\tincludeVamm: boolean;\n\tincludePhoenix: boolean;\n\tincludeOpenbook: boolean;\n\tincludeSerum: boolean;\n\tincludeOracle: boolean;\n\tincludeIndicative: boolean;\n}\n\nexport interface BulkL2FetchingParams {\n\tmarkets: BulkL2FetchingQueryParams[];\n\tgrouping?: number;\n}\n\nconst BACKGROUND_L2_POLLING_KEY = Symbol('BACKGROUND_L2_POLLING_KEY');\n\n/**\n * Fetches the L2 data for the given markets and their depth\n */\nexport function fetchBulkMarketsDlobL2Data(\n\tdlobServerHttpUrl: string,\n\tmarkets: {\n\t\tmarketId: MarketId;\n\t\tdepth: number;\n\t}[],\n\tgroupingSize?: number,\n\texcludeIndicativeLiquidity = false\n): Promise<L2WithOracleAndMarketData[]> {\n\tconst params: BulkL2FetchingParams = {\n\t\tmarkets: markets.map((m) => ({\n\t\t\tmarketIndex: m.marketId.marketIndex,\n\t\t\tmarketType: m.marketId.marketTypeStr,\n\t\t\tdepth: m.depth,\n\t\t\tincludeVamm: m.marketId.isPerp,\n\t\t\tincludePhoenix: m.marketId.isSpot,\n\t\t\tincludeSerum: m.marketId.isSpot,\n\t\t\tincludeOpenbook: m.marketId.isSpot,\n\t\t\tincludeOracle: true,\n\t\t\tincludeIndicative: !excludeIndicativeLiquidity,\n\t\t})),\n\t\tgrouping: groupingSize,\n\t};\n\n\tconst queryParamsMap: {\n\t\t[K in keyof BulkL2FetchingQueryParams]: string;\n\t} & {\n\t\tgrouping?: string;\n\t} = {\n\t\tmarketType: params.markets.map((market) => market.marketType).join(','),\n\t\tmarketIndex: params.markets.map((market) => market.marketIndex).join(','),\n\t\tdepth: params.markets.map((market) => market.depth).join(','),\n\t\tincludeVamm: params.markets.map((market) => market.includeVamm).join(','),\n\t\tincludePhoenix: params.markets\n\t\t\t.map((market) => market.includePhoenix)\n\t\t\t.join(','),\n\t\tincludeOpenbook: params.markets\n\t\t\t.map((market) => market.includeOpenbook)\n\t\t\t.join(','),\n\t\tincludeSerum: params.markets.map((market) => market.includeSerum).join(','),\n\t\tgrouping: params.grouping\n\t\t\t? params.markets.map(() => params.grouping).join(',')\n\t\t\t: undefined,\n\t\tincludeOracle: params.markets\n\t\t\t.map((market) => market.includeOracle)\n\t\t\t.join(','),\n\t\tincludeIndicative: params.markets\n\t\t\t.map((market) => market.includeIndicative)\n\t\t\t.join(','),\n\t};\n\n\tconst queryParams = encodeQueryParams(queryParamsMap);\n\n\t// Use cached endpoint when exclusively fetching background markets\n\tconst useCachedEndpoint = !params.markets.some(\n\t\t(market) => market.depth !== 1\n\t);\n\n\tconst endpoint = useCachedEndpoint\n\t\t? `${dlobServerHttpUrl}/batchL2Cache`\n\t\t: `${dlobServerHttpUrl}/batchL2`;\n\n\treturn new Promise<L2WithOracleAndMarketData[]>((resolve, reject) => {\n\t\tPollingSequenceGuard.fetch(BACKGROUND_L2_POLLING_KEY, () => {\n\t\t\treturn fetch(`${endpoint}?${queryParams}`);\n\t\t})\n\t\t\t.then(async (response) => {\n\t\t\t\tconst responseData = await response.json();\n\t\t\t\tconst resultsArray = responseData.l2s as RawL2Output[];\n\t\t\t\tconst deserializedL2 = resultsArray.map(deserializeL2Response);\n\t\t\t\tresolve(deserializedL2);\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\treject(error);\n\t\t\t});\n\t});\n}\n\nexport async function fetchAuctionOrderParams(params: RegularOrderParams) {\n\ttry {\n\t\treturn await fetchAuctionOrderParamsFromDlob(params);\n\t} catch (error) {\n\t\tconsole.error(error);\n\t\tconsole.log('Falling back to L2 data');\n\t\treturn await fetchAuctionOrderParamsFromL2(params);\n\t}\n}\n\n/**\n * Fetches auction order parameters from the auction params endpoint\n */\nexport async function fetchAuctionOrderParamsFromDlob({\n\tmarketIndex,\n\tmarketType = MarketType.PERP,\n\tdirection,\n\tamount,\n\tdlobServerHttpUrl,\n\tassetType,\n\tdriftClient,\n\toptionalAuctionParamsInputs = {},\n}: RegularOrderParams): Promise<OptionalOrderParams> {\n\tconst baseAmount =\n\t\tassetType === 'base'\n\t\t\t? amount\n\t\t\t: (() => {\n\t\t\t\t\tconst oraclePrice =\n\t\t\t\t\t\tdriftClient.getOracleDataForPerpMarket(marketIndex).price;\n\t\t\t\t\treturn amount.mul(oraclePrice).div(PRICE_PRECISION);\n\t\t\t })();\n\n\t// Build URL parameters for server request\n\tconst urlParamsObject: Record<string, string> = {\n\t\t// Required fields\n\t\tassetType: 'base',\n\t\tmarketType: ENUM_UTILS.toStr(marketType),\n\t\tmarketIndex: marketIndex.toString(),\n\t\tdirection: ENUM_UTILS.toStr(direction),\n\t\tamount: baseAmount.toString(),\n\t};\n\n\t// Add defined optional parameters\n\tObject.entries(optionalAuctionParamsInputs).forEach(([key, value]) => {\n\t\tif (value !== undefined) {\n\t\t\turlParamsObject[key] = value.toString();\n\t\t}\n\t});\n\n\tconst urlParams = encodeQueryParams(urlParamsObject);\n\n\t// Get order params from server\n\tconst requestUrl = `${dlobServerHttpUrl}/auctionParams?${urlParams.toString()}`;\n\tconst response = await fetch(requestUrl);\n\n\tif (!response.ok) {\n\t\tthrow new Error(\n\t\t\t`Server responded with ${response.status}: ${response.statusText}`\n\t\t);\n\t}\n\n\tconst serverResponse: ServerAuctionParamsResponse = await response.json();\n\tconst serverAuctionParams = serverResponse?.data?.params;\n\tinvariant(serverAuctionParams, 'Server auction params are required');\n\tconst mappedParams: MappedAuctionParams =\n\t\tmapAuctionParamsResponse(serverAuctionParams);\n\n\t// Convert MappedAuctionParams to OptionalOrderParams\n\treturn {\n\t\torderType: mappedParams.orderType,\n\t\tmarketType: mappedParams.marketType,\n\t\tuserOrderId: mappedParams.userOrderId,\n\t\tdirection: mappedParams.direction,\n\t\tbaseAssetAmount: mappedParams.baseAssetAmount,\n\t\tmarketIndex: mappedParams.marketIndex,\n\t\treduceOnly: mappedParams.reduceOnly,\n\t\tpostOnly: mappedParams.postOnly ?? DefaultOrderParams.postOnly,\n\t\ttriggerPrice: mappedParams.triggerPrice || null,\n\t\ttriggerCondition:\n\t\t\tmappedParams.triggerCondition ?? DefaultOrderParams.triggerCondition,\n\t\toraclePriceOffset: mappedParams.oraclePriceOffset?.toNumber() || null,\n\t\tauctionDuration: mappedParams.auctionDuration || null,\n\t\tmaxTs: mappedParams.maxTs,\n\t\tauctionStartPrice: mappedParams.auctionStartPrice || null,\n\t\tauctionEndPrice: mappedParams.auctionEndPrice || null,\n\t\t// no price, because market orders don't need a price\n\t};\n}\n\nconst DEFAULT_L2_DEPTH_FOR_AUCTION_ORDER_PARAMS = 100;\n\n/**\n * Fetches auction order parameters from the L2 data\n */\nexport async function fetchAuctionOrderParamsFromL2({\n\tdlobServerHttpUrl,\n\tmarketIndex,\n\tmarketType,\n\tdirection,\n\tassetType,\n\tamount,\n\toptionalAuctionParamsInputs,\n\tdriftClient,\n\tdynamicSlippageConfig,\n}: RegularOrderParams): Promise<OptionalOrderParams> {\n\tconst marketId = new MarketId(marketIndex, marketType);\n\tconst baseAmount =\n\t\tassetType === 'base'\n\t\t\t? amount\n\t\t\t: (() => {\n\t\t\t\t\tconst oraclePrice =\n\t\t\t\t\t\tdriftClient.getOracleDataForPerpMarket(marketIndex).price;\n\t\t\t\t\treturn amount.mul(oraclePrice).div(PRICE_PRECISION);\n\t\t\t })();\n\n\tconst l2DataResponse = await fetchBulkMarketsDlobL2Data(dlobServerHttpUrl, [\n\t\t{\n\t\t\tmarketId,\n\t\t\tdepth: DEFAULT_L2_DEPTH_FOR_AUCTION_ORDER_PARAMS,\n\t\t},\n\t]);\n\tconst oraclePriceData = l2DataResponse[0].oracleData;\n\tconst oraclePriceBn = oraclePriceData?.price;\n\tconst markPriceBn = l2DataResponse[0].markPrice;\n\tconst l2Data = convertToL2OrderBook(l2DataResponse);\n\n\tconst priceImpactData = calculatePriceImpactFromL2(\n\t\tmarketId,\n\t\tdirection,\n\t\tbaseAmount,\n\t\tl2Data,\n\t\toraclePriceBn\n\t);\n\n\tconst startPrices = COMMON_UI_UTILS.getPriceObject({\n\t\toraclePrice: oraclePriceBn,\n\t\tbestOffer: priceImpactData.bestPrice,\n\t\tentryPrice: priceImpactData.entryPrice,\n\t\tworstPrice: priceImpactData.worstPrice,\n\t\tmarkPrice: markPriceBn,\n\t\tdirection: direction,\n\t});\n\tconst slippageToleranceInput = optionalAuctionParamsInputs.slippageTolerance;\n\tconst derivedSlippage =\n\t\tslippageToleranceInput === 'dynamic'\n\t\t\t? calculateDynamicSlippageFromL2({\n\t\t\t\t\tl2Data,\n\t\t\t\t\tmarketId,\n\t\t\t\t\tstartPrice:\n\t\t\t\t\t\tstartPrices[\n\t\t\t\t\t\t\toptionalAuctionParamsInputs.auctionStartPriceOffsetFrom as keyof typeof startPrices\n\t\t\t\t\t\t],\n\t\t\t\t\tworstPrice: priceImpactData.worstPrice,\n\t\t\t\t\toraclePrice: oraclePriceBn,\n\t\t\t\t\tdynamicSlippageConfig,\n\t\t\t })\n\t\t\t: typeof slippageToleranceInput === 'number'\n\t\t\t? slippageToleranceInput\n\t\t\t: 0.005;\n\n\tconst auctionOrderParams = COMMON_UI_UTILS.deriveMarketOrderParams({\n\t\tmarketType: marketType,\n\t\tmarketIndex: marketIndex,\n\t\tdirection: direction,\n\t\tmaxLeverageSelected: optionalAuctionParamsInputs.maxLeverageSelected,\n\t\tmaxLeverageOrderSize: optionalAuctionParamsInputs.maxLeverageOrderSize,\n\t\tbaseAmount: baseAmount,\n\t\treduceOnly: optionalAuctionParamsInputs.reduceOnly,\n\t\tallowInfSlippage: false,\n\t\toraclePrice: oraclePriceBn,\n\t\tbestPrice: priceImpactData.bestPrice,\n\t\tentryPrice: priceImpactData.entryPrice,\n\t\tworstPrice: priceImpactData.worstPrice,\n\t\tmarkPrice: markPriceBn,\n\t\tauctionDuration: optionalAuctionParamsInputs.auctionDuration,\n\t\tauctionStartPriceOffset:\n\t\t\toptionalAuctionParamsInputs.auctionStartPriceOffset,\n\t\tauctionEndPriceOffset: optionalAuctionParamsInputs.auctionEndPriceOffset,\n\t\tauctionStartPriceOffsetFrom:\n\t\t\toptionalAuctionParamsInputs.auctionStartPriceOffsetFrom,\n\t\tauctionEndPriceOffsetFrom:\n\t\t\toptionalAuctionParamsInputs.auctionEndPriceOffsetFrom,\n\t\tslippageTolerance: derivedSlippage,\n\t\tisOracleOrder: optionalAuctionParamsInputs.isOracleOrder,\n\t\tadditionalEndPriceBuffer:\n\t\t\toptionalAuctionParamsInputs.additionalEndPriceBuffer,\n\t\tforceUpToSlippage: optionalAuctionParamsInputs.forceUpToSlippage,\n\t});\n\n\tif (!auctionOrderParams) {\n\t\tthrow new Error('Failed to derive auction params from L2');\n\t}\n\n\treturn auctionOrderParams;\n}\n\ntype FetchTopMakersParams = {\n\tdlobServerHttpUrl: string;\n\tmarketIndex: number;\n\tmarketType: MarketType;\n\tside: 'bid' | 'ask';\n\tlimit: number;\n};\n\n/**\n * Fetches the top makers information, for use as inputs in placeAndTake market orders.\n * The side of the request should be opposite of the side of the placeAndTake market order.\n */\nexport async function fetchTopMakers(params: FetchTopMakersParams): Promise<\n\t{\n\t\tuserAccountPubKey: PublicKey;\n\t\tuserAccount: UserAccount;\n\t}[]\n> {\n\ttry {\n\t\tconst { dlobServerHttpUrl, marketIndex, marketType, side, limit } = params;\n\n\t\tconst urlParams = encodeQueryParams({\n\t\t\tmarketIndex: marketIndex.toString(),\n\t\t\tmarketType: ENUM_UTILS.toStr(marketType),\n\t\t\tside,\n\t\t\tlimit: limit.toString(),\n\t\t\tincludeAccounts: 'true',\n\t\t});\n\n\t\tconst requestUrl = `${dlobServerHttpUrl}/topMakers?${urlParams}`;\n\t\tconst response = await fetch(requestUrl);\n\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(\n\t\t\t\t`Server responded with ${response.status}: ${response.statusText}`\n\t\t\t);\n\t\t}\n\n\t\tconst serverResponse: {\n\t\t\tuserAccountPubKey: string;\n\t\t\taccountBase64: string;\n\t\t}[] = await response.json();\n\t\tconst mappedParams: {\n\t\t\tuserAccountPubKey: PublicKey;\n\t\t\tuserAccount: UserAccount;\n\t\t}[] = serverResponse.map((value) => ({\n\t\t\tuserAccountPubKey: new PublicKey(value.userAccountPubKey),\n\t\t\tuserAccount: decodeUser(Buffer.from(value.accountBase64, 'base64')),\n\t\t}));\n\n\t\treturn mappedParams;\n\t} catch (e) {\n\t\tconsole.error(e);\n\t\treturn [];\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/dlobServer/index.ts"],"names":[],"mappings":";;;;;;AAAA,yCAayB;AACzB,mDAAqD;AACrD,kGAI0D;AAC1D,yDAAkE;AAClE,mDAAqE;AACrE,iEAO2C;AAC3C,uFAAoF;AACpF,qEAAiF;AACjF,uEAAoE;AACpE,oEAAuC;AAqDvC,MAAM,yBAAyB,GAAG,MAAM,CAAC,2BAA2B,CAAC,CAAC;AAEtE;;GAEG;AACH,SAAgB,0BAA0B,CACzC,iBAAyB,EACzB,OAGG,EACH,YAAqB,EACrB,0BAA0B,GAAG,KAAK;IAElC,MAAM,MAAM,GAAyB;QACpC,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;YAC5B,WAAW,E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n} from '@drift-labs/sdk';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport {\n\tmapAuctionParamsResponse,\n\tServerAuctionParamsResponse,\n\tMappedAuctionParams,\n} from '../../../../../utils/auctionParamsResponseMapper';\nimport { encodeQueryParams } from '../../../../../../utils/fetch';\nimport { MarketId, TradeOffsetPrice } from '../../../../../../types';\nimport {\n\tconvertToL2OrderBook,\n\tdeserializeL2Response,\n\tL2WithOracleAndMarketData,\n\tRawL2Output,\n\tcalculateDynamicSlippageFromL2,\n\tDynamicSlippageConfig,\n} from '../../../../../../utils/orderbook';\nimport { PollingSequenceGuard } from '../../../../../../utils/pollingSequenceGuard';\nimport { calculatePriceImpactFromL2 } from '../../../../../../utils/priceImpact';\nimport { COMMON_UI_UTILS } from '../../../../../../common-ui-utils';\nimport invariant from 'tiny-invariant';\n\nexport interface OptionalAuctionParamsRequestInputs {\n\t// Optional parameters that can override defaults or provide additional configuration\n\tmaxLeverageSelected?: boolean;\n\tmaxLeverageOrderSize?: BN;\n\treduceOnly?: boolean;\n\tauctionDuration?: number;\n\tauctionStartPriceOffset?: number;\n\tauctionEndPriceOffset?: number;\n\tauctionStartPriceOffsetFrom?: TradeOffsetPrice;\n\tauctionEndPriceOffsetFrom?: TradeOffsetPrice;\n\tslippageTolerance?: number | 'dynamic';\n\tauctionPriceCaps?: {\n\t\tmin: BN;\n\t\tmax: BN;\n\t};\n\tisOracleOrder?: boolean;\n\tadditionalEndPriceBuffer?: BN;\n\tforceUpToSlippage?: boolean;\n\torderType?: 'market' | 'oracle';\n}\n\ninterface RegularOrderParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tassetType: 'base' | 'quote';\n\tmarketType?: MarketType;\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\tamount: BN;\n\toptionalAuctionParamsInputs?: OptionalAuctionParamsRequestInputs;\n\tdlobServerHttpUrl: string;\n\tdynamicSlippageConfig?: DynamicSlippageConfig;\n}\n\nexport interface BulkL2FetchingQueryParams {\n\tmarketIndex: number;\n\tmarketType: string;\n\tdepth: number;\n\tincludeVamm: boolean;\n\tincludePhoenix: boolean;\n\tincludeOpenbook: boolean;\n\tincludeSerum: boolean;\n\tincludeOracle: boolean;\n\tincludeIndicative: boolean;\n}\n\nexport interface BulkL2FetchingParams {\n\tmarkets: BulkL2FetchingQueryParams[];\n\tgrouping?: number;\n}\n\nconst BACKGROUND_L2_POLLING_KEY = Symbol('BACKGROUND_L2_POLLING_KEY');\n\n/**\n * Fetches the L2 data for the given markets and their depth\n */\nexport function fetchBulkMarketsDlobL2Data(\n\tdlobServerHttpUrl: string,\n\tmarkets: {\n\t\tmarketId: MarketId;\n\t\tdepth: number;\n\t}[],\n\tgroupingSize?: number,\n\texcludeIndicativeLiquidity = false\n): Promise<L2WithOracleAndMarketData[]> {\n\tconst params: BulkL2FetchingParams = {\n\t\tmarkets: markets.map((m) => ({\n\t\t\tmarketIndex: m.marketId.marketIndex,\n\t\t\tmarketType: m.marketId.marketTypeStr,\n\t\t\tdepth: m.depth,\n\t\t\tincludeVamm: m.marketId.isPerp,\n\t\t\tincludePhoenix: m.marketId.isSpot,\n\t\t\tincludeSerum: m.marketId.isSpot,\n\t\t\tincludeOpenbook: m.marketId.isSpot,\n\t\t\tincludeOracle: true,\n\t\t\tincludeIndicative: !excludeIndicativeLiquidity,\n\t\t})),\n\t\tgrouping: groupingSize,\n\t};\n\n\tconst queryParamsMap: {\n\t\t[K in keyof BulkL2FetchingQueryParams]: string;\n\t} & {\n\t\tgrouping?: string;\n\t} = {\n\t\tmarketType: params.markets.map((market) => market.marketType).join(','),\n\t\tmarketIndex: params.markets.map((market) => market.marketIndex).join(','),\n\t\tdepth: params.markets.map((market) => market.depth).join(','),\n\t\tincludeVamm: params.markets.map((market) => market.includeVamm).join(','),\n\t\tincludePhoenix: params.markets\n\t\t\t.map((market) => market.includePhoenix)\n\t\t\t.join(','),\n\t\tincludeOpenbook: params.markets\n\t\t\t.map((market) => market.includeOpenbook)\n\t\t\t.join(','),\n\t\tincludeSerum: params.markets.map((market) => market.includeSerum).join(','),\n\t\tgrouping: params.grouping\n\t\t\t? params.markets.map(() => params.grouping).join(',')\n\t\t\t: undefined,\n\t\tincludeOracle: params.markets\n\t\t\t.map((market) => market.includeOracle)\n\t\t\t.join(','),\n\t\tincludeIndicative: params.markets\n\t\t\t.map((market) => market.includeIndicative)\n\t\t\t.join(','),\n\t};\n\n\tconst queryParams = encodeQueryParams(queryParamsMap);\n\n\t// Use cached endpoint when exclusively fetching background markets\n\tconst useCachedEndpoint = !params.markets.some(\n\t\t(market) => market.depth !== 1\n\t);\n\n\tconst endpoint = useCachedEndpoint\n\t\t? `${dlobServerHttpUrl}/batchL2Cache`\n\t\t: `${dlobServerHttpUrl}/batchL2`;\n\n\treturn new Promise<L2WithOracleAndMarketData[]>((resolve, reject) => {\n\t\tPollingSequenceGuard.fetch(BACKGROUND_L2_POLLING_KEY, () => {\n\t\t\treturn fetch(`${endpoint}?${queryParams}`);\n\t\t})\n\t\t\t.then(async (response) => {\n\t\t\t\tconst responseData = await response.json();\n\t\t\t\tconst resultsArray = responseData.l2s as RawL2Output[];\n\t\t\t\tconst deserializedL2 = resultsArray.map(deserializeL2Response);\n\t\t\t\tresolve(deserializedL2);\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\treject(error);\n\t\t\t});\n\t});\n}\n\nexport async function fetchAuctionOrderParams(params: RegularOrderParams) {\n\ttry {\n\t\treturn await fetchAuctionOrderParamsFromDlob(params);\n\t} catch (error) {\n\t\tconsole.error(error);\n\t\tconsole.log('Falling back to L2 data');\n\t\treturn await fetchAuctionOrderParamsFromL2(params);\n\t}\n}\n\n/**\n * Fetches auction order parameters from the auction params endpoint\n */\nexport async function fetchAuctionOrderParamsFromDlob({\n\tmarketIndex,\n\tmarketType = MarketType.PERP,\n\tdirection,\n\tamount,\n\tdlobServerHttpUrl,\n\tassetType,\n\tdriftClient,\n\toptionalAuctionParamsInputs = {},\n}: RegularOrderParams): Promise<OptionalOrderParams> {\n\tconst baseAmount =\n\t\tassetType === 'base'\n\t\t\t? amount\n\t\t\t: (() => {\n\t\t\t\t\tconst oraclePrice =\n\t\t\t\t\t\tdriftClient.getOracleDataForPerpMarket(marketIndex).price;\n\t\t\t\t\treturn amount.mul(BASE_PRECISION).div(oraclePrice);\n\t\t\t })();\n\n\t// Build URL parameters for server request\n\tconst urlParamsObject: Record<string, string> = {\n\t\t// Required fields\n\t\tassetType: 'base',\n\t\tmarketType: ENUM_UTILS.toStr(marketType),\n\t\tmarketIndex: marketIndex.toString(),\n\t\tdirection: ENUM_UTILS.toStr(direction),\n\t\tamount: baseAmount.toString(),\n\t};\n\n\t// Add defined optional parameters\n\tObject.entries(optionalAuctionParamsInputs).forEach(([key, value]) => {\n\t\tif (value !== undefined) {\n\t\t\turlParamsObject[key] = value.toString();\n\t\t}\n\t});\n\n\tconst urlParams = encodeQueryParams(urlParamsObject);\n\n\t// Get order params from server\n\tconst requestUrl = `${dlobServerHttpUrl}/auctionParams?${urlParams.toString()}`;\n\tconst response = await fetch(requestUrl);\n\n\tif (!response.ok) {\n\t\tthrow new Error(\n\t\t\t`Server responded with ${response.status}: ${response.statusText}`\n\t\t);\n\t}\n\n\tconst serverResponse: ServerAuctionParamsResponse = await response.json();\n\tconst serverAuctionParams = serverResponse?.data?.params;\n\tinvariant(serverAuctionParams, 'Server auction params are required');\n\tconst mappedParams: MappedAuctionParams =\n\t\tmapAuctionParamsResponse(serverAuctionParams);\n\n\t// Convert MappedAuctionParams to OptionalOrderParams\n\treturn {\n\t\torderType: mappedParams.orderType,\n\t\tmarketType: mappedParams.marketType,\n\t\tuserOrderId: mappedParams.userOrderId,\n\t\tdirection: mappedParams.direction,\n\t\tbaseAssetAmount: mappedParams.baseAssetAmount,\n\t\tmarketIndex: mappedParams.marketIndex,\n\t\treduceOnly: mappedParams.reduceOnly,\n\t\tpostOnly: mappedParams.postOnly ?? DefaultOrderParams.postOnly,\n\t\ttriggerPrice: mappedParams.triggerPrice || null,\n\t\ttriggerCondition:\n\t\t\tmappedParams.triggerCondition ?? DefaultOrderParams.triggerCondition,\n\t\toraclePriceOffset: mappedParams.oraclePriceOffset?.toNumber() || null,\n\t\tauctionDuration: mappedParams.auctionDuration || null,\n\t\tmaxTs: mappedParams.maxTs,\n\t\tauctionStartPrice: mappedParams.auctionStartPrice || null,\n\t\tauctionEndPrice: mappedParams.auctionEndPrice || null,\n\t\t// no price, because market orders don't need a price\n\t};\n}\n\nconst DEFAULT_L2_DEPTH_FOR_AUCTION_ORDER_PARAMS = 100;\n\n/**\n * Fetches auction order parameters from the L2 data\n */\nexport async function fetchAuctionOrderParamsFromL2({\n\tdlobServerHttpUrl,\n\tmarketIndex,\n\tmarketType,\n\tdirection,\n\tassetType,\n\tamount,\n\toptionalAuctionParamsInputs,\n\tdriftClient,\n\tdynamicSlippageConfig,\n}: RegularOrderParams): Promise<OptionalOrderParams> {\n\tconst marketId = new MarketId(marketIndex, marketType);\n\tconst baseAmount =\n\t\tassetType === 'base'\n\t\t\t? amount\n\t\t\t: (() => {\n\t\t\t\t\tconst oraclePrice =\n\t\t\t\t\t\tdriftClient.getOracleDataForPerpMarket(marketIndex).price;\n\t\t\t\t\treturn amount.mul(oraclePrice).div(PRICE_PRECISION);\n\t\t\t })();\n\n\tconst l2DataResponse = await fetchBulkMarketsDlobL2Data(dlobServerHttpUrl, [\n\t\t{\n\t\t\tmarketId,\n\t\t\tdepth: DEFAULT_L2_DEPTH_FOR_AUCTION_ORDER_PARAMS,\n\t\t},\n\t]);\n\tconst oraclePriceData = l2DataResponse[0].oracleData;\n\tconst oraclePriceBn = oraclePriceData?.price;\n\tconst markPriceBn = l2DataResponse[0].markPrice;\n\tconst l2Data = convertToL2OrderBook(l2DataResponse);\n\n\tconst priceImpactData = calculatePriceImpactFromL2(\n\t\tmarketId,\n\t\tdirection,\n\t\tbaseAmount,\n\t\tl2Data,\n\t\toraclePriceBn\n\t);\n\n\tconst startPrices = COMMON_UI_UTILS.getPriceObject({\n\t\toraclePrice: oraclePriceBn,\n\t\tbestOffer: priceImpactData.bestPrice,\n\t\tentryPrice: priceImpactData.entryPrice,\n\t\tworstPrice: priceImpactData.worstPrice,\n\t\tmarkPrice: markPriceBn,\n\t\tdirection: direction,\n\t});\n\tconst slippageToleranceInput = optionalAuctionParamsInputs.slippageTolerance;\n\tconst derivedSlippage =\n\t\tslippageToleranceInput === 'dynamic'\n\t\t\t? calculateDynamicSlippageFromL2({\n\t\t\t\t\tl2Data,\n\t\t\t\t\tmarketId,\n\t\t\t\t\tstartPrice:\n\t\t\t\t\t\tstartPrices[\n\t\t\t\t\t\t\toptionalAuctionParamsInputs.auctionStartPriceOffsetFrom as keyof typeof startPrices\n\t\t\t\t\t\t],\n\t\t\t\t\tworstPrice: priceImpactData.worstPrice,\n\t\t\t\t\toraclePrice: oraclePriceBn,\n\t\t\t\t\tdynamicSlippageConfig,\n\t\t\t })\n\t\t\t: typeof slippageToleranceInput === 'number'\n\t\t\t? slippageToleranceInput\n\t\t\t: 0.005;\n\n\tconst auctionOrderParams = COMMON_UI_UTILS.deriveMarketOrderParams({\n\t\tmarketType: marketType,\n\t\tmarketIndex: marketIndex,\n\t\tdirection: direction,\n\t\tmaxLeverageSelected: optionalAuctionParamsInputs.maxLeverageSelected,\n\t\tmaxLeverageOrderSize: optionalAuctionParamsInputs.maxLeverageOrderSize,\n\t\tbaseAmount: baseAmount,\n\t\treduceOnly: optionalAuctionParamsInputs.reduceOnly,\n\t\tallowInfSlippage: false,\n\t\toraclePrice: oraclePriceBn,\n\t\tbestPrice: priceImpactData.bestPrice,\n\t\tentryPrice: priceImpactData.entryPrice,\n\t\tworstPrice: priceImpactData.worstPrice,\n\t\tmarkPrice: markPriceBn,\n\t\tauctionDuration: optionalAuctionParamsInputs.auctionDuration,\n\t\tauctionStartPriceOffset:\n\t\t\toptionalAuctionParamsInputs.auctionStartPriceOffset,\n\t\tauctionEndPriceOffset: optionalAuctionParamsInputs.auctionEndPriceOffset,\n\t\tauctionStartPriceOffsetFrom:\n\t\t\toptionalAuctionParamsInputs.auctionStartPriceOffsetFrom,\n\t\tauctionEndPriceOffsetFrom:\n\t\t\toptionalAuctionParamsInputs.auctionEndPriceOffsetFrom,\n\t\tslippageTolerance: derivedSlippage,\n\t\tisOracleOrder: optionalAuctionParamsInputs.isOracleOrder,\n\t\tadditionalEndPriceBuffer:\n\t\t\toptionalAuctionParamsInputs.additionalEndPriceBuffer,\n\t\tforceUpToSlippage: optionalAuctionParamsInputs.forceUpToSlippage,\n\t});\n\n\tif (!auctionOrderParams) {\n\t\tthrow new Error('Failed to derive auction params from L2');\n\t}\n\n\treturn auctionOrderParams;\n}\n\ntype FetchTopMakersParams = {\n\tdlobServerHttpUrl: string;\n\tmarketIndex: number;\n\tmarketType: MarketType;\n\tside: 'bid' | 'ask';\n\tlimit: number;\n};\n\n/**\n * Fetches the top makers information, for use as inputs in placeAndTake market orders.\n * The side of the request should be opposite of the side of the placeAndTake market order.\n */\nexport async function fetchTopMakers(params: FetchTopMakersParams): Promise<\n\t{\n\t\tuserAccountPubKey: PublicKey;\n\t\tuserAccount: UserAccount;\n\t}[]\n> {\n\ttry {\n\t\tconst { dlobServerHttpUrl, marketIndex, marketType, side, limit } = params;\n\n\t\tconst urlParams = encodeQueryParams({\n\t\t\tmarketIndex: marketIndex.toString(),\n\t\t\tmarketType: ENUM_UTILS.toStr(marketType),\n\t\t\tside,\n\t\t\tlimit: limit.toString(),\n\t\t\tincludeAccounts: 'true',\n\t\t});\n\n\t\tconst requestUrl = `${dlobServerHttpUrl}/topMakers?${urlParams}`;\n\t\tconst response = await fetch(requestUrl);\n\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(\n\t\t\t\t`Server responded with ${response.status}: ${response.statusText}`\n\t\t\t);\n\t\t}\n\n\t\tconst serverResponse: {\n\t\t\tuserAccountPubKey: string;\n\t\t\taccountBase64: string;\n\t\t}[] = await response.json();\n\t\tconst mappedParams: {\n\t\t\tuserAccountPubKey: PublicKey;\n\t\t\tuserAccount: UserAccount;\n\t\t}[] = serverResponse.map((value) => ({\n\t\t\tuserAccountPubKey: new PublicKey(value.userAccountPubKey),\n\t\t\tuserAccount: decodeUser(Buffer.from(value.accountBase64, 'base64')),\n\t\t}));\n\n\t\treturn mappedParams;\n\t} catch (e) {\n\t\tconsole.error(e);\n\t\treturn [];\n\t}\n}\n"]}
|
|
@@ -23,11 +23,15 @@ export interface OpenPerpMarketOrderBaseParams {
|
|
|
23
23
|
export interface OpenPerpMarketOrderBaseParamsWithSwift extends Omit<OpenPerpMarketOrderBaseParams, 'placeAndTake'> {
|
|
24
24
|
swiftOptions: SwiftOrderOptions;
|
|
25
25
|
}
|
|
26
|
-
export
|
|
26
|
+
export type OpenPerpMarketOrderParams<T extends boolean = boolean, S extends Omit<SwiftOrderOptions, 'swiftServerUrl'> = Omit<SwiftOrderOptions, 'swiftServerUrl'>> = T extends true ? OpenPerpMarketOrderBaseParams & {
|
|
27
27
|
useSwift: T;
|
|
28
|
-
swiftOptions
|
|
29
|
-
placeAndTake?:
|
|
30
|
-
}
|
|
28
|
+
swiftOptions: S;
|
|
29
|
+
placeAndTake?: never;
|
|
30
|
+
} : OpenPerpMarketOrderBaseParams & {
|
|
31
|
+
useSwift: T;
|
|
32
|
+
placeAndTake?: PlaceAndTakeParams;
|
|
33
|
+
swiftOptions?: never;
|
|
34
|
+
};
|
|
31
35
|
/**
|
|
32
36
|
* Creates and submits a Swift (signed message) order. Only available for perp orders.
|
|
33
37
|
*/
|
|
@@ -91,4 +95,4 @@ export declare const createOpenPerpMarketOrderTxn: (params: WithTxnParams<OpenPe
|
|
|
91
95
|
*
|
|
92
96
|
* @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)
|
|
93
97
|
*/
|
|
94
|
-
export declare const createOpenPerpMarketOrder: <T extends boolean>(params: WithTxnParams<OpenPerpMarketOrderParams<T>>) => Promise<TxnOrSwiftResult<T>>;
|
|
98
|
+
export declare const createOpenPerpMarketOrder: <T extends boolean>(params: WithTxnParams<OpenPerpMarketOrderParams<T, SwiftOrderOptions>>) => Promise<TxnOrSwiftResult<T>>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.ts"],"names":[],"mappings":";;;AAAA,yCAUyB;AAMzB,mDAAqD;AACrD,sDAG2B;AAC3B,kEAA6E;AAC7E,8CAIuB;AACvB,mEAA6E;AAE7E,kEAAyE;AAiCzE;;GAEG;AACI,KAAK,UAAU,sBAAsB,CAAC,EAC5C,WAAW,EACX,IAAI,EACJ,SAAS,EACT,WAAW,EACX,SAAS,EACT,MAAM,EACN,aAAa,EACb,iBAAiB,EACjB,2BAA2B,EAC3B,YAAY,EACZ,WAAW,GAAG,CAAC,GACyB;IACxC,IAAI,MAAM,CAAC,MAAM,EAAE,EAAE,CAAC;QACrB,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;IACrD,CAAC;IAED,mCAAmC;IACnC,MAAM,kBAAkB,GAAG,MAAM,IAAA,oCAAuB,EAAC;QACxD,WAAW;QACX,IAAI;QACJ,SAAS;QACT,WAAW;QACX,UAAU,EAAE,gBAAU,CAAC,IAAI;QAC3B,SAAS;QACT,MAAM;QACN,iBAAiB;QACjB,2BAA2B;KAC3B,CAAC,CAAC;IAEH,MAAM,WAAW,GAAG,WAAW,CAAC,0BAA0B,CAAC,WAAW,CAAC,CAAC,KAAK,CAAC;IAC9E,MAAM,gBAAgB,GAAG,MAAM,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC,GAAG,CAAC,qBAAe,CAAC,CAAC;IAEtE,MAAM,QAAQ,GAAG,0BAAkB,CAAC,0BAA0B,CAC7D,WAAW,EACX,WAAW,EACX,IAAI,EACJ,gBAAgB,EAChB,SAAS,CACT,CAAC;IAEF,MAAM,WAAW,GAAG;QACnB,GAAG,kBAAkB;QACrB,WAAW;QACX,QAAQ;KACR,CAAC;IAEF,MAAM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lBW,QAAA,4BAA4B,gCAkBvC;AAEF;;;;;;;;;;;;;;;GAeG;AACI,MAAM,yBAAyB,GAAG,KAAK,EAC7C,MAAmD,EACpB,EAAE;IACjC,MAAM,EAAE,QAAQ,EAAE,YAAY,EAAE,GAAG,IAAI,EAAE,GAAG,MAAM,CAAC;IAEnD,wDAAwD;IACxD,IAAI,QAAQ,EAAE,CAAC;QACd,IAAI,CAAC,YAAY,EAAE,CAAC;YACnB,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;QACnE,CAAC;QAED,MAAM,gBAAgB,GAAG,MAAM,sBAAsB,CAAC;YACrD,GAAG,IAAI;YACP,YAAY;SACZ,CAAC,CAAC;QAEH,OAAO,gBAE8B,CAAC;IACvC,CAAC;IAED,MAAM,sBAAsB,GAAG,MAAM,IAAA,oCAA4B,EAAC,IAAI,CAAC,CAAC;IAExE,OAAO,sBAE8B,CAAC;AACvC,CAAC,CAAC;AA1BW,QAAA,yBAAyB,6BA0BpC","sourcesContent":["import {\n\tDriftClient,\n\tUser,\n\tBN,\n\tPositionDirection,\n\tOptionalOrderParams,\n\tMarketType,\n\tgetUserStatsAccountPublicKey,\n\tReferrerInfo,\n\tPRICE_PRECISION,\n} from '@drift-labs/sdk';\nimport {\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport {\n\tprepSignAndSendSwiftOrder,\n\tSwiftOrderOptions,\n} from '../openSwiftOrder';\nimport { buildNonMarketOrderParams } from '../../../../../utils/orderParams';\nimport {\n\tfetchAuctionOrderParams,\n\tfetchTopMakers,\n\tOptionalAuctionParamsRequestInputs,\n} from '../dlobServer';\nimport { ORDER_COMMON_UTILS } from '../../../../../../common-ui-utils/order';\nimport { TxnOrSwiftResult, WithTxnParams } from '../types';\nimport { NoTopMakersError } from '../../../../../Drift/constants/errors';\nimport { PlaceAndTakeParams, OptionalTriggerOrderParams } from '../types';\n\nexport interface OpenPerpMarketOrderBaseParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tassetType: 'base' | 'quote';\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\tamount: BN;\n\tdlobServerHttpUrl: string;\n\t// mainly used for UI order identification\n\tuserOrderId?: number;\n\tplaceAndTake?: PlaceAndTakeParams;\n\toptionalAuctionParamsInputs?: OptionalAuctionParamsRequestInputs;\n\tbracketOrders?: {\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t};\n}\n\nexport interface OpenPerpMarketOrderBaseParamsWithSwift\n\textends Omit<OpenPerpMarketOrderBaseParams, 'placeAndTake'> {\n\tswiftOptions: SwiftOrderOptions;\n}\n\nexport interface OpenPerpMarketOrderParams<T extends boolean = boolean>\n\textends OpenPerpMarketOrderBaseParams {\n\tuseSwift: T;\n\tswiftOptions?: T extends true ? SwiftOrderOptions : never;\n\tplaceAndTake?: T extends true ? never : PlaceAndTakeParams;\n}\n\n/**\n * Creates and submits a Swift (signed message) order. Only available for perp orders.\n */\nexport async function createSwiftMarketOrder({\n\tdriftClient,\n\tuser,\n\tassetType,\n\tmarketIndex,\n\tdirection,\n\tamount,\n\tbracketOrders,\n\tdlobServerHttpUrl,\n\toptionalAuctionParamsInputs,\n\tswiftOptions,\n\tuserOrderId = 0,\n}: OpenPerpMarketOrderBaseParamsWithSwift): Promise<void> {\n\tif (amount.isZero()) {\n\t\tthrow new Error('Amount must be greater than zero');\n\t}\n\n\t// Get order parameters from server\n\tconst fetchedOrderParams = await fetchAuctionOrderParams({\n\t\tdriftClient,\n\t\tuser,\n\t\tassetType,\n\t\tmarketIndex,\n\t\tmarketType: MarketType.PERP,\n\t\tdirection,\n\t\tamount,\n\t\tdlobServerHttpUrl,\n\t\toptionalAuctionParamsInputs,\n\t});\n\n\tconst oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;\n\tconst totalQuoteAmount = amount.mul(oraclePrice).div(PRICE_PRECISION);\n\n\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\tmarketIndex,\n\t\tdriftClient,\n\t\tuser,\n\t\ttotalQuoteAmount,\n\t\tdirection\n\t);\n\n\tconst orderParams = {\n\t\t...fetchedOrderParams,\n\t\tuserOrderId,\n\t\tbitFlags,\n\t};\n\n\tconst userAccount = user.getUserAccount();\n\tconst slotBuffer = swiftOptions.signedMessageOrderSlotBuffer || 7;\n\n\tawait prepSignAndSendSwiftOrder({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tmarketIndex,\n\t\tslotBuffer,\n\t\tswiftOptions,\n\t\torderParams: {\n\t\t\tmain: orderParams,\n\t\t\ttakeProfit: bracketOrders?.takeProfit,\n\t\t\tstopLoss: bracketOrders?.stopLoss,\n\t\t},\n\t});\n}\n\n/**\n * Creates a placeAndTake transaction instruction.\n * Fallbacks to a regular market order if no top makers are found.\n */\nexport const createPlaceAndTakePerpMarketOrderIx = async ({\n\tassetType,\n\tdirection,\n\tdlobServerHttpUrl,\n\tmarketIndex,\n\tdriftClient,\n\tuser,\n\tuserOrderId,\n\tamount,\n\treferrerInfo,\n\tauctionDurationPercentage,\n\toptionalAuctionParamsInputs,\n}: OpenPerpMarketOrderBaseParams & {\n\tdirection: PositionDirection;\n\tdlobServerHttpUrl: string;\n\tmarketIndex: number;\n\tdriftClient: DriftClient;\n\tuser: User;\n\treferrerInfo?: ReferrerInfo;\n\tauctionDurationPercentage?: number;\n}) => {\n\tconst counterPartySide = ENUM_UTILS.match(direction, PositionDirection.LONG)\n\t\t? 'ask'\n\t\t: 'bid';\n\n\tconst [fetchedOrderParams, topMakersResult] = await Promise.all([\n\t\tfetchAuctionOrderParams({\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tassetType,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tamount,\n\t\t\tdlobServerHttpUrl,\n\t\t\toptionalAuctionParamsInputs,\n\t\t}),\n\t\tfetchTopMakers({\n\t\t\tdlobServerHttpUrl,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tside: counterPartySide,\n\t\t\tlimit: 4,\n\t\t}),\n\t]);\n\n\tconst oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;\n\tconst totalQuoteAmount = amount.mul(oraclePrice).div(PRICE_PRECISION);\n\n\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\tmarketIndex,\n\t\tdriftClient,\n\t\tuser,\n\t\ttotalQuoteAmount,\n\t\tdirection\n\t);\n\tfetchedOrderParams.bitFlags = bitFlags;\n\tfetchedOrderParams.userOrderId = userOrderId;\n\n\tif (!topMakersResult || topMakersResult.length === 0) {\n\t\tthrow new NoTopMakersError('No top makers found', fetchedOrderParams);\n\t}\n\n\tconst topMakersInfo = topMakersResult.map((maker) => ({\n\t\tmaker: maker.userAccountPubKey,\n\t\tmakerUserAccount: maker.userAccount,\n\t\tmakerStats: getUserStatsAccountPublicKey(\n\t\t\tdriftClient.program.programId,\n\t\t\tmaker.userAccount.authority\n\t\t),\n\t}));\n\n\tconst placeAndTakeIx = await driftClient.getPlaceAndTakePerpOrderIx(\n\t\tfetchedOrderParams,\n\t\ttopMakersInfo,\n\t\treferrerInfo,\n\t\tundefined,\n\t\tauctionDurationPercentage,\n\t\tuser.getUserAccount().subAccountId\n\t);\n\n\treturn placeAndTakeIx;\n};\n\n/**\n * Creates transaction instructions for opening a perp market order.\n * If swiftOptions is provided, it will create a Swift (signed message) order instead.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param assetType - Whether the amount is in base or quote units\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n *\n * @returns Promise resolving to an array of transaction instructions for regular orders\n */\nexport const createOpenPerpMarketOrderIxs = async ({\n\tdriftClient,\n\tuser,\n\tassetType,\n\tmarketIndex,\n\tdirection,\n\tamount,\n\tbracketOrders,\n\tdlobServerHttpUrl,\n\tplaceAndTake,\n\tuserOrderId,\n\toptionalAuctionParamsInputs = {},\n}: OpenPerpMarketOrderBaseParams): Promise<TransactionInstruction[]> => {\n\tif (!amount || amount.isZero()) {\n\t\tthrow new Error('Amount must be greater than zero');\n\t}\n\n\tconst allOrders: OptionalOrderParams[] = [];\n\tconst allIxs: TransactionInstruction[] = [];\n\n\tif (placeAndTake?.enable) {\n\t\ttry {\n\t\t\tconst placeAndTakeIx = await createPlaceAndTakePerpMarketOrderIx({\n\t\t\t\tassetType,\n\t\t\t\tamount,\n\t\t\t\tdirection,\n\t\t\t\tdlobServerHttpUrl,\n\t\t\t\tmarketIndex,\n\t\t\t\tdriftClient,\n\t\t\t\tuser,\n\t\t\t\tuserOrderId,\n\t\t\t\treferrerInfo: placeAndTake.referrerInfo,\n\t\t\t\tauctionDurationPercentage: placeAndTake.auctionDurationPercentage,\n\t\t\t\toptionalAuctionParamsInputs,\n\t\t\t});\n\t\t\tallIxs.push(placeAndTakeIx);\n\t\t} catch (e) {\n\t\t\tif (e instanceof NoTopMakersError) {\n\t\t\t\t// fallback to regular order\n\t\t\t\tallOrders.push(e.orderParams);\n\t\t\t} else {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tconst fetchedOrderParams = await fetchAuctionOrderParams({\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tassetType,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tamount,\n\t\t\tdlobServerHttpUrl,\n\t\t\toptionalAuctionParamsInputs,\n\t\t});\n\n\t\tconst oraclePrice =\n\t\t\tdriftClient.getOracleDataForPerpMarket(marketIndex).price;\n\t\tconst totalQuoteAmount = amount.mul(oraclePrice).div(PRICE_PRECISION);\n\n\t\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\t\tmarketIndex,\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\ttotalQuoteAmount,\n\t\t\tdirection\n\t\t);\n\n\t\tconst orderParams = {\n\t\t\t...fetchedOrderParams,\n\t\t\tuserOrderId,\n\t\t\tbitFlags,\n\t\t};\n\n\t\tallOrders.push(orderParams);\n\t}\n\n\tconst bracketOrdersDirection = ENUM_UTILS.match(\n\t\tdirection,\n\t\tPositionDirection.LONG\n\t)\n\t\t? PositionDirection.SHORT\n\t\t: PositionDirection.LONG;\n\n\tif (bracketOrders?.takeProfit) {\n\t\tconst takeProfitParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount: bracketOrders.takeProfit.baseAssetAmount ?? amount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'takeProfit',\n\t\t\t\ttriggerPrice: bracketOrders.takeProfit.triggerPrice,\n\t\t\t\tlimitPrice: bracketOrders.takeProfit.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: bracketOrders.takeProfit.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(takeProfitParams);\n\t}\n\n\tif (bracketOrders?.stopLoss) {\n\t\tconst stopLossParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount: bracketOrders.stopLoss.baseAssetAmount ?? amount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'stopLoss',\n\t\t\t\ttriggerPrice: bracketOrders.stopLoss.triggerPrice,\n\t\t\t\tlimitPrice: bracketOrders.stopLoss.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: bracketOrders.stopLoss.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(stopLossParams);\n\t}\n\n\t// Regular order flow - create transaction instruction\n\tif (allOrders.length > 0) {\n\t\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(allOrders);\n\t\tallIxs.push(placeOrderIx);\n\t}\n\n\treturn allIxs;\n};\n\n/**\n * Creates a complete transaction for opening a perp market order.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n *\n * @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)\n */\nexport const createOpenPerpMarketOrderTxn = async (\n\tparams: WithTxnParams<OpenPerpMarketOrderBaseParams>\n): Promise<Transaction | VersionedTransaction> => {\n\tconst { driftClient } = params;\n\n\t// Regular order flow - create transaction instruction and build transaction\n\tconst placeOrderIx = await createOpenPerpMarketOrderIxs(params);\n\tconst openPerpMarketOrderTxn = await driftClient.txHandler.buildTransaction({\n\t\tinstructions: placeOrderIx,\n\t\ttxVersion: 0,\n\t\tconnection: driftClient.connection,\n\t\tpreFlightCommitment: 'confirmed',\n\t\tfetchAllMarketLookupTableAccounts:\n\t\t\tdriftClient.fetchAllLookupTableAccounts.bind(driftClient),\n\t\ttxParams: params.txParams,\n\t});\n\n\treturn openPerpMarketOrderTxn;\n};\n\n/**\n * Creates a transaction or swift order for a perp market order.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n * @param useSwift - Whether to use Swift (signed message) orders instead of regular transactions\n * @param swiftOptions - Options for Swift (signed message) orders. Required if useSwift is true\n * @param userOrderId - The user order id for UI identification\n *\n * @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)\n */\nexport const createOpenPerpMarketOrder = async <T extends boolean>(\n\tparams: WithTxnParams<OpenPerpMarketOrderParams<T>>\n): Promise<TxnOrSwiftResult<T>> => {\n\tconst { useSwift, swiftOptions, ...rest } = params;\n\n\t// If useSwift is true, return the Swift result directly\n\tif (useSwift) {\n\t\tif (!swiftOptions) {\n\t\t\tthrow new Error('swiftOptions is required when useSwift is true');\n\t\t}\n\n\t\tconst swiftOrderResult = await createSwiftMarketOrder({\n\t\t\t...rest,\n\t\t\tswiftOptions,\n\t\t});\n\n\t\treturn swiftOrderResult as T extends true\n\t\t\t? void\n\t\t\t: Transaction | VersionedTransaction;\n\t}\n\n\tconst openPerpMarketOrderTxn = await createOpenPerpMarketOrderTxn(rest);\n\n\treturn openPerpMarketOrderTxn as T extends true\n\t\t? void\n\t\t: Transaction | VersionedTransaction;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.ts"],"names":[],"mappings":";;;AAAA,yCAUyB;AAMzB,mDAAqD;AACrD,sDAG2B;AAC3B,kEAA6E;AAC7E,8CAIuB;AACvB,mEAA6E;AAE7E,kEAAyE;AA2CzE;;GAEG;AACI,KAAK,UAAU,sBAAsB,CAAC,EAC5C,WAAW,EACX,IAAI,EACJ,SAAS,EACT,WAAW,EACX,SAAS,EACT,MAAM,EACN,aAAa,EACb,iBAAiB,EACjB,2BAA2B,EAC3B,YAAY,EACZ,WAAW,GAAG,CAAC,GACyB;IACxC,IAAI,MAAM,CAAC,MAAM,EAAE,EAAE,CAAC;QACrB,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;IACrD,CAAC;IAED,mCAAmC;IACnC,MAAM,kBAAkB,GAAG,MAAM,IAAA,oCAAuB,EAAC;QACxD,WAAW;QACX,IAAI;QACJ,SAAS;QACT,WAAW;QACX,UAAU,EAAE,gBAAU,CAAC,IAAI;QAC3B,SAAS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CAAC;IAE/B,4EAA4E;IAC5E,MAAM,YAAY,GAAG,MAAM,IAAA,oCAA4B,EAAC,MAAM,CAAC,CAAC;IAChE,MAAM,sBAAsB,GAAG,MAAM,WAAW,CAAC,SAAS,CAAC,gBAAgB,CAAC;QAC3E,YAAY,EAAE,YAAY;QAC1B,SAAS,EAAE,CAAC;QACZ,UAAU,EAAE,WAAW,CAAC,UAAU;QAClC,mBAAmB,EAAE,WAAW;QAChC,iCAAiC,EAChC,WAAW,CAAC,2BAA2B,CAAC,IAAI,CAAC,WAAW,CAAC;QAC1D,QAAQ,EAAE,MAAM,CAAC,QAAQ;KACzB,CAAC,CAAC;IAEH,OAAO,sBAAsB,CAAC;AAC/B,CAAC,CAAC;AAlBW,QAAA,4BAA4B,gCAkBvC;AAEF;;;;;;;;;;;;;;;GAeG;AACI,MAAM,yBAAyB,GAAG,KAAK,EAC7C,MAAsE,EACvC,EAAE;IACjC,MAAM,EAAE,QAAQ,EAAE,YAAY,EAAE,GAAG,IAAI,EAAE,GAAG,MAAM,CAAC;IAEnD,wDAAwD;IACxD,IAAI,QAAQ,EAAE,CAAC;QACd,IAAI,CAAC,YAAY,EAAE,CAAC;YACnB,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;QACnE,CAAC;QAED,MAAM,gBAAgB,GAAG,MAAM,sBAAsB,CAAC;YACrD,GAAG,IAAI;YACP,YAAY;SACZ,CAAC,CAAC;QAEH,OAAO,gBAAuC,CAAC;IAChD,CAAC;IAED,MAAM,sBAAsB,GAAG,MAAM,IAAA,oCAA4B,EAAC,IAAI,CAAC,CAAC;IAExE,OAAO,sBAA6C,CAAC;AACtD,CAAC,CAAC;AAtBW,QAAA,yBAAyB,6BAsBpC","sourcesContent":["import {\n\tDriftClient,\n\tUser,\n\tBN,\n\tPositionDirection,\n\tOptionalOrderParams,\n\tMarketType,\n\tgetUserStatsAccountPublicKey,\n\tReferrerInfo,\n\tPRICE_PRECISION,\n} from '@drift-labs/sdk';\nimport {\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport {\n\tprepSignAndSendSwiftOrder,\n\tSwiftOrderOptions,\n} from '../openSwiftOrder';\nimport { buildNonMarketOrderParams } from '../../../../../utils/orderParams';\nimport {\n\tfetchAuctionOrderParams,\n\tfetchTopMakers,\n\tOptionalAuctionParamsRequestInputs,\n} from '../dlobServer';\nimport { ORDER_COMMON_UTILS } from '../../../../../../common-ui-utils/order';\nimport { TxnOrSwiftResult, WithTxnParams } from '../types';\nimport { NoTopMakersError } from '../../../../../Drift/constants/errors';\nimport { PlaceAndTakeParams, OptionalTriggerOrderParams } from '../types';\n\nexport interface OpenPerpMarketOrderBaseParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tassetType: 'base' | 'quote';\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\tamount: BN;\n\tdlobServerHttpUrl: string;\n\t// mainly used for UI order identification\n\tuserOrderId?: number;\n\tplaceAndTake?: PlaceAndTakeParams;\n\toptionalAuctionParamsInputs?: OptionalAuctionParamsRequestInputs;\n\tbracketOrders?: {\n\t\ttakeProfit?: OptionalTriggerOrderParams;\n\t\tstopLoss?: OptionalTriggerOrderParams;\n\t};\n}\n\nexport interface OpenPerpMarketOrderBaseParamsWithSwift\n\textends Omit<OpenPerpMarketOrderBaseParams, 'placeAndTake'> {\n\tswiftOptions: SwiftOrderOptions;\n}\n\nexport type OpenPerpMarketOrderParams<\n\tT extends boolean = boolean,\n\tS extends Omit<SwiftOrderOptions, 'swiftServerUrl'> = Omit<\n\t\tSwiftOrderOptions,\n\t\t'swiftServerUrl'\n\t>\n> = T extends true\n\t? OpenPerpMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tswiftOptions: S;\n\t\t\tplaceAndTake?: never;\n\t }\n\t: OpenPerpMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tplaceAndTake?: PlaceAndTakeParams;\n\t\t\tswiftOptions?: never;\n\t };\n/**\n * Creates and submits a Swift (signed message) order. Only available for perp orders.\n */\nexport async function createSwiftMarketOrder({\n\tdriftClient,\n\tuser,\n\tassetType,\n\tmarketIndex,\n\tdirection,\n\tamount,\n\tbracketOrders,\n\tdlobServerHttpUrl,\n\toptionalAuctionParamsInputs,\n\tswiftOptions,\n\tuserOrderId = 0,\n}: OpenPerpMarketOrderBaseParamsWithSwift): Promise<void> {\n\tif (amount.isZero()) {\n\t\tthrow new Error('Amount must be greater than zero');\n\t}\n\n\t// Get order parameters from server\n\tconst fetchedOrderParams = await fetchAuctionOrderParams({\n\t\tdriftClient,\n\t\tuser,\n\t\tassetType,\n\t\tmarketIndex,\n\t\tmarketType: MarketType.PERP,\n\t\tdirection,\n\t\tamount,\n\t\tdlobServerHttpUrl,\n\t\toptionalAuctionParamsInputs,\n\t});\n\n\tconst oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;\n\tconst totalQuoteAmount = amount.mul(oraclePrice).div(PRICE_PRECISION);\n\n\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\tmarketIndex,\n\t\tdriftClient,\n\t\tuser,\n\t\ttotalQuoteAmount,\n\t\tdirection\n\t);\n\n\tconst orderParams = {\n\t\t...fetchedOrderParams,\n\t\tuserOrderId,\n\t\tbitFlags,\n\t};\n\n\tconst userAccount = user.getUserAccount();\n\tconst slotBuffer = swiftOptions.signedMessageOrderSlotBuffer || 7;\n\n\tawait prepSignAndSendSwiftOrder({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tmarketIndex,\n\t\tslotBuffer,\n\t\tswiftOptions,\n\t\torderParams: {\n\t\t\tmain: orderParams,\n\t\t\ttakeProfit: bracketOrders?.takeProfit,\n\t\t\tstopLoss: bracketOrders?.stopLoss,\n\t\t},\n\t});\n}\n\n/**\n * Creates a placeAndTake transaction instruction.\n * Fallbacks to a regular market order if no top makers are found.\n */\nexport const createPlaceAndTakePerpMarketOrderIx = async ({\n\tassetType,\n\tdirection,\n\tdlobServerHttpUrl,\n\tmarketIndex,\n\tdriftClient,\n\tuser,\n\tuserOrderId,\n\tamount,\n\treferrerInfo,\n\tauctionDurationPercentage,\n\toptionalAuctionParamsInputs,\n}: OpenPerpMarketOrderBaseParams & {\n\tdirection: PositionDirection;\n\tdlobServerHttpUrl: string;\n\tmarketIndex: number;\n\tdriftClient: DriftClient;\n\tuser: User;\n\treferrerInfo?: ReferrerInfo;\n\tauctionDurationPercentage?: number;\n}) => {\n\tconst counterPartySide = ENUM_UTILS.match(direction, PositionDirection.LONG)\n\t\t? 'ask'\n\t\t: 'bid';\n\n\tconst [fetchedOrderParams, topMakersResult] = await Promise.all([\n\t\tfetchAuctionOrderParams({\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tassetType,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tamount,\n\t\t\tdlobServerHttpUrl,\n\t\t\toptionalAuctionParamsInputs,\n\t\t}),\n\t\tfetchTopMakers({\n\t\t\tdlobServerHttpUrl,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tside: counterPartySide,\n\t\t\tlimit: 4,\n\t\t}),\n\t]);\n\n\tconst oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;\n\tconst totalQuoteAmount = amount.mul(oraclePrice).div(PRICE_PRECISION);\n\n\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\tmarketIndex,\n\t\tdriftClient,\n\t\tuser,\n\t\ttotalQuoteAmount,\n\t\tdirection\n\t);\n\tfetchedOrderParams.bitFlags = bitFlags;\n\tfetchedOrderParams.userOrderId = userOrderId;\n\n\tif (!topMakersResult || topMakersResult.length === 0) {\n\t\tthrow new NoTopMakersError('No top makers found', fetchedOrderParams);\n\t}\n\n\tconst topMakersInfo = topMakersResult.map((maker) => ({\n\t\tmaker: maker.userAccountPubKey,\n\t\tmakerUserAccount: maker.userAccount,\n\t\tmakerStats: getUserStatsAccountPublicKey(\n\t\t\tdriftClient.program.programId,\n\t\t\tmaker.userAccount.authority\n\t\t),\n\t}));\n\n\tconst placeAndTakeIx = await driftClient.getPlaceAndTakePerpOrderIx(\n\t\tfetchedOrderParams,\n\t\ttopMakersInfo,\n\t\treferrerInfo,\n\t\tundefined,\n\t\tauctionDurationPercentage,\n\t\tuser.getUserAccount().subAccountId\n\t);\n\n\treturn placeAndTakeIx;\n};\n\n/**\n * Creates transaction instructions for opening a perp market order.\n * If swiftOptions is provided, it will create a Swift (signed message) order instead.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param assetType - Whether the amount is in base or quote units\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n *\n * @returns Promise resolving to an array of transaction instructions for regular orders\n */\nexport const createOpenPerpMarketOrderIxs = async ({\n\tdriftClient,\n\tuser,\n\tassetType,\n\tmarketIndex,\n\tdirection,\n\tamount,\n\tbracketOrders,\n\tdlobServerHttpUrl,\n\tplaceAndTake,\n\tuserOrderId,\n\toptionalAuctionParamsInputs = {},\n}: OpenPerpMarketOrderBaseParams): Promise<TransactionInstruction[]> => {\n\tif (!amount || amount.isZero()) {\n\t\tthrow new Error('Amount must be greater than zero');\n\t}\n\n\tconst allOrders: OptionalOrderParams[] = [];\n\tconst allIxs: TransactionInstruction[] = [];\n\n\tif (placeAndTake?.enable) {\n\t\ttry {\n\t\t\tconst placeAndTakeIx = await createPlaceAndTakePerpMarketOrderIx({\n\t\t\t\tassetType,\n\t\t\t\tamount,\n\t\t\t\tdirection,\n\t\t\t\tdlobServerHttpUrl,\n\t\t\t\tmarketIndex,\n\t\t\t\tdriftClient,\n\t\t\t\tuser,\n\t\t\t\tuserOrderId,\n\t\t\t\treferrerInfo: placeAndTake.referrerInfo,\n\t\t\t\tauctionDurationPercentage: placeAndTake.auctionDurationPercentage,\n\t\t\t\toptionalAuctionParamsInputs,\n\t\t\t});\n\t\t\tallIxs.push(placeAndTakeIx);\n\t\t} catch (e) {\n\t\t\tif (e instanceof NoTopMakersError) {\n\t\t\t\t// fallback to regular order\n\t\t\t\tallOrders.push(e.orderParams);\n\t\t\t} else {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tconst fetchedOrderParams = await fetchAuctionOrderParams({\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\tassetType,\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tamount,\n\t\t\tdlobServerHttpUrl,\n\t\t\toptionalAuctionParamsInputs,\n\t\t});\n\n\t\tconst oraclePrice =\n\t\t\tdriftClient.getOracleDataForPerpMarket(marketIndex).price;\n\t\tconst totalQuoteAmount = amount.mul(oraclePrice).div(PRICE_PRECISION);\n\n\t\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\t\tmarketIndex,\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\ttotalQuoteAmount,\n\t\t\tdirection\n\t\t);\n\n\t\tconst orderParams = {\n\t\t\t...fetchedOrderParams,\n\t\t\tuserOrderId,\n\t\t\tbitFlags,\n\t\t};\n\n\t\tallOrders.push(orderParams);\n\t}\n\n\tconst bracketOrdersDirection = ENUM_UTILS.match(\n\t\tdirection,\n\t\tPositionDirection.LONG\n\t)\n\t\t? PositionDirection.SHORT\n\t\t: PositionDirection.LONG;\n\n\tif (bracketOrders?.takeProfit) {\n\t\tconst takeProfitParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount: bracketOrders.takeProfit.baseAssetAmount ?? amount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'takeProfit',\n\t\t\t\ttriggerPrice: bracketOrders.takeProfit.triggerPrice,\n\t\t\t\tlimitPrice: bracketOrders.takeProfit.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: bracketOrders.takeProfit.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(takeProfitParams);\n\t}\n\n\tif (bracketOrders?.stopLoss) {\n\t\tconst stopLossParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount: bracketOrders.stopLoss.baseAssetAmount ?? amount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'stopLoss',\n\t\t\t\ttriggerPrice: bracketOrders.stopLoss.triggerPrice,\n\t\t\t\tlimitPrice: bracketOrders.stopLoss.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: bracketOrders.stopLoss.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(stopLossParams);\n\t}\n\n\t// Regular order flow - create transaction instruction\n\tif (allOrders.length > 0) {\n\t\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(allOrders);\n\t\tallIxs.push(placeOrderIx);\n\t}\n\n\treturn allIxs;\n};\n\n/**\n * Creates a complete transaction for opening a perp market order.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n *\n * @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)\n */\nexport const createOpenPerpMarketOrderTxn = async (\n\tparams: WithTxnParams<OpenPerpMarketOrderBaseParams>\n): Promise<Transaction | VersionedTransaction> => {\n\tconst { driftClient } = params;\n\n\t// Regular order flow - create transaction instruction and build transaction\n\tconst placeOrderIx = await createOpenPerpMarketOrderIxs(params);\n\tconst openPerpMarketOrderTxn = await driftClient.txHandler.buildTransaction({\n\t\tinstructions: placeOrderIx,\n\t\ttxVersion: 0,\n\t\tconnection: driftClient.connection,\n\t\tpreFlightCommitment: 'confirmed',\n\t\tfetchAllMarketLookupTableAccounts:\n\t\t\tdriftClient.fetchAllLookupTableAccounts.bind(driftClient),\n\t\ttxParams: params.txParams,\n\t});\n\n\treturn openPerpMarketOrderTxn;\n};\n\n/**\n * Creates a transaction or swift order for a perp market order.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will place the order\n * @param marketIndex - The perp market index to trade\n * @param direction - The direction of the trade (long/short)\n * @param amount - The amount to trade\n * @param optionalAuctionParamsInputs - Optional parameters for auction params endpoint and order configuration\n * @param dlobServerHttpUrl - Server URL for the auction params endpoint\n * @param useSwift - Whether to use Swift (signed message) orders instead of regular transactions\n * @param swiftOptions - Options for Swift (signed message) orders. Required if useSwift is true\n * @param userOrderId - The user order id for UI identification\n *\n * @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)\n */\nexport const createOpenPerpMarketOrder = async <T extends boolean>(\n\tparams: WithTxnParams<OpenPerpMarketOrderParams<T, SwiftOrderOptions>>\n): Promise<TxnOrSwiftResult<T>> => {\n\tconst { useSwift, swiftOptions, ...rest } = params;\n\n\t// If useSwift is true, return the Swift result directly\n\tif (useSwift) {\n\t\tif (!swiftOptions) {\n\t\t\tthrow new Error('swiftOptions is required when useSwift is true');\n\t\t}\n\n\t\tconst swiftOrderResult = await createSwiftMarketOrder({\n\t\t\t...rest,\n\t\t\tswiftOptions,\n\t\t});\n\n\t\treturn swiftOrderResult as TxnOrSwiftResult<T>;\n\t}\n\n\tconst openPerpMarketOrderTxn = await createOpenPerpMarketOrderTxn(rest);\n\n\treturn openPerpMarketOrderTxn as TxnOrSwiftResult<T>;\n};\n"]}
|
|
@@ -16,10 +16,13 @@ export interface OpenPerpNonMarketOrderBaseParams extends Omit<NonMarketOrderPar
|
|
|
16
16
|
export interface OpenPerpNonMarketOrderParamsWithSwift extends OpenPerpNonMarketOrderBaseParams {
|
|
17
17
|
swiftOptions: SwiftOrderOptions;
|
|
18
18
|
}
|
|
19
|
-
export
|
|
19
|
+
export type OpenPerpNonMarketOrderParams<T extends boolean = boolean, S extends Omit<SwiftOrderOptions, 'swiftServerUrl'> = Omit<SwiftOrderOptions, 'swiftServerUrl'>> = T extends true ? OpenPerpNonMarketOrderBaseParams & {
|
|
20
20
|
useSwift: T;
|
|
21
|
-
swiftOptions
|
|
22
|
-
}
|
|
21
|
+
swiftOptions: S;
|
|
22
|
+
} : OpenPerpNonMarketOrderBaseParams & {
|
|
23
|
+
useSwift: T;
|
|
24
|
+
swiftOptions?: never;
|
|
25
|
+
};
|
|
23
26
|
/**
|
|
24
27
|
* Creates a transaction instruction to open multiple non-market orders.
|
|
25
28
|
*/
|
|
@@ -44,4 +47,4 @@ export declare const createSwiftLimitOrder: (params: OpenPerpNonMarketOrderParam
|
|
|
44
47
|
orderConfig: LimitOrderParamsOrderConfig;
|
|
45
48
|
}) => Promise<void>;
|
|
46
49
|
export declare const createOpenPerpNonMarketOrderTxn: (params: WithTxnParams<OpenPerpNonMarketOrderBaseParams>) => Promise<Transaction | VersionedTransaction>;
|
|
47
|
-
export declare const createOpenPerpNonMarketOrder: <T extends boolean>(params: WithTxnParams<OpenPerpNonMarketOrderParams<T>>) => Promise<TxnOrSwiftResult<T>>;
|
|
50
|
+
export declare const createOpenPerpNonMarketOrder: <T extends boolean>(params: WithTxnParams<OpenPerpNonMarketOrderParams<T, SwiftOrderOptions>>) => Promise<TxnOrSwiftResult<T>>;
|
|
@@ -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,uE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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"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../../src/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.ts"],"names":[],"mappings":";;;;;;AAAA,yCAcyB;AAMzB,sDAG2B;AAC3B,kEAG0C;AAC1C,mDAAqD;AACrD,8CAAwD;AACxD,uEAG2C;AAC3C,gEAA6E;AAC7E,oEAAuC;AA8CvC,MAAM,0BAA0B,GAAG,KAAK,EAAE,EACzC,WAAW,EACX,IAAI,EACJ,WAAW,EACX,SAAS,EACT,eAAe,EACf,WAAW,GAAG,CAAC,EACf,UAAU,GAAG,KAAK,EAClB,QAAQ,GAAG,oBAAc,CAAC,IAAI,EAC9B,WAAW,GAMX,EAAgC,EAAE;IAClC,MAAM,WAAW,GAAG,MAAM,IAAA,oCAAuB,EAAC;QACjD,WAAW;QACX,IAAI;QACJ,SAAS,EAAE,MAAM;QACjB,WAAW;QACX,UAAU,EAAE,gBAAU,CAAC,IAAI;QAC3B,SAAS;QACT,MAAM,EAAE,eAAe;QACvB,iBAAiB,EAAE,WAAW,CAAC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\tPostOnlyParams,\n\tgetLimitOrderParams,\n\tOptionalOrderParams,\n\tPRICE_PRECISION_EXP,\n\tBigNum,\n\toraclePriceBands as getOraclePriceBands,\n\tPositionDirection,\n\tOrderParamsBitFlag,\n\tPRICE_PRECISION,\n} from '@drift-labs/sdk';\nimport {\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport {\n\tprepSignAndSendSwiftOrder,\n\tSwiftOrderOptions,\n} from '../openSwiftOrder';\nimport {\n\tbuildNonMarketOrderParams,\n\tresolveBaseAssetAmount,\n} from '../../../../../utils/orderParams';\nimport { ENUM_UTILS } from '../../../../../../utils';\nimport { fetchAuctionOrderParams } from '../dlobServer';\nimport {\n\tCOMMON_UI_UTILS,\n\tORDER_COMMON_UTILS,\n} from '../../../../../../common-ui-utils';\nimport { createPlaceAndTakePerpMarketOrderIx } from '../openPerpMarketOrder';\nimport invariant from 'tiny-invariant';\nimport {\n\tTxnOrSwiftResult,\n\tLimitAuctionConfig,\n\tLimitOrderParamsOrderConfig,\n\tNonMarketOrderParamsConfig,\n\tWithTxnParams,\n} from '../types';\n\nexport interface OpenPerpNonMarketOrderBaseParams\n\textends Omit<NonMarketOrderParamsConfig, 'marketType' | 'baseAssetAmount'> {\n\tdriftClient: DriftClient;\n\tuser: User;\n\t// Either new approach\n\tamount?: BN;\n\tassetType?: 'base' | 'quote';\n\t// Or legacy approach\n\tbaseAssetAmount?: BN;\n\t// Common optional params\n\treduceOnly?: boolean;\n\tpostOnly?: PostOnlyParams;\n\tuserOrderId?: number;\n\tautoEnterHighLeverageModeBufferPct?: number;\n}\n\nexport interface OpenPerpNonMarketOrderParamsWithSwift\n\textends OpenPerpNonMarketOrderBaseParams {\n\tswiftOptions: SwiftOrderOptions;\n}\n\nexport type OpenPerpNonMarketOrderParams<\n\tT extends boolean = boolean,\n\tS extends Omit<SwiftOrderOptions, 'swiftServerUrl'> = Omit<\n\t\tSwiftOrderOptions,\n\t\t'swiftServerUrl'\n\t>\n> = T extends true\n\t? OpenPerpNonMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tswiftOptions: S;\n\t }\n\t: OpenPerpNonMarketOrderBaseParams & {\n\t\t\tuseSwift: T;\n\t\t\tswiftOptions?: never;\n\t };\n\nconst getLimitAuctionOrderParams = async ({\n\tdriftClient,\n\tuser,\n\tmarketIndex,\n\tdirection,\n\tbaseAssetAmount,\n\tuserOrderId = 0,\n\treduceOnly = false,\n\tpostOnly = PostOnlyParams.NONE,\n\torderConfig,\n}: OpenPerpNonMarketOrderBaseParams & {\n\tbaseAssetAmount: BN;\n\torderConfig: LimitOrderParamsOrderConfig & {\n\t\tlimitAuction: LimitAuctionConfig;\n\t};\n}): Promise<OptionalOrderParams> => {\n\tconst orderParams = await fetchAuctionOrderParams({\n\t\tdriftClient,\n\t\tuser,\n\t\tassetType: 'base',\n\t\tmarketIndex,\n\t\tmarketType: MarketType.PERP,\n\t\tdirection,\n\t\tamount: baseAssetAmount,\n\t\tdlobServerHttpUrl: orderConfig.limitAuction.dlobServerHttpUrl,\n\t\toptionalAuctionParamsInputs:\n\t\t\torderConfig.limitAuction.optionalLimitAuctionParams,\n\t});\n\n\tconst perpMarketAccount = driftClient.getPerpMarketAccount(marketIndex);\n\n\tinvariant(perpMarketAccount, 'Perp market account not found');\n\tinvariant(orderConfig.limitAuction.oraclePrice, 'Oracle price not found');\n\tinvariant(orderParams.auctionStartPrice, 'Auction start price not found');\n\n\tconst oraclePriceBands = orderConfig.limitAuction.oraclePrice\n\t\t? getOraclePriceBands(perpMarketAccount, {\n\t\t\t\tprice: orderConfig.limitAuction.oraclePrice,\n\t\t })\n\t\t: undefined;\n\tconst auctionDuration = ORDER_COMMON_UTILS.getPerpAuctionDuration(\n\t\torderConfig.limitPrice.sub(orderParams.auctionStartPrice).abs(),\n\t\torderConfig.limitAuction.oraclePrice,\n\t\tperpMarketAccount.contractTier\n\t);\n\tconst limitAuctionParams = COMMON_UI_UTILS.getLimitAuctionParams({\n\t\tdirection,\n\t\tinputPrice: BigNum.from(orderConfig.limitPrice, PRICE_PRECISION_EXP),\n\t\tstartPriceFromSettings: orderParams.auctionStartPrice,\n\t\tduration: auctionDuration,\n\t\tauctionStartPriceOffset: orderConfig.limitAuction.auctionStartPriceOffset,\n\t\toraclePriceBands,\n\t});\n\n\tconst limitAuctionOrderParams = getLimitOrderParams({\n\t\tmarketIndex,\n\t\tmarketType: MarketType.PERP,\n\t\tdirection,\n\t\tbaseAssetAmount,\n\t\treduceOnly,\n\t\tpostOnly,\n\t\tprice: orderConfig.limitPrice,\n\t\tuserOrderId,\n\t\t...limitAuctionParams,\n\t});\n\n\tconst oraclePrice = driftClient.getOracleDataForPerpMarket(marketIndex).price;\n\tconst totalQuoteAmount = baseAssetAmount\n\t\t.mul(oraclePrice)\n\t\t.div(PRICE_PRECISION);\n\n\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\tmarketIndex,\n\t\tdriftClient,\n\t\tuser,\n\t\ttotalQuoteAmount,\n\t\tdirection\n\t);\n\n\treturn {\n\t\t...limitAuctionOrderParams,\n\t\tbitFlags,\n\t};\n};\n\n/**\n * Creates a transaction instruction to open multiple non-market orders.\n */\nexport const createMultipleOpenPerpNonMarketOrderIx = async (params: {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tmarketIndex: number;\n\tdirection: PositionDirection;\n\torderParamsConfigs: NonMarketOrderParamsConfig[];\n\tenterHighLeverageMode?: boolean;\n}): Promise<TransactionInstruction> => {\n\tconst { driftClient, orderParamsConfigs } = params;\n\n\tconst orderParams = orderParamsConfigs.map(buildNonMarketOrderParams);\n\n\tif (params.enterHighLeverageMode && orderParams.length > 0) {\n\t\torderParams[0].bitFlags = OrderParamsBitFlag.UpdateHighLeverageMode;\n\t}\n\n\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(orderParams);\n\treturn placeOrderIx;\n};\n\n/**\n * Creates a transaction instruction to open a non-market order.\n * Allows for bracket orders to be opened in the same transaction.\n *\n * If `limitAuction` is enabled, a placeAndTake order is created to simulate a market auction order,\n * with the end price being the limit price.\n */\nexport const createOpenPerpNonMarketOrderIxs = async (\n\tparams: OpenPerpNonMarketOrderBaseParams\n): Promise<TransactionInstruction[]> => {\n\tconst {\n\t\tdriftClient,\n\t\tuser,\n\t\tmarketIndex,\n\t\tdirection,\n\t\treduceOnly = false,\n\t\tpostOnly = PostOnlyParams.NONE,\n\t\torderConfig,\n\t\tuserOrderId = 0,\n\t} = params;\n\t// Support both new (amount + assetType) and legacy (baseAssetAmount) approaches\n\tconst finalBaseAssetAmount = resolveBaseAssetAmount({\n\t\tamount: 'amount' in params ? params.amount : undefined,\n\t\tassetType: 'assetType' in params ? params.assetType : undefined,\n\t\tbaseAssetAmount:\n\t\t\t'baseAssetAmount' in params ? params.baseAssetAmount : undefined,\n\t\tlimitPrice:\n\t\t\t'limitPrice' in params.orderConfig\n\t\t\t\t? params.orderConfig.limitPrice\n\t\t\t\t: undefined,\n\t});\n\n\tif (!finalBaseAssetAmount || finalBaseAssetAmount.isZero()) {\n\t\tthrow new Error('Final base asset amount must be greater than zero');\n\t}\n\n\tconst allOrders: OptionalOrderParams[] = [];\n\tconst allIxs: TransactionInstruction[] = [];\n\n\t// handle limit auction\n\tif (orderConfig.orderType === 'limit' && orderConfig.limitAuction?.enable) {\n\t\tconst limitAuctionOrderParams = await getLimitAuctionOrderParams({\n\t\t\t...params,\n\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\torderConfig: orderConfig as LimitOrderParamsOrderConfig & {\n\t\t\t\tlimitAuction: LimitAuctionConfig;\n\t\t\t},\n\t\t});\n\n\t\tlet createdPlaceAndTakeIx = false;\n\n\t\t// if it is a limit auction order, we create a placeAndTake order to simulate a market order.\n\t\t// this is useful when a limit order is crossing, and we want to achieve the best fill price through a placeAndTake.\n\t\t// falls back to limit order with auction params if the placeAndTake order creation fails\n\t\tif (\n\t\t\tlimitAuctionOrderParams.auctionDuration &&\n\t\t\tlimitAuctionOrderParams.auctionDuration > 0 &&\n\t\t\torderConfig.limitAuction?.usePlaceAndTake?.enable\n\t\t) {\n\t\t\ttry {\n\t\t\t\tconst placeAndTakeIx = await createPlaceAndTakePerpMarketOrderIx({\n\t\t\t\t\tassetType: 'base',\n\t\t\t\t\tamount: finalBaseAssetAmount,\n\t\t\t\t\tdirection,\n\t\t\t\t\tdlobServerHttpUrl: orderConfig.limitAuction.dlobServerHttpUrl,\n\t\t\t\t\tmarketIndex,\n\t\t\t\t\tdriftClient,\n\t\t\t\t\tuser,\n\t\t\t\t\tuserOrderId,\n\t\t\t\t\toptionalAuctionParamsInputs:\n\t\t\t\t\t\torderConfig.limitAuction.optionalLimitAuctionParams,\n\t\t\t\t\tauctionDurationPercentage:\n\t\t\t\t\t\torderConfig.limitAuction.usePlaceAndTake.auctionDurationPercentage,\n\t\t\t\t\treferrerInfo: orderConfig.limitAuction.usePlaceAndTake.referrerInfo,\n\t\t\t\t});\n\t\t\t\tallIxs.push(placeAndTakeIx);\n\t\t\t\tcreatedPlaceAndTakeIx = true;\n\t\t\t} catch (e) {\n\t\t\t\tconsole.error(\n\t\t\t\t\t'Failed to create placeAndTake order for limit auction order',\n\t\t\t\t\te\n\t\t\t\t);\n\t\t\t\tcreatedPlaceAndTakeIx = false;\n\t\t\t}\n\t\t}\n\n\t\t// fallback to normal limit order with auction params\n\t\tif (!createdPlaceAndTakeIx) {\n\t\t\tallOrders.push(limitAuctionOrderParams);\n\t\t}\n\t} else {\n\t\tconst orderParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection,\n\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\torderConfig,\n\t\t\treduceOnly,\n\t\t\tpostOnly,\n\t\t\tuserOrderId,\n\t\t});\n\n\t\tconst oraclePrice =\n\t\t\tdriftClient.getOracleDataForPerpMarket(marketIndex).price;\n\t\tconst totalQuoteAmount = finalBaseAssetAmount\n\t\t\t.mul(oraclePrice)\n\t\t\t.div(PRICE_PRECISION);\n\n\t\tconst bitFlags = ORDER_COMMON_UTILS.getPerpOrderParamsBitFlags(\n\t\t\tmarketIndex,\n\t\t\tdriftClient,\n\t\t\tuser,\n\t\t\ttotalQuoteAmount,\n\t\t\tdirection\n\t\t);\n\t\torderParams.bitFlags = bitFlags;\n\n\t\tallOrders.push(orderParams);\n\t}\n\n\tconst bracketOrdersDirection = ENUM_UTILS.match(\n\t\tdirection,\n\t\tPositionDirection.LONG\n\t)\n\t\t? PositionDirection.SHORT\n\t\t: PositionDirection.LONG;\n\n\tif ('bracketOrders' in orderConfig && orderConfig.bracketOrders?.takeProfit) {\n\t\tconst takeProfitParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount:\n\t\t\t\torderConfig.bracketOrders.takeProfit.baseAssetAmount ??\n\t\t\t\tfinalBaseAssetAmount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'takeProfit',\n\t\t\t\ttriggerPrice: orderConfig.bracketOrders.takeProfit.triggerPrice,\n\t\t\t\tlimitPrice: orderConfig.bracketOrders.takeProfit.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: orderConfig.bracketOrders.takeProfit.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(takeProfitParams);\n\t}\n\n\tif ('bracketOrders' in orderConfig && orderConfig.bracketOrders?.stopLoss) {\n\t\tconst stopLossParams = buildNonMarketOrderParams({\n\t\t\tmarketIndex,\n\t\t\tmarketType: MarketType.PERP,\n\t\t\tdirection: bracketOrdersDirection,\n\t\t\tbaseAssetAmount:\n\t\t\t\torderConfig.bracketOrders.stopLoss.baseAssetAmount ??\n\t\t\t\tfinalBaseAssetAmount,\n\t\t\torderConfig: {\n\t\t\t\torderType: 'stopLoss',\n\t\t\t\ttriggerPrice: orderConfig.bracketOrders.stopLoss.triggerPrice,\n\t\t\t\tlimitPrice: orderConfig.bracketOrders.stopLoss.limitPrice,\n\t\t\t},\n\t\t\treduceOnly: orderConfig.bracketOrders.stopLoss.reduceOnly ?? true,\n\t\t});\n\t\tallOrders.push(stopLossParams);\n\t}\n\n\tif (allOrders.length > 0) {\n\t\tconst placeOrderIx = await driftClient.getPlaceOrdersIx(allOrders);\n\t\tallIxs.push(placeOrderIx);\n\t}\n\n\treturn allIxs;\n};\n\nexport const MINIMUM_SWIFT_LIMIT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS = 35;\n\nexport const createSwiftLimitOrder = async (\n\tparams: OpenPerpNonMarketOrderParamsWithSwift & {\n\t\torderConfig: LimitOrderParamsOrderConfig;\n\t}\n): Promise<void> => {\n\tconst { driftClient, user, marketIndex, swiftOptions, orderConfig } = params;\n\n\tconst limitPrice = orderConfig.limitPrice;\n\n\tif (limitPrice.isZero()) {\n\t\tthrow new Error('LIMIT orders require limitPrice');\n\t}\n\n\t// Support both new (amount + assetType) and legacy (baseAssetAmount) approaches\n\tconst finalBaseAssetAmount = resolveBaseAssetAmount({\n\t\tamount: 'amount' in params ? params.amount : undefined,\n\t\tassetType: 'assetType' in params ? params.assetType : undefined,\n\t\tbaseAssetAmount:\n\t\t\t'baseAssetAmount' in params ? params.baseAssetAmount : undefined,\n\t\tlimitPrice,\n\t});\n\n\tconst orderParams = orderConfig.limitAuction?.enable\n\t\t? await getLimitAuctionOrderParams({\n\t\t\t\t...params,\n\t\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\t\torderConfig: orderConfig as LimitOrderParamsOrderConfig & {\n\t\t\t\t\tlimitAuction: LimitAuctionConfig;\n\t\t\t\t},\n\t\t })\n\t\t: buildNonMarketOrderParams({\n\t\t\t\tmarketIndex,\n\t\t\t\tmarketType: MarketType.PERP,\n\t\t\t\tdirection: params.direction,\n\t\t\t\tbaseAssetAmount: finalBaseAssetAmount,\n\t\t\t\torderConfig,\n\t\t\t\treduceOnly: params.reduceOnly,\n\t\t\t\tpostOnly: params.postOnly,\n\t\t\t\tuserOrderId: params.userOrderId,\n\t\t });\n\n\tconst userAccount = user.getUserAccount();\n\tconst slotBuffer = Math.max(\n\t\t(swiftOptions.signedMessageOrderSlotBuffer || 0) +\n\t\t\t(orderParams.auctionDuration || 0),\n\t\tMINIMUM_SWIFT_LIMIT_ORDER_SIGNING_EXPIRATION_BUFFER_SLOTS\n\t); // limit orders require a much larger buffer, to replace the auction duration usually found in market orders\n\n\tawait prepSignAndSendSwiftOrder({\n\t\tdriftClient,\n\t\tsubAccountId: userAccount.subAccountId,\n\t\tmarketIndex,\n\t\tslotBuffer,\n\t\tswiftOptions,\n\t\torderParams: {\n\t\t\tmain: orderParams,\n\t\t\ttakeProfit: orderConfig.bracketOrders?.takeProfit,\n\t\t\tstopLoss: orderConfig.bracketOrders?.stopLoss,\n\t\t},\n\t});\n};\n\nexport const createOpenPerpNonMarketOrderTxn = async (\n\tparams: WithTxnParams<OpenPerpNonMarketOrderBaseParams>\n): Promise<Transaction | VersionedTransaction> => {\n\tconst { driftClient } = params;\n\n\tconst instructions = await createOpenPerpNonMarketOrderIxs(params);\n\n\tconst openPerpNonMarketOrderTxn = await driftClient.buildTransaction(\n\t\tinstructions,\n\t\tparams.txParams\n\t);\n\n\treturn openPerpNonMarketOrderTxn;\n};\n\nexport const createOpenPerpNonMarketOrder = async <T extends boolean>(\n\tparams: WithTxnParams<OpenPerpNonMarketOrderParams<T, SwiftOrderOptions>>\n): Promise<TxnOrSwiftResult<T>> => {\n\tconst { swiftOptions, useSwift, orderConfig } = params;\n\n\t// If useSwift is true, return the Swift result directly\n\tif (useSwift) {\n\t\tif (orderConfig.orderType !== 'limit') {\n\t\t\tthrow new Error('Only limit orders are supported with Swift');\n\t\t}\n\n\t\tif (!swiftOptions) {\n\t\t\tthrow new Error('swiftOptions is required when useSwift is true');\n\t\t}\n\n\t\tif (\n\t\t\tparams.postOnly &&\n\t\t\t!ENUM_UTILS.match(params.postOnly, PostOnlyParams.NONE)\n\t\t) {\n\t\t\tthrow new Error('Post only orders are not supported with Swift');\n\t\t}\n\n\t\tconst swiftOrderResult = await createSwiftLimitOrder({\n\t\t\t...params,\n\t\t\tswiftOptions,\n\t\t\torderConfig,\n\t\t});\n\n\t\treturn swiftOrderResult as TxnOrSwiftResult<T>;\n\t}\n\n\tconst marketOrderTxn = await createOpenPerpNonMarketOrderTxn(params);\n\n\treturn marketOrderTxn as TxnOrSwiftResult<T>;\n};\n"]}
|
package/lib/drift/cli.js
CHANGED
|
@@ -386,9 +386,7 @@ async function openPerpMarketOrderCommand(args) {
|
|
|
386
386
|
marketIndex,
|
|
387
387
|
direction: directionEnum,
|
|
388
388
|
amount: amountBN,
|
|
389
|
-
dlobServerHttpUrl,
|
|
390
389
|
useSwift: false,
|
|
391
|
-
// TODO: why doesn't TS throw an error here for undefined swiftOptions?
|
|
392
390
|
});
|
|
393
391
|
await executeTransaction(orderTxn, 'Open Perp Order');
|
|
394
392
|
}
|
|
@@ -427,7 +425,6 @@ async function openPerpMarketOrderSwiftCommand(args) {
|
|
|
427
425
|
marketIndex,
|
|
428
426
|
direction: directionEnum,
|
|
429
427
|
amount: amountBN,
|
|
430
|
-
dlobServerHttpUrl,
|
|
431
428
|
useSwift: true,
|
|
432
429
|
swiftOptions: {
|
|
433
430
|
wallet: {
|
|
@@ -437,7 +434,6 @@ async function openPerpMarketOrderSwiftCommand(args) {
|
|
|
437
434
|
},
|
|
438
435
|
publicKey: wallet.publicKey,
|
|
439
436
|
},
|
|
440
|
-
swiftServerUrl,
|
|
441
437
|
callbacks: createSwiftOrderCallbacks('Open Perp Order'),
|
|
442
438
|
},
|
|
443
439
|
});
|
|
@@ -617,7 +613,6 @@ async function openPerpNonMarketOrderSwiftCommand(args) {
|
|
|
617
613
|
},
|
|
618
614
|
publicKey: wallet.publicKey,
|
|
619
615
|
},
|
|
620
|
-
swiftServerUrl,
|
|
621
616
|
callbacks: createSwiftOrderCallbacks('Open Perp Non-Market Order'),
|
|
622
617
|
};
|
|
623
618
|
console.log('\n👁️ Monitoring order status...');
|
package/lib/drift/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../../src/drift/cli.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0DAA4C;AAC5C,6CAAkE;AAClE,yCAYyB;AACzB,yCAAiC;AACjC,2EAAwE;AAExE,oCAAsC;AACtC,iDAA+C;AAC/C,2CAA6B;AAO7B,4CAA4C;AAC5C,MAAM,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;AACjC,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC;AAEzD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,uBAAuB;AACvB,IAAI,kBAAsC,CAAC;AAC3C,IAAI,MAAqB,CAAC;AAM1B;;GAEG;AACH,SAAS,SAAS,CAAC,IAAc;IAChC,MAAM,MAAM,GAAY,EAAE,CAAC;IAE3B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACtC,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;QACpB,IAAI,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;YAC1B,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YACjD,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;gBACzB,gCAAgC;gBAChC,IAAI,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;oBACzB,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;gBAChC,C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AC,OAAO,IAAI,KAAK,CAAC,CAAC;QAC9D,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACjB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import * as anchor from '@coral-xyz/anchor';\nimport { PublicKey, VersionedTransaction } from '@solana/web3.js';\nimport {\n\tBN,\n\tloadKeypair,\n\tPositionDirection,\n\tOrderType,\n\tPostOnlyParams,\n\tSwapMode,\n\tBASE_PRECISION,\n\tQUOTE_PRECISION,\n\tPRICE_PRECISION,\n\tMainnetSpotMarkets,\n\tDevnetSpotMarkets,\n} from '@drift-labs/sdk';\nimport { sign } from 'tweetnacl';\nimport { CentralServerDrift } from './Drift/clients/CentralServerDrift';\nimport { SwiftOrderOptions } from './base/actions/trade/openPerpOrder/openSwiftOrder';\nimport { ENUM_UTILS } from '../utils';\nimport { API_URLS } from './constants/apiUrls';\nimport * as path from 'path';\nimport {\n\tNonMarketOrderType,\n\tLimitOrderParamsOrderConfig,\n\tNonMarketOrderParamsConfig,\n} from './base/actions/trade/openPerpOrder/types';\n\n// Load environment variables from .env file\nconst dotenv = require('dotenv');\ndotenv.config({ path: path.resolve(__dirname, '.env') });\n\n/**\n * CLI Tool for CentralServerDrift client\n *\n * This CLI tool allows you to execute various Drift protocol operations via command line\n * with human-readable parameters that are automatically converted to the proper precision.\n *\n * Prerequisites:\n * - Create a .env file in the same directory as this CLI file with:\n * ANCHOR_WALLET=[private key byte array]\n * ENDPOINT=https://your-rpc-endpoint.com\n *\n * Usage Examples:\n * ts-node cli.ts deposit --marketIndex=0 --amount=2 --userAccount=11111111111111111111111111111111\n * ts-node cli.ts withdraw --marketIndex=0 --amount=1.5 --userAccount=11111111111111111111111111111111\n * ts-node cli.ts settleFunding --userAccount=11111111111111111111111111111111\n * ts-node cli.ts settlePnl --marketIndexes=0,1 --userAccount=11111111111111111111111111111111\n * ts-node cli.ts openPerpMarketOrder --marketIndex=0 --direction=long --amount=0.1 --assetType=base --userAccount=11111111111111111111111111111111\n * ts-node cli.ts openPerpMarketOrderSwift --marketIndex=0 --direction=short --amount=100 --assetType=quote --userAccount=11111111111111111111111111111111\n * ts-node cli.ts openPerpNonMarketOrder --marketIndex=0 --direction=long --baseAssetAmount=0.1 --orderType=limit --limitPrice=100 --userAccount=11111111111111111111111111111111\n * ts-node cli.ts openPerpNonMarketOrderSwift --marketIndex=0 --direction=long --baseAssetAmount=0.1 --orderType=limit --limitPrice=99.5 --userAccount=11111111111111111111111111111111\n * ts-node cli.ts editOrder --userAccount=11111111111111111111111111111111 --orderId=123 --newLimitPrice=105.5\n * ts-node cli.ts cancelOrder --userAccount=11111111111111111111111111111111 --orderIds=123,456,789\n * ts-node cli.ts cancelAllOrders --userAccount=11111111111111111111111111111111 --marketType=perp\n * ts-node cli.ts swap --userAccount=11111111111111111111111111111111 --fromMarketIndex=1 --toMarketIndex=0 --fromAmount=1.5 --slippage=100 --swapMode=ExactIn\n * ts-node cli.ts swap --userAccount=11111111111111111111111111111111 --fromMarketIndex=1 --toMarketIndex=0 --toAmount=150 --slippage=100 --swapMode=ExactOut\n */\n\n// Shared configuration\nlet centralServerDrift: CentralServerDrift;\nlet wallet: anchor.Wallet;\n\ninterface CliArgs {\n\t[key: string]: string | string[];\n}\n\n/**\n * Parse command line arguments into a key-value object\n */\nfunction parseArgs(args: string[]): CliArgs {\n\tconst parsed: CliArgs = {};\n\n\tfor (let i = 0; i < args.length; i++) {\n\t\tconst arg = args[i];\n\t\tif (arg.startsWith('--')) {\n\t\t\tconst [key, value] = arg.substring(2).split('=');\n\t\t\tif (value !== undefined) {\n\t\t\t\t// Handle comma-separated arrays\n\t\t\t\tif (value.includes(',')) {\n\t\t\t\t\tparsed[key] = value.split(',');\n\t\t\t\t} else {\n\t\t\t\t\tparsed[key] = value;\n\t\t\t\t}\n\t\t\t} else if (i + 1 < args.length && !args[i + 1].startsWith('--')) {\n\t\t\t\t// Handle space-separated values\n\t\t\t\tconst nextValue = args[i + 1];\n\t\t\t\tif (nextValue.includes(',')) {\n\t\t\t\t\tparsed[key] = nextValue.split(',');\n\t\t\t\t} else {\n\t\t\t\t\tparsed[key] = nextValue;\n\t\t\t\t}\n\t\t\t\ti++; // Skip the next argument as it's the value\n\t\t\t} else {\n\t\t\t\tparsed[key] = 'true'; // Boolean flag\n\t\t\t}\n\t\t}\n\t}\n\n\treturn parsed;\n}\n\n/**\n * Convert human-readable amount to BN with proper precision\n */\nfunction parseAmount(amount: string, precision: BN = QUOTE_PRECISION): BN {\n\tconst floatAmount = parseFloat(amount);\n\tif (isNaN(floatAmount)) {\n\t\tthrow new Error(`Invalid amount: ${amount}`);\n\t}\n\n\t// Convert to the proper precision\n\tconst scaledAmount = Math.floor(floatAmount * precision.toNumber());\n\treturn new BN(scaledAmount);\n}\n\n/**\n * Parse direction string to PositionDirection\n */\nfunction parseDirection(direction: string): PositionDirection {\n\tconst normalized = direction.toLowerCase();\n\tif (normalized === 'long' || normalized === 'buy') {\n\t\treturn PositionDirection.LONG;\n\t} else if (normalized === 'short' || normalized === 'sell') {\n\t\treturn PositionDirection.SHORT;\n\t} else {\n\t\tthrow new Error(\n\t\t\t`Invalid direction: ${direction}. Use 'long', 'short', 'buy', or 'sell'`\n\t\t);\n\t}\n}\n\n/**\n * Parse order type string to OrderType\n */\nfunction _parseOrderType(orderType: string): OrderType {\n\tconst normalized = orderType.toLowerCase();\n\tswitch (normalized) {\n\t\tcase 'limit':\n\t\t\treturn OrderType.LIMIT;\n\t\tcase 'market':\n\t\t\treturn OrderType.MARKET;\n\t\tcase 'oracle':\n\t\t\treturn OrderType.ORACLE;\n\t\tcase 'trigger_market':\n\t\tcase 'stopmarket':\n\t\t\treturn OrderType.TRIGGER_MARKET;\n\t\tcase 'trigger_limit':\n\t\tcase 'stoplimit':\n\t\t\treturn OrderType.TRIGGER_LIMIT;\n\t\tdefault:\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid order type: ${orderType}. Use 'limit', 'market', 'oracle', 'trigger_market', or 'trigger_limit'`\n\t\t\t);\n\t}\n}\n\n/**\n * Parse post only string to PostOnlyParams\n */\nfunction parsePostOnly(postOnly: string): PostOnlyParams {\n\tconst normalized = postOnly.toLowerCase();\n\tswitch (normalized) {\n\t\tcase 'none':\n\t\tcase 'false':\n\t\t\treturn PostOnlyParams.NONE;\n\t\tcase 'must_post_only':\n\t\tcase 'true':\n\t\t\treturn PostOnlyParams.MUST_POST_ONLY;\n\t\tcase 'try_post_only':\n\t\t\treturn PostOnlyParams.TRY_POST_ONLY;\n\t\tcase 'slide':\n\t\t\treturn PostOnlyParams.SLIDE;\n\t\tdefault:\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid post only: ${postOnly}. Use 'none', 'must_post_only', 'try_post_only', or 'slide'`\n\t\t\t);\n\t}\n}\n\n/**\n * Parse swap mode string to SwapMode\n */\nfunction parseSwapMode(swapMode: string): SwapMode {\n\tconst normalized = swapMode.toLowerCase();\n\tswitch (normalized) {\n\t\tcase 'exactin':\n\t\tcase 'exact_in':\n\t\t\treturn 'ExactIn';\n\t\tcase 'exactout':\n\t\tcase 'exact_out':\n\t\t\treturn 'ExactOut';\n\t\tdefault:\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid swap mode: ${swapMode}. Use 'ExactIn' or 'ExactOut'`\n\t\t\t);\n\t}\n}\n\n/**\n * Get the precision for a spot market based on environment and market index\n */\nfunction getMarketPrecision(\n\tmarketIndex: number,\n\tisMainnet: boolean = true\n): BN {\n\tconst markets = isMainnet ? MainnetSpotMarkets : DevnetSpotMarkets;\n\tconst market = markets.find((m) => m.marketIndex === marketIndex);\n\n\tif (!market) {\n\t\tconsole.warn(\n\t\t\t`⚠️ Market ${marketIndex} not found, using QUOTE_PRECISION as fallback`\n\t\t);\n\t\treturn QUOTE_PRECISION;\n\t}\n\n\treturn market.precision;\n}\n\n/**\n * Initialize CentralServerDrift instance\n */\nasync function initializeCentralServerDrift(): Promise<void> {\n\tconsole.log('🚀 Initializing CentralServerDrift...\\n');\n\n\t// Validate required environment variables\n\tif (!process.env.ANCHOR_WALLET) {\n\t\tthrow new Error('ANCHOR_WALLET must be set in .env file');\n\t}\n\n\tif (!process.env.ENDPOINT) {\n\t\tthrow new Error(\n\t\t\t'ENDPOINT environment variable must be set to your Solana RPC endpoint'\n\t\t);\n\t}\n\n\t// Set up the wallet\n\twallet = new anchor.Wallet(loadKeypair(process.env.ANCHOR_WALLET as string));\n\n\tconsole.log(`✅ Wallet Public Key: ${wallet.publicKey.toString()}`);\n\tconsole.log(`✅ RPC Endpoint: ${process.env.ENDPOINT}\\n`);\n\n\t// Initialize CentralServerDrift\n\tconsole.log('🏗️ Initializing CentralServerDrift...');\n\tcentralServerDrift = new CentralServerDrift({\n\t\tsolanaRpcEndpoint: process.env.ENDPOINT as string,\n\t\tdriftEnv: 'mainnet-beta', // Change to 'devnet' for devnet testing\n\t\tadditionalDriftClientConfig: {\n\t\t\ttxVersion: 0,\n\t\t\ttxParams: {\n\t\t\t\tcomputeUnits: 200000,\n\t\t\t\tcomputeUnitsPrice: 1000,\n\t\t\t},\n\t\t},\n\t});\n\n\tconsole.log('✅ CentralServerDrift instance created successfully\\n');\n\n\t// Subscribe to market data\n\tconsole.log('📡 Subscribing to market data...');\n\tawait centralServerDrift.subscribe();\n\tconsole.log('✅ Successfully subscribed to market data\\n');\n}\n\n/**\n * Execute a regular transaction\n */\nasync function executeTransaction(\n\ttxn: VersionedTransaction,\n\ttransactionType: string\n): Promise<void> {\n\tconsole.log(`✅ ${transactionType} transaction created successfully`);\n\tconsole.log('\\n📝 Signing Transaction...');\n\n\ttxn.sign([wallet.payer]);\n\tconsole.log('✅ Transaction signed successfully');\n\n\tconsole.log('\\n🚀 Sending transaction to the network...');\n\tconst { txSig } = await centralServerDrift.sendSignedTransaction(txn);\n\n\tconsole.log('✅ Transaction sent successfully!');\n\tconsole.log(`📋 Transaction Signature: ${txSig?.toString()}`);\n\tconsole.log(`🔍 View on Solscan: https://solscan.io/tx/${txSig?.toString()}`);\n}\n\nconst createSwiftOrderCallbacks = (\n\torderType: string\n): SwiftOrderOptions['callbacks'] => {\n\tconst terminalCall = () => {\n\t\tconsole.log('🏁 Order monitoring completed');\n\t};\n\n\treturn {\n\t\tonSigningExpiry: () => {\n\t\t\tconsole.log('Swift order signing expired');\n\t\t},\n\t\tonSigningSuccess: (signedMessage, orderUuid, orderParamsMessage) => {\n\t\t\tconsole.log(\n\t\t\t\t'Swift order signed successfully. Signed message:',\n\t\t\t\tsignedMessage,\n\t\t\t\torderUuid,\n\t\t\t\torderParamsMessage\n\t\t\t);\n\t\t},\n\t\tonSent: () => {\n\t\t\tconsole.log(`✅ ${orderType} Swift order submitted successfully`);\n\t\t},\n\t\tonConfirmed: (event) => {\n\t\t\tconsole.log('✅ Order confirmed!');\n\t\t\tconsole.log(`📋 Order ID: ${event.orderId}`);\n\t\t\tconsole.log(`📋 Hash: ${event.hash}`);\n\t\t\tterminalCall();\n\t\t},\n\t\tonExpired: (event) => {\n\t\t\tconsole.error('⏰ Order expired:', event.message);\n\t\t\tterminalCall();\n\t\t},\n\t\tonErrored: (event) => {\n\t\t\tconsole.error('❌ Order failed:', event.message);\n\t\t\tconsole.error(`📋 Status: ${event.status}`);\n\t\t\tterminalCall();\n\t\t},\n\t};\n};\n\n/**\n * CLI Command: deposit\n */\nasync function depositCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndex = parseInt(args.marketIndex as string);\n\tconst amount = args.amount as string;\n\n\tif (!userAccount || isNaN(marketIndex) || !amount) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndex, --amount'\n\t\t);\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst amountBN = parseAmount(amount, QUOTE_PRECISION); // Most deposits are USDC (quote precision)\n\n\tconsole.log('--- 📥 Deposit Transaction ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Index: ${marketIndex}`);\n\tconsole.log(`💰 Amount: ${amount} (${amountBN.toString()} raw units)`);\n\n\tconst depositTxn = await centralServerDrift.getDepositTxn(\n\t\tuserAccountPubkey,\n\t\tamountBN,\n\t\tmarketIndex\n\t);\n\n\tawait executeTransaction(depositTxn as VersionedTransaction, 'Deposit');\n}\n\n/**\n * CLI Command: withdraw\n */\nasync function withdrawCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndex = parseInt(args.marketIndex as string);\n\tconst amount = args.amount as string;\n\tconst isBorrow = args.isBorrow === 'true';\n\tconst isMax = args.isMax === 'true';\n\n\tif (!userAccount || isNaN(marketIndex) || !amount) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndex, --amount'\n\t\t);\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst amountBN = parseAmount(amount, QUOTE_PRECISION);\n\n\tconsole.log('--- 📤 Withdraw Transaction ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Index: ${marketIndex}`);\n\tconsole.log(`💰 Amount: ${amount} (${amountBN.toString()} raw units)`);\n\tconsole.log(`💳 Is Borrow: ${isBorrow}`);\n\tconsole.log(`📊 Is Max: ${isMax}`);\n\n\tconst withdrawTxn = await centralServerDrift.getWithdrawTxn(\n\t\tuserAccountPubkey,\n\t\tamountBN,\n\t\tmarketIndex,\n\t\t{ isBorrow, isMax }\n\t);\n\n\tawait executeTransaction(withdrawTxn as VersionedTransaction, 'Withdraw');\n}\n\n/**\n * CLI Command: settleFunding\n */\nasync function settleFundingCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\n\tif (!userAccount) {\n\t\tthrow new Error('Required arguments: --userAccount');\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\n\tconsole.log('--- 💰 Settle Funding Transaction ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\n\tconst settleFundingTxn = await centralServerDrift.getSettleFundingTxn(\n\t\tuserAccountPubkey\n\t);\n\n\tawait executeTransaction(\n\t\tsettleFundingTxn as VersionedTransaction,\n\t\t'Settle Funding'\n\t);\n}\n\n/**\n * CLI Command: settlePnl\n */\nasync function settlePnlCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndexesArg = args.marketIndexes;\n\n\tif (!userAccount || !marketIndexesArg) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndexes (comma-separated)'\n\t\t);\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst marketIndexes = Array.isArray(marketIndexesArg)\n\t\t? marketIndexesArg.map((idx) => parseInt(idx))\n\t\t: [parseInt(marketIndexesArg as string)];\n\n\tconsole.log('--- 📈 Settle PnL Transaction ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`📊 Market Indexes: ${marketIndexes.join(', ')}`);\n\n\tconst settlePnlTxn = await centralServerDrift.getSettlePnlTxn(\n\t\tuserAccountPubkey,\n\t\tmarketIndexes\n\t);\n\n\tawait executeTransaction(settlePnlTxn as VersionedTransaction, 'Settle PnL');\n}\n\n/**\n * CLI Command: openPerpMarketOrder (regular transaction)\n */\nasync function openPerpMarketOrderCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndex = parseInt(args.marketIndex as string);\n\tconst direction = args.direction as string;\n\tconst amount = args.amount as string;\n\tconst assetType = (args.assetType as string) || 'base';\n\tconst dlobServerHttpUrl = API_URLS.DLOB;\n\n\tif (!userAccount || isNaN(marketIndex) || !direction || !amount) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndex, --direction, --amount'\n\t\t);\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst directionEnum = parseDirection(direction);\n\tconst precision = assetType === 'base' ? BASE_PRECISION : QUOTE_PRECISION;\n\tconst amountBN = parseAmount(amount, precision);\n\n\tconsole.log('--- 🎯 Open Perp Order Transaction ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Index: ${marketIndex}`);\n\tconsole.log(\n\t\t`📊 Direction: ${direction} (${ENUM_UTILS.toStr(directionEnum)})`\n\t);\n\tconsole.log(`💰 Amount: ${amount} (${amountBN.toString()} raw units)`);\n\tconsole.log(`💱 Asset Type: ${assetType}`);\n\tconsole.log(`🌐 DLOB Server: ${dlobServerHttpUrl}`);\n\n\tconst orderTxn = await centralServerDrift.getOpenPerpMarketOrderTxn({\n\t\tuserAccountPublicKey: userAccountPubkey,\n\t\tassetType: assetType as 'base' | 'quote',\n\t\tmarketIndex,\n\t\tdirection: directionEnum,\n\t\tamount: amountBN,\n\t\tdlobServerHttpUrl,\n\t\tuseSwift: false,\n\t\t// TODO: why doesn't TS throw an error here for undefined swiftOptions?\n\t});\n\n\tawait executeTransaction(orderTxn as VersionedTransaction, 'Open Perp Order');\n}\n\n/**\n * CLI Command: openPerpMarketOrderSwift (Swift signed message order)\n */\nasync function openPerpMarketOrderSwiftCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndex = parseInt(args.marketIndex as string);\n\tconst direction = args.direction as string;\n\tconst amount = args.amount as string;\n\tconst assetType = (args.assetType as string) || 'base';\n\tconst dlobServerHttpUrl = API_URLS.DLOB;\n\tconst swiftServerUrl = (args.swiftServerUrl as string) || API_URLS.SWIFT;\n\n\tif (!userAccount || isNaN(marketIndex) || !direction || !amount) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndex, --direction, --amount'\n\t\t);\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst directionEnum = parseDirection(direction);\n\tconst precision = assetType === 'base' ? BASE_PRECISION : QUOTE_PRECISION;\n\tconst amountBN = parseAmount(amount, precision);\n\n\tconsole.log('--- ⚡ Open Perp Order Swift ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Index: ${marketIndex}`);\n\tconsole.log(\n\t\t`📊 Direction: ${direction} (${ENUM_UTILS.toStr(directionEnum)})`\n\t);\n\tconsole.log(`💰 Amount: ${amount} (${amountBN.toString()} raw units)`);\n\tconsole.log(`💱 Asset Type: ${assetType}`);\n\tconsole.log(`🌐 DLOB Server: ${dlobServerHttpUrl}`);\n\tconsole.log(`⚡ Swift Server: ${swiftServerUrl}`);\n\tconsole.log(`🔑 Wallet Public Key: ${wallet.publicKey.toString()}`);\n\n\tconsole.log('\\n👁️ Monitoring order status...');\n\n\ttry {\n\t\tawait centralServerDrift.getOpenPerpMarketOrderTxn({\n\t\t\tuserAccountPublicKey: userAccountPubkey,\n\t\t\tassetType: assetType as 'base' | 'quote',\n\t\t\tmarketIndex,\n\t\t\tdirection: directionEnum,\n\t\t\tamount: amountBN,\n\t\t\tdlobServerHttpUrl,\n\t\t\tuseSwift: true,\n\t\t\tswiftOptions: {\n\t\t\t\twallet: {\n\t\t\t\t\tsignMessage: async (message: Uint8Array) => {\n\t\t\t\t\t\tconst signature = sign.detached(message, wallet.payer.secretKey);\n\t\t\t\t\t\treturn new Uint8Array(signature);\n\t\t\t\t\t},\n\t\t\t\t\tpublicKey: wallet.publicKey,\n\t\t\t\t},\n\t\t\t\tswiftServerUrl,\n\t\t\t\tcallbacks: createSwiftOrderCallbacks('Open Perp Order'),\n\t\t\t},\n\t\t});\n\t\tconsole.log('✅ [CLI] Swift order finished');\n\t} catch (error) {\n\t\tconsole.error('❌ [CLI] Error creating Swift order:', error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * CLI Command: openPerpNonMarketOrder (regular limit/oracle order)\n */\nasync function openPerpNonMarketOrderCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndex = parseInt(args.marketIndex as string);\n\tconst direction = args.direction as string;\n\tconst amount = args.amount as string;\n\tconst assetType = (args.assetType as string) || 'base';\n\tconst baseAssetAmount = args.baseAssetAmount as string;\n\tconst orderType = args.orderType as NonMarketOrderType;\n\tconst limitPrice = args.limitPrice as string;\n\tconst triggerPrice = args.triggerPrice as string;\n\tconst reduceOnly = (args.reduceOnly as string) === 'true';\n\tconst postOnly = (args.postOnly as string) || 'none';\n\tconst oraclePriceOffset = args.oraclePriceOffset as string;\n\n\tif (!userAccount || isNaN(marketIndex) || !direction || !orderType) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndex, --direction, --orderType'\n\t\t);\n\t}\n\n\tif (!amount && !baseAssetAmount) {\n\t\tthrow new Error('Either --amount or --baseAssetAmount must be provided');\n\t}\n\n\t// Validate price requirements based on order type\n\tif (orderType === 'limit') {\n\t\tif (!limitPrice) {\n\t\t\tthrow new Error(`Order type '${orderType}' requires --limitPrice`);\n\t\t}\n\t} else if (orderType === 'takeProfit' || orderType === 'stopLoss') {\n\t\tif (!triggerPrice) {\n\t\t\tthrow new Error(`Order type '${orderType}' requires --triggerPrice`);\n\t\t}\n\t} else if (orderType === 'oracleLimit') {\n\t\tif (!oraclePriceOffset) {\n\t\t\tthrow new Error(`Order type '${orderType}' requires --oraclePriceOffset`);\n\t\t}\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst directionEnum = parseDirection(direction);\n\tconst postOnlyEnum = parsePostOnly(postOnly);\n\tconst limitPriceBN = limitPrice\n\t\t? parseAmount(limitPrice, PRICE_PRECISION)\n\t\t: undefined;\n\tconst triggerPriceBN = triggerPrice\n\t\t? parseAmount(triggerPrice, PRICE_PRECISION)\n\t\t: undefined;\n\tconst oraclePriceOffsetBN = oraclePriceOffset\n\t\t? parseAmount(oraclePriceOffset, PRICE_PRECISION)\n\t\t: undefined;\n\n\tconst orderConfig: NonMarketOrderParamsConfig['orderConfig'] =\n\t\torderType === 'limit'\n\t\t\t? {\n\t\t\t\t\torderType,\n\t\t\t\t\tlimitPrice: limitPriceBN!,\n\t\t\t }\n\t\t\t: orderType === 'takeProfit' || orderType === 'stopLoss'\n\t\t\t? {\n\t\t\t\t\torderType,\n\t\t\t\t\ttriggerPrice: triggerPriceBN!,\n\t\t\t }\n\t\t\t: {\n\t\t\t\t\torderType,\n\t\t\t\t\toraclePriceOffset: oraclePriceOffsetBN!,\n\t\t\t };\n\n\tconsole.log('--- 📋 Open Perp Non-Market Order ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Index: ${marketIndex}`);\n\tconsole.log(\n\t\t`📊 Direction: ${direction} (${ENUM_UTILS.toStr(directionEnum)})`\n\t);\n\n\tlet amountBN: BN;\n\tif (amount) {\n\t\tconst precision = assetType === 'base' ? BASE_PRECISION : QUOTE_PRECISION;\n\t\tamountBN = parseAmount(amount, precision);\n\t\tconsole.log(`💰 Amount: ${amount} (${amountBN.toString()} raw units)`);\n\t\tconsole.log(`💱 Asset Type: ${assetType}`);\n\t} else {\n\t\tamountBN = parseAmount(baseAssetAmount, BASE_PRECISION);\n\t\tconsole.log(\n\t\t\t`💰 Base Asset Amount: ${baseAssetAmount} (${amountBN.toString()} raw units)`\n\t\t);\n\t}\n\n\tif (limitPriceBN) {\n\t\tconsole.log(\n\t\t\t`💵 Limit Price: ${limitPrice} (${limitPriceBN.toString()} raw units)`\n\t\t);\n\t}\n\tif (triggerPriceBN) {\n\t\tconsole.log(\n\t\t\t`🎯 Trigger Price: ${triggerPrice} (${triggerPriceBN.toString()} raw units)`\n\t\t);\n\t}\n\tconsole.log(`📝 Order Type: ${orderType}`);\n\tconsole.log(`🔄 Reduce Only: ${reduceOnly}`);\n\tconsole.log(`📌 Post Only: ${postOnly} (${ENUM_UTILS.toStr(postOnlyEnum)})`);\n\n\t// Just call the main method - it will handle both approaches internally\n\tconst orderTxn = await centralServerDrift.getOpenPerpNonMarketOrderTxn({\n\t\tuserAccountPublicKey: userAccountPubkey,\n\t\tmarketIndex,\n\t\tdirection: directionEnum,\n\t\torderConfig,\n\t\tuseSwift: false,\n\t\treduceOnly,\n\t\tpostOnly: postOnlyEnum,\n\t\tassetType: assetType as 'base' | 'quote',\n\t\tamount: amountBN,\n\t});\n\n\tawait executeTransaction(\n\t\torderTxn as VersionedTransaction,\n\t\t'Open Perp Non-Market Order'\n\t);\n}\n\n/**\n * CLI Command: openPerpNonMarketOrderSwift (Swift signed message limit order)\n */\nasync function openPerpNonMarketOrderSwiftCommand(\n\targs: CliArgs\n): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndex = parseInt(args.marketIndex as string);\n\tconst direction = args.direction as string;\n\tconst amount = args.amount as string;\n\tconst assetType = (args.assetType as string) || 'base';\n\tconst baseAssetAmount = args.baseAssetAmount as string;\n\tconst orderType = args.orderType as NonMarketOrderType;\n\tconst limitPrice = args.limitPrice as string;\n\tconst reduceOnly = (args.reduceOnly as string) === 'true';\n\tconst postOnly = (args.postOnly as string) || 'none';\n\tconst swiftServerUrl = API_URLS.SWIFT;\n\n\tif (!userAccount || isNaN(marketIndex) || !direction || !orderType) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndex, --direction, --orderType'\n\t\t);\n\t}\n\n\tif (!amount && !baseAssetAmount) {\n\t\tthrow new Error('Either --amount or --baseAssetAmount must be provided');\n\t}\n\n\t// Swift orders only support LIMIT order type\n\tif (orderType.toLowerCase() !== 'limit') {\n\t\tthrow new Error('Swift orders only support LIMIT order type');\n\t}\n\n\t// LIMIT orders require limitPrice\n\tif (!limitPrice) {\n\t\tthrow new Error('LIMIT orders require --limitPrice');\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst directionEnum = parseDirection(direction);\n\tconst postOnlyEnum = parsePostOnly(postOnly);\n\tconst limitPriceBN = parseAmount(limitPrice, PRICE_PRECISION);\n\n\tconst orderConfig: LimitOrderParamsOrderConfig = {\n\t\torderType: 'limit',\n\t\tlimitPrice: limitPriceBN!,\n\t};\n\n\tconsole.log('--- ⚡ Open Perp Non-Market Order Swift ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Index: ${marketIndex}`);\n\tconsole.log(\n\t\t`📊 Direction: ${direction} (${ENUM_UTILS.toStr(directionEnum)})`\n\t);\n\n\tlet amountBN: BN;\n\tif (amount) {\n\t\tconst precision = assetType === 'base' ? BASE_PRECISION : QUOTE_PRECISION;\n\t\tamountBN = parseAmount(amount, precision);\n\t\tconsole.log(`💰 Amount: ${amount} (${amountBN.toString()} raw units)`);\n\t\tconsole.log(`💱 Asset Type: ${assetType}`);\n\t} else {\n\t\tamountBN = parseAmount(baseAssetAmount, BASE_PRECISION);\n\t\tconsole.log(\n\t\t\t`💰 Base Asset Amount: ${baseAssetAmount} (${amountBN.toString()} raw units)`\n\t\t);\n\t}\n\n\tconsole.log(\n\t\t`💵 Limit Price: ${limitPrice} (${limitPriceBN.toString()} raw units)`\n\t);\n\tconsole.log(`📝 Order Type: ${orderType})`);\n\tconsole.log(`🔄 Reduce Only: ${reduceOnly}`);\n\tconsole.log(`📌 Post Only: ${postOnly} (${ENUM_UTILS.toStr(postOnlyEnum)})`);\n\tconsole.log(`⚡ Swift Server: ${swiftServerUrl}`);\n\tconsole.log(`🔑 Wallet Public Key: ${wallet.publicKey.toString()}`);\n\n\ttry {\n\t\tconst swiftOptions: SwiftOrderOptions = {\n\t\t\twallet: {\n\t\t\t\tsignMessage: async (message: Uint8Array) => {\n\t\t\t\t\tconst signature = sign.detached(message, wallet.payer.secretKey);\n\t\t\t\t\treturn new Uint8Array(signature);\n\t\t\t\t},\n\t\t\t\tpublicKey: wallet.publicKey,\n\t\t\t},\n\t\t\tswiftServerUrl,\n\t\t\tcallbacks: createSwiftOrderCallbacks('Open Perp Non-Market Order'),\n\t\t};\n\n\t\tconsole.log('\\n👁️ Monitoring order status...');\n\n\t\t// Use the main method - it handles both approaches internally\n\t\tawait centralServerDrift.getOpenPerpNonMarketOrderTxn({\n\t\t\tuserAccountPublicKey: userAccountPubkey,\n\t\t\tmarketIndex,\n\t\t\tdirection: directionEnum,\n\t\t\torderConfig,\n\t\t\treduceOnly,\n\t\t\tpostOnly: postOnlyEnum,\n\t\t\tassetType: assetType as 'base' | 'quote',\n\t\t\tamount: amountBN,\n\t\t\tuseSwift: true,\n\t\t\tswiftOptions,\n\t\t});\n\n\t\tconsole.log('✅ [CLI] Swift order finished');\n\t} catch (error) {\n\t\tconsole.error('❌ [CLI] Error creating Swift non-market order:', error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * Show CLI usage information\n */\nfunction showUsage(): void {\n\tconsole.log('📋 Drift CLI Usage');\n\tconsole.log('');\n\tconsole.log('Available Commands:');\n\tconsole.log('');\n\n\tconsole.log('💰 deposit');\n\tconsole.log(\n\t\t' ts-node cli.ts deposit --userAccount=<pubkey> --marketIndex=<num> --amount=<num>'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts deposit --userAccount=11111111111111111111111111111111 --marketIndex=0 --amount=100'\n\t);\n\tconsole.log('');\n\n\tconsole.log('💸 withdraw');\n\tconsole.log(\n\t\t' ts-node cli.ts withdraw --userAccount=<pubkey> --marketIndex=<num> --amount=<num> [--isBorrow=<bool>] [--isMax=<bool>]'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts withdraw --userAccount=11111111111111111111111111111111 --marketIndex=0 --amount=50'\n\t);\n\tconsole.log('');\n\n\tconsole.log('🏦 settleFunding');\n\tconsole.log(' ts-node cli.ts settleFunding --userAccount=<pubkey>');\n\tconsole.log(\n\t\t' Example: ts-node cli.ts settleFunding --userAccount=11111111111111111111111111111111'\n\t);\n\tconsole.log('');\n\n\tconsole.log('📊 settlePnl');\n\tconsole.log(\n\t\t' ts-node cli.ts settlePnl --userAccount=<pubkey> --marketIndexes=<comma-separated>'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts settlePnl --userAccount=11111111111111111111111111111111 --marketIndexes=0,1'\n\t);\n\tconsole.log('');\n\n\tconsole.log('🎯 openPerpMarketOrder');\n\tconsole.log(\n\t\t' ts-node cli.ts openPerpMarketOrder --userAccount=<pubkey> --marketIndex=<num> --direction=<long|short> --amount=<num> [--assetType=<base|quote>]'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts openPerpMarketOrder --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=long --amount=0.1 --assetType=base'\n\t);\n\tconsole.log('');\n\n\tconsole.log('⚡ openPerpMarketOrderSwift');\n\tconsole.log(\n\t\t' ts-node cli.ts openPerpMarketOrderSwift --userAccount=<pubkey> --marketIndex=<num> --direction=<long|short> --amount=<num> [--assetType=<base|quote>]'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts openPerpMarketOrderSwift --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=short --amount=100 --assetType=quote'\n\t);\n\tconsole.log('');\n\n\tconsole.log('📋 openPerpNonMarketOrder');\n\tconsole.log(\n\t\t' ts-node cli.ts openPerpNonMarketOrder --userAccount=<pubkey> --marketIndex=<num> --direction=<long|short> --amount=<num> [--assetType=<base|quote>] --orderType=<limit|trigger_limit|trigger_market|oracle> [--limitPrice=<num>] [--triggerPrice=<num>] [--reduceOnly=<true|false>] [--postOnly=<none|must_post_only|try_post_only|slide>]'\n\t);\n\tconsole.log(\n\t\t' New LIMIT: ts-node cli.ts openPerpNonMarketOrder --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=long --amount=0.1 --assetType=base --orderType=limit --limitPrice=100'\n\t);\n\tconsole.log(\n\t\t' New QUOTE: ts-node cli.ts openPerpNonMarketOrder --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=long --amount=100 --assetType=quote --orderType=limit --limitPrice=100'\n\t);\n\tconsole.log(\n\t\t' Legacy: ts-node cli.ts openPerpNonMarketOrder --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=long --baseAssetAmount=0.1 --orderType=limit --limitPrice=100'\n\t);\n\tconsole.log('');\n\n\tconsole.log('⚡ openPerpNonMarketOrderSwift');\n\tconsole.log(\n\t\t' ts-node cli.ts openPerpNonMarketOrderSwift --userAccount=<pubkey> --marketIndex=<num> --direction=<long|short> --amount=<num> [--assetType=<base|quote>] --orderType=limit --limitPrice=<num> [--reduceOnly=<true|false>] [--postOnly=<none|must_post_only|try_post_only|slide>]'\n\t);\n\tconsole.log(\n\t\t' New: ts-node cli.ts openPerpNonMarketOrderSwift --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=long --amount=0.1 --assetType=base --orderType=limit --limitPrice=99.5'\n\t);\n\tconsole.log(\n\t\t' Legacy: ts-node cli.ts openPerpNonMarketOrderSwift --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=long --baseAssetAmount=0.1 --orderType=limit --limitPrice=99.5'\n\t);\n\tconsole.log('');\n\n\tconsole.log('✏️ editOrder');\n\tconsole.log(\n\t\t' ts-node cli.ts editOrder --userAccount=<pubkey> --orderId=<num> [--newDirection=<long|short>] [--newBaseAmount=<num>] [--newLimitPrice=<num>] [--newTriggerPrice=<num>] [--reduceOnly=<true|false>] [--postOnly=<true|false>]'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts editOrder --userAccount=11111111111111111111111111111111 --orderId=123 --newLimitPrice=105.5'\n\t);\n\tconsole.log('');\n\n\tconsole.log('❌ cancelOrder');\n\tconsole.log(\n\t\t' ts-node cli.ts cancelOrder --userAccount=<pubkey> --orderIds=<comma-separated-list>'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts cancelOrder --userAccount=11111111111111111111111111111111 --orderIds=123,456,789'\n\t);\n\tconsole.log('');\n\n\tconsole.log('🧹 cancelAllOrders');\n\tconsole.log(\n\t\t' ts-node cli.ts cancelAllOrders --userAccount=<pubkey> [--marketType=<perp|spot>] [--marketIndex=<num>] [--direction=<long|short>]'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts cancelAllOrders --userAccount=11111111111111111111111111111111 --marketType=perp'\n\t);\n\tconsole.log('');\n\n\tconsole.log('🔄 swap');\n\tconsole.log(\n\t\t' ts-node cli.ts swap --userAccount=<pubkey> --fromMarketIndex=<num> --toMarketIndex=<num> [--fromAmount=<num>] [--toAmount=<num>] [--slippage=<bps>] [--swapMode=<ExactIn|ExactOut>]'\n\t);\n\tconsole.log(\n\t\t' ExactIn: ts-node cli.ts swap --userAccount=11111111111111111111111111111111 --fromMarketIndex=1 --toMarketIndex=0 --fromAmount=1.5 --swapMode=ExactIn'\n\t);\n\tconsole.log(\n\t\t' ExactOut: ts-node cli.ts swap --userAccount=11111111111111111111111111111111 --fromMarketIndex=1 --toMarketIndex=0 --toAmount=150 --swapMode=ExactOut'\n\t);\n\tconsole.log('');\n\n\tconsole.log('Options:');\n\tconsole.log(' --help, -h Show this help message');\n\tconsole.log('');\n\tconsole.log('Notes:');\n\tconsole.log(\n\t\t' - Amounts are in human-readable format (e.g., 1.5 USDC, 0.1 SOL)'\n\t);\n\tconsole.log(' - Direction can be: long, short, buy, sell');\n\tconsole.log(\n\t\t' - Asset type: base (for native tokens like SOL) or quote (for USDC amounts)'\n\t);\n\tconsole.log(' - Swap modes:');\n\tconsole.log(\n\t\t' * ExactIn: Specify --fromAmount (how much input token to swap)'\n\t);\n\tconsole.log(\n\t\t' * ExactOut: Specify --toAmount (how much output token to receive)'\n\t);\n\tconsole.log(' - Ensure your .env file contains ANCHOR_WALLET and ENDPOINT');\n}\n\n/**\n * CLI Command: editOrder\n */\nasync function editOrderCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst orderId = parseInt(args.orderId as string);\n\tconst newDirection = args.newDirection as string;\n\tconst newBaseAmount = args.newBaseAmount as string;\n\tconst newLimitPrice = args.newLimitPrice as string;\n\tconst newTriggerPrice = args.newTriggerPrice as string;\n\tconst reduceOnly = (args.reduceOnly as string) === 'true';\n\tconst postOnly = (args.postOnly as string) === 'true';\n\n\tif (!userAccount || isNaN(orderId)) {\n\t\tthrow new Error('Required arguments: --userAccount, --orderId');\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst editParams: any = {};\n\n\tif (newDirection) {\n\t\teditParams.newDirection = parseDirection(newDirection);\n\t}\n\n\tif (newBaseAmount) {\n\t\teditParams.newBaseAmount = parseAmount(newBaseAmount, BASE_PRECISION);\n\t}\n\n\tif (newLimitPrice) {\n\t\teditParams.newLimitPrice = parseAmount(newLimitPrice, PRICE_PRECISION);\n\t}\n\n\tif (newTriggerPrice) {\n\t\teditParams.newTriggerPrice = parseAmount(newTriggerPrice, PRICE_PRECISION);\n\t}\n\n\tif (reduceOnly) {\n\t\teditParams.reduceOnly = true;\n\t}\n\n\tif (postOnly) {\n\t\teditParams.postOnly = true;\n\t}\n\n\tconsole.log('--- ✏️ Edit Order ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🆔 Order ID: ${orderId}`);\n\tconsole.log(`📝 Edit Parameters:`, editParams);\n\n\tconst editOrderTxn = await centralServerDrift.getEditOrderTxn(\n\t\tuserAccountPubkey,\n\t\torderId,\n\t\teditParams\n\t);\n\n\tawait executeTransaction(editOrderTxn as VersionedTransaction, 'Edit Order');\n}\n\n/**\n * CLI Command: cancelOrder\n */\nasync function cancelOrderCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst orderIds = args.orderIds as string;\n\n\tif (!userAccount || !orderIds) {\n\t\tthrow new Error('Required arguments: --userAccount, --orderIds');\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst orderIdArray = orderIds.split(',').map((id) => parseInt(id.trim()));\n\n\tconsole.log('--- ❌ Cancel Orders ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🆔 Order IDs: ${orderIdArray.join(', ')}`);\n\n\tconst cancelOrderTxn = await centralServerDrift.getCancelOrdersTxn(\n\t\tuserAccountPubkey,\n\t\torderIdArray\n\t);\n\n\tawait executeTransaction(\n\t\tcancelOrderTxn as VersionedTransaction,\n\t\t'Cancel Orders'\n\t);\n}\n\n/**\n * CLI Command: cancelAllOrders\n */\nasync function cancelAllOrdersCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketType = args.marketType as string;\n\tconst marketIndex = args.marketIndex\n\t\t? parseInt(args.marketIndex as string)\n\t\t: undefined;\n\tconst direction = args.direction as string;\n\n\tif (!userAccount) {\n\t\tthrow new Error('Required arguments: --userAccount');\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tlet marketTypeEnum = undefined;\n\tlet directionEnum = undefined;\n\n\tif (marketType) {\n\t\tmarketTypeEnum =\n\t\t\tmarketType.toLowerCase() === 'perp' ? { perp: {} } : { spot: {} };\n\t}\n\n\tif (direction) {\n\t\tdirectionEnum = parseDirection(direction);\n\t}\n\n\tconsole.log('--- 🧹 Cancel All Orders ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Type Filter: ${marketType || 'none'}`);\n\tconsole.log(\n\t\t`📊 Market Index Filter: ${\n\t\t\tmarketIndex !== undefined ? marketIndex : 'none'\n\t\t}`\n\t);\n\tconsole.log(`📈 Direction Filter: ${direction || 'none'}`);\n\n\tconst cancelAllOrdersTxn = await centralServerDrift.getCancelAllOrdersTxn(\n\t\tuserAccountPubkey,\n\t\tmarketTypeEnum,\n\t\tmarketIndex,\n\t\tdirectionEnum\n\t);\n\n\tawait executeTransaction(\n\t\tcancelAllOrdersTxn as VersionedTransaction,\n\t\t'Cancel All Orders'\n\t);\n}\n\n/**\n * CLI Command: swap\n */\nasync function swapCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst fromMarketIndex = parseInt(args.fromMarketIndex as string);\n\tconst toMarketIndex = parseInt(args.toMarketIndex as string);\n\tconst fromAmount = args.fromAmount as string;\n\tconst toAmount = args.toAmount as string;\n\tconst slippage = args.slippage ? parseInt(args.slippage as string) : 10; // Default 0.1%\n\tconst swapMode = (args.swapMode as string) || 'ExactIn';\n\n\tif (!userAccount || isNaN(fromMarketIndex) || isNaN(toMarketIndex)) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --fromMarketIndex, --toMarketIndex'\n\t\t);\n\t}\n\n\tconst swapModeEnum = parseSwapMode(swapMode);\n\n\t// Validate amount parameters based on swap mode\n\tif (swapModeEnum === 'ExactIn') {\n\t\tif (!fromAmount) {\n\t\t\tthrow new Error('ExactIn swap mode requires --fromAmount');\n\t\t}\n\t\tif (toAmount) {\n\t\t\tconsole.warn(\n\t\t\t\t'⚠️ Warning: --toAmount ignored in ExactIn mode, using --fromAmount'\n\t\t\t);\n\t\t}\n\t} else if (swapModeEnum === 'ExactOut') {\n\t\tif (!toAmount) {\n\t\t\tthrow new Error('ExactOut swap mode requires --toAmount');\n\t\t}\n\t\tif (fromAmount) {\n\t\t\tconsole.warn(\n\t\t\t\t'⚠️ Warning: --fromAmount ignored in ExactOut mode, using --toAmount'\n\t\t\t);\n\t\t}\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\n\t// Use the appropriate amount based on swap mode\n\tconst amount = swapModeEnum === 'ExactIn' ? fromAmount : toAmount;\n\n\t// Determine which market to use for precision (input market for ExactIn, output market for ExactOut)\n\tconst precisionMarketIndex =\n\t\tswapModeEnum === 'ExactIn' ? fromMarketIndex : toMarketIndex;\n\n\t// Get the appropriate precision for the amount based on the market\n\tconst isMainnet = true; // Default to mainnet, could be made configurable\n\tconst precision = getMarketPrecision(precisionMarketIndex, isMainnet);\n\tconst amountBN = parseAmount(amount, precision);\n\n\tconsole.log('--- 🔄 Swap Transaction ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`📤 From Market Index: ${fromMarketIndex}`);\n\tconsole.log(`📥 To Market Index: ${toMarketIndex}`);\n\tconsole.log(`🔄 Swap Mode: ${swapMode}`);\n\tconsole.log(\n\t\t`🎯 Using precision from market ${precisionMarketIndex}: ${precision.toString()}`\n\t);\n\n\tif (swapModeEnum === 'ExactIn') {\n\t\tconsole.log(\n\t\t\t`💰 From Amount: ${fromAmount} (${amountBN.toString()} raw units)`\n\t\t);\n\t\tconsole.log(`💰 To Amount: Will be calculated based on quote`);\n\t} else {\n\t\tconsole.log(`💰 From Amount: Will be calculated based on quote`);\n\t\tconsole.log(`💰 To Amount: ${toAmount} (${amountBN.toString()} raw units)`);\n\t}\n\n\tconsole.log(`📊 Slippage: ${slippage} BPS (${slippage / 100}%)`);\n\n\tconst swapTxn = await centralServerDrift.getSwapTxn(\n\t\tuserAccountPubkey,\n\t\tfromMarketIndex,\n\t\ttoMarketIndex,\n\t\tamountBN,\n\t\t{\n\t\t\tslippageBps: slippage,\n\t\t\tswapMode: swapModeEnum,\n\t\t}\n\t);\n\n\tawait executeTransaction(swapTxn as VersionedTransaction, 'Swap');\n}\n\n/**\n * Main CLI entry point\n */\nasync function main(): Promise<void> {\n\tconst args = process.argv.slice(2);\n\n\tif (\n\t\targs.length === 0 ||\n\t\targs[0] === '--help' ||\n\t\targs[0] === '-h' ||\n\t\targs[0] === 'help'\n\t) {\n\t\tshowUsage();\n\t\treturn;\n\t}\n\n\tconst command = args[0];\n\tconst parsedArgs = parseArgs(args.slice(1));\n\n\t// Initialize the client first\n\tawait initializeCentralServerDrift();\n\n\t// Route to appropriate command\n\tswitch (command) {\n\t\tcase 'deposit':\n\t\t\tawait depositCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'withdraw':\n\t\t\tawait withdrawCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'settleFunding':\n\t\t\tawait settleFundingCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'settlePnl':\n\t\t\tawait settlePnlCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'openPerpMarketOrder':\n\t\t\tawait openPerpMarketOrderCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'openPerpMarketOrderSwift':\n\t\t\tawait openPerpMarketOrderSwiftCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'openPerpNonMarketOrder':\n\t\t\tawait openPerpNonMarketOrderCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'openPerpNonMarketOrderSwift':\n\t\t\tawait openPerpNonMarketOrderSwiftCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'editOrder':\n\t\t\tawait editOrderCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'cancelOrder':\n\t\t\tawait cancelOrderCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'cancelAllOrders':\n\t\t\tawait cancelAllOrdersCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'swap':\n\t\t\tawait swapCommand(parsedArgs);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tconsole.error(`❌ Unknown command: ${command}`);\n\t\t\tconsole.error('');\n\t\t\tshowUsage();\n\t\t\tprocess.exit(1);\n\t}\n}\n\n// Run CLI if this file is executed directly\nif (require.main === module) {\n\tmain()\n\t\t.then(() => {\n\t\t\tconsole.log('\\n✨ Command executed successfully!');\n\t\t\t// Don't exit immediately for Swift orders (they need time to process)\n\t\t\tsetTimeout(() => process.exit(0), 2000);\n\t\t})\n\t\t.catch((error) => {\n\t\t\tconsole.error('\\n💥 Command failed:', error.message || error);\n\t\t\tprocess.exit(1);\n\t\t});\n}\n\nexport { main, parseArgs, parseAmount, parseDirection, parseSwapMode };\n"]}
|
|
1
|
+
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../../src/drift/cli.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0DAA4C;AAC5C,6CAAkE;AAClE,yCAYyB;AACzB,yCAAiC;AACjC,2EAAwE;AAExE,oCAAsC;AACtC,iDAA+C;AAC/C,2CAA6B;AAO7B,4CAA4C;AAC5C,MAAM,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;AACjC,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC;AAEzD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,uBAAuB;AACvB,IAAI,kBAAsC,CAAC;AAC3C,IAAI,MAAqB,CAAC;AAM1B;;GAEG;AACH,SAAS,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CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YAClB,SAAS,EAAE,CAAC;YACZ,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACF,CAAC;AAgBQ,oBAAI;AAdb,4CAA4C;AAC5C,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;IAC7B,IAAI,EAAE;SACJ,IAAI,CAAC,GAAG,EAAE;QACV,OAAO,CAAC,GAAG,CAAC,oCAAoC,CAAC,CAAC;QAClD,sEAAsE;QACtE,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;IACzC,CAAC,CAAC;SACD,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;QAChB,OAAO,CAAC,KAAK,CAAC,sBAAsB,EAAE,KAAK,CAAC,OAAO,IAAI,KAAK,CAAC,CAAC;QAC9D,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACjB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import * as anchor from '@coral-xyz/anchor';\nimport { PublicKey, VersionedTransaction } from '@solana/web3.js';\nimport {\n\tBN,\n\tloadKeypair,\n\tPositionDirection,\n\tOrderType,\n\tPostOnlyParams,\n\tSwapMode,\n\tBASE_PRECISION,\n\tQUOTE_PRECISION,\n\tPRICE_PRECISION,\n\tMainnetSpotMarkets,\n\tDevnetSpotMarkets,\n} from '@drift-labs/sdk';\nimport { sign } from 'tweetnacl';\nimport { CentralServerDrift } from './Drift/clients/CentralServerDrift';\nimport { CentralServerSwiftOrderOptions } from './Drift/clients/CentralServerDrift/types';\nimport { ENUM_UTILS } from '../utils';\nimport { API_URLS } from './constants/apiUrls';\nimport * as path from 'path';\nimport {\n\tNonMarketOrderType,\n\tLimitOrderParamsOrderConfig,\n\tNonMarketOrderParamsConfig,\n} from './base/actions/trade/openPerpOrder/types';\n\n// Load environment variables from .env file\nconst dotenv = require('dotenv');\ndotenv.config({ path: path.resolve(__dirname, '.env') });\n\n/**\n * CLI Tool for CentralServerDrift client\n *\n * This CLI tool allows you to execute various Drift protocol operations via command line\n * with human-readable parameters that are automatically converted to the proper precision.\n *\n * Prerequisites:\n * - Create a .env file in the same directory as this CLI file with:\n * ANCHOR_WALLET=[private key byte array]\n * ENDPOINT=https://your-rpc-endpoint.com\n *\n * Usage Examples:\n * ts-node cli.ts deposit --marketIndex=0 --amount=2 --userAccount=11111111111111111111111111111111\n * ts-node cli.ts withdraw --marketIndex=0 --amount=1.5 --userAccount=11111111111111111111111111111111\n * ts-node cli.ts settleFunding --userAccount=11111111111111111111111111111111\n * ts-node cli.ts settlePnl --marketIndexes=0,1 --userAccount=11111111111111111111111111111111\n * ts-node cli.ts openPerpMarketOrder --marketIndex=0 --direction=long --amount=0.1 --assetType=base --userAccount=11111111111111111111111111111111\n * ts-node cli.ts openPerpMarketOrderSwift --marketIndex=0 --direction=short --amount=100 --assetType=quote --userAccount=11111111111111111111111111111111\n * ts-node cli.ts openPerpNonMarketOrder --marketIndex=0 --direction=long --baseAssetAmount=0.1 --orderType=limit --limitPrice=100 --userAccount=11111111111111111111111111111111\n * ts-node cli.ts openPerpNonMarketOrderSwift --marketIndex=0 --direction=long --baseAssetAmount=0.1 --orderType=limit --limitPrice=99.5 --userAccount=11111111111111111111111111111111\n * ts-node cli.ts editOrder --userAccount=11111111111111111111111111111111 --orderId=123 --newLimitPrice=105.5\n * ts-node cli.ts cancelOrder --userAccount=11111111111111111111111111111111 --orderIds=123,456,789\n * ts-node cli.ts cancelAllOrders --userAccount=11111111111111111111111111111111 --marketType=perp\n * ts-node cli.ts swap --userAccount=11111111111111111111111111111111 --fromMarketIndex=1 --toMarketIndex=0 --fromAmount=1.5 --slippage=100 --swapMode=ExactIn\n * ts-node cli.ts swap --userAccount=11111111111111111111111111111111 --fromMarketIndex=1 --toMarketIndex=0 --toAmount=150 --slippage=100 --swapMode=ExactOut\n */\n\n// Shared configuration\nlet centralServerDrift: CentralServerDrift;\nlet wallet: anchor.Wallet;\n\ninterface CliArgs {\n\t[key: string]: string | string[];\n}\n\n/**\n * Parse command line arguments into a key-value object\n */\nfunction parseArgs(args: string[]): CliArgs {\n\tconst parsed: CliArgs = {};\n\n\tfor (let i = 0; i < args.length; i++) {\n\t\tconst arg = args[i];\n\t\tif (arg.startsWith('--')) {\n\t\t\tconst [key, value] = arg.substring(2).split('=');\n\t\t\tif (value !== undefined) {\n\t\t\t\t// Handle comma-separated arrays\n\t\t\t\tif (value.includes(',')) {\n\t\t\t\t\tparsed[key] = value.split(',');\n\t\t\t\t} else {\n\t\t\t\t\tparsed[key] = value;\n\t\t\t\t}\n\t\t\t} else if (i + 1 < args.length && !args[i + 1].startsWith('--')) {\n\t\t\t\t// Handle space-separated values\n\t\t\t\tconst nextValue = args[i + 1];\n\t\t\t\tif (nextValue.includes(',')) {\n\t\t\t\t\tparsed[key] = nextValue.split(',');\n\t\t\t\t} else {\n\t\t\t\t\tparsed[key] = nextValue;\n\t\t\t\t}\n\t\t\t\ti++; // Skip the next argument as it's the value\n\t\t\t} else {\n\t\t\t\tparsed[key] = 'true'; // Boolean flag\n\t\t\t}\n\t\t}\n\t}\n\n\treturn parsed;\n}\n\n/**\n * Convert human-readable amount to BN with proper precision\n */\nfunction parseAmount(amount: string, precision: BN = QUOTE_PRECISION): BN {\n\tconst floatAmount = parseFloat(amount);\n\tif (isNaN(floatAmount)) {\n\t\tthrow new Error(`Invalid amount: ${amount}`);\n\t}\n\n\t// Convert to the proper precision\n\tconst scaledAmount = Math.floor(floatAmount * precision.toNumber());\n\treturn new BN(scaledAmount);\n}\n\n/**\n * Parse direction string to PositionDirection\n */\nfunction parseDirection(direction: string): PositionDirection {\n\tconst normalized = direction.toLowerCase();\n\tif (normalized === 'long' || normalized === 'buy') {\n\t\treturn PositionDirection.LONG;\n\t} else if (normalized === 'short' || normalized === 'sell') {\n\t\treturn PositionDirection.SHORT;\n\t} else {\n\t\tthrow new Error(\n\t\t\t`Invalid direction: ${direction}. Use 'long', 'short', 'buy', or 'sell'`\n\t\t);\n\t}\n}\n\n/**\n * Parse order type string to OrderType\n */\nfunction _parseOrderType(orderType: string): OrderType {\n\tconst normalized = orderType.toLowerCase();\n\tswitch (normalized) {\n\t\tcase 'limit':\n\t\t\treturn OrderType.LIMIT;\n\t\tcase 'market':\n\t\t\treturn OrderType.MARKET;\n\t\tcase 'oracle':\n\t\t\treturn OrderType.ORACLE;\n\t\tcase 'trigger_market':\n\t\tcase 'stopmarket':\n\t\t\treturn OrderType.TRIGGER_MARKET;\n\t\tcase 'trigger_limit':\n\t\tcase 'stoplimit':\n\t\t\treturn OrderType.TRIGGER_LIMIT;\n\t\tdefault:\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid order type: ${orderType}. Use 'limit', 'market', 'oracle', 'trigger_market', or 'trigger_limit'`\n\t\t\t);\n\t}\n}\n\n/**\n * Parse post only string to PostOnlyParams\n */\nfunction parsePostOnly(postOnly: string): PostOnlyParams {\n\tconst normalized = postOnly.toLowerCase();\n\tswitch (normalized) {\n\t\tcase 'none':\n\t\tcase 'false':\n\t\t\treturn PostOnlyParams.NONE;\n\t\tcase 'must_post_only':\n\t\tcase 'true':\n\t\t\treturn PostOnlyParams.MUST_POST_ONLY;\n\t\tcase 'try_post_only':\n\t\t\treturn PostOnlyParams.TRY_POST_ONLY;\n\t\tcase 'slide':\n\t\t\treturn PostOnlyParams.SLIDE;\n\t\tdefault:\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid post only: ${postOnly}. Use 'none', 'must_post_only', 'try_post_only', or 'slide'`\n\t\t\t);\n\t}\n}\n\n/**\n * Parse swap mode string to SwapMode\n */\nfunction parseSwapMode(swapMode: string): SwapMode {\n\tconst normalized = swapMode.toLowerCase();\n\tswitch (normalized) {\n\t\tcase 'exactin':\n\t\tcase 'exact_in':\n\t\t\treturn 'ExactIn';\n\t\tcase 'exactout':\n\t\tcase 'exact_out':\n\t\t\treturn 'ExactOut';\n\t\tdefault:\n\t\t\tthrow new Error(\n\t\t\t\t`Invalid swap mode: ${swapMode}. Use 'ExactIn' or 'ExactOut'`\n\t\t\t);\n\t}\n}\n\n/**\n * Get the precision for a spot market based on environment and market index\n */\nfunction getMarketPrecision(\n\tmarketIndex: number,\n\tisMainnet: boolean = true\n): BN {\n\tconst markets = isMainnet ? MainnetSpotMarkets : DevnetSpotMarkets;\n\tconst market = markets.find((m) => m.marketIndex === marketIndex);\n\n\tif (!market) {\n\t\tconsole.warn(\n\t\t\t`⚠️ Market ${marketIndex} not found, using QUOTE_PRECISION as fallback`\n\t\t);\n\t\treturn QUOTE_PRECISION;\n\t}\n\n\treturn market.precision;\n}\n\n/**\n * Initialize CentralServerDrift instance\n */\nasync function initializeCentralServerDrift(): Promise<void> {\n\tconsole.log('🚀 Initializing CentralServerDrift...\\n');\n\n\t// Validate required environment variables\n\tif (!process.env.ANCHOR_WALLET) {\n\t\tthrow new Error('ANCHOR_WALLET must be set in .env file');\n\t}\n\n\tif (!process.env.ENDPOINT) {\n\t\tthrow new Error(\n\t\t\t'ENDPOINT environment variable must be set to your Solana RPC endpoint'\n\t\t);\n\t}\n\n\t// Set up the wallet\n\twallet = new anchor.Wallet(loadKeypair(process.env.ANCHOR_WALLET as string));\n\n\tconsole.log(`✅ Wallet Public Key: ${wallet.publicKey.toString()}`);\n\tconsole.log(`✅ RPC Endpoint: ${process.env.ENDPOINT}\\n`);\n\n\t// Initialize CentralServerDrift\n\tconsole.log('🏗️ Initializing CentralServerDrift...');\n\tcentralServerDrift = new CentralServerDrift({\n\t\tsolanaRpcEndpoint: process.env.ENDPOINT as string,\n\t\tdriftEnv: 'mainnet-beta', // Change to 'devnet' for devnet testing\n\t\tadditionalDriftClientConfig: {\n\t\t\ttxVersion: 0,\n\t\t\ttxParams: {\n\t\t\t\tcomputeUnits: 200000,\n\t\t\t\tcomputeUnitsPrice: 1000,\n\t\t\t},\n\t\t},\n\t});\n\n\tconsole.log('✅ CentralServerDrift instance created successfully\\n');\n\n\t// Subscribe to market data\n\tconsole.log('📡 Subscribing to market data...');\n\tawait centralServerDrift.subscribe();\n\tconsole.log('✅ Successfully subscribed to market data\\n');\n}\n\n/**\n * Execute a regular transaction\n */\nasync function executeTransaction(\n\ttxn: VersionedTransaction,\n\ttransactionType: string\n): Promise<void> {\n\tconsole.log(`✅ ${transactionType} transaction created successfully`);\n\tconsole.log('\\n📝 Signing Transaction...');\n\n\ttxn.sign([wallet.payer]);\n\tconsole.log('✅ Transaction signed successfully');\n\n\tconsole.log('\\n🚀 Sending transaction to the network...');\n\tconst { txSig } = await centralServerDrift.sendSignedTransaction(txn);\n\n\tconsole.log('✅ Transaction sent successfully!');\n\tconsole.log(`📋 Transaction Signature: ${txSig?.toString()}`);\n\tconsole.log(`🔍 View on Solscan: https://solscan.io/tx/${txSig?.toString()}`);\n}\n\nconst createSwiftOrderCallbacks = (\n\torderType: string\n): CentralServerSwiftOrderOptions['callbacks'] => {\n\tconst terminalCall = () => {\n\t\tconsole.log('🏁 Order monitoring completed');\n\t};\n\n\treturn {\n\t\tonSigningExpiry: () => {\n\t\t\tconsole.log('Swift order signing expired');\n\t\t},\n\t\tonSigningSuccess: (signedMessage, orderUuid, orderParamsMessage) => {\n\t\t\tconsole.log(\n\t\t\t\t'Swift order signed successfully. Signed message:',\n\t\t\t\tsignedMessage,\n\t\t\t\torderUuid,\n\t\t\t\torderParamsMessage\n\t\t\t);\n\t\t},\n\t\tonSent: () => {\n\t\t\tconsole.log(`✅ ${orderType} Swift order submitted successfully`);\n\t\t},\n\t\tonConfirmed: (event) => {\n\t\t\tconsole.log('✅ Order confirmed!');\n\t\t\tconsole.log(`📋 Order ID: ${event.orderId}`);\n\t\t\tconsole.log(`📋 Hash: ${event.hash}`);\n\t\t\tterminalCall();\n\t\t},\n\t\tonExpired: (event) => {\n\t\t\tconsole.error('⏰ Order expired:', event.message);\n\t\t\tterminalCall();\n\t\t},\n\t\tonErrored: (event) => {\n\t\t\tconsole.error('❌ Order failed:', event.message);\n\t\t\tconsole.error(`📋 Status: ${event.status}`);\n\t\t\tterminalCall();\n\t\t},\n\t};\n};\n\n/**\n * CLI Command: deposit\n */\nasync function depositCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndex = parseInt(args.marketIndex as string);\n\tconst amount = args.amount as string;\n\n\tif (!userAccount || isNaN(marketIndex) || !amount) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndex, --amount'\n\t\t);\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst amountBN = parseAmount(amount, QUOTE_PRECISION); // Most deposits are USDC (quote precision)\n\n\tconsole.log('--- 📥 Deposit Transaction ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Index: ${marketIndex}`);\n\tconsole.log(`💰 Amount: ${amount} (${amountBN.toString()} raw units)`);\n\n\tconst depositTxn = await centralServerDrift.getDepositTxn(\n\t\tuserAccountPubkey,\n\t\tamountBN,\n\t\tmarketIndex\n\t);\n\n\tawait executeTransaction(depositTxn as VersionedTransaction, 'Deposit');\n}\n\n/**\n * CLI Command: withdraw\n */\nasync function withdrawCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndex = parseInt(args.marketIndex as string);\n\tconst amount = args.amount as string;\n\tconst isBorrow = args.isBorrow === 'true';\n\tconst isMax = args.isMax === 'true';\n\n\tif (!userAccount || isNaN(marketIndex) || !amount) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndex, --amount'\n\t\t);\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst amountBN = parseAmount(amount, QUOTE_PRECISION);\n\n\tconsole.log('--- 📤 Withdraw Transaction ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Index: ${marketIndex}`);\n\tconsole.log(`💰 Amount: ${amount} (${amountBN.toString()} raw units)`);\n\tconsole.log(`💳 Is Borrow: ${isBorrow}`);\n\tconsole.log(`📊 Is Max: ${isMax}`);\n\n\tconst withdrawTxn = await centralServerDrift.getWithdrawTxn(\n\t\tuserAccountPubkey,\n\t\tamountBN,\n\t\tmarketIndex,\n\t\t{ isBorrow, isMax }\n\t);\n\n\tawait executeTransaction(withdrawTxn as VersionedTransaction, 'Withdraw');\n}\n\n/**\n * CLI Command: settleFunding\n */\nasync function settleFundingCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\n\tif (!userAccount) {\n\t\tthrow new Error('Required arguments: --userAccount');\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\n\tconsole.log('--- 💰 Settle Funding Transaction ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\n\tconst settleFundingTxn = await centralServerDrift.getSettleFundingTxn(\n\t\tuserAccountPubkey\n\t);\n\n\tawait executeTransaction(\n\t\tsettleFundingTxn as VersionedTransaction,\n\t\t'Settle Funding'\n\t);\n}\n\n/**\n * CLI Command: settlePnl\n */\nasync function settlePnlCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndexesArg = args.marketIndexes;\n\n\tif (!userAccount || !marketIndexesArg) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndexes (comma-separated)'\n\t\t);\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst marketIndexes = Array.isArray(marketIndexesArg)\n\t\t? marketIndexesArg.map((idx) => parseInt(idx))\n\t\t: [parseInt(marketIndexesArg as string)];\n\n\tconsole.log('--- 📈 Settle PnL Transaction ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`📊 Market Indexes: ${marketIndexes.join(', ')}`);\n\n\tconst settlePnlTxn = await centralServerDrift.getSettlePnlTxn(\n\t\tuserAccountPubkey,\n\t\tmarketIndexes\n\t);\n\n\tawait executeTransaction(settlePnlTxn as VersionedTransaction, 'Settle PnL');\n}\n\n/**\n * CLI Command: openPerpMarketOrder (regular transaction)\n */\nasync function openPerpMarketOrderCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndex = parseInt(args.marketIndex as string);\n\tconst direction = args.direction as string;\n\tconst amount = args.amount as string;\n\tconst assetType = (args.assetType as string) || 'base';\n\tconst dlobServerHttpUrl = API_URLS.DLOB;\n\n\tif (!userAccount || isNaN(marketIndex) || !direction || !amount) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndex, --direction, --amount'\n\t\t);\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst directionEnum = parseDirection(direction);\n\tconst precision = assetType === 'base' ? BASE_PRECISION : QUOTE_PRECISION;\n\tconst amountBN = parseAmount(amount, precision);\n\n\tconsole.log('--- 🎯 Open Perp Order Transaction ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Index: ${marketIndex}`);\n\tconsole.log(\n\t\t`📊 Direction: ${direction} (${ENUM_UTILS.toStr(directionEnum)})`\n\t);\n\tconsole.log(`💰 Amount: ${amount} (${amountBN.toString()} raw units)`);\n\tconsole.log(`💱 Asset Type: ${assetType}`);\n\tconsole.log(`🌐 DLOB Server: ${dlobServerHttpUrl}`);\n\n\tconst orderTxn = await centralServerDrift.getOpenPerpMarketOrderTxn({\n\t\tuserAccountPublicKey: userAccountPubkey,\n\t\tassetType: assetType as 'base' | 'quote',\n\t\tmarketIndex,\n\t\tdirection: directionEnum,\n\t\tamount: amountBN,\n\t\tuseSwift: false,\n\t});\n\n\tawait executeTransaction(orderTxn as VersionedTransaction, 'Open Perp Order');\n}\n\n/**\n * CLI Command: openPerpMarketOrderSwift (Swift signed message order)\n */\nasync function openPerpMarketOrderSwiftCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndex = parseInt(args.marketIndex as string);\n\tconst direction = args.direction as string;\n\tconst amount = args.amount as string;\n\tconst assetType = (args.assetType as string) || 'base';\n\tconst dlobServerHttpUrl = API_URLS.DLOB;\n\tconst swiftServerUrl = (args.swiftServerUrl as string) || API_URLS.SWIFT;\n\n\tif (!userAccount || isNaN(marketIndex) || !direction || !amount) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndex, --direction, --amount'\n\t\t);\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst directionEnum = parseDirection(direction);\n\tconst precision = assetType === 'base' ? BASE_PRECISION : QUOTE_PRECISION;\n\tconst amountBN = parseAmount(amount, precision);\n\n\tconsole.log('--- ⚡ Open Perp Order Swift ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Index: ${marketIndex}`);\n\tconsole.log(\n\t\t`📊 Direction: ${direction} (${ENUM_UTILS.toStr(directionEnum)})`\n\t);\n\tconsole.log(`💰 Amount: ${amount} (${amountBN.toString()} raw units)`);\n\tconsole.log(`💱 Asset Type: ${assetType}`);\n\tconsole.log(`🌐 DLOB Server: ${dlobServerHttpUrl}`);\n\tconsole.log(`⚡ Swift Server: ${swiftServerUrl}`);\n\tconsole.log(`🔑 Wallet Public Key: ${wallet.publicKey.toString()}`);\n\n\tconsole.log('\\n👁️ Monitoring order status...');\n\n\ttry {\n\t\tawait centralServerDrift.getOpenPerpMarketOrderTxn({\n\t\t\tuserAccountPublicKey: userAccountPubkey,\n\t\t\tassetType: assetType as 'base' | 'quote',\n\t\t\tmarketIndex,\n\t\t\tdirection: directionEnum,\n\t\t\tamount: amountBN,\n\t\t\tuseSwift: true,\n\t\t\tswiftOptions: {\n\t\t\t\twallet: {\n\t\t\t\t\tsignMessage: async (message: Uint8Array) => {\n\t\t\t\t\t\tconst signature = sign.detached(message, wallet.payer.secretKey);\n\t\t\t\t\t\treturn new Uint8Array(signature);\n\t\t\t\t\t},\n\t\t\t\t\tpublicKey: wallet.publicKey,\n\t\t\t\t},\n\t\t\t\tcallbacks: createSwiftOrderCallbacks('Open Perp Order'),\n\t\t\t},\n\t\t});\n\t\tconsole.log('✅ [CLI] Swift order finished');\n\t} catch (error) {\n\t\tconsole.error('❌ [CLI] Error creating Swift order:', error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * CLI Command: openPerpNonMarketOrder (regular limit/oracle order)\n */\nasync function openPerpNonMarketOrderCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndex = parseInt(args.marketIndex as string);\n\tconst direction = args.direction as string;\n\tconst amount = args.amount as string;\n\tconst assetType = (args.assetType as string) || 'base';\n\tconst baseAssetAmount = args.baseAssetAmount as string;\n\tconst orderType = args.orderType as NonMarketOrderType;\n\tconst limitPrice = args.limitPrice as string;\n\tconst triggerPrice = args.triggerPrice as string;\n\tconst reduceOnly = (args.reduceOnly as string) === 'true';\n\tconst postOnly = (args.postOnly as string) || 'none';\n\tconst oraclePriceOffset = args.oraclePriceOffset as string;\n\n\tif (!userAccount || isNaN(marketIndex) || !direction || !orderType) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndex, --direction, --orderType'\n\t\t);\n\t}\n\n\tif (!amount && !baseAssetAmount) {\n\t\tthrow new Error('Either --amount or --baseAssetAmount must be provided');\n\t}\n\n\t// Validate price requirements based on order type\n\tif (orderType === 'limit') {\n\t\tif (!limitPrice) {\n\t\t\tthrow new Error(`Order type '${orderType}' requires --limitPrice`);\n\t\t}\n\t} else if (orderType === 'takeProfit' || orderType === 'stopLoss') {\n\t\tif (!triggerPrice) {\n\t\t\tthrow new Error(`Order type '${orderType}' requires --triggerPrice`);\n\t\t}\n\t} else if (orderType === 'oracleLimit') {\n\t\tif (!oraclePriceOffset) {\n\t\t\tthrow new Error(`Order type '${orderType}' requires --oraclePriceOffset`);\n\t\t}\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst directionEnum = parseDirection(direction);\n\tconst postOnlyEnum = parsePostOnly(postOnly);\n\tconst limitPriceBN = limitPrice\n\t\t? parseAmount(limitPrice, PRICE_PRECISION)\n\t\t: undefined;\n\tconst triggerPriceBN = triggerPrice\n\t\t? parseAmount(triggerPrice, PRICE_PRECISION)\n\t\t: undefined;\n\tconst oraclePriceOffsetBN = oraclePriceOffset\n\t\t? parseAmount(oraclePriceOffset, PRICE_PRECISION)\n\t\t: undefined;\n\n\tconst orderConfig: NonMarketOrderParamsConfig['orderConfig'] =\n\t\torderType === 'limit'\n\t\t\t? {\n\t\t\t\t\torderType,\n\t\t\t\t\tlimitPrice: limitPriceBN!,\n\t\t\t }\n\t\t\t: orderType === 'takeProfit' || orderType === 'stopLoss'\n\t\t\t? {\n\t\t\t\t\torderType,\n\t\t\t\t\ttriggerPrice: triggerPriceBN!,\n\t\t\t }\n\t\t\t: {\n\t\t\t\t\torderType,\n\t\t\t\t\toraclePriceOffset: oraclePriceOffsetBN!,\n\t\t\t };\n\n\tconsole.log('--- 📋 Open Perp Non-Market Order ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Index: ${marketIndex}`);\n\tconsole.log(\n\t\t`📊 Direction: ${direction} (${ENUM_UTILS.toStr(directionEnum)})`\n\t);\n\n\tlet amountBN: BN;\n\tif (amount) {\n\t\tconst precision = assetType === 'base' ? BASE_PRECISION : QUOTE_PRECISION;\n\t\tamountBN = parseAmount(amount, precision);\n\t\tconsole.log(`💰 Amount: ${amount} (${amountBN.toString()} raw units)`);\n\t\tconsole.log(`💱 Asset Type: ${assetType}`);\n\t} else {\n\t\tamountBN = parseAmount(baseAssetAmount, BASE_PRECISION);\n\t\tconsole.log(\n\t\t\t`💰 Base Asset Amount: ${baseAssetAmount} (${amountBN.toString()} raw units)`\n\t\t);\n\t}\n\n\tif (limitPriceBN) {\n\t\tconsole.log(\n\t\t\t`💵 Limit Price: ${limitPrice} (${limitPriceBN.toString()} raw units)`\n\t\t);\n\t}\n\tif (triggerPriceBN) {\n\t\tconsole.log(\n\t\t\t`🎯 Trigger Price: ${triggerPrice} (${triggerPriceBN.toString()} raw units)`\n\t\t);\n\t}\n\tconsole.log(`📝 Order Type: ${orderType}`);\n\tconsole.log(`🔄 Reduce Only: ${reduceOnly}`);\n\tconsole.log(`📌 Post Only: ${postOnly} (${ENUM_UTILS.toStr(postOnlyEnum)})`);\n\n\t// Just call the main method - it will handle both approaches internally\n\tconst orderTxn = await centralServerDrift.getOpenPerpNonMarketOrderTxn({\n\t\tuserAccountPublicKey: userAccountPubkey,\n\t\tmarketIndex,\n\t\tdirection: directionEnum,\n\t\torderConfig,\n\t\tuseSwift: false,\n\t\treduceOnly,\n\t\tpostOnly: postOnlyEnum,\n\t\tassetType: assetType as 'base' | 'quote',\n\t\tamount: amountBN,\n\t});\n\n\tawait executeTransaction(\n\t\torderTxn as VersionedTransaction,\n\t\t'Open Perp Non-Market Order'\n\t);\n}\n\n/**\n * CLI Command: openPerpNonMarketOrderSwift (Swift signed message limit order)\n */\nasync function openPerpNonMarketOrderSwiftCommand(\n\targs: CliArgs\n): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketIndex = parseInt(args.marketIndex as string);\n\tconst direction = args.direction as string;\n\tconst amount = args.amount as string;\n\tconst assetType = (args.assetType as string) || 'base';\n\tconst baseAssetAmount = args.baseAssetAmount as string;\n\tconst orderType = args.orderType as NonMarketOrderType;\n\tconst limitPrice = args.limitPrice as string;\n\tconst reduceOnly = (args.reduceOnly as string) === 'true';\n\tconst postOnly = (args.postOnly as string) || 'none';\n\tconst swiftServerUrl = API_URLS.SWIFT;\n\n\tif (!userAccount || isNaN(marketIndex) || !direction || !orderType) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --marketIndex, --direction, --orderType'\n\t\t);\n\t}\n\n\tif (!amount && !baseAssetAmount) {\n\t\tthrow new Error('Either --amount or --baseAssetAmount must be provided');\n\t}\n\n\t// Swift orders only support LIMIT order type\n\tif (orderType.toLowerCase() !== 'limit') {\n\t\tthrow new Error('Swift orders only support LIMIT order type');\n\t}\n\n\t// LIMIT orders require limitPrice\n\tif (!limitPrice) {\n\t\tthrow new Error('LIMIT orders require --limitPrice');\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst directionEnum = parseDirection(direction);\n\tconst postOnlyEnum = parsePostOnly(postOnly);\n\tconst limitPriceBN = parseAmount(limitPrice, PRICE_PRECISION);\n\n\tconst orderConfig: LimitOrderParamsOrderConfig = {\n\t\torderType: 'limit',\n\t\tlimitPrice: limitPriceBN!,\n\t};\n\n\tconsole.log('--- ⚡ Open Perp Non-Market Order Swift ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Index: ${marketIndex}`);\n\tconsole.log(\n\t\t`📊 Direction: ${direction} (${ENUM_UTILS.toStr(directionEnum)})`\n\t);\n\n\tlet amountBN: BN;\n\tif (amount) {\n\t\tconst precision = assetType === 'base' ? BASE_PRECISION : QUOTE_PRECISION;\n\t\tamountBN = parseAmount(amount, precision);\n\t\tconsole.log(`💰 Amount: ${amount} (${amountBN.toString()} raw units)`);\n\t\tconsole.log(`💱 Asset Type: ${assetType}`);\n\t} else {\n\t\tamountBN = parseAmount(baseAssetAmount, BASE_PRECISION);\n\t\tconsole.log(\n\t\t\t`💰 Base Asset Amount: ${baseAssetAmount} (${amountBN.toString()} raw units)`\n\t\t);\n\t}\n\n\tconsole.log(\n\t\t`💵 Limit Price: ${limitPrice} (${limitPriceBN.toString()} raw units)`\n\t);\n\tconsole.log(`📝 Order Type: ${orderType})`);\n\tconsole.log(`🔄 Reduce Only: ${reduceOnly}`);\n\tconsole.log(`📌 Post Only: ${postOnly} (${ENUM_UTILS.toStr(postOnlyEnum)})`);\n\tconsole.log(`⚡ Swift Server: ${swiftServerUrl}`);\n\tconsole.log(`🔑 Wallet Public Key: ${wallet.publicKey.toString()}`);\n\n\ttry {\n\t\tconst swiftOptions: CentralServerSwiftOrderOptions = {\n\t\t\twallet: {\n\t\t\t\tsignMessage: async (message: Uint8Array) => {\n\t\t\t\t\tconst signature = sign.detached(message, wallet.payer.secretKey);\n\t\t\t\t\treturn new Uint8Array(signature);\n\t\t\t\t},\n\t\t\t\tpublicKey: wallet.publicKey,\n\t\t\t},\n\t\t\tcallbacks: createSwiftOrderCallbacks('Open Perp Non-Market Order'),\n\t\t};\n\n\t\tconsole.log('\\n👁️ Monitoring order status...');\n\n\t\t// Use the main method - it handles both approaches internally\n\t\tawait centralServerDrift.getOpenPerpNonMarketOrderTxn({\n\t\t\tuserAccountPublicKey: userAccountPubkey,\n\t\t\tmarketIndex,\n\t\t\tdirection: directionEnum,\n\t\t\torderConfig,\n\t\t\treduceOnly,\n\t\t\tpostOnly: postOnlyEnum,\n\t\t\tassetType: assetType as 'base' | 'quote',\n\t\t\tamount: amountBN,\n\t\t\tuseSwift: true,\n\t\t\tswiftOptions,\n\t\t});\n\n\t\tconsole.log('✅ [CLI] Swift order finished');\n\t} catch (error) {\n\t\tconsole.error('❌ [CLI] Error creating Swift non-market order:', error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * Show CLI usage information\n */\nfunction showUsage(): void {\n\tconsole.log('📋 Drift CLI Usage');\n\tconsole.log('');\n\tconsole.log('Available Commands:');\n\tconsole.log('');\n\n\tconsole.log('💰 deposit');\n\tconsole.log(\n\t\t' ts-node cli.ts deposit --userAccount=<pubkey> --marketIndex=<num> --amount=<num>'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts deposit --userAccount=11111111111111111111111111111111 --marketIndex=0 --amount=100'\n\t);\n\tconsole.log('');\n\n\tconsole.log('💸 withdraw');\n\tconsole.log(\n\t\t' ts-node cli.ts withdraw --userAccount=<pubkey> --marketIndex=<num> --amount=<num> [--isBorrow=<bool>] [--isMax=<bool>]'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts withdraw --userAccount=11111111111111111111111111111111 --marketIndex=0 --amount=50'\n\t);\n\tconsole.log('');\n\n\tconsole.log('🏦 settleFunding');\n\tconsole.log(' ts-node cli.ts settleFunding --userAccount=<pubkey>');\n\tconsole.log(\n\t\t' Example: ts-node cli.ts settleFunding --userAccount=11111111111111111111111111111111'\n\t);\n\tconsole.log('');\n\n\tconsole.log('📊 settlePnl');\n\tconsole.log(\n\t\t' ts-node cli.ts settlePnl --userAccount=<pubkey> --marketIndexes=<comma-separated>'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts settlePnl --userAccount=11111111111111111111111111111111 --marketIndexes=0,1'\n\t);\n\tconsole.log('');\n\n\tconsole.log('🎯 openPerpMarketOrder');\n\tconsole.log(\n\t\t' ts-node cli.ts openPerpMarketOrder --userAccount=<pubkey> --marketIndex=<num> --direction=<long|short> --amount=<num> [--assetType=<base|quote>]'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts openPerpMarketOrder --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=long --amount=0.1 --assetType=base'\n\t);\n\tconsole.log('');\n\n\tconsole.log('⚡ openPerpMarketOrderSwift');\n\tconsole.log(\n\t\t' ts-node cli.ts openPerpMarketOrderSwift --userAccount=<pubkey> --marketIndex=<num> --direction=<long|short> --amount=<num> [--assetType=<base|quote>]'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts openPerpMarketOrderSwift --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=short --amount=100 --assetType=quote'\n\t);\n\tconsole.log('');\n\n\tconsole.log('📋 openPerpNonMarketOrder');\n\tconsole.log(\n\t\t' ts-node cli.ts openPerpNonMarketOrder --userAccount=<pubkey> --marketIndex=<num> --direction=<long|short> --amount=<num> [--assetType=<base|quote>] --orderType=<limit|trigger_limit|trigger_market|oracle> [--limitPrice=<num>] [--triggerPrice=<num>] [--reduceOnly=<true|false>] [--postOnly=<none|must_post_only|try_post_only|slide>]'\n\t);\n\tconsole.log(\n\t\t' New LIMIT: ts-node cli.ts openPerpNonMarketOrder --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=long --amount=0.1 --assetType=base --orderType=limit --limitPrice=100'\n\t);\n\tconsole.log(\n\t\t' New QUOTE: ts-node cli.ts openPerpNonMarketOrder --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=long --amount=100 --assetType=quote --orderType=limit --limitPrice=100'\n\t);\n\tconsole.log(\n\t\t' Legacy: ts-node cli.ts openPerpNonMarketOrder --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=long --baseAssetAmount=0.1 --orderType=limit --limitPrice=100'\n\t);\n\tconsole.log('');\n\n\tconsole.log('⚡ openPerpNonMarketOrderSwift');\n\tconsole.log(\n\t\t' ts-node cli.ts openPerpNonMarketOrderSwift --userAccount=<pubkey> --marketIndex=<num> --direction=<long|short> --amount=<num> [--assetType=<base|quote>] --orderType=limit --limitPrice=<num> [--reduceOnly=<true|false>] [--postOnly=<none|must_post_only|try_post_only|slide>]'\n\t);\n\tconsole.log(\n\t\t' New: ts-node cli.ts openPerpNonMarketOrderSwift --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=long --amount=0.1 --assetType=base --orderType=limit --limitPrice=99.5'\n\t);\n\tconsole.log(\n\t\t' Legacy: ts-node cli.ts openPerpNonMarketOrderSwift --userAccount=11111111111111111111111111111111 --marketIndex=0 --direction=long --baseAssetAmount=0.1 --orderType=limit --limitPrice=99.5'\n\t);\n\tconsole.log('');\n\n\tconsole.log('✏️ editOrder');\n\tconsole.log(\n\t\t' ts-node cli.ts editOrder --userAccount=<pubkey> --orderId=<num> [--newDirection=<long|short>] [--newBaseAmount=<num>] [--newLimitPrice=<num>] [--newTriggerPrice=<num>] [--reduceOnly=<true|false>] [--postOnly=<true|false>]'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts editOrder --userAccount=11111111111111111111111111111111 --orderId=123 --newLimitPrice=105.5'\n\t);\n\tconsole.log('');\n\n\tconsole.log('❌ cancelOrder');\n\tconsole.log(\n\t\t' ts-node cli.ts cancelOrder --userAccount=<pubkey> --orderIds=<comma-separated-list>'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts cancelOrder --userAccount=11111111111111111111111111111111 --orderIds=123,456,789'\n\t);\n\tconsole.log('');\n\n\tconsole.log('🧹 cancelAllOrders');\n\tconsole.log(\n\t\t' ts-node cli.ts cancelAllOrders --userAccount=<pubkey> [--marketType=<perp|spot>] [--marketIndex=<num>] [--direction=<long|short>]'\n\t);\n\tconsole.log(\n\t\t' Example: ts-node cli.ts cancelAllOrders --userAccount=11111111111111111111111111111111 --marketType=perp'\n\t);\n\tconsole.log('');\n\n\tconsole.log('🔄 swap');\n\tconsole.log(\n\t\t' ts-node cli.ts swap --userAccount=<pubkey> --fromMarketIndex=<num> --toMarketIndex=<num> [--fromAmount=<num>] [--toAmount=<num>] [--slippage=<bps>] [--swapMode=<ExactIn|ExactOut>]'\n\t);\n\tconsole.log(\n\t\t' ExactIn: ts-node cli.ts swap --userAccount=11111111111111111111111111111111 --fromMarketIndex=1 --toMarketIndex=0 --fromAmount=1.5 --swapMode=ExactIn'\n\t);\n\tconsole.log(\n\t\t' ExactOut: ts-node cli.ts swap --userAccount=11111111111111111111111111111111 --fromMarketIndex=1 --toMarketIndex=0 --toAmount=150 --swapMode=ExactOut'\n\t);\n\tconsole.log('');\n\n\tconsole.log('Options:');\n\tconsole.log(' --help, -h Show this help message');\n\tconsole.log('');\n\tconsole.log('Notes:');\n\tconsole.log(\n\t\t' - Amounts are in human-readable format (e.g., 1.5 USDC, 0.1 SOL)'\n\t);\n\tconsole.log(' - Direction can be: long, short, buy, sell');\n\tconsole.log(\n\t\t' - Asset type: base (for native tokens like SOL) or quote (for USDC amounts)'\n\t);\n\tconsole.log(' - Swap modes:');\n\tconsole.log(\n\t\t' * ExactIn: Specify --fromAmount (how much input token to swap)'\n\t);\n\tconsole.log(\n\t\t' * ExactOut: Specify --toAmount (how much output token to receive)'\n\t);\n\tconsole.log(' - Ensure your .env file contains ANCHOR_WALLET and ENDPOINT');\n}\n\n/**\n * CLI Command: editOrder\n */\nasync function editOrderCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst orderId = parseInt(args.orderId as string);\n\tconst newDirection = args.newDirection as string;\n\tconst newBaseAmount = args.newBaseAmount as string;\n\tconst newLimitPrice = args.newLimitPrice as string;\n\tconst newTriggerPrice = args.newTriggerPrice as string;\n\tconst reduceOnly = (args.reduceOnly as string) === 'true';\n\tconst postOnly = (args.postOnly as string) === 'true';\n\n\tif (!userAccount || isNaN(orderId)) {\n\t\tthrow new Error('Required arguments: --userAccount, --orderId');\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst editParams: any = {};\n\n\tif (newDirection) {\n\t\teditParams.newDirection = parseDirection(newDirection);\n\t}\n\n\tif (newBaseAmount) {\n\t\teditParams.newBaseAmount = parseAmount(newBaseAmount, BASE_PRECISION);\n\t}\n\n\tif (newLimitPrice) {\n\t\teditParams.newLimitPrice = parseAmount(newLimitPrice, PRICE_PRECISION);\n\t}\n\n\tif (newTriggerPrice) {\n\t\teditParams.newTriggerPrice = parseAmount(newTriggerPrice, PRICE_PRECISION);\n\t}\n\n\tif (reduceOnly) {\n\t\teditParams.reduceOnly = true;\n\t}\n\n\tif (postOnly) {\n\t\teditParams.postOnly = true;\n\t}\n\n\tconsole.log('--- ✏️ Edit Order ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🆔 Order ID: ${orderId}`);\n\tconsole.log(`📝 Edit Parameters:`, editParams);\n\n\tconst editOrderTxn = await centralServerDrift.getEditOrderTxn(\n\t\tuserAccountPubkey,\n\t\torderId,\n\t\teditParams\n\t);\n\n\tawait executeTransaction(editOrderTxn as VersionedTransaction, 'Edit Order');\n}\n\n/**\n * CLI Command: cancelOrder\n */\nasync function cancelOrderCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst orderIds = args.orderIds as string;\n\n\tif (!userAccount || !orderIds) {\n\t\tthrow new Error('Required arguments: --userAccount, --orderIds');\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tconst orderIdArray = orderIds.split(',').map((id) => parseInt(id.trim()));\n\n\tconsole.log('--- ❌ Cancel Orders ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🆔 Order IDs: ${orderIdArray.join(', ')}`);\n\n\tconst cancelOrderTxn = await centralServerDrift.getCancelOrdersTxn(\n\t\tuserAccountPubkey,\n\t\torderIdArray\n\t);\n\n\tawait executeTransaction(\n\t\tcancelOrderTxn as VersionedTransaction,\n\t\t'Cancel Orders'\n\t);\n}\n\n/**\n * CLI Command: cancelAllOrders\n */\nasync function cancelAllOrdersCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst marketType = args.marketType as string;\n\tconst marketIndex = args.marketIndex\n\t\t? parseInt(args.marketIndex as string)\n\t\t: undefined;\n\tconst direction = args.direction as string;\n\n\tif (!userAccount) {\n\t\tthrow new Error('Required arguments: --userAccount');\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\tlet marketTypeEnum = undefined;\n\tlet directionEnum = undefined;\n\n\tif (marketType) {\n\t\tmarketTypeEnum =\n\t\t\tmarketType.toLowerCase() === 'perp' ? { perp: {} } : { spot: {} };\n\t}\n\n\tif (direction) {\n\t\tdirectionEnum = parseDirection(direction);\n\t}\n\n\tconsole.log('--- 🧹 Cancel All Orders ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`🏪 Market Type Filter: ${marketType || 'none'}`);\n\tconsole.log(\n\t\t`📊 Market Index Filter: ${\n\t\t\tmarketIndex !== undefined ? marketIndex : 'none'\n\t\t}`\n\t);\n\tconsole.log(`📈 Direction Filter: ${direction || 'none'}`);\n\n\tconst cancelAllOrdersTxn = await centralServerDrift.getCancelAllOrdersTxn(\n\t\tuserAccountPubkey,\n\t\tmarketTypeEnum,\n\t\tmarketIndex,\n\t\tdirectionEnum\n\t);\n\n\tawait executeTransaction(\n\t\tcancelAllOrdersTxn as VersionedTransaction,\n\t\t'Cancel All Orders'\n\t);\n}\n\n/**\n * CLI Command: swap\n */\nasync function swapCommand(args: CliArgs): Promise<void> {\n\tconst userAccount = args.userAccount as string;\n\tconst fromMarketIndex = parseInt(args.fromMarketIndex as string);\n\tconst toMarketIndex = parseInt(args.toMarketIndex as string);\n\tconst fromAmount = args.fromAmount as string;\n\tconst toAmount = args.toAmount as string;\n\tconst slippage = args.slippage ? parseInt(args.slippage as string) : 10; // Default 0.1%\n\tconst swapMode = (args.swapMode as string) || 'ExactIn';\n\n\tif (!userAccount || isNaN(fromMarketIndex) || isNaN(toMarketIndex)) {\n\t\tthrow new Error(\n\t\t\t'Required arguments: --userAccount, --fromMarketIndex, --toMarketIndex'\n\t\t);\n\t}\n\n\tconst swapModeEnum = parseSwapMode(swapMode);\n\n\t// Validate amount parameters based on swap mode\n\tif (swapModeEnum === 'ExactIn') {\n\t\tif (!fromAmount) {\n\t\t\tthrow new Error('ExactIn swap mode requires --fromAmount');\n\t\t}\n\t\tif (toAmount) {\n\t\t\tconsole.warn(\n\t\t\t\t'⚠️ Warning: --toAmount ignored in ExactIn mode, using --fromAmount'\n\t\t\t);\n\t\t}\n\t} else if (swapModeEnum === 'ExactOut') {\n\t\tif (!toAmount) {\n\t\t\tthrow new Error('ExactOut swap mode requires --toAmount');\n\t\t}\n\t\tif (fromAmount) {\n\t\t\tconsole.warn(\n\t\t\t\t'⚠️ Warning: --fromAmount ignored in ExactOut mode, using --toAmount'\n\t\t\t);\n\t\t}\n\t}\n\n\tconst userAccountPubkey = new PublicKey(userAccount);\n\n\t// Use the appropriate amount based on swap mode\n\tconst amount = swapModeEnum === 'ExactIn' ? fromAmount : toAmount;\n\n\t// Determine which market to use for precision (input market for ExactIn, output market for ExactOut)\n\tconst precisionMarketIndex =\n\t\tswapModeEnum === 'ExactIn' ? fromMarketIndex : toMarketIndex;\n\n\t// Get the appropriate precision for the amount based on the market\n\tconst isMainnet = true; // Default to mainnet, could be made configurable\n\tconst precision = getMarketPrecision(precisionMarketIndex, isMainnet);\n\tconst amountBN = parseAmount(amount, precision);\n\n\tconsole.log('--- 🔄 Swap Transaction ---');\n\tconsole.log(`👤 User Account: ${userAccount}`);\n\tconsole.log(`📤 From Market Index: ${fromMarketIndex}`);\n\tconsole.log(`📥 To Market Index: ${toMarketIndex}`);\n\tconsole.log(`🔄 Swap Mode: ${swapMode}`);\n\tconsole.log(\n\t\t`🎯 Using precision from market ${precisionMarketIndex}: ${precision.toString()}`\n\t);\n\n\tif (swapModeEnum === 'ExactIn') {\n\t\tconsole.log(\n\t\t\t`💰 From Amount: ${fromAmount} (${amountBN.toString()} raw units)`\n\t\t);\n\t\tconsole.log(`💰 To Amount: Will be calculated based on quote`);\n\t} else {\n\t\tconsole.log(`💰 From Amount: Will be calculated based on quote`);\n\t\tconsole.log(`💰 To Amount: ${toAmount} (${amountBN.toString()} raw units)`);\n\t}\n\n\tconsole.log(`📊 Slippage: ${slippage} BPS (${slippage / 100}%)`);\n\n\tconst swapTxn = await centralServerDrift.getSwapTxn(\n\t\tuserAccountPubkey,\n\t\tfromMarketIndex,\n\t\ttoMarketIndex,\n\t\tamountBN,\n\t\t{\n\t\t\tslippageBps: slippage,\n\t\t\tswapMode: swapModeEnum,\n\t\t}\n\t);\n\n\tawait executeTransaction(swapTxn as VersionedTransaction, 'Swap');\n}\n\n/**\n * Main CLI entry point\n */\nasync function main(): Promise<void> {\n\tconst args = process.argv.slice(2);\n\n\tif (\n\t\targs.length === 0 ||\n\t\targs[0] === '--help' ||\n\t\targs[0] === '-h' ||\n\t\targs[0] === 'help'\n\t) {\n\t\tshowUsage();\n\t\treturn;\n\t}\n\n\tconst command = args[0];\n\tconst parsedArgs = parseArgs(args.slice(1));\n\n\t// Initialize the client first\n\tawait initializeCentralServerDrift();\n\n\t// Route to appropriate command\n\tswitch (command) {\n\t\tcase 'deposit':\n\t\t\tawait depositCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'withdraw':\n\t\t\tawait withdrawCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'settleFunding':\n\t\t\tawait settleFundingCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'settlePnl':\n\t\t\tawait settlePnlCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'openPerpMarketOrder':\n\t\t\tawait openPerpMarketOrderCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'openPerpMarketOrderSwift':\n\t\t\tawait openPerpMarketOrderSwiftCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'openPerpNonMarketOrder':\n\t\t\tawait openPerpNonMarketOrderCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'openPerpNonMarketOrderSwift':\n\t\t\tawait openPerpNonMarketOrderSwiftCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'editOrder':\n\t\t\tawait editOrderCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'cancelOrder':\n\t\t\tawait cancelOrderCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'cancelAllOrders':\n\t\t\tawait cancelAllOrdersCommand(parsedArgs);\n\t\t\tbreak;\n\t\tcase 'swap':\n\t\t\tawait swapCommand(parsedArgs);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tconsole.error(`❌ Unknown command: ${command}`);\n\t\t\tconsole.error('');\n\t\t\tshowUsage();\n\t\t\tprocess.exit(1);\n\t}\n}\n\n// Run CLI if this file is executed directly\nif (require.main === module) {\n\tmain()\n\t\t.then(() => {\n\t\t\tconsole.log('\\n✨ Command executed successfully!');\n\t\t\t// Don't exit immediately for Swift orders (they need time to process)\n\t\t\tsetTimeout(() => process.exit(0), 2000);\n\t\t})\n\t\t.catch((error) => {\n\t\t\tconsole.error('\\n💥 Command failed:', error.message || error);\n\t\t\tprocess.exit(1);\n\t\t});\n}\n\nexport { main, parseArgs, parseAmount, parseDirection, parseSwapMode };\n"]}
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"CentralServerDrift.js","sourceRoot":"","sources":["../../../../src/drift/Drift/clients/CentralServerDrift.ts"],"names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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;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"]}
|