@drift-labs/common 1.0.18 โ 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/actions/actionHelpers/actionHelpers.d.ts +9 -9
- package/lib/common-ui-utils/commonUiUtils.d.ts +4 -1
- 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/predictionMarket.d.ts +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/DriftL2OrderbookManager.d.ts +10 -10
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js +4 -0
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/index.js.map +1 -1
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/types.d.ts +2 -1
- package/lib/drift/Drift/clients/AuthorityDrift/DriftOperations/types.js.map +1 -1
- package/lib/drift/Drift/clients/CentralServerDrift/index.d.ts +5 -0
- package/lib/drift/Drift/clients/CentralServerDrift/index.js +9 -3
- 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 +8 -2
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js +8 -2
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpMarketOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js +8 -2
- package/lib/drift/base/actions/trade/openPerpOrder/openPerpNonMarketOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.d.ts +6 -0
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js +5 -3
- package/lib/drift/base/actions/trade/openPerpOrder/openSwiftOrder/index.js.map +1 -1
- package/lib/drift/base/actions/trade/openPerpOrder/types.d.ts +1 -0
- package/lib/drift/base/actions/trade/openPerpOrder/types.js.map +1 -1
- package/lib/drift/base/actions/user/create.d.ts +9 -2
- package/lib/drift/base/actions/user/create.js +10 -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 +10 -0
- package/lib/serializableTypes.js +317 -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 -2
- package/lib/utils/math.d.ts +3 -3
- package/package.json +8 -5
|
@@ -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,13 +24,14 @@ 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,7 +39,9 @@ const createUserAndDepositCollateralBaseIxs = async ({ driftClient, amount, spot
|
|
|
38
39
|
const tokenProgram = spotMarketAccount
|
|
39
40
|
? (0, sdk_1.getTokenProgramForSpotMarket)(spotMarketAccount)
|
|
40
41
|
: undefined;
|
|
41
|
-
|
|
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);
|
|
42
45
|
const referrerNameAccountPromise = referrerName
|
|
43
46
|
? driftClient.fetchReferrerNameAccount(referrerName)
|
|
44
47
|
: Promise.resolve(undefined);
|
|
@@ -64,9 +67,8 @@ const createUserAndDepositCollateralBaseIxs = async ({ driftClient, amount, spot
|
|
|
64
67
|
referrerStats: referrerNameAccount.userStats,
|
|
65
68
|
}
|
|
66
69
|
: undefined;
|
|
67
|
-
const ixs =
|
|
68
|
-
const
|
|
69
|
-
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];
|
|
70
72
|
const nextSubAccountPublicKey = (0, sdk_1.getUserAccountPublicKeySync)(driftClient.program.programId, authority, nextSubaccountId);
|
|
71
73
|
const delegateIx = delegate
|
|
72
74
|
? await driftClient.getUpdateUserDelegateIx(delegate, {
|
|
@@ -103,13 +105,14 @@ exports.createUserAndDepositCollateralBaseIxs = createUserAndDepositCollateralBa
|
|
|
103
105
|
* @param fromSubAccountId - Optional sub-account ID to transfer funds from
|
|
104
106
|
* @param customMaxMarginRatio - Optional custom maximum margin ratio for the account
|
|
105
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)
|
|
106
109
|
*
|
|
107
110
|
* @returns Promise resolving to an object containing:
|
|
108
111
|
* - transaction: The built transaction ready for signing (Transaction or VersionedTransaction)
|
|
109
112
|
* - userAccountPublicKey: The public key of the created user account
|
|
110
113
|
* - subAccountId: The ID of the newly created sub-account
|
|
111
114
|
*/
|
|
112
|
-
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, }) => {
|
|
113
116
|
const { ixs, userAccountPublicKey, subAccountId } = await (0, exports.createUserAndDepositCollateralBaseIxs)({
|
|
114
117
|
driftClient,
|
|
115
118
|
amount,
|
|
@@ -121,6 +124,7 @@ const createUserAndDepositCollateralBaseTxn = async ({ driftClient, amount, spot
|
|
|
121
124
|
poolId,
|
|
122
125
|
fromSubAccountId,
|
|
123
126
|
customMaxMarginRatio,
|
|
127
|
+
externalWallet,
|
|
124
128
|
});
|
|
125
129
|
const tx = await driftClient.buildTransaction(ixs, txParams);
|
|
126
130
|
return { transaction: tx, userAccountPublicKey, subAccountId };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/user/create.ts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;IAED,OAAO;QACN,YAAY,EAAE,gBAAgB;QAC9B,oBAAoB;QACpB,GAAG;KACH,CAAC;AACH,CAAC,CAAC;AA5GW,QAAA,qCAAqC,yCA4GhD;AAOF;;;;;;;;;;;;;;;;;;;;;;;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,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;KACpB,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;AAlCW,QAAA,qCAAqC,yCAkChD","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}\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\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\tconst associatedDepositTokenAddressPromise =\n\t\tgetTokenAddressForDepositAndWithdraw(\n\t\t\tspotMarketConfig.mint,\n\t\t\tauthority,\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 = [];\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,MAAM,gBAAgB,GAAG,MAAA,gBAAgB,aAAhB,gBAAgB,uBAAhB,gBAAgB,CAAE,0BAA0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M,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>]');
|