@drift-labs/common 1.0.41 → 1.0.43

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.
@@ -3,3 +3,4 @@ export * from './trade';
3
3
  export * from './perp';
4
4
  export * from './spot';
5
5
  export * from './builder';
6
+ export * from './swift';
@@ -19,4 +19,5 @@ __exportStar(require("./trade"), exports);
19
19
  __exportStar(require("./perp"), exports);
20
20
  __exportStar(require("./spot"), exports);
21
21
  __exportStar(require("./builder"), exports);
22
+ __exportStar(require("./swift"), exports);
22
23
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/drift/base/actions/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,yCAAuB;AACvB,0CAAwB;AACxB,yCAAuB;AACvB,yCAAuB;AACvB,4CAA0B","sourcesContent":["export * from './user';\nexport * from './trade';\nexport * from './perp';\nexport * from './spot';\nexport * from './builder';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/drift/base/actions/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,yCAAuB;AACvB,0CAAwB;AACxB,yCAAuB;AACvB,yCAAuB;AACvB,4CAA0B;AAC1B,0CAAwB","sourcesContent":["export * from './user';\nexport * from './trade';\nexport * from './perp';\nexport * from './spot';\nexport * from './builder';\nexport * from './swift';\n"]}
@@ -1,8 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createDepositTxn = exports.createDepositIxs = void 0;
4
- const sdk_1 = require("@drift-labs/sdk");
5
- const spl_token_1 = require("@solana/spl-token");
4
+ const token_1 = require("../../../../utils/token");
6
5
  /**
7
6
  * Creates transaction instructions for depositing a spot token.
8
7
  *
@@ -18,10 +17,7 @@ const spl_token_1 = require("@solana/spl-token");
18
17
  const createDepositIxs = async ({ driftClient, user, amount, spotMarketConfig, isMaxBorrowRepayment, externalWallet, }) => {
19
18
  const authority = externalWallet !== null && externalWallet !== void 0 ? externalWallet : user.getUserAccount().authority;
20
19
  const spotMarketAccount = driftClient.getSpotMarketAccount(spotMarketConfig.marketIndex);
21
- const isSol = spotMarketAccount.mint.equals(sdk_1.WRAPPED_SOL_MINT);
22
- const associatedDepositTokenAddress = isSol
23
- ? authority
24
- : await (0, spl_token_1.getAssociatedTokenAddress)(spotMarketAccount.mint, authority, true, (0, sdk_1.getTokenProgramForSpotMarket)(spotMarketAccount));
20
+ const associatedDepositTokenAddress = await (0, token_1.getTokenAddressForDepositAndWithdraw)(spotMarketAccount, authority);
25
21
  let finalDepositAmount = amount;
26
22
  if (isMaxBorrowRepayment) {
27
23
  // we over-estimate to ensure that there is no borrow dust left
@@ -1 +1 @@
1
- {"version":3,"file":"deposit.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/spot/deposit.ts"],"names":[],"mappings":";;;AAAA,yCAQyB;AAOzB,iDAA8D;AAe9D;;;;;;;;;;;GAWG;AACI,MAAM,gBAAgB,GAAG,KAAK,EAAE,EACtC,WAAW,EACX,IAAI,EACJ,MAAM,EACN,gBAAgB,EAChB,oBAAoB,EACpB,cAAc,GACS,EAAqC,EAAE;IAC9D,MAAM,SAAS,GAAG,cAAc,aAAd,cAAc,cAAd,cAAc,GAAI,IAAI,CAAC,cAAc,EAAE,CAAC,SAAS,CAAC;IACpE,MAAM,iBAAiB,GAAG,WAAW,CAAC,oBAAoB,CACzD,gBAAgB,CAAC,WAAW,CAC5B,CAAC;IACF,MAAM,KAAK,GAAG,iBAAiB,CAAC,IAAI,CAAC,MAAM,CAAC,sBAAgB,CAAC,CAAC;IAC9D,MAAM,6BAA6B,GAAG,KAAK;QAC1C,CAAC,CAAC,SAAS;QACX,CAAC,CAAC,MAAM,IAAA,qCAAyB,EAC/B,iBAAiB,CAAC,IAAI,EACtB,SAAS,EACT,IAAI,EACJ,IAAA,kCAA4B,EAAC,iBAAiB,CAAC,CAC9C,CAAC;IAEL,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kBAAkB;QAC1B,gBAAgB;QAChB,oBAAoB;QACpB,cAAc;KACd,CAAC,CAAC;IAEH,gEAAgE;IAChE,MAAM,yBAAyB,GAAG,KAAK,IAAI,EAAE;;QAC5C,MAAM,YAAY,GAAG,MAAM,WAAW,CAAC,2BAA2B,EAAE,CAAC;QACrE,uEAAuE;QACvE,OAAO,CACN,MAAA,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,CAAC,mCACtE,EAAE,CACF,CAAC;IACH,CAAC,CAAC;IAEF,MAAM,UAAU,GAAG,MAAM,WAAW,CAAC,SAAS,CAAC,gBAAgB,CAAC;QAC/D,YAAY,EAAE,UAAU;QACxB,SAAS,EAAE,CAAC;QACZ,UAAU,EAAE,WAAW,CAAC,UAAU;QAClC,mBAAmB,EAAE,WAAW;QAChC,iCAAiC,EAAE,yBAAyB;QAC5D,QAAQ;KACR,CAAC,CAAC;IAEH,OAAO,UAAU,CAAC;AACnB,CAAC,CAAC;AAhEW,QAAA,gBAAgB,oBAgE3B","sourcesContent":["import {\n\tBigNum,\n\tDriftClient,\n\tgetTokenProgramForSpotMarket,\n\tSpotMarketConfig,\n\tTxParams,\n\tUser,\n\tWRAPPED_SOL_MINT,\n} from '@drift-labs/sdk';\nimport {\n\tPublicKey,\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport { getAssociatedTokenAddress } from '@solana/spl-token';\n\ninterface CreateDepositIxParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tamount: BigNum;\n\tspotMarketConfig: Pick<SpotMarketConfig, 'mint' | 'marketIndex'>;\n\tisMaxBorrowRepayment?: boolean;\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 user's authority wallet.\n\t */\n\texternalWallet?: PublicKey;\n}\n\n/**\n * Creates transaction instructions for depositing a spot token.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will perform the deposit\n * @param amount - The amount to deposit (in BigNum format)\n * @param spotMarketConfig - The spot market configuration for the token being deposited\n * @param isMaxBorrowRepayment - Whether this deposit is for maximum borrow repayment (scales amount by 2x, set to reduce only)\n * @param externalWallet - Optional external wallet to deposit from (instead of user's authority wallet)\n *\n * @returns Promise resolving to an array of transaction instructions for the deposit\n */\nexport const createDepositIxs = async ({\n\tdriftClient,\n\tuser,\n\tamount,\n\tspotMarketConfig,\n\tisMaxBorrowRepayment,\n\texternalWallet,\n}: CreateDepositIxParams): Promise<TransactionInstruction[]> => {\n\tconst authority = externalWallet ?? user.getUserAccount().authority;\n\tconst spotMarketAccount = driftClient.getSpotMarketAccount(\n\t\tspotMarketConfig.marketIndex\n\t);\n\tconst isSol = spotMarketAccount.mint.equals(WRAPPED_SOL_MINT);\n\tconst associatedDepositTokenAddress = isSol\n\t\t? authority\n\t\t: await getAssociatedTokenAddress(\n\t\t\t\tspotMarketAccount.mint,\n\t\t\t\tauthority,\n\t\t\t\ttrue,\n\t\t\t\tgetTokenProgramForSpotMarket(spotMarketAccount)\n\t\t );\n\n\tlet finalDepositAmount = amount;\n\n\tif (isMaxBorrowRepayment) {\n\t\t// we over-estimate to ensure that there is no borrow dust left\n\t\t// since isMaxBorrowRepayment = reduceOnly, it is safe to over-estimate\n\t\tfinalDepositAmount = finalDepositAmount.scale(2, 1);\n\t}\n\n\tconst depositIxs = await driftClient.getDepositTxnIx(\n\t\tfinalDepositAmount.val,\n\t\tspotMarketConfig.marketIndex,\n\t\tassociatedDepositTokenAddress,\n\t\tuser.getUserAccount().subAccountId,\n\t\tisMaxBorrowRepayment,\n\t\texternalWallet ? { authority: externalWallet } : undefined\n\t);\n\n\treturn depositIxs;\n};\n\ninterface CreateDepositTxnParams extends CreateDepositIxParams {\n\ttxParams?: TxParams;\n\tinitSwiftAccount?: boolean;\n}\n\n/**\n * Creates a complete transaction for depositing assets into a spot market.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will perform the deposit\n * @param amount - The amount to deposit (in BigNum format)\n * @param spotMarketConfig - The spot market configuration for the token being deposited\n * @param isMaxBorrowRepayment - Whether this deposit is for maximum borrow repayment (scales amount by 2x)\n * @param txParams - Optional transaction parameters for building the transaction (compute units, priority fees, etc.)\n * @param initSwiftAccount - Optional flag to initialize a Swift account during the deposit\n * @param externalWallet - Optional external wallet to deposit from (instead of user's authority wallet)\n *\n * @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)\n */\nexport const createDepositTxn = async ({\n\tdriftClient,\n\tuser,\n\tamount,\n\tspotMarketConfig,\n\tisMaxBorrowRepayment,\n\ttxParams,\n\tinitSwiftAccount: _initSwiftAccount,\n\texternalWallet,\n}: CreateDepositTxnParams): Promise<Transaction | VersionedTransaction> => {\n\t// const authority = user.getUserAccount().authority;\n\t// const associatedDepositTokenAddress =\n\t// \tawait getTokenAddressForDepositAndWithdraw(\n\t// \t\tspotMarketConfig.mint,\n\t// \t\tauthority\n\t// \t);\n\n\tlet finalDepositAmount = amount;\n\n\tif (isMaxBorrowRepayment) {\n\t\t// we over-estimate to ensure that there is no borrow dust left\n\t\t// since isMaxBorrowRepayment = reduceOnly, it is safe to over-estimate\n\t\tfinalDepositAmount = finalDepositAmount.scale(2, 1);\n\t}\n\n\t// we choose to not use createDepositIxs here because it doesn't have the initSwiftAccount logic\n\t// const depositTxn = await driftClient.createDepositTxn(\n\t// \tfinalDepositAmount.val,\n\t// \tspotMarketConfig.marketIndex,\n\t// \tassociatedDepositTokenAddress,\n\t// \tuser.getUserAccount().subAccountId,\n\t// \tisMaxBorrowRepayment,\n\t// \ttxParams,\n\t// \tinitSwiftAccount\n\t// );\n\tconst depositIxs = await createDepositIxs({\n\t\tdriftClient,\n\t\tuser,\n\t\tamount: finalDepositAmount,\n\t\tspotMarketConfig,\n\t\tisMaxBorrowRepayment,\n\t\texternalWallet,\n\t});\n\n\t// Wrapper to filter out null lookup tables from the driftClient\n\tconst fetchFilteredLookupTables = async () => {\n\t\tconst lookupTables = await driftClient.fetchAllLookupTableAccounts();\n\t\t// Filter out null/undefined values and return empty array if undefined\n\t\treturn (\n\t\t\tlookupTables?.filter((table) => table !== null && table !== undefined) ??\n\t\t\t[]\n\t\t);\n\t};\n\n\tconst depositTxn = await driftClient.txHandler.buildTransaction({\n\t\tinstructions: depositIxs,\n\t\ttxVersion: 0,\n\t\tconnection: driftClient.connection,\n\t\tpreFlightCommitment: 'confirmed',\n\t\tfetchAllMarketLookupTableAccounts: fetchFilteredLookupTables,\n\t\ttxParams,\n\t});\n\n\treturn depositTxn;\n};\n"]}
1
+ {"version":3,"file":"deposit.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/spot/deposit.ts"],"names":[],"mappings":";;;AAaA,mDAA+E;AAe/E;;;;;;;;;;;GAWG;AACI,MAAM,gBAAgB,GAAG,KAAK,EAAE,EACtC,WAAW,EACX,IAAI,EACJ,MAAM,EACN,gBAAgB,EAChB,oBAAoB,EACpB,cAAc,GACS,EAAqC,EAAE;IAC9D,MAAM,SAAS,GAAG,cAAc,aAAd,cAAc,cAAd,cAAc,GAAI,IAAI,CAAC,cAAc,EAAE,CAAC,SAAS,CAAC;IACpE,MAAM,iBAAiB,GAAG,WAAW,CAAC,oBAAoB,CACzD,gBAAgB,CAAC,WAAW,CAC5B,CAAC;IACF,MAAM,6BAA6B,GAClC,MAAM,IAAA,4CAAoC,EAAC,iBAAiB,EAAE,SAAS,CAAC,CAAC;IAE1E,IAAI,kBAAkB,GAAG,MAAM,CAAC;IAEhC,IAAI,oBAAoB,EAAE,CAAC;QAC1B,+DAA+D;QAC/D,uEAAuE;QACvE,kBAAkB,GAAG,kBAAkB,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IACrD,CAAC;IAED,MAAM,UAAU,GAAG,MAAM,WAAW,CAAC,eAAe,CACnD,kBAAkB,CAAC,GAAG,EACtB,gBAAgB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,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,CAAC,mCACtE,EAAE,CACF,CAAC;IACH,CAAC,CAAC;IAEF,MAAM,UAAU,GAAG,MAAM,WAAW,CAAC,SAAS,CAAC,gBAAgB,CAAC;QAC/D,YAAY,EAAE,UAAU;QACxB,SAAS,EAAE,CAAC;QACZ,UAAU,EAAE,WAAW,CAAC,UAAU;QAClC,mBAAmB,EAAE,WAAW;QAChC,iCAAiC,EAAE,yBAAyB;QAC5D,QAAQ;KACR,CAAC,CAAC;IAEH,OAAO,UAAU,CAAC;AACnB,CAAC,CAAC;AAhEW,QAAA,gBAAgB,oBAgE3B","sourcesContent":["import {\n\tBigNum,\n\tDriftClient,\n\tSpotMarketConfig,\n\tTxParams,\n\tUser,\n} from '@drift-labs/sdk';\nimport {\n\tPublicKey,\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport { getTokenAddressForDepositAndWithdraw } from '../../../../utils/token';\n\ninterface CreateDepositIxParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tamount: BigNum;\n\tspotMarketConfig: Pick<SpotMarketConfig, 'mint' | 'marketIndex'>;\n\tisMaxBorrowRepayment?: boolean;\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 user's authority wallet.\n\t */\n\texternalWallet?: PublicKey;\n}\n\n/**\n * Creates transaction instructions for depositing a spot token.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will perform the deposit\n * @param amount - The amount to deposit (in BigNum format)\n * @param spotMarketConfig - The spot market configuration for the token being deposited\n * @param isMaxBorrowRepayment - Whether this deposit is for maximum borrow repayment (scales amount by 2x, set to reduce only)\n * @param externalWallet - Optional external wallet to deposit from (instead of user's authority wallet)\n *\n * @returns Promise resolving to an array of transaction instructions for the deposit\n */\nexport const createDepositIxs = async ({\n\tdriftClient,\n\tuser,\n\tamount,\n\tspotMarketConfig,\n\tisMaxBorrowRepayment,\n\texternalWallet,\n}: CreateDepositIxParams): Promise<TransactionInstruction[]> => {\n\tconst authority = externalWallet ?? user.getUserAccount().authority;\n\tconst spotMarketAccount = driftClient.getSpotMarketAccount(\n\t\tspotMarketConfig.marketIndex\n\t);\n\tconst associatedDepositTokenAddress =\n\t\tawait getTokenAddressForDepositAndWithdraw(spotMarketAccount, authority);\n\n\tlet finalDepositAmount = amount;\n\n\tif (isMaxBorrowRepayment) {\n\t\t// we over-estimate to ensure that there is no borrow dust left\n\t\t// since isMaxBorrowRepayment = reduceOnly, it is safe to over-estimate\n\t\tfinalDepositAmount = finalDepositAmount.scale(2, 1);\n\t}\n\n\tconst depositIxs = await driftClient.getDepositTxnIx(\n\t\tfinalDepositAmount.val,\n\t\tspotMarketConfig.marketIndex,\n\t\tassociatedDepositTokenAddress,\n\t\tuser.getUserAccount().subAccountId,\n\t\tisMaxBorrowRepayment,\n\t\texternalWallet ? { authority: externalWallet } : undefined\n\t);\n\n\treturn depositIxs;\n};\n\ninterface CreateDepositTxnParams extends CreateDepositIxParams {\n\ttxParams?: TxParams;\n\tinitSwiftAccount?: boolean;\n}\n\n/**\n * Creates a complete transaction for depositing assets into a spot market.\n *\n * @param driftClient - The Drift client instance for interacting with the protocol\n * @param user - The user account that will perform the deposit\n * @param amount - The amount to deposit (in BigNum format)\n * @param spotMarketConfig - The spot market configuration for the token being deposited\n * @param isMaxBorrowRepayment - Whether this deposit is for maximum borrow repayment (scales amount by 2x)\n * @param txParams - Optional transaction parameters for building the transaction (compute units, priority fees, etc.)\n * @param initSwiftAccount - Optional flag to initialize a Swift account during the deposit\n * @param externalWallet - Optional external wallet to deposit from (instead of user's authority wallet)\n *\n * @returns Promise resolving to a built transaction ready for signing (Transaction or VersionedTransaction)\n */\nexport const createDepositTxn = async ({\n\tdriftClient,\n\tuser,\n\tamount,\n\tspotMarketConfig,\n\tisMaxBorrowRepayment,\n\ttxParams,\n\tinitSwiftAccount: _initSwiftAccount,\n\texternalWallet,\n}: CreateDepositTxnParams): Promise<Transaction | VersionedTransaction> => {\n\t// const authority = user.getUserAccount().authority;\n\t// const associatedDepositTokenAddress =\n\t// \tawait getTokenAddressForDepositAndWithdraw(\n\t// \t\tspotMarketConfig.mint,\n\t// \t\tauthority\n\t// \t);\n\n\tlet finalDepositAmount = amount;\n\n\tif (isMaxBorrowRepayment) {\n\t\t// we over-estimate to ensure that there is no borrow dust left\n\t\t// since isMaxBorrowRepayment = reduceOnly, it is safe to over-estimate\n\t\tfinalDepositAmount = finalDepositAmount.scale(2, 1);\n\t}\n\n\t// we choose to not use createDepositIxs here because it doesn't have the initSwiftAccount logic\n\t// const depositTxn = await driftClient.createDepositTxn(\n\t// \tfinalDepositAmount.val,\n\t// \tspotMarketConfig.marketIndex,\n\t// \tassociatedDepositTokenAddress,\n\t// \tuser.getUserAccount().subAccountId,\n\t// \tisMaxBorrowRepayment,\n\t// \ttxParams,\n\t// \tinitSwiftAccount\n\t// );\n\tconst depositIxs = await createDepositIxs({\n\t\tdriftClient,\n\t\tuser,\n\t\tamount: finalDepositAmount,\n\t\tspotMarketConfig,\n\t\tisMaxBorrowRepayment,\n\t\texternalWallet,\n\t});\n\n\t// Wrapper to filter out null lookup tables from the driftClient\n\tconst fetchFilteredLookupTables = async () => {\n\t\tconst lookupTables = await driftClient.fetchAllLookupTableAccounts();\n\t\t// Filter out null/undefined values and return empty array if undefined\n\t\treturn (\n\t\t\tlookupTables?.filter((table) => table !== null && table !== undefined) ??\n\t\t\t[]\n\t\t);\n\t};\n\n\tconst depositTxn = await driftClient.txHandler.buildTransaction({\n\t\tinstructions: depositIxs,\n\t\ttxVersion: 0,\n\t\tconnection: driftClient.connection,\n\t\tpreFlightCommitment: 'confirmed',\n\t\tfetchAllMarketLookupTableAccounts: fetchFilteredLookupTables,\n\t\ttxParams,\n\t});\n\n\treturn depositTxn;\n};\n"]}
@@ -20,7 +20,7 @@ const createWithdrawIx = async ({ driftClient, amount, spotMarketConfig, user, i
20
20
  }
21
21
  }
22
22
  const authority = user.getUserAccount().authority;
23
- const associatedDepositTokenAddress = await (0, token_1.getTokenAddressForDepositAndWithdraw)(spotMarketConfig.mint, authority, (0, sdk_1.getTokenProgramForSpotMarket)(driftClient.getSpotMarketAccount(spotMarketConfig.marketIndex)));
23
+ const associatedDepositTokenAddress = await (0, token_1.getTokenAddressForDepositAndWithdraw)(driftClient.getSpotMarketAccount(spotMarketConfig.marketIndex), authority);
24
24
  const withdrawIxs = await driftClient.getWithdrawalIxs(finalWithdrawAmount.val, spotMarketConfig.marketIndex, associatedDepositTokenAddress, reduceOnly, user.getUserAccount().subAccountId, undefined);
25
25
  return withdrawIxs;
26
26
  };
@@ -1 +1 @@
1
- {"version":3,"file":"withdraw.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/spot/withdraw.ts"],"names":[],"mappings":";;;AAAA,yCAOyB;AAMzB,mDAA+E;AAWxE,MAAM,gBAAgB,GAAG,KAAK,EAAE,EACtC,WAAW,EACX,MAAM,EACN,gBAAgB,EAChB,IAAI,EACJ,QAAQ,EACR,KAAK,GACmB,EAAqC,EAAE;;IAC/D,MAAM,UAAU,GAAG,CAAC,QAAQ,CAAC;IAE7B,IAAI,mBAAmB,GAAG,MAAM,CAAC;IAEjC,IAAI,KAAK,IAAI,UAAU,EAAE,CAAC;QACzB,+DAA+D;QAC/D,wDAAwD;QACxD,mBAAmB,GAAG,mBAAmB,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QACtD,MAAM,aAAa,GAAG,MAAA,IAAI;aACxB,cAAc,EAAE;aAChB,aAAa,CAAC,IAAI,CAClB,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,WAAW,KAAK,gBAAgB,CAAC,WAAW,CACnE,0CAAE,aAAa,CAAC;QAClB,IAAI,aAAa,IAAI,aAAa,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;YACjD,uDA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AAI,CAAC,WAAW,CAAC;QAC1D,QAAQ;KACR,CAAC,CAAC;IAEH,OAAO,WAAW,CAAC;AACpB,CAAC,CAAC;AA7BW,QAAA,iBAAiB,qBA6B5B","sourcesContent":["import {\n\tBigNum,\n\tDriftClient,\n\tgetTokenProgramForSpotMarket,\n\tSpotMarketConfig,\n\tTxParams,\n\tUser,\n} from '@drift-labs/sdk';\nimport {\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport { getTokenAddressForDepositAndWithdraw } from '../../../../utils/token';\n\ninterface CreateWithdrawIxParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tamount: BigNum;\n\tspotMarketConfig: SpotMarketConfig;\n\tisBorrow?: boolean;\n\tisMax?: boolean;\n}\n\nexport const createWithdrawIx = async ({\n\tdriftClient,\n\tamount,\n\tspotMarketConfig,\n\tuser,\n\tisBorrow,\n\tisMax,\n}: CreateWithdrawIxParams): Promise<TransactionInstruction[]> => {\n\tconst reduceOnly = !isBorrow;\n\n\tlet finalWithdrawAmount = amount;\n\n\tif (isMax && reduceOnly) {\n\t\t// we over-estimate to ensure that there is no borrow dust left\n\t\t// since reduceOnly is true, it is safe to over-estimate\n\t\tfinalWithdrawAmount = finalWithdrawAmount.scale(2, 1);\n\t\tconst scaledBalance = user\n\t\t\t.getUserAccount()\n\t\t\t.spotPositions.find(\n\t\t\t\t(position) => position.marketIndex === spotMarketConfig.marketIndex\n\t\t\t)?.scaledBalance;\n\t\tif (scaledBalance && scaledBalance.abs().gtn(0)) {\n\t\t\t// we use scaledBalance in case amount argument is zero\n\t\t\tfinalWithdrawAmount = BigNum.max(\n\t\t\t\tfinalWithdrawAmount,\n\t\t\t\tBigNum.from(scaledBalance, spotMarketConfig.precisionExp).scale(2, 1)\n\t\t\t);\n\t\t}\n\t}\n\n\tconst authority = user.getUserAccount().authority;\n\tconst associatedDepositTokenAddress =\n\t\tawait getTokenAddressForDepositAndWithdraw(\n\t\t\tspotMarketConfig.mint,\n\t\t\tauthority,\n\t\t\tgetTokenProgramForSpotMarket(\n\t\t\t\tdriftClient.getSpotMarketAccount(spotMarketConfig.marketIndex)\n\t\t\t)\n\t\t);\n\n\tconst withdrawIxs = await driftClient.getWithdrawalIxs(\n\t\tfinalWithdrawAmount.val,\n\t\tspotMarketConfig.marketIndex,\n\t\tassociatedDepositTokenAddress,\n\t\treduceOnly,\n\t\tuser.getUserAccount().subAccountId,\n\t\tundefined\n\t);\n\n\treturn withdrawIxs;\n};\n\ninterface CreateWithdrawTxnParams extends CreateWithdrawIxParams {\n\ttxParams?: TxParams;\n}\n\nexport const createWithdrawTxn = async ({\n\tdriftClient,\n\tamount,\n\tspotMarketConfig,\n\tuser,\n\tisBorrow,\n\tisMax,\n\ttxParams,\n}: CreateWithdrawTxnParams): Promise<Transaction | VersionedTransaction> => {\n\tconst withdrawIxs = await createWithdrawIx({\n\t\tdriftClient,\n\t\tamount,\n\t\tspotMarketConfig,\n\t\tuser,\n\t\tisBorrow,\n\t\tisMax,\n\t});\n\n\tconst withdrawTxn = await driftClient.txHandler.buildTransaction({\n\t\tinstructions: withdrawIxs,\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,\n\t});\n\n\treturn withdrawTxn;\n};\n"]}
1
+ {"version":3,"file":"withdraw.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/spot/withdraw.ts"],"names":[],"mappings":";;;AAAA,yCAMyB;AAMzB,mDAA+E;AAWxE,MAAM,gBAAgB,GAAG,KAAK,EAAE,EACtC,WAAW,EACX,MAAM,EACN,gBAAgB,EAChB,IAAI,EACJ,QAAQ,EACR,KAAK,GACmB,EAAqC,EAAE;;IAC/D,MAAM,UAAU,GAAG,CAAC,QAAQ,CAAC;IAE7B,IAAI,mBAAmB,GAAG,MAAM,CAAC;IA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AA+C,EAAE;IAC1E,MAAM,WAAW,GAAG,MAAM,IAAA,wBAAgB,EAAC;QAC1C,WAAW;QACX,MAAM;QACN,gBAAgB;QAChB,IAAI;QACJ,QAAQ;QACR,KAAK;KACL,CAAC,CAAC;IAEH,MAAM,WAAW,GAAG,MAAM,WAAW,CAAC,SAAS,CAAC,gBAAgB,CAAC;QAChE,YAAY,EAAE,WAAW;QACzB,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;KACR,CAAC,CAAC;IAEH,OAAO,WAAW,CAAC;AACpB,CAAC,CAAC;AA7BW,QAAA,iBAAiB,qBA6B5B","sourcesContent":["import {\n\tBigNum,\n\tDriftClient,\n\tSpotMarketConfig,\n\tTxParams,\n\tUser,\n} from '@drift-labs/sdk';\nimport {\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\nimport { getTokenAddressForDepositAndWithdraw } from '../../../../utils/token';\n\ninterface CreateWithdrawIxParams {\n\tdriftClient: DriftClient;\n\tuser: User;\n\tamount: BigNum;\n\tspotMarketConfig: SpotMarketConfig;\n\tisBorrow?: boolean;\n\tisMax?: boolean;\n}\n\nexport const createWithdrawIx = async ({\n\tdriftClient,\n\tamount,\n\tspotMarketConfig,\n\tuser,\n\tisBorrow,\n\tisMax,\n}: CreateWithdrawIxParams): Promise<TransactionInstruction[]> => {\n\tconst reduceOnly = !isBorrow;\n\n\tlet finalWithdrawAmount = amount;\n\n\tif (isMax && reduceOnly) {\n\t\t// we over-estimate to ensure that there is no borrow dust left\n\t\t// since reduceOnly is true, it is safe to over-estimate\n\t\tfinalWithdrawAmount = finalWithdrawAmount.scale(2, 1);\n\t\tconst scaledBalance = user\n\t\t\t.getUserAccount()\n\t\t\t.spotPositions.find(\n\t\t\t\t(position) => position.marketIndex === spotMarketConfig.marketIndex\n\t\t\t)?.scaledBalance;\n\t\tif (scaledBalance && scaledBalance.abs().gtn(0)) {\n\t\t\t// we use scaledBalance in case amount argument is zero\n\t\t\tfinalWithdrawAmount = BigNum.max(\n\t\t\t\tfinalWithdrawAmount,\n\t\t\t\tBigNum.from(scaledBalance, spotMarketConfig.precisionExp).scale(2, 1)\n\t\t\t);\n\t\t}\n\t}\n\n\tconst authority = user.getUserAccount().authority;\n\tconst associatedDepositTokenAddress =\n\t\tawait getTokenAddressForDepositAndWithdraw(\n\t\t\tdriftClient.getSpotMarketAccount(spotMarketConfig.marketIndex),\n\t\t\tauthority\n\t\t);\n\n\tconst withdrawIxs = await driftClient.getWithdrawalIxs(\n\t\tfinalWithdrawAmount.val,\n\t\tspotMarketConfig.marketIndex,\n\t\tassociatedDepositTokenAddress,\n\t\treduceOnly,\n\t\tuser.getUserAccount().subAccountId,\n\t\tundefined\n\t);\n\n\treturn withdrawIxs;\n};\n\ninterface CreateWithdrawTxnParams extends CreateWithdrawIxParams {\n\ttxParams?: TxParams;\n}\n\nexport const createWithdrawTxn = async ({\n\tdriftClient,\n\tamount,\n\tspotMarketConfig,\n\tuser,\n\tisBorrow,\n\tisMax,\n\ttxParams,\n}: CreateWithdrawTxnParams): Promise<Transaction | VersionedTransaction> => {\n\tconst withdrawIxs = await createWithdrawIx({\n\t\tdriftClient,\n\t\tamount,\n\t\tspotMarketConfig,\n\t\tuser,\n\t\tisBorrow,\n\t\tisMax,\n\t});\n\n\tconst withdrawTxn = await driftClient.txHandler.buildTransaction({\n\t\tinstructions: withdrawIxs,\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,\n\t});\n\n\treturn withdrawTxn;\n};\n"]}
@@ -0,0 +1,64 @@
1
+ import { DriftClient, PublicKey, TxParams } from '@drift-labs/sdk';
2
+ import { Transaction, TransactionInstruction, VersionedTransaction } from '@solana/web3.js';
3
+ interface CreateSwiftAccountIxParams {
4
+ driftClient: DriftClient;
5
+ authority: PublicKey;
6
+ numOrders?: number;
7
+ /**
8
+ * Optional external wallet to use as payer. If provided, this wallet will pay
9
+ * for the account creation instead of the default wallet.
10
+ */
11
+ rentPayerOverride?: PublicKey;
12
+ }
13
+ /**
14
+ * Creates a transaction instruction for initializing a Swift (signed message user orders) account.
15
+ *
16
+ * @param driftClient - The Drift client instance
17
+ * @param authority - The public key of the account authority
18
+ * @param numOrders - The number of order slots to allocate (default: 8)
19
+ * @param rentPayerOverride - Optional wallet to pay for account creation instead of the default wallet
20
+ *
21
+ * @returns The Swift account public key and the initialization instruction
22
+ */
23
+ export declare const createSwiftAccountIx: ({ driftClient, authority, numOrders, rentPayerOverride, }: CreateSwiftAccountIxParams) => Promise<{
24
+ swiftAccountPublicKey: PublicKey;
25
+ ix: TransactionInstruction;
26
+ }>;
27
+ interface CreateSwiftAccountTxnParams extends CreateSwiftAccountIxParams {
28
+ txParams?: TxParams;
29
+ }
30
+ /**
31
+ * Creates a complete transaction for initializing a Swift (signed message user orders) account.
32
+ *
33
+ * Wraps {@link createSwiftAccountIx} and builds a transaction ready for signing and submission.
34
+ *
35
+ * @param driftClient - The Drift client instance
36
+ * @param authority - The public key of the account authority
37
+ * @param numOrders - The number of order slots to allocate (default: 8)
38
+ * @param rentPayerOverride - Optional wallet to pay for account creation instead of the default wallet
39
+ * @param txParams - Optional transaction parameters (compute units, priority fees, etc.)
40
+ *
41
+ * @returns The built transaction and the Swift account public key
42
+ */
43
+ export declare const createSwiftAccountTxn: ({ driftClient, authority, numOrders, rentPayerOverride: externalWallet, txParams, }: CreateSwiftAccountTxnParams) => Promise<{
44
+ transaction: Transaction | VersionedTransaction;
45
+ swiftAccountPublicKey: PublicKey;
46
+ }>;
47
+ /**
48
+ * Creates a Swift account instruction only if one doesn't already exist for the given authority.
49
+ *
50
+ * Always returns the Swift account public key. The `ix` will be `null` if the account
51
+ * is already initialized, indicating no transaction is needed.
52
+ *
53
+ * @param driftClient - The Drift client instance
54
+ * @param authority - The public key of the account authority
55
+ * @param numOrders - The number of order slots to allocate (default: 8)
56
+ * @param rentPayerOverride - Optional wallet to pay for account creation instead of the default wallet
57
+ *
58
+ * @returns The Swift account public key and the initialization instruction (null if already initialized)
59
+ */
60
+ export declare const createSwiftAccountIxIfNotExists: ({ driftClient, authority, numOrders, rentPayerOverride, }: CreateSwiftAccountIxParams) => Promise<{
61
+ swiftAccountPublicKey: PublicKey;
62
+ ix: TransactionInstruction | null;
63
+ }>;
64
+ export {};
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createSwiftAccountIxIfNotExists = exports.createSwiftAccountTxn = exports.createSwiftAccountIx = void 0;
4
+ const sdk_1 = require("@drift-labs/sdk");
5
+ /**
6
+ * Creates a transaction instruction for initializing a Swift (signed message user orders) account.
7
+ *
8
+ * @param driftClient - The Drift client instance
9
+ * @param authority - The public key of the account authority
10
+ * @param numOrders - The number of order slots to allocate (default: 8)
11
+ * @param rentPayerOverride - Optional wallet to pay for account creation instead of the default wallet
12
+ *
13
+ * @returns The Swift account public key and the initialization instruction
14
+ */
15
+ const createSwiftAccountIx = async ({ driftClient, authority, numOrders = 8, rentPayerOverride, }) => {
16
+ const [swiftAccountPublicKey, ix] = await driftClient.getInitializeSignedMsgUserOrdersAccountIx(authority, numOrders, { externalWallet: rentPayerOverride });
17
+ return { swiftAccountPublicKey, ix };
18
+ };
19
+ exports.createSwiftAccountIx = createSwiftAccountIx;
20
+ /**
21
+ * Creates a complete transaction for initializing a Swift (signed message user orders) account.
22
+ *
23
+ * Wraps {@link createSwiftAccountIx} and builds a transaction ready for signing and submission.
24
+ *
25
+ * @param driftClient - The Drift client instance
26
+ * @param authority - The public key of the account authority
27
+ * @param numOrders - The number of order slots to allocate (default: 8)
28
+ * @param rentPayerOverride - Optional wallet to pay for account creation instead of the default wallet
29
+ * @param txParams - Optional transaction parameters (compute units, priority fees, etc.)
30
+ *
31
+ * @returns The built transaction and the Swift account public key
32
+ */
33
+ const createSwiftAccountTxn = async ({ driftClient, authority, numOrders, rentPayerOverride: externalWallet, txParams, }) => {
34
+ const { swiftAccountPublicKey, ix } = await (0, exports.createSwiftAccountIx)({
35
+ driftClient,
36
+ authority,
37
+ numOrders,
38
+ rentPayerOverride: externalWallet,
39
+ });
40
+ const transaction = await driftClient.buildTransaction([ix], txParams);
41
+ return { transaction, swiftAccountPublicKey };
42
+ };
43
+ exports.createSwiftAccountTxn = createSwiftAccountTxn;
44
+ /**
45
+ * Creates a Swift account instruction only if one doesn't already exist for the given authority.
46
+ *
47
+ * Always returns the Swift account public key. The `ix` will be `null` if the account
48
+ * is already initialized, indicating no transaction is needed.
49
+ *
50
+ * @param driftClient - The Drift client instance
51
+ * @param authority - The public key of the account authority
52
+ * @param numOrders - The number of order slots to allocate (default: 8)
53
+ * @param rentPayerOverride - Optional wallet to pay for account creation instead of the default wallet
54
+ *
55
+ * @returns The Swift account public key and the initialization instruction (null if already initialized)
56
+ */
57
+ const createSwiftAccountIxIfNotExists = async ({ driftClient, authority, numOrders = 8, rentPayerOverride, }) => {
58
+ const isInitialized = await driftClient.isSignedMsgUserOrdersAccountInitialized(authority);
59
+ if (isInitialized) {
60
+ const swiftAccountPublicKey = (0, sdk_1.getSignedMsgUserAccountPublicKey)(driftClient.program.programId, authority);
61
+ return { swiftAccountPublicKey, ix: null };
62
+ }
63
+ return await (0, exports.createSwiftAccountIx)({
64
+ driftClient,
65
+ authority,
66
+ numOrders,
67
+ rentPayerOverride,
68
+ });
69
+ };
70
+ exports.createSwiftAccountIxIfNotExists = createSwiftAccountIxIfNotExists;
71
+ //# sourceMappingURL=create.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/swift/create.ts"],"names":[],"mappings":";;;AAAA,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AC7B,SAAS,CACT,CAAC;QAEF,OAAO,EAAE,qBAAqB,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC;IAC5C,CAAC;IAED,OAAO,MAAM,IAAA,4BAAoB,EAAC;QACjC,WAAW;QACX,SAAS;QACT,SAAS;QACT,iBAAiB;KACjB,CAAC,CAAC;AACJ,CAAC,CAAC;AA3BW,QAAA,+BAA+B,mCA2B1C","sourcesContent":["import {\n\tDriftClient,\n\tgetSignedMsgUserAccountPublicKey,\n\tPublicKey,\n\tTxParams,\n} from '@drift-labs/sdk';\nimport {\n\tTransaction,\n\tTransactionInstruction,\n\tVersionedTransaction,\n} from '@solana/web3.js';\n\ninterface CreateSwiftAccountIxParams {\n\tdriftClient: DriftClient;\n\tauthority: PublicKey;\n\tnumOrders?: number;\n\t/**\n\t * Optional external wallet to use as payer. If provided, this wallet will pay\n\t * for the account creation instead of the default wallet.\n\t */\n\trentPayerOverride?: PublicKey;\n}\n\n/**\n * Creates a transaction instruction for initializing a Swift (signed message user orders) account.\n *\n * @param driftClient - The Drift client instance\n * @param authority - The public key of the account authority\n * @param numOrders - The number of order slots to allocate (default: 8)\n * @param rentPayerOverride - Optional wallet to pay for account creation instead of the default wallet\n *\n * @returns The Swift account public key and the initialization instruction\n */\nexport const createSwiftAccountIx = async ({\n\tdriftClient,\n\tauthority,\n\tnumOrders = 8,\n\trentPayerOverride,\n}: CreateSwiftAccountIxParams): Promise<{\n\tswiftAccountPublicKey: PublicKey;\n\tix: TransactionInstruction;\n}> => {\n\tconst [swiftAccountPublicKey, ix] =\n\t\tawait driftClient.getInitializeSignedMsgUserOrdersAccountIx(\n\t\t\tauthority,\n\t\t\tnumOrders,\n\t\t\t{ externalWallet: rentPayerOverride }\n\t\t);\n\n\treturn { swiftAccountPublicKey, ix };\n};\n\ninterface CreateSwiftAccountTxnParams extends CreateSwiftAccountIxParams {\n\ttxParams?: TxParams;\n}\n\n/**\n * Creates a complete transaction for initializing a Swift (signed message user orders) account.\n *\n * Wraps {@link createSwiftAccountIx} and builds a transaction ready for signing and submission.\n *\n * @param driftClient - The Drift client instance\n * @param authority - The public key of the account authority\n * @param numOrders - The number of order slots to allocate (default: 8)\n * @param rentPayerOverride - Optional wallet to pay for account creation instead of the default wallet\n * @param txParams - Optional transaction parameters (compute units, priority fees, etc.)\n *\n * @returns The built transaction and the Swift account public key\n */\nexport const createSwiftAccountTxn = async ({\n\tdriftClient,\n\tauthority,\n\tnumOrders,\n\trentPayerOverride: externalWallet,\n\ttxParams,\n}: CreateSwiftAccountTxnParams): Promise<{\n\ttransaction: Transaction | VersionedTransaction;\n\tswiftAccountPublicKey: PublicKey;\n}> => {\n\tconst { swiftAccountPublicKey, ix } = await createSwiftAccountIx({\n\t\tdriftClient,\n\t\tauthority,\n\t\tnumOrders,\n\t\trentPayerOverride: externalWallet,\n\t});\n\n\tconst transaction = await driftClient.buildTransaction([ix], txParams);\n\n\treturn { transaction, swiftAccountPublicKey };\n};\n\n/**\n * Creates a Swift account instruction only if one doesn't already exist for the given authority.\n *\n * Always returns the Swift account public key. The `ix` will be `null` if the account\n * is already initialized, indicating no transaction is needed.\n *\n * @param driftClient - The Drift client instance\n * @param authority - The public key of the account authority\n * @param numOrders - The number of order slots to allocate (default: 8)\n * @param rentPayerOverride - Optional wallet to pay for account creation instead of the default wallet\n *\n * @returns The Swift account public key and the initialization instruction (null if already initialized)\n */\nexport const createSwiftAccountIxIfNotExists = async ({\n\tdriftClient,\n\tauthority,\n\tnumOrders = 8,\n\trentPayerOverride,\n}: CreateSwiftAccountIxParams): Promise<{\n\tswiftAccountPublicKey: PublicKey;\n\tix: TransactionInstruction | null;\n}> => {\n\tconst isInitialized =\n\t\tawait driftClient.isSignedMsgUserOrdersAccountInitialized(authority);\n\n\tif (isInitialized) {\n\t\tconst swiftAccountPublicKey = getSignedMsgUserAccountPublicKey(\n\t\t\tdriftClient.program.programId,\n\t\t\tauthority\n\t\t);\n\n\t\treturn { swiftAccountPublicKey, ix: null };\n\t}\n\n\treturn await createSwiftAccountIx({\n\t\tdriftClient,\n\t\tauthority,\n\t\tnumOrders,\n\t\trentPayerOverride,\n\t});\n};\n"]}
@@ -0,0 +1 @@
1
+ export * from './create';
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./create"), exports);
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/drift/base/actions/swift/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2CAAyB","sourcesContent":["export * from './create';\n"]}
@@ -36,12 +36,12 @@ const createUserAndDepositCollateralBaseIxs = async ({ driftClient, amount, spot
36
36
  const nextSubaccountId = (_a = userStatsAccount === null || userStatsAccount === void 0 ? void 0 : userStatsAccount.numberOfSubAccountsCreated) !== null && _a !== void 0 ? _a : 0; // userId is zero indexed
37
37
  // Get the spot market account to determine the correct token program for Token-2022 tokens
38
38
  const spotMarketAccount = driftClient.getSpotMarketAccount(spotMarketConfig.marketIndex);
39
- const tokenProgram = spotMarketAccount
40
- ? (0, sdk_1.getTokenProgramForSpotMarket)(spotMarketAccount)
41
- : undefined;
39
+ if (!spotMarketAccount) {
40
+ throw new Error(`Spot market account not found for market index ${spotMarketConfig.marketIndex}`);
41
+ }
42
42
  // Use external wallet for token address if provided, otherwise use authority
43
43
  const depositSourceWallet = externalWallet !== null && externalWallet !== void 0 ? externalWallet : authority;
44
- const associatedDepositTokenAddressPromise = (0, token_1.getTokenAddressForDepositAndWithdraw)(spotMarketConfig.mint, depositSourceWallet, tokenProgram);
44
+ const associatedDepositTokenAddressPromise = (0, token_1.getTokenAddressForDepositAndWithdraw)(spotMarketAccount, depositSourceWallet);
45
45
  const referrerNameAccountPromise = referrerName
46
46
  ? driftClient.fetchReferrerNameAccount(referrerName)
47
47
  : Promise.resolve(undefined);
@@ -1 +1 @@
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,0BAA0B,mCAAI,CAAC,CAAC,CAAC,yBAAyB;IAErG,2FAA2F;IAC3F,MAAM,iBAAiB,GAAG,WAAW,CAAC,oBAAoB,CACzD,gBAAgB,CAAC,WAAW,CAC5B,CAAC;IACF,MAAM,YAAY,GAAG,iBAAiB;QACrC,CAAC,CAAC,IAAA,kCAA4B,EAAC,iBAAiB,CAAC;QACjD,CAAC,CAAC,SAAS,CAAC;IAEb,6EAA6E;IAC7E,MAAM,mBAAmB,GAAG,cAAc,aAAd,cAAc,cAAd,cAAc,GAAI,SAAS,CAAC;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M,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
+ {"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;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,0BAA0B,mCAAI,CAAC,CAAC,CAAC,yBAAyB;IAErG,2FAA2F;IAC3F,MAAM,iBAAiB,GAAG,WAAW,CAAC,oBAAoB,CACzD,gBAAgB,CAAC,WAAW,CAC5B,CAAC;IAEF,IAAI,CAAC,iBAAiB,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CACd,kDAAkD,gBAAgB,CAAC,WAAW,EAAE,CAChF,CAAC;IACH,CAAC;IAED,6EAA6E;IAC7E,MAAM,mBAAmB,GAAG,cAAc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C,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\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\n\tif (!spotMarketAccount) {\n\t\tthrow new Error(\n\t\t\t`Spot market account not found for market index ${spotMarketConfig.marketIndex}`\n\t\t);\n\t}\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\tspotMarketAccount,\n\t\t\tdepositSourceWallet\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,15 +1,16 @@
1
+ import { SpotMarketAccount } from '@drift-labs/sdk';
1
2
  import { Connection, PublicKey, TransactionInstruction } from '@solana/web3.js';
2
3
  export { TOKEN_PROGRAM_ID, createTransferCheckedInstruction, } from '@solana/spl-token';
3
4
  export declare const getTokenAddress: (mintAddress: string, userPubKey: string) => Promise<PublicKey>;
4
5
  /**
5
- * Get the associated token address for the given mint and user public key. If the mint is SOL, return the user public key.
6
+ * Get the associated token address for the given spot market and authority. If the mint is SOL, return the authority public key.
6
7
  * This should be used for spot token movement in and out of the user's wallet.
7
- * @param mintAddress - The mint address
8
- * @param authorityPubKey - The authority's public key
9
- * @param tokenProgram - The token program ID (defaults to TOKEN_PROGRAM_ID, use TOKEN_2022_PROGRAM_ID for Token-2022 tokens)
8
+ * Automatically resolves the correct token program (TOKEN_PROGRAM_ID or TOKEN_2022_PROGRAM_ID) from the spot market account.
9
+ * @param spotMarketAccount - The spot market account
10
+ * @param authority - The authority's public key
10
11
  * @returns The associated token address
11
12
  */
12
- export declare const getTokenAddressForDepositAndWithdraw: (mintAddress: PublicKey, authorityPubKey: PublicKey, tokenProgram?: PublicKey) => Promise<PublicKey>;
13
+ export declare const getTokenAddressForDepositAndWithdraw: (spotMarketAccount: SpotMarketAccount, authority: PublicKey) => Promise<PublicKey>;
13
14
  export declare const getTokenAccount: (connection: Connection, mintAddress: string, userPubKey: string) => Promise<{
14
15
  pubkey: PublicKey;
15
16
  account: import('@solana/web3.js').AccountInfo<import('@solana/web3.js').ParsedAccountData>;
@@ -12,18 +12,18 @@ const getTokenAddress = (mintAddress, userPubKey) => {
12
12
  };
13
13
  exports.getTokenAddress = getTokenAddress;
14
14
  /**
15
- * Get the associated token address for the given mint and user public key. If the mint is SOL, return the user public key.
15
+ * Get the associated token address for the given spot market and authority. If the mint is SOL, return the authority public key.
16
16
  * This should be used for spot token movement in and out of the user's wallet.
17
- * @param mintAddress - The mint address
18
- * @param authorityPubKey - The authority's public key
19
- * @param tokenProgram - The token program ID (defaults to TOKEN_PROGRAM_ID, use TOKEN_2022_PROGRAM_ID for Token-2022 tokens)
17
+ * Automatically resolves the correct token program (TOKEN_PROGRAM_ID or TOKEN_2022_PROGRAM_ID) from the spot market account.
18
+ * @param spotMarketAccount - The spot market account
19
+ * @param authority - The authority's public key
20
20
  * @returns The associated token address
21
21
  */
22
- const getTokenAddressForDepositAndWithdraw = async (mintAddress, authorityPubKey, tokenProgram = spl_token_1.TOKEN_PROGRAM_ID) => {
23
- const isSol = mintAddress.equals(sdk_1.WRAPPED_SOL_MINT);
22
+ const getTokenAddressForDepositAndWithdraw = async (spotMarketAccount, authority) => {
23
+ const isSol = spotMarketAccount.mint.equals(sdk_1.WRAPPED_SOL_MINT);
24
24
  if (isSol)
25
- return authorityPubKey;
26
- return (0, spl_token_1.getAssociatedTokenAddress)(mintAddress, authorityPubKey, true, tokenProgram);
25
+ return authority;
26
+ return (0, spl_token_1.getAssociatedTokenAddress)(spotMarketAccount.mint, authority, true, (0, sdk_1.getTokenProgramForSpotMarket)(spotMarketAccount));
27
27
  };
28
28
  exports.getTokenAddressForDepositAndWithdraw = getTokenAddressForDepositAndWithdraw;
29
29
  const getTokenAccount = async (connection, mintAddress, userPubKey) => {
@@ -1 +1 @@
1
- {"version":3,"file":"token.js","sourceRoot":"","sources":["../../src/utils/token.ts"],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CAAC,iBAAiB,CAAC,CACxC,CAAC,CAAC,CAAC,IAAI,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAEhC,OAAO,aAAa,CAAC;AACtB,CAAC,CAAC;AA3BW,QAAA,eAAe,mBA2B1B;AAEK,MAAM,oBAAoB,GAAG,KAAK,EACxC,KAAgB,EAChB,WAAsB,EACtB,KAAiB,EACiB,EAAE;IACpC,IAAI,CAAC,KAAK,EAAE,CAAC;QACZ,KAAK,GAAG,KAAK,CAAC;IACf,CAAC;IAED,MAAM,iBAAiB,GAAG,MAAM,IAAA,qCAAyB,EACxD,WAAW,EACX,KAAK,EACL,IAAI,CACJ,CAAC;IAEF,MAAM,WAAW,GAAG,MAAM,IAAA,mDAAuC,EAChE,KAAK,EACL,iBAAiB,EACjB,KAAK,EACL,WAAW,CACX,CAAC;IAEF,OAAO,WAAW,CAAC;AACpB,CAAC,CAAC;AAvBW,QAAA,oBAAoB,wBAuB/B","sourcesContent":["import { WRAPPED_SOL_MINT } from '@drift-labs/sdk';\nimport {\n\tcreateAssociatedTokenAccountInstruction,\n\tgetAssociatedTokenAddress,\n\tTOKEN_PROGRAM_ID,\n} from '@solana/spl-token';\nimport { Connection, PublicKey, TransactionInstruction } from '@solana/web3.js';\n\nexport {\n\tTOKEN_PROGRAM_ID,\n\tcreateTransferCheckedInstruction,\n} from '@solana/spl-token';\n\nexport const getTokenAddress = (\n\tmintAddress: string,\n\tuserPubKey: string\n): Promise<PublicKey> => {\n\treturn getAssociatedTokenAddress(\n\t\tnew PublicKey(mintAddress),\n\t\tnew PublicKey(userPubKey),\n\t\ttrue\n\t);\n};\n\n/**\n * Get the associated token address for the given mint and user public key. If the mint is SOL, return the user public key.\n * This should be used for spot token movement in and out of the user's wallet.\n * @param mintAddress - The mint address\n * @param authorityPubKey - The authority's public key\n * @param tokenProgram - The token program ID (defaults to TOKEN_PROGRAM_ID, use TOKEN_2022_PROGRAM_ID for Token-2022 tokens)\n * @returns The associated token address\n */\nexport const getTokenAddressForDepositAndWithdraw = async (\n\tmintAddress: PublicKey,\n\tauthorityPubKey: PublicKey,\n\ttokenProgram: PublicKey = TOKEN_PROGRAM_ID\n): Promise<PublicKey> => {\n\tconst isSol = mintAddress.equals(WRAPPED_SOL_MINT);\n\n\tif (isSol) return authorityPubKey;\n\n\treturn getAssociatedTokenAddress(\n\t\tmintAddress,\n\t\tauthorityPubKey,\n\t\ttrue,\n\t\ttokenProgram\n\t);\n};\n\nexport const getTokenAccount = async (\n\tconnection: Connection,\n\tmintAddress: string,\n\tuserPubKey: string\n): Promise<{\n\tpubkey: PublicKey;\n\taccount: import('@solana/web3.js').AccountInfo<\n\t\timport('@solana/web3.js').ParsedAccountData\n\t>;\n}> => {\n\tconst tokenAccounts = await connection.getParsedTokenAccountsByOwner(\n\t\tnew PublicKey(userPubKey),\n\t\t{ mint: new PublicKey(mintAddress) }\n\t);\n\n\tconst associatedAddress = await getAssociatedTokenAddress(\n\t\tnew PublicKey(mintAddress),\n\t\tnew PublicKey(userPubKey),\n\t\ttrue\n\t);\n\n\tconst targetAccount =\n\t\ttokenAccounts.value.filter((account) =>\n\t\t\taccount.pubkey.equals(associatedAddress)\n\t\t)[0] || tokenAccounts.value[0];\n\n\treturn targetAccount;\n};\n\nexport const createTokenAccountIx = async (\n\towner: PublicKey,\n\tmintAddress: PublicKey,\n\tpayer?: PublicKey\n): Promise<TransactionInstruction> => {\n\tif (!payer) {\n\t\tpayer = owner;\n\t}\n\n\tconst associatedAddress = await getAssociatedTokenAddress(\n\t\tmintAddress,\n\t\towner,\n\t\ttrue\n\t);\n\n\tconst createAtaIx = await createAssociatedTokenAccountInstruction(\n\t\tpayer,\n\t\tassociatedAddress,\n\t\towner,\n\t\tmintAddress\n\t);\n\n\treturn createAtaIx;\n};\n"]}
1
+ {"version":3,"file":"token.js","sourceRoot":"","sources":["../../src/utils/token.ts"],"names":[],"mappings":";;;AAAA,yCAIyB;AACzB,iDAG2B;AAC3B,6CAAgF;AAEhF,+CAG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AAC,CAAC,IAAI,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAEhC,OAAO,aAAa,CAAC;AACtB,CAAC,CAAC;AA3BW,QAAA,eAAe,mBA2B1B;AAEK,MAAM,oBAAoB,GAAG,KAAK,EACxC,KAAgB,EAChB,WAAsB,EACtB,KAAiB,EACiB,EAAE;IACpC,IAAI,CAAC,KAAK,EAAE,CAAC;QACZ,KAAK,GAAG,KAAK,CAAC;IACf,CAAC;IAED,MAAM,iBAAiB,GAAG,MAAM,IAAA,qCAAyB,EACxD,WAAW,EACX,KAAK,EACL,IAAI,CACJ,CAAC;IAEF,MAAM,WAAW,GAAG,MAAM,IAAA,mDAAuC,EAChE,KAAK,EACL,iBAAiB,EACjB,KAAK,EACL,WAAW,CACX,CAAC;IAEF,OAAO,WAAW,CAAC;AACpB,CAAC,CAAC;AAvBW,QAAA,oBAAoB,wBAuB/B","sourcesContent":["import {\n\tSpotMarketAccount,\n\tWRAPPED_SOL_MINT,\n\tgetTokenProgramForSpotMarket,\n} from '@drift-labs/sdk';\nimport {\n\tcreateAssociatedTokenAccountInstruction,\n\tgetAssociatedTokenAddress,\n} from '@solana/spl-token';\nimport { Connection, PublicKey, TransactionInstruction } from '@solana/web3.js';\n\nexport {\n\tTOKEN_PROGRAM_ID,\n\tcreateTransferCheckedInstruction,\n} from '@solana/spl-token';\n\nexport const getTokenAddress = (\n\tmintAddress: string,\n\tuserPubKey: string\n): Promise<PublicKey> => {\n\treturn getAssociatedTokenAddress(\n\t\tnew PublicKey(mintAddress),\n\t\tnew PublicKey(userPubKey),\n\t\ttrue\n\t);\n};\n\n/**\n * Get the associated token address for the given spot market and authority. If the mint is SOL, return the authority public key.\n * This should be used for spot token movement in and out of the user's wallet.\n * Automatically resolves the correct token program (TOKEN_PROGRAM_ID or TOKEN_2022_PROGRAM_ID) from the spot market account.\n * @param spotMarketAccount - The spot market account\n * @param authority - The authority's public key\n * @returns The associated token address\n */\nexport const getTokenAddressForDepositAndWithdraw = async (\n\tspotMarketAccount: SpotMarketAccount,\n\tauthority: PublicKey\n): Promise<PublicKey> => {\n\tconst isSol = spotMarketAccount.mint.equals(WRAPPED_SOL_MINT);\n\n\tif (isSol) return authority;\n\n\treturn getAssociatedTokenAddress(\n\t\tspotMarketAccount.mint,\n\t\tauthority,\n\t\ttrue,\n\t\tgetTokenProgramForSpotMarket(spotMarketAccount)\n\t);\n};\n\nexport const getTokenAccount = async (\n\tconnection: Connection,\n\tmintAddress: string,\n\tuserPubKey: string\n): Promise<{\n\tpubkey: PublicKey;\n\taccount: import('@solana/web3.js').AccountInfo<\n\t\timport('@solana/web3.js').ParsedAccountData\n\t>;\n}> => {\n\tconst tokenAccounts = await connection.getParsedTokenAccountsByOwner(\n\t\tnew PublicKey(userPubKey),\n\t\t{ mint: new PublicKey(mintAddress) }\n\t);\n\n\tconst associatedAddress = await getAssociatedTokenAddress(\n\t\tnew PublicKey(mintAddress),\n\t\tnew PublicKey(userPubKey),\n\t\ttrue\n\t);\n\n\tconst targetAccount =\n\t\ttokenAccounts.value.filter((account) =>\n\t\t\taccount.pubkey.equals(associatedAddress)\n\t\t)[0] || tokenAccounts.value[0];\n\n\treturn targetAccount;\n};\n\nexport const createTokenAccountIx = async (\n\towner: PublicKey,\n\tmintAddress: PublicKey,\n\tpayer?: PublicKey\n): Promise<TransactionInstruction> => {\n\tif (!payer) {\n\t\tpayer = owner;\n\t}\n\n\tconst associatedAddress = await getAssociatedTokenAddress(\n\t\tmintAddress,\n\t\towner,\n\t\ttrue\n\t);\n\n\tconst createAtaIx = await createAssociatedTokenAccountInstruction(\n\t\tpayer,\n\t\tassociatedAddress,\n\t\towner,\n\t\tmintAddress\n\t);\n\n\treturn createAtaIx;\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drift-labs/common",
3
- "version": "1.0.41",
3
+ "version": "1.0.43",
4
4
  "description": "Common functions for Drift",
5
5
  "main": "./lib/index.js",
6
6
  "types": "./lib/index.d.ts",