@drift-labs/common 1.0.17 โ 1.0.19
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/EnvironmentConstants.js +2 -2
- package/lib/EnvironmentConstants.js.map +1 -1
- package/lib/actions/actionHelpers/actionHelpers.d.ts +9 -9
- package/lib/clients/redisClient.d.ts +0 -1
- package/lib/clients/swiftClient.d.ts +1 -1
- package/lib/clients/swiftClient.js +60 -20
- package/lib/clients/swiftClient.js.map +1 -1
- package/lib/clients/tvFeed.d.ts +2 -1
- package/lib/clients/tvFeed.js +4 -3
- package/lib/clients/tvFeed.js.map +1 -1
- package/lib/common-ui-utils/commonUiUtils.d.ts +4 -2
- package/lib/common-ui-utils/commonUiUtils.js.map +1 -1
- package/lib/common-ui-utils/user.js +3 -1
- package/lib/common-ui-utils/user.js.map +1 -1
- package/lib/constants/autogenerated/driftErrors.json +5 -1
- package/lib/constants/predictionMarket.d.ts +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/DriftL2OrderbookManager.d.ts +10 -10
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.d.ts +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js +18 -5
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js.map +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/types.d.ts +10 -2
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/types.js.map +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/index.d.ts +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/index.js.map +1 -1
- package/lib/drift/Drift/clients/CentralServerDrift/index.d.ts +7 -2
- package/lib/drift/Drift/clients/CentralServerDrift/index.js +13 -7
- package/lib/drift/Drift/clients/CentralServerDrift/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/index.d.ts +1 -0
- package/lib/drift/base/actions/trade/openPerpOrder/index.js +1 -0
- package/lib/drift/base/actions/trade/openPerpOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.d.ts +34 -0
- package/lib/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.js +45 -0
- package/lib/drift/base/actions/trade/openPerpOrder/isolatedPositionDeposit.js.map +1 -0
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.d.ts +12 -4
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js +17 -4
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js +11 -7
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.d.ts +15 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js +12 -8
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/positionMaxLeverage.d.ts +2 -2
- package/lib/drift/base/actions/trade/openPerpOrder/positionMaxLeverage.js +6 -2
- package/lib/drift/base/actions/trade/openPerpOrder/positionMaxLeverage.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/types.d.ts +1 -0
- package/lib/drift/base/actions/trade/openPerpOrder/types.js.map +1 -1
- package/lib/drift/base/actions/trade/swap.d.ts +6 -13
- package/lib/drift/base/actions/trade/swap.js +11 -36
- package/lib/drift/base/actions/trade/swap.js.map +1 -1
- package/lib/drift/base/actions/user/create.d.ts +9 -2
- package/lib/drift/base/actions/user/create.js +15 -6
- package/lib/drift/base/actions/user/create.js.map +1 -1
- package/lib/drift/base/details/user/balances.d.ts +1 -1
- package/lib/drift/base/details/user/positions.d.ts +1 -1
- package/lib/drift/cli.js +28 -6
- package/lib/drift/cli.js.map +1 -1
- package/lib/drift/utils/funding.d.ts +0 -1
- package/lib/serializableTypes.d.ts +11 -0
- package/lib/serializableTypes.js +321 -217
- package/lib/serializableTypes.js.map +1 -1
- package/lib/types/UIMarket.d.ts +2 -2
- package/lib/utils/NumLib.d.ts +4 -4
- package/lib/utils/ResultSlotIncrementer.d.ts +4 -0
- package/lib/utils/ResultSlotIncrementer.js +8 -0
- package/lib/utils/ResultSlotIncrementer.js.map +1 -1
- package/lib/utils/index.d.ts +2 -3
- package/lib/utils/math.d.ts +3 -3
- package/lib/utils/token.d.ts +2 -1
- package/lib/utils/token.js +3 -2
- package/lib/utils/token.js.map +1 -1
- package/package.json +20 -5
|
@@ -1,13 +1,11 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.createSwapTxn = exports.createSwapIxDetails = void 0;
|
|
4
|
-
const sdk_1 = require("@drift-labs/sdk");
|
|
5
4
|
/**
|
|
6
5
|
* Creates swap instruction details for a swap through Drift
|
|
7
6
|
*
|
|
8
7
|
* @param driftClient - The Drift client instance
|
|
9
8
|
* @param swapClient - The swap client instance for performing the swap (supports UnifiedSwapClient or JupiterClient)
|
|
10
|
-
* @param jupiterClient - @deprecated Use swapClient instead. Kept for backwards compatibility.
|
|
11
9
|
* @param quote - Quote response from swap provider with routing information
|
|
12
10
|
* @param swapFromMarketIndex - Source token market index
|
|
13
11
|
* @param swapToMarketIndex - Destination token market index
|
|
@@ -17,37 +15,16 @@ const sdk_1 = require("@drift-labs/sdk");
|
|
|
17
15
|
* @returns ixs - Array of Solana transaction instructions for the swap
|
|
18
16
|
* @returns lookupTables - Address lookup table accounts for transaction compression
|
|
19
17
|
*/
|
|
20
|
-
const createSwapIxDetails = async ({ driftClient, swapClient,
|
|
21
|
-
|
|
22
|
-
const
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
swapIxsDetails = await driftClient.getSwapIxV2({
|
|
31
|
-
swapClient: clientToUse,
|
|
32
|
-
outMarketIndex: swapToMarketIndex,
|
|
33
|
-
inMarketIndex: swapFromMarketIndex,
|
|
34
|
-
amount,
|
|
35
|
-
quote,
|
|
36
|
-
});
|
|
37
|
-
}
|
|
38
|
-
else {
|
|
39
|
-
// JupiterClient path
|
|
40
|
-
swapIxsDetails = await driftClient.getJupiterSwapIxV6({
|
|
41
|
-
jupiterClient: clientToUse,
|
|
42
|
-
outMarketIndex: swapToMarketIndex,
|
|
43
|
-
inMarketIndex: swapFromMarketIndex,
|
|
44
|
-
amount,
|
|
45
|
-
quote,
|
|
46
|
-
userAccountPublicKey: userPublicKey,
|
|
47
|
-
// we skip passing in the associated token accounts and have the swap client derive them instead.
|
|
48
|
-
// The swap client will also add the ixs to create the associated token accounts if they don't exist.
|
|
49
|
-
});
|
|
50
|
-
}
|
|
18
|
+
const createSwapIxDetails = async ({ driftClient, swapClient, quote, swapFromMarketIndex, swapToMarketIndex, amount, user, }) => {
|
|
19
|
+
const userPublicKey = user.userAccountPublicKey;
|
|
20
|
+
const swapIxsDetails = await driftClient.getSwapIxV2({
|
|
21
|
+
swapClient,
|
|
22
|
+
outMarketIndex: swapToMarketIndex,
|
|
23
|
+
inMarketIndex: swapFromMarketIndex,
|
|
24
|
+
amount,
|
|
25
|
+
quote,
|
|
26
|
+
userAccountPublicKey: userPublicKey,
|
|
27
|
+
});
|
|
51
28
|
return swapIxsDetails;
|
|
52
29
|
};
|
|
53
30
|
exports.createSwapIxDetails = createSwapIxDetails;
|
|
@@ -56,7 +33,6 @@ exports.createSwapIxDetails = createSwapIxDetails;
|
|
|
56
33
|
*
|
|
57
34
|
* @param driftClient - The Drift client instance
|
|
58
35
|
* @param swapClient - The swap client instance for performing the swap (supports UnifiedSwapClient or JupiterClient)
|
|
59
|
-
* @param jupiterClient - @deprecated Use swapClient instead. Kept for backwards compatibility.
|
|
60
36
|
* @param quote - Quote response from swap provider with routing information
|
|
61
37
|
* @param swapFromMarketIndex - Source token market index
|
|
62
38
|
* @param swapToMarketIndex - Destination token market index
|
|
@@ -65,11 +41,10 @@ exports.createSwapIxDetails = createSwapIxDetails;
|
|
|
65
41
|
* @param txParams - Transaction parameters for fees and compute units
|
|
66
42
|
* @returns Promise resolving to either a legacy Transaction or VersionedTransaction ready for signing
|
|
67
43
|
*/
|
|
68
|
-
const createSwapTxn = async ({ driftClient, swapClient,
|
|
44
|
+
const createSwapTxn = async ({ driftClient, swapClient, quote, swapFromMarketIndex, swapToMarketIndex, amount, user, txParams, }) => {
|
|
69
45
|
const swapIxsDetails = await (0, exports.createSwapIxDetails)({
|
|
70
46
|
driftClient,
|
|
71
47
|
swapClient,
|
|
72
|
-
jupiterClient,
|
|
73
48
|
quote,
|
|
74
49
|
swapFromMarketIndex,
|
|
75
50
|
swapToMarketIndex,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swap.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/trade/swap.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"swap.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/trade/swap.ts"],"names":[],"mappings":";;;AAmCA;;;;;;;;;;;;;GAaG;AACI,MAAM,mBAAmB,GAAG,KAAK,EAAE,EACzC,WAAW,EACX,UAAU,EACV,KAAK,EACL,mBAAmB,EACnB,iBAAiB,EACjB,MAAM,EACN,IAAI,GACuB,EAGzB,EAAE;IACJ,MAAM,aAAa,GAAG,IAAI,CAAC,oBAAoB,CAAC;IAEhD,MAAM,cAAc,GAAG,MAAM,WAAW,CAAC,WAAW,CAAC;QACpD,UAAU;QACV,cAAc,EAAE,iBAAiB;QACjC,aAAa,EAAE,mBAAmB;QAClC,MAAM;QACN,KAAK;QACL,oBAAoB,EAAE,aAAa;KACnC,CAAC,CAAC;IAEH,OAAO,cAAc,CAAC;AACvB,CAAC,CAAC;AAxBW,QAAA,mBAAmB,uBAwB9B;AAWF;;;;;;;;;;;;GAYG;AACI,MAAM,aAAa,GAAG,KAAK,EAAE,EACnC,WAAW,EACX,UAAU,EACV,KAAK,EACL,mBAAmB,EACnB,iBAAiB,EACjB,MAAM,EACN,IAAI,EACJ,QAAQ,GACa,EAA+C,EAAE;IACtE,MAAM,cAAc,GAAG,MAAM,IAAA,2BAAmB,EAAC;QAChD,WAAW;QACX,UAAU;QACV,KAAK;QACL,mBAAmB;QACnB,iBAAiB;QACjB,MAAM;QACN,IAAI;KACJ,CAAC,CAAC;IAEH,MAAM,EAAE,GAAG,MAAM,WAAW,CAAC,gBAAgB,CAC5C,cAAc,CAAC,GAAG,EAClB,QAAQ,EACR,CAAC,EACD,cAAc,CAAC,YAAY,CAC3B,CAAC;IAEF,OAAO,EAAE,CAAC;AACX,CAAC,CAAC;AA5BW,QAAA,aAAa,iBA4BxB","sourcesContent":["import {\n\tBN,\n\tDriftClient,\n\tTxParams,\n\tUnifiedQuoteResponse,\n\tUnifiedSwapClient,\n\tUser,\n} from '@drift-labs/sdk';\nimport {\n\tAddressLookupTableAccount,\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\n\n/**\n * Parameters for creating swap instruction details\n */\ninterface CreateSwapIxDetailsParams {\n\t/** The Drift client instance for interacting with the Drift protocol */\n\tdriftClient: DriftClient;\n\t/** Quote response from swap provider containing swap route information */\n\tquote: UnifiedQuoteResponse;\n\t/** Swap client instance for performing the swap */\n\tswapClient?: UnifiedSwapClient;\n\t/** Market index of the token being swapped from */\n\tswapFromMarketIndex: number;\n\t/** Market index of the token being swapped to */\n\tswapToMarketIndex: number;\n\t/** Amount to swap in base units */\n\tamount: BN;\n\t/** User instance containing account information */\n\tuser: User;\n}\n\n/**\n * Creates swap instruction details for a swap through Drift\n *\n * @param driftClient - The Drift client instance\n * @param swapClient - The swap client instance for performing the swap (supports UnifiedSwapClient or JupiterClient)\n * @param quote - Quote response from swap provider with routing information\n * @param swapFromMarketIndex - Source token market index\n * @param swapToMarketIndex - Destination token market index\n * @param amount - Amount to swap in base units\n * @param user - User account instance\n * @returns Promise resolving to an object containing transaction instructions and lookup tables\n * @returns ixs - Array of Solana transaction instructions for the swap\n * @returns lookupTables - Address lookup table accounts for transaction compression\n */\nexport const createSwapIxDetails = async ({\n\tdriftClient,\n\tswapClient,\n\tquote,\n\tswapFromMarketIndex,\n\tswapToMarketIndex,\n\tamount,\n\tuser,\n}: CreateSwapIxDetailsParams): Promise<{\n\tixs: TransactionInstruction[];\n\tlookupTables: AddressLookupTableAccount[];\n}> => {\n\tconst userPublicKey = user.userAccountPublicKey;\n\n\tconst swapIxsDetails = await driftClient.getSwapIxV2({\n\t\tswapClient,\n\t\toutMarketIndex: swapToMarketIndex,\n\t\tinMarketIndex: swapFromMarketIndex,\n\t\tamount,\n\t\tquote,\n\t\tuserAccountPublicKey: userPublicKey,\n\t});\n\n\treturn swapIxsDetails;\n};\n\n/**\n * Parameters for creating a complete swap transaction\n * Extends CreateSwapIxDetailsParams with additional transaction parameters\n */\ninterface CreateSwapTxnParams extends CreateSwapIxDetailsParams {\n\t/** Transaction parameters including compute units, priority fees, and other options */\n\ttxParams?: TxParams;\n}\n\n/**\n * Creates a complete swap transaction ready for signing and submission\n *\n * @param driftClient - The Drift client instance\n * @param swapClient - The swap client instance for performing the swap (supports UnifiedSwapClient or JupiterClient)\n * @param quote - Quote response from swap provider with routing information\n * @param swapFromMarketIndex - Source token market index\n * @param swapToMarketIndex - Destination token market index\n * @param amount - Amount to swap in base units\n * @param user - User account instance\n * @param txParams - Transaction parameters for fees and compute units\n * @returns Promise resolving to either a legacy Transaction or VersionedTransaction ready for signing\n */\nexport const createSwapTxn = async ({\n\tdriftClient,\n\tswapClient,\n\tquote,\n\tswapFromMarketIndex,\n\tswapToMarketIndex,\n\tamount,\n\tuser,\n\ttxParams,\n}: CreateSwapTxnParams): Promise<Transaction | VersionedTransaction> => {\n\tconst swapIxsDetails = await createSwapIxDetails({\n\t\tdriftClient,\n\t\tswapClient,\n\t\tquote,\n\t\tswapFromMarketIndex,\n\t\tswapToMarketIndex,\n\t\tamount,\n\t\tuser,\n\t});\n\n\tconst tx = await driftClient.buildTransaction(\n\t\tswapIxsDetails.ixs,\n\t\ttxParams,\n\t\t0,\n\t\tswapIxsDetails.lookupTables\n\t);\n\n\treturn tx;\n};\n"]}
|
|
@@ -12,6 +12,11 @@ interface CreateUserAndDepositCollateralBaseIxsParams {
|
|
|
12
12
|
fromSubAccountId?: number;
|
|
13
13
|
customMaxMarginRatio?: number;
|
|
14
14
|
delegate?: PublicKey;
|
|
15
|
+
/**
|
|
16
|
+
* Optional external wallet to deposit from. If provided, the deposit will be made
|
|
17
|
+
* from this wallet instead of the authority wallet.
|
|
18
|
+
*/
|
|
19
|
+
externalWallet?: PublicKey;
|
|
15
20
|
}
|
|
16
21
|
/**
|
|
17
22
|
* Creates transaction instructions for initializing a new user account and depositing collateral.
|
|
@@ -31,13 +36,14 @@ interface CreateUserAndDepositCollateralBaseIxsParams {
|
|
|
31
36
|
* @param fromSubAccountId - Optional sub-account ID to transfer funds from
|
|
32
37
|
* @param customMaxMarginRatio - Optional custom maximum margin ratio for the account
|
|
33
38
|
* @param delegate - Optional delegate public key for the account. Immediately assigns this as the delegate of the account.
|
|
39
|
+
* @param externalWallet - Optional external wallet to deposit from (instead of authority wallet)
|
|
34
40
|
*
|
|
35
41
|
* @returns Promise resolving to an object containing:
|
|
36
42
|
* - subAccountId: The ID of the newly created sub-account
|
|
37
43
|
* - userAccountPublicKey: The public key of the created user account
|
|
38
44
|
* - ixs: Array of transaction instructions to execute
|
|
39
45
|
*/
|
|
40
|
-
export declare const createUserAndDepositCollateralBaseIxs: ({ driftClient, amount, spotMarketConfig, authority, userStatsAccount, referrerName, accountName, poolId, fromSubAccountId, customMaxMarginRatio, delegate, }: CreateUserAndDepositCollateralBaseIxsParams) => Promise<{
|
|
46
|
+
export declare const createUserAndDepositCollateralBaseIxs: ({ driftClient, amount, spotMarketConfig, authority, userStatsAccount, referrerName, accountName, poolId, fromSubAccountId, customMaxMarginRatio, delegate, externalWallet, }: CreateUserAndDepositCollateralBaseIxsParams) => Promise<{
|
|
41
47
|
subAccountId: number;
|
|
42
48
|
userAccountPublicKey: PublicKey;
|
|
43
49
|
ixs: TransactionInstruction[];
|
|
@@ -63,13 +69,14 @@ interface CreateUserAndDepositCollateralBaseTxnParams extends CreateUserAndDepos
|
|
|
63
69
|
* @param fromSubAccountId - Optional sub-account ID to transfer funds from
|
|
64
70
|
* @param customMaxMarginRatio - Optional custom maximum margin ratio for the account
|
|
65
71
|
* @param txParams - Transaction parameters for building the transaction (compute units, priority fees, etc.)
|
|
72
|
+
* @param externalWallet - Optional external wallet to deposit from (instead of authority wallet)
|
|
66
73
|
*
|
|
67
74
|
* @returns Promise resolving to an object containing:
|
|
68
75
|
* - transaction: The built transaction ready for signing (Transaction or VersionedTransaction)
|
|
69
76
|
* - userAccountPublicKey: The public key of the created user account
|
|
70
77
|
* - subAccountId: The ID of the newly created sub-account
|
|
71
78
|
*/
|
|
72
|
-
export declare const createUserAndDepositCollateralBaseTxn: ({ driftClient, amount, spotMarketConfig, authority, userStatsAccount, referrerName, accountName, poolId, fromSubAccountId, customMaxMarginRatio, txParams, }: CreateUserAndDepositCollateralBaseTxnParams) => Promise<{
|
|
79
|
+
export declare const createUserAndDepositCollateralBaseTxn: ({ driftClient, amount, spotMarketConfig, authority, userStatsAccount, referrerName, accountName, poolId, fromSubAccountId, customMaxMarginRatio, txParams, externalWallet, }: CreateUserAndDepositCollateralBaseTxnParams) => Promise<{
|
|
73
80
|
transaction: Transaction | VersionedTransaction;
|
|
74
81
|
userAccountPublicKey: PublicKey;
|
|
75
82
|
subAccountId: number;
|
|
@@ -24,16 +24,24 @@ const user_1 = require("../../../../common-ui-utils/user");
|
|
|
24
24
|
* @param fromSubAccountId - Optional sub-account ID to transfer funds from
|
|
25
25
|
* @param customMaxMarginRatio - Optional custom maximum margin ratio for the account
|
|
26
26
|
* @param delegate - Optional delegate public key for the account. Immediately assigns this as the delegate of the account.
|
|
27
|
+
* @param externalWallet - Optional external wallet to deposit from (instead of authority wallet)
|
|
27
28
|
*
|
|
28
29
|
* @returns Promise resolving to an object containing:
|
|
29
30
|
* - subAccountId: The ID of the newly created sub-account
|
|
30
31
|
* - userAccountPublicKey: The public key of the created user account
|
|
31
32
|
* - ixs: Array of transaction instructions to execute
|
|
32
33
|
*/
|
|
33
|
-
const createUserAndDepositCollateralBaseIxs = async ({ driftClient, amount, spotMarketConfig, authority, userStatsAccount, referrerName, accountName, poolId = pools_1.MAIN_POOL_ID, fromSubAccountId, customMaxMarginRatio, delegate, }) => {
|
|
34
|
+
const createUserAndDepositCollateralBaseIxs = async ({ driftClient, amount, spotMarketConfig, authority, userStatsAccount, referrerName, accountName, poolId = pools_1.MAIN_POOL_ID, fromSubAccountId, customMaxMarginRatio, delegate, externalWallet, }) => {
|
|
34
35
|
var _a;
|
|
35
36
|
const nextSubaccountId = (_a = userStatsAccount === null || userStatsAccount === void 0 ? void 0 : userStatsAccount.numberOfSubAccountsCreated) !== null && _a !== void 0 ? _a : 0; // userId is zero indexed
|
|
36
|
-
|
|
37
|
+
// Get the spot market account to determine the correct token program for Token-2022 tokens
|
|
38
|
+
const spotMarketAccount = driftClient.getSpotMarketAccount(spotMarketConfig.marketIndex);
|
|
39
|
+
const tokenProgram = spotMarketAccount
|
|
40
|
+
? (0, sdk_1.getTokenProgramForSpotMarket)(spotMarketAccount)
|
|
41
|
+
: undefined;
|
|
42
|
+
// Use external wallet for token address if provided, otherwise use authority
|
|
43
|
+
const depositSourceWallet = externalWallet !== null && externalWallet !== void 0 ? externalWallet : authority;
|
|
44
|
+
const associatedDepositTokenAddressPromise = (0, token_1.getTokenAddressForDepositAndWithdraw)(spotMarketConfig.mint, depositSourceWallet, tokenProgram);
|
|
37
45
|
const referrerNameAccountPromise = referrerName
|
|
38
46
|
? driftClient.fetchReferrerNameAccount(referrerName)
|
|
39
47
|
: Promise.resolve(undefined);
|
|
@@ -59,9 +67,8 @@ const createUserAndDepositCollateralBaseIxs = async ({ driftClient, amount, spot
|
|
|
59
67
|
referrerStats: referrerNameAccount.userStats,
|
|
60
68
|
}
|
|
61
69
|
: undefined;
|
|
62
|
-
const ixs =
|
|
63
|
-
const
|
|
64
|
-
ixs.push(...createAndDepositIxs);
|
|
70
|
+
const { ixs: createAndDepositIxs, userAccountPublicKey } = await driftClient.createInitializeUserAccountAndDepositCollateralIxs(amount, associatedDepositTokenAddress, spotMarketConfig.marketIndex, nextSubaccountId, accountNameToUse, fromSubAccountId, referrerInfo, sdk_1.ZERO, customMaxMarginRatio, poolId, externalWallet ? { externalWallet } : undefined);
|
|
71
|
+
const ixs = [...createAndDepositIxs];
|
|
65
72
|
const nextSubAccountPublicKey = (0, sdk_1.getUserAccountPublicKeySync)(driftClient.program.programId, authority, nextSubaccountId);
|
|
66
73
|
const delegateIx = delegate
|
|
67
74
|
? await driftClient.getUpdateUserDelegateIx(delegate, {
|
|
@@ -98,13 +105,14 @@ exports.createUserAndDepositCollateralBaseIxs = createUserAndDepositCollateralBa
|
|
|
98
105
|
* @param fromSubAccountId - Optional sub-account ID to transfer funds from
|
|
99
106
|
* @param customMaxMarginRatio - Optional custom maximum margin ratio for the account
|
|
100
107
|
* @param txParams - Transaction parameters for building the transaction (compute units, priority fees, etc.)
|
|
108
|
+
* @param externalWallet - Optional external wallet to deposit from (instead of authority wallet)
|
|
101
109
|
*
|
|
102
110
|
* @returns Promise resolving to an object containing:
|
|
103
111
|
* - transaction: The built transaction ready for signing (Transaction or VersionedTransaction)
|
|
104
112
|
* - userAccountPublicKey: The public key of the created user account
|
|
105
113
|
* - subAccountId: The ID of the newly created sub-account
|
|
106
114
|
*/
|
|
107
|
-
const createUserAndDepositCollateralBaseTxn = async ({ driftClient, amount, spotMarketConfig, authority, userStatsAccount, referrerName, accountName, poolId = pools_1.MAIN_POOL_ID, fromSubAccountId, customMaxMarginRatio, txParams, }) => {
|
|
115
|
+
const createUserAndDepositCollateralBaseTxn = async ({ driftClient, amount, spotMarketConfig, authority, userStatsAccount, referrerName, accountName, poolId = pools_1.MAIN_POOL_ID, fromSubAccountId, customMaxMarginRatio, txParams, externalWallet, }) => {
|
|
108
116
|
const { ixs, userAccountPublicKey, subAccountId } = await (0, exports.createUserAndDepositCollateralBaseIxs)({
|
|
109
117
|
driftClient,
|
|
110
118
|
amount,
|
|
@@ -116,6 +124,7 @@ const createUserAndDepositCollateralBaseTxn = async ({ driftClient, amount, spot
|
|
|
116
124
|
poolId,
|
|
117
125
|
fromSubAccountId,
|
|
118
126
|
customMaxMarginRatio,
|
|
127
|
+
externalWallet,
|
|
119
128
|
});
|
|
120
129
|
const tx = await driftClient.buildTransaction(ixs, txParams);
|
|
121
130
|
return { transaction: tx, userAccountPublicKey, subAccountId };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/user/create.ts"],"names":[],"mappings":";;;AAAA,yCAWyB;AACzB,mDAA+E;AAC/E,+DAAgF;AAChF,uDAA2D;AAM3D,2DAA8D;AAgB9D;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACI,MAAM,qCAAqC,GAAG,KAAK,EAAE,EAC3D,WAAW,EACX,MAAM,EACN,gBAAgB,EAChB,SAAS,EACT,gBAAgB,EAChB,YAAY,EACZ,WAAW,EACX,MAAM,GAAG,oBAAY,EACrB,gBAAgB,EAChB,oBAAoB,EACpB,QAAQ,GACqC,EAI3C,EAAE;;IACJ,MAAM,gBAAgB,GAAG,MAAA,gBAAgB,aAAhB,gBAAgB,uBAAhB,gBAAgB,CAAE,0BAA0B,mCAAI,CAAC,CAAC,CAAC,yBAAyB;IAErG,MAAM,oCAAoC,GACzC,IAAA,4CAAoC,EAAC,gBAAgB,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;IACxE,MAAM,0BAA0B,GAC/B,YAAY;QACX,CAAC,CAAC,WAAW,CAAC,wBAAwB,CAAC,YAAY,CAAC;QACpD,CAAC,CAAC,OAAO,CAAC,O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ReferrerNameAccount,\n\tSpotMarketConfig,\n\tTxParams,\n\tUserStatsAccount,\n\tZERO,\n} from '@drift-labs/sdk';\nimport { getTokenAddressForDepositAndWithdraw } from '../../../../utils/token';\nimport { DEFAULT_ACCOUNT_NAMES_BY_POOL_ID } from '../../constants/accountNames';\nimport { MAIN_POOL_ID } from '../../../../constants/pools';\nimport {\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport { USER_UTILS } from '../../../../common-ui-utils/user';\n\ninterface CreateUserAndDepositCollateralBaseIxsParams {\n\tdriftClient: DriftClient;\n\tamount: BN;\n\tspotMarketConfig: SpotMarketConfig;\n\tauthority: PublicKey;\n\tuserStatsAccount: UserStatsAccount | undefined;\n\treferrerName?: string;\n\taccountName?: string;\n\tpoolId?: number;\n\tfromSubAccountId?: number;\n\tcustomMaxMarginRatio?: number;\n\tdelegate?: PublicKey;\n}\n\n/**\n * Creates transaction instructions for initializing a new user account and depositing collateral.\n *\n * This function generates the necessary transaction instructions to:\n * 1. Initialize a new user account in the Drift protocol\n * 2. Deposit collateral into the newly created account\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param amount - The amount of collateral to deposit (in base units)\n * @param spotMarketConfig - The spot market config of the deposit collateral\n * @param authority - The public key of the account authority (wallet owner)\n * @param userStatsAccount - Existing user stats account, used to determine next sub-account ID\n * @param referrerName - Optional name of the referrer for referral tracking\n * @param accountName - Optional custom name for the account (defaults to pool-specific name)\n * @param poolId - The pool ID to associate the account with (defaults to MAIN_POOL_ID)\n * @param fromSubAccountId - Optional sub-account ID to transfer funds from\n * @param customMaxMarginRatio - Optional custom maximum margin ratio for the account\n * @param delegate - Optional delegate public key for the account. Immediately assigns this as the delegate of the account.\n *\n * @returns Promise resolving to an object containing:\n * - subAccountId: The ID of the newly created sub-account\n * - userAccountPublicKey: The public key of the created user account\n * - ixs: Array of transaction instructions to execute\n */\nexport const createUserAndDepositCollateralBaseIxs = async ({\n\tdriftClient,\n\tamount,\n\tspotMarketConfig,\n\tauthority,\n\tuserStatsAccount,\n\treferrerName,\n\taccountName,\n\tpoolId = MAIN_POOL_ID,\n\tfromSubAccountId,\n\tcustomMaxMarginRatio,\n\tdelegate,\n}: CreateUserAndDepositCollateralBaseIxsParams): Promise<{\n\tsubAccountId: number;\n\tuserAccountPublicKey: PublicKey;\n\tixs: TransactionInstruction[];\n}> => {\n\tconst nextSubaccountId = userStatsAccount?.numberOfSubAccountsCreated ?? 0; // userId is zero indexed\n\n\tconst associatedDepositTokenAddressPromise =\n\t\tgetTokenAddressForDepositAndWithdraw(spotMarketConfig.mint, authority);\n\tconst referrerNameAccountPromise: Promise<ReferrerNameAccount | undefined> =\n\t\treferrerName\n\t\t\t? driftClient.fetchReferrerNameAccount(referrerName)\n\t\t\t: Promise.resolve(undefined);\n\tconst subaccountExistsPromise = USER_UTILS.checkIfUserAccountExists(\n\t\tdriftClient,\n\t\t{\n\t\t\ttype: 'subAccountId',\n\t\t\tsubAccountId: nextSubaccountId,\n\t\t\tauthority,\n\t\t}\n\t);\n\n\tconst [associatedDepositTokenAddress, referrerNameAccount, subaccountExists] =\n\t\tawait Promise.all([\n\t\t\tassociatedDepositTokenAddressPromise,\n\t\t\treferrerNameAccountPromise,\n\t\t\tsubaccountExistsPromise,\n\t\t]);\n\n\tif (subaccountExists) {\n\t\tthrow new Error('Subaccount already exists');\n\t}\n\n\tconst accountNameToUse =\n\t\taccountName ??\n\t\t(poolId !== MAIN_POOL_ID || nextSubaccountId === 0\n\t\t\t? DEFAULT_ACCOUNT_NAMES_BY_POOL_ID[poolId]\n\t\t\t: `Account ${nextSubaccountId}`);\n\n\tconst referrerInfo: ReferrerInfo | undefined = referrerNameAccount\n\t\t? {\n\t\t\t\treferrer: referrerNameAccount.user,\n\t\t\t\treferrerStats: referrerNameAccount.userStats,\n\t\t }\n\t\t: undefined;\n\n\tconst ixs = [];\n\tconst { ixs: createAndDepositIxs, userAccountPublicKey } =\n\t\tawait driftClient.createInitializeUserAccountAndDepositCollateralIxs(\n\t\t\tamount,\n\t\t\tassociatedDepositTokenAddress,\n\t\t\tspotMarketConfig.marketIndex,\n\t\t\tnextSubaccountId,\n\t\t\taccountNameToUse,\n\t\t\tfromSubAccountId,\n\t\t\treferrerInfo,\n\t\t\tZERO,\n\t\t\tcustomMaxMarginRatio,\n\t\t\tpoolId\n\t\t);\n\tixs.push(...createAndDepositIxs);\n\n\tconst nextSubAccountPublicKey = getUserAccountPublicKeySync(\n\t\tdriftClient.program.programId,\n\t\tauthority,\n\t\tnextSubaccountId\n\t);\n\tconst delegateIx = delegate\n\t\t? await driftClient.getUpdateUserDelegateIx(delegate, {\n\t\t\t\tsubAccountId: nextSubaccountId,\n\t\t\t\tuserAccountPublicKey: nextSubAccountPublicKey,\n\t\t\t\tauthority,\n\t\t })\n\t\t: undefined;\n\n\tif (delegateIx) {\n\t\tixs.push(delegateIx);\n\t}\n\n\treturn {\n\t\tsubAccountId: nextSubaccountId,\n\t\tuserAccountPublicKey,\n\t\tixs,\n\t};\n};\n\ninterface CreateUserAndDepositCollateralBaseTxnParams\n\textends CreateUserAndDepositCollateralBaseIxsParams {\n\ttxParams?: TxParams;\n}\n\n/**\n * Creates a complete transaction for initializing a new user account and depositing collateral.\n *\n * This function is a higher-level wrapper around `createUserAndDepositCollateralBaseIxs` that:\n * 1. Generates the necessary transaction instructions\n * 2. Builds a complete transaction ready for signing and submission\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param amount - The amount of collateral to deposit (in base units)\n * @param spotMarketConfig - The spot market config of the deposit collateral\n * @param authority - The public key of the account authority (wallet owner)\n * @param userStatsAccount - Existing user stats account, used to determine next sub-account ID\n * @param referrerName - Optional name of the referrer for referral tracking\n * @param accountName - Optional custom name for the account (defaults to pool-specific name)\n * @param poolId - The pool ID to associate the account with (defaults to MAIN_POOL_ID)\n * @param fromSubAccountId - Optional sub-account ID to transfer funds from\n * @param customMaxMarginRatio - Optional custom maximum margin ratio for the account\n * @param txParams - Transaction parameters for building the transaction (compute units, priority fees, etc.)\n *\n * @returns Promise resolving to an object containing:\n * - transaction: The built transaction ready for signing (Transaction or VersionedTransaction)\n * - userAccountPublicKey: The public key of the created user account\n * - subAccountId: The ID of the newly created sub-account\n */\nexport const createUserAndDepositCollateralBaseTxn = async ({\n\tdriftClient,\n\tamount,\n\tspotMarketConfig,\n\tauthority,\n\tuserStatsAccount,\n\treferrerName,\n\taccountName,\n\tpoolId = MAIN_POOL_ID,\n\tfromSubAccountId,\n\tcustomMaxMarginRatio,\n\ttxParams,\n}: CreateUserAndDepositCollateralBaseTxnParams): Promise<{\n\ttransaction: Transaction | VersionedTransaction;\n\tuserAccountPublicKey: PublicKey;\n\tsubAccountId: number;\n}> => {\n\tconst { ixs, userAccountPublicKey, subAccountId } =\n\t\tawait createUserAndDepositCollateralBaseIxs({\n\t\t\tdriftClient,\n\t\t\tamount,\n\t\t\tspotMarketConfig,\n\t\t\tauthority,\n\t\t\tuserStatsAccount,\n\t\t\treferrerName,\n\t\t\taccountName,\n\t\t\tpoolId,\n\t\t\tfromSubAccountId,\n\t\t\tcustomMaxMarginRatio,\n\t\t});\n\n\tconst tx = await driftClient.buildTransaction(ixs, txParams);\n\n\treturn { transaction: tx, userAccountPublicKey, subAccountId };\n};\n"]}
|
|
1
|
+
{"version":3,"file":"create.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/user/create.ts"],"names":[],"mappings":";;;AAAA,yCAYyB;AACzB,mDAA+E;AAC/E,+DAAgF;AAChF,uDAA2D;AAM3D,2DAA8D;AAqB9D;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACI,MAAM,qCAAqC,GAAG,KAAK,EAAE,EAC3D,WAAW,EACX,MAAM,EACN,gBAAgB,EAChB,SAAS,EACT,gBAAgB,EAChB,YAAY,EACZ,WAAW,EACX,MAAM,GAAG,oBAAY,EACrB,gBAAgB,EAChB,oBAAoB,EACpB,QAAQ,EACR,cAAc,GAC+B,EAI3C,EAAE;;IACJ,MAA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AAM,EACN,gBAAgB,EAChB,SAAS,EACT,gBAAgB,EAChB,YAAY,EACZ,WAAW,EACX,MAAM,GAAG,oBAAY,EACrB,gBAAgB,EAChB,oBAAoB,EACpB,QAAQ,EACR,cAAc,GAC+B,EAI3C,EAAE;IACJ,MAAM,EAAE,GAAG,EAAE,oBAAoB,EAAE,YAAY,EAAE,GAChD,MAAM,IAAA,6CAAqC,EAAC;QAC3C,WAAW;QACX,MAAM;QACN,gBAAgB;QAChB,SAAS;QACT,gBAAgB;QAChB,YAAY;QACZ,WAAW;QACX,MAAM;QACN,gBAAgB;QAChB,oBAAoB;QACpB,cAAc;KACd,CAAC,CAAC;IAEJ,MAAM,EAAE,GAAG,MAAM,WAAW,CAAC,gBAAgB,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;IAE7D,OAAO,EAAE,WAAW,EAAE,EAAE,EAAE,oBAAoB,EAAE,YAAY,EAAE,CAAC;AAChE,CAAC,CAAC;AApCW,QAAA,qCAAqC,yCAoChD","sourcesContent":["import {\n\tBN,\n\tDriftClient,\n\tgetTokenProgramForSpotMarket,\n\tgetUserAccountPublicKeySync,\n\tPublicKey,\n\tReferrerInfo,\n\tReferrerNameAccount,\n\tSpotMarketConfig,\n\tTxParams,\n\tUserStatsAccount,\n\tZERO,\n} from '@drift-labs/sdk';\nimport { getTokenAddressForDepositAndWithdraw } from '../../../../utils/token';\nimport { DEFAULT_ACCOUNT_NAMES_BY_POOL_ID } from '../../constants/accountNames';\nimport { MAIN_POOL_ID } from '../../../../constants/pools';\nimport {\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport { USER_UTILS } from '../../../../common-ui-utils/user';\n\ninterface CreateUserAndDepositCollateralBaseIxsParams {\n\tdriftClient: DriftClient;\n\tamount: BN;\n\tspotMarketConfig: SpotMarketConfig;\n\tauthority: PublicKey;\n\tuserStatsAccount: UserStatsAccount | undefined;\n\treferrerName?: string;\n\taccountName?: string;\n\tpoolId?: number;\n\tfromSubAccountId?: number;\n\tcustomMaxMarginRatio?: number;\n\tdelegate?: PublicKey;\n\t/**\n\t * Optional external wallet to deposit from. If provided, the deposit will be made\n\t * from this wallet instead of the authority wallet.\n\t */\n\texternalWallet?: PublicKey;\n}\n\n/**\n * Creates transaction instructions for initializing a new user account and depositing collateral.\n *\n * This function generates the necessary transaction instructions to:\n * 1. Initialize a new user account in the Drift protocol\n * 2. Deposit collateral into the newly created account\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param amount - The amount of collateral to deposit (in base units)\n * @param spotMarketConfig - The spot market config of the deposit collateral\n * @param authority - The public key of the account authority (wallet owner)\n * @param userStatsAccount - Existing user stats account, used to determine next sub-account ID\n * @param referrerName - Optional name of the referrer for referral tracking\n * @param accountName - Optional custom name for the account (defaults to pool-specific name)\n * @param poolId - The pool ID to associate the account with (defaults to MAIN_POOL_ID)\n * @param fromSubAccountId - Optional sub-account ID to transfer funds from\n * @param customMaxMarginRatio - Optional custom maximum margin ratio for the account\n * @param delegate - Optional delegate public key for the account. Immediately assigns this as the delegate of the account.\n * @param externalWallet - Optional external wallet to deposit from (instead of authority wallet)\n *\n * @returns Promise resolving to an object containing:\n * - subAccountId: The ID of the newly created sub-account\n * - userAccountPublicKey: The public key of the created user account\n * - ixs: Array of transaction instructions to execute\n */\nexport const createUserAndDepositCollateralBaseIxs = async ({\n\tdriftClient,\n\tamount,\n\tspotMarketConfig,\n\tauthority,\n\tuserStatsAccount,\n\treferrerName,\n\taccountName,\n\tpoolId = MAIN_POOL_ID,\n\tfromSubAccountId,\n\tcustomMaxMarginRatio,\n\tdelegate,\n\texternalWallet,\n}: CreateUserAndDepositCollateralBaseIxsParams): Promise<{\n\tsubAccountId: number;\n\tuserAccountPublicKey: PublicKey;\n\tixs: TransactionInstruction[];\n}> => {\n\tconst nextSubaccountId = userStatsAccount?.numberOfSubAccountsCreated ?? 0; // userId is zero indexed\n\n\t// Get the spot market account to determine the correct token program for Token-2022 tokens\n\tconst spotMarketAccount = driftClient.getSpotMarketAccount(\n\t\tspotMarketConfig.marketIndex\n\t);\n\tconst tokenProgram = spotMarketAccount\n\t\t? getTokenProgramForSpotMarket(spotMarketAccount)\n\t\t: undefined;\n\n\t// Use external wallet for token address if provided, otherwise use authority\n\tconst depositSourceWallet = externalWallet ?? authority;\n\tconst associatedDepositTokenAddressPromise =\n\t\tgetTokenAddressForDepositAndWithdraw(\n\t\t\tspotMarketConfig.mint,\n\t\t\tdepositSourceWallet,\n\t\t\ttokenProgram\n\t\t);\n\tconst referrerNameAccountPromise: Promise<ReferrerNameAccount | undefined> =\n\t\treferrerName\n\t\t\t? driftClient.fetchReferrerNameAccount(referrerName)\n\t\t\t: Promise.resolve(undefined);\n\tconst subaccountExistsPromise = USER_UTILS.checkIfUserAccountExists(\n\t\tdriftClient,\n\t\t{\n\t\t\ttype: 'subAccountId',\n\t\t\tsubAccountId: nextSubaccountId,\n\t\t\tauthority,\n\t\t}\n\t);\n\n\tconst [associatedDepositTokenAddress, referrerNameAccount, subaccountExists] =\n\t\tawait Promise.all([\n\t\t\tassociatedDepositTokenAddressPromise,\n\t\t\treferrerNameAccountPromise,\n\t\t\tsubaccountExistsPromise,\n\t\t]);\n\n\tif (subaccountExists) {\n\t\tthrow new Error('Subaccount already exists');\n\t}\n\n\tconst accountNameToUse =\n\t\taccountName ??\n\t\t(poolId !== MAIN_POOL_ID || nextSubaccountId === 0\n\t\t\t? DEFAULT_ACCOUNT_NAMES_BY_POOL_ID[poolId]\n\t\t\t: `Account ${nextSubaccountId}`);\n\n\tconst referrerInfo: ReferrerInfo | undefined = referrerNameAccount\n\t\t? {\n\t\t\t\treferrer: referrerNameAccount.user,\n\t\t\t\treferrerStats: referrerNameAccount.userStats,\n\t\t }\n\t\t: undefined;\n\n\tconst { ixs: createAndDepositIxs, userAccountPublicKey } =\n\t\tawait driftClient.createInitializeUserAccountAndDepositCollateralIxs(\n\t\t\tamount,\n\t\t\tassociatedDepositTokenAddress,\n\t\t\tspotMarketConfig.marketIndex,\n\t\t\tnextSubaccountId,\n\t\t\taccountNameToUse,\n\t\t\tfromSubAccountId,\n\t\t\treferrerInfo,\n\t\t\tZERO,\n\t\t\tcustomMaxMarginRatio,\n\t\t\tpoolId,\n\t\t\texternalWallet ? { externalWallet } : undefined\n\t\t);\n\tconst ixs: TransactionInstruction[] = [...createAndDepositIxs];\n\n\tconst nextSubAccountPublicKey = getUserAccountPublicKeySync(\n\t\tdriftClient.program.programId,\n\t\tauthority,\n\t\tnextSubaccountId\n\t);\n\tconst delegateIx = delegate\n\t\t? await driftClient.getUpdateUserDelegateIx(delegate, {\n\t\t\t\tsubAccountId: nextSubaccountId,\n\t\t\t\tuserAccountPublicKey: nextSubAccountPublicKey,\n\t\t\t\tauthority,\n\t\t })\n\t\t: undefined;\n\n\tif (delegateIx) {\n\t\tixs.push(delegateIx);\n\t}\n\n\treturn {\n\t\tsubAccountId: nextSubaccountId,\n\t\tuserAccountPublicKey,\n\t\tixs,\n\t};\n};\n\ninterface CreateUserAndDepositCollateralBaseTxnParams\n\textends CreateUserAndDepositCollateralBaseIxsParams {\n\ttxParams?: TxParams;\n}\n\n/**\n * Creates a complete transaction for initializing a new user account and depositing collateral.\n *\n * This function is a higher-level wrapper around `createUserAndDepositCollateralBaseIxs` that:\n * 1. Generates the necessary transaction instructions\n * 2. Builds a complete transaction ready for signing and submission\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param amount - The amount of collateral to deposit (in base units)\n * @param spotMarketConfig - The spot market config of the deposit collateral\n * @param authority - The public key of the account authority (wallet owner)\n * @param userStatsAccount - Existing user stats account, used to determine next sub-account ID\n * @param referrerName - Optional name of the referrer for referral tracking\n * @param accountName - Optional custom name for the account (defaults to pool-specific name)\n * @param poolId - The pool ID to associate the account with (defaults to MAIN_POOL_ID)\n * @param fromSubAccountId - Optional sub-account ID to transfer funds from\n * @param customMaxMarginRatio - Optional custom maximum margin ratio for the account\n * @param txParams - Transaction parameters for building the transaction (compute units, priority fees, etc.)\n * @param externalWallet - Optional external wallet to deposit from (instead of authority wallet)\n *\n * @returns Promise resolving to an object containing:\n * - transaction: The built transaction ready for signing (Transaction or VersionedTransaction)\n * - userAccountPublicKey: The public key of the created user account\n * - subAccountId: The ID of the newly created sub-account\n */\nexport const createUserAndDepositCollateralBaseTxn = async ({\n\tdriftClient,\n\tamount,\n\tspotMarketConfig,\n\tauthority,\n\tuserStatsAccount,\n\treferrerName,\n\taccountName,\n\tpoolId = MAIN_POOL_ID,\n\tfromSubAccountId,\n\tcustomMaxMarginRatio,\n\ttxParams,\n\texternalWallet,\n}: CreateUserAndDepositCollateralBaseTxnParams): Promise<{\n\ttransaction: Transaction | VersionedTransaction;\n\tuserAccountPublicKey: PublicKey;\n\tsubAccountId: number;\n}> => {\n\tconst { ixs, userAccountPublicKey, subAccountId } =\n\t\tawait createUserAndDepositCollateralBaseIxs({\n\t\t\tdriftClient,\n\t\t\tamount,\n\t\t\tspotMarketConfig,\n\t\t\tauthority,\n\t\t\tuserStatsAccount,\n\t\t\treferrerName,\n\t\t\taccountName,\n\t\t\tpoolId,\n\t\t\tfromSubAccountId,\n\t\t\tcustomMaxMarginRatio,\n\t\t\texternalWallet,\n\t\t});\n\n\tconst tx = await driftClient.buildTransaction(ixs, txParams);\n\n\treturn { transaction: tx, userAccountPublicKey, subAccountId };\n};\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { BigNum, DriftClient, PerpPosition, PositionDirection, User } from '@drift-labs/sdk';
|
|
2
2
|
/**
|
|
3
3
|
* Comprehensive position information derived from a PerpPosition at a specific reference price.
|
|
4
4
|
* This interface contains all the key metrics needed for position display and analysis.
|
package/lib/drift/cli.js
CHANGED
|
@@ -62,6 +62,7 @@ dotenv.config({ path: path.resolve(__dirname, '.env') });
|
|
|
62
62
|
* ts-node cli.ts swap --userAccount=11111111111111111111111111111111 --fromMarketIndex=1 --toMarketIndex=0 --fromAmount=1.5 --slippage=100 --swapMode=ExactIn
|
|
63
63
|
* ts-node cli.ts swap --userAccount=11111111111111111111111111111111 --fromMarketIndex=1 --toMarketIndex=0 --toAmount=150 --slippage=100 --swapMode=ExactOut
|
|
64
64
|
* ts-node cli.ts createUserAndDeposit --marketIndex=0 --amount=100 --accountName="Primary"
|
|
65
|
+
* ts-node cli.ts createUserAndDeposit --marketIndex=0 --amount=100 --fromWallet=22222222222222222222222222222222 --forAuthority=33333333333333333333333333333333
|
|
65
66
|
*/
|
|
66
67
|
// Shared configuration
|
|
67
68
|
let centralServerDrift;
|
|
@@ -207,6 +208,7 @@ function getMarketPrecision(marketIndex, isMainnet = true) {
|
|
|
207
208
|
* Initialize CentralServerDrift instance
|
|
208
209
|
*/
|
|
209
210
|
async function initializeCentralServerDrift() {
|
|
211
|
+
var _a;
|
|
210
212
|
console.log('๐ Initializing CentralServerDrift...\n');
|
|
211
213
|
// Validate required environment variables
|
|
212
214
|
if (!process.env.ANCHOR_WALLET) {
|
|
@@ -220,10 +222,12 @@ async function initializeCentralServerDrift() {
|
|
|
220
222
|
console.log(`โ
Wallet Public Key: ${wallet.publicKey.toString()}`);
|
|
221
223
|
console.log(`โ
RPC Endpoint: ${process.env.ENDPOINT}\n`);
|
|
222
224
|
// Initialize CentralServerDrift
|
|
223
|
-
|
|
225
|
+
const driftEnv = (_a = process.env.DRIFT_ENV) !== null && _a !== void 0 ? _a : 'devnet';
|
|
226
|
+
console.log(`๐๏ธ Initializing CentralServerDrift... (${driftEnv})`);
|
|
227
|
+
const rpcEndpoint = process.env.ENDPOINT;
|
|
224
228
|
centralServerDrift = new CentralServerDrift_1.CentralServerDrift({
|
|
225
|
-
solanaRpcEndpoint:
|
|
226
|
-
driftEnv
|
|
229
|
+
solanaRpcEndpoint: rpcEndpoint,
|
|
230
|
+
driftEnv,
|
|
227
231
|
supportedPerpMarkets: [0, 1, 2], // SOL, BTC, ETH
|
|
228
232
|
supportedSpotMarkets: [0, 1], // USDC, SOL
|
|
229
233
|
additionalDriftClientConfig: {
|
|
@@ -323,9 +327,15 @@ async function createUserAndDepositCommand(args) {
|
|
|
323
327
|
const poolIdArg = args.poolId;
|
|
324
328
|
const fromSubAccountIdArg = args.fromSubAccountId;
|
|
325
329
|
const customMaxMarginRatioArg = args.customMaxMarginRatio;
|
|
330
|
+
const fromWallet = args.fromWallet;
|
|
331
|
+
const forAuthority = args.forAuthority;
|
|
326
332
|
if (!marketIndexArg || !amountArg) {
|
|
327
333
|
throw new Error('Required arguments: --marketIndex, --amount');
|
|
328
334
|
}
|
|
335
|
+
// If external wallet is provided, authority must also be specified
|
|
336
|
+
if (fromWallet && !forAuthority) {
|
|
337
|
+
throw new Error('When using --fromWallet, you must also specify --forAuthority (the account owner)');
|
|
338
|
+
}
|
|
329
339
|
const marketIndex = parseInt(marketIndexArg, 10);
|
|
330
340
|
if (isNaN(marketIndex)) {
|
|
331
341
|
throw new Error(`Invalid marketIndex: ${marketIndexArg}`);
|
|
@@ -360,8 +370,16 @@ async function createUserAndDepositCommand(args) {
|
|
|
360
370
|
}
|
|
361
371
|
options.customMaxMarginRatio = customMaxMarginRatio;
|
|
362
372
|
}
|
|
373
|
+
// Parse external wallet and authority if provided
|
|
374
|
+
const externalWallet = fromWallet ? new web3_js_1.PublicKey(fromWallet) : undefined;
|
|
375
|
+
const authority = forAuthority
|
|
376
|
+
? new web3_js_1.PublicKey(forAuthority)
|
|
377
|
+
: wallet.publicKey;
|
|
378
|
+
if (externalWallet) {
|
|
379
|
+
options.externalWallet = externalWallet;
|
|
380
|
+
}
|
|
363
381
|
console.log('--- ๐ Create User & Deposit Transaction ---');
|
|
364
|
-
console.log(`๐ Authority (
|
|
382
|
+
console.log(`๐ Authority (account owner): ${authority.toString()}`);
|
|
365
383
|
console.log(`๐ช Spot Market Index: ${marketIndex}`);
|
|
366
384
|
console.log(`๐ฐ Initial Deposit: ${amountArg} (${amountBN.toString()} raw units)`);
|
|
367
385
|
if (options.accountName) {
|
|
@@ -379,8 +397,11 @@ async function createUserAndDepositCommand(args) {
|
|
|
379
397
|
if (options.customMaxMarginRatio !== undefined) {
|
|
380
398
|
console.log(`๐ Custom Max Margin Ratio: ${options.customMaxMarginRatio}`);
|
|
381
399
|
}
|
|
400
|
+
if (externalWallet) {
|
|
401
|
+
console.log(`๐ผ From External Wallet: ${externalWallet.toBase58()}`);
|
|
402
|
+
}
|
|
382
403
|
const hasOptions = Object.keys(options).length > 0;
|
|
383
|
-
const { transaction, userAccountPublicKey, subAccountId } = await centralServerDrift.getCreateAndDepositTxn(
|
|
404
|
+
const { transaction, userAccountPublicKey, subAccountId } = await centralServerDrift.getCreateAndDepositTxn(authority, amountBN, marketIndex, hasOptions ? options : undefined);
|
|
384
405
|
console.log(`๐ New User Account: ${userAccountPublicKey.toString()}`);
|
|
385
406
|
console.log(`๐งพ Subaccount ID: ${subAccountId}`);
|
|
386
407
|
await executeTransaction(transaction, 'Create User & Deposit');
|
|
@@ -741,8 +762,9 @@ function showUsage() {
|
|
|
741
762
|
console.log(' Example (external wallet): ts-node cli.ts deposit --userAccount=11111111111111111111111111111111 --marketIndex=0 --amount=100 --fromWallet=22222222222222222222222222222222');
|
|
742
763
|
console.log('');
|
|
743
764
|
console.log('๐ createUserAndDeposit');
|
|
744
|
-
console.log(' ts-node cli.ts createUserAndDeposit --marketIndex=<num> --amount=<num> [--accountName=<string>] [--referrerName=<string>] [--poolId=<num>] [--fromSubAccountId=<num>] [--customMaxMarginRatio=<num>]');
|
|
765
|
+
console.log(' ts-node cli.ts createUserAndDeposit --marketIndex=<num> --amount=<num> [--accountName=<string>] [--referrerName=<string>] [--poolId=<num>] [--fromSubAccountId=<num>] [--customMaxMarginRatio=<num>] [--fromWallet=<pubkey> --forAuthority=<pubkey>]');
|
|
745
766
|
console.log(' Example: ts-node cli.ts createUserAndDeposit --marketIndex=0 --amount=100 --accountName="Primary"');
|
|
767
|
+
console.log(' Example (external wallet): ts-node cli.ts createUserAndDeposit --marketIndex=0 --amount=100 --fromWallet=22222222222222222222222222222222 --forAuthority=33333333333333333333333333333333');
|
|
746
768
|
console.log('');
|
|
747
769
|
console.log('๐ธ withdraw');
|
|
748
770
|
console.log(' ts-node cli.ts withdraw --userAccount=<pubkey> --marketIndex=<num> --amount=<num> [--isBorrow=<bool>] [--isMax=<bool>]');
|