UNPKG

@drift-labs/common

Version:

Common functions for Drift

44 lines 2.8 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createTokenAccountIx = exports.getTokenAccount = exports.getTokenAddressForDepositAndWithdraw = exports.getTokenAddress = exports.createTransferCheckedInstruction = exports.TOKEN_PROGRAM_ID = void 0; const sdk_1 = require("@drift-labs/sdk"); const spl_token_1 = require("@solana/spl-token"); const web3_js_1 = require("@solana/web3.js"); var spl_token_2 = require("@solana/spl-token"); Object.defineProperty(exports, "TOKEN_PROGRAM_ID", { enumerable: true, get: function () { return spl_token_2.TOKEN_PROGRAM_ID; } }); Object.defineProperty(exports, "createTransferCheckedInstruction", { enumerable: true, get: function () { return spl_token_2.createTransferCheckedInstruction; } }); const getTokenAddress = (mintAddress, userPubKey) => { return (0, spl_token_1.getAssociatedTokenAddress)(new web3_js_1.PublicKey(mintAddress), new web3_js_1.PublicKey(userPubKey), true); }; exports.getTokenAddress = getTokenAddress; /** * Get the associated token address for the given mint and user public key. If the mint is SOL, return the user public key. * This should be used for spot token movement in and out of the user's wallet. * @param mintAddress - The mint address * @param authorityPubKey - The authority's public key * @returns The associated token address */ const getTokenAddressForDepositAndWithdraw = async (mintAddress, authorityPubKey) => { const isSol = mintAddress.equals(sdk_1.WRAPPED_SOL_MINT); if (isSol) return authorityPubKey; return (0, spl_token_1.getAssociatedTokenAddress)(mintAddress, authorityPubKey, true); }; exports.getTokenAddressForDepositAndWithdraw = getTokenAddressForDepositAndWithdraw; const getTokenAccount = async (connection, mintAddress, userPubKey) => { const tokenAccounts = await connection.getParsedTokenAccountsByOwner(new web3_js_1.PublicKey(userPubKey), { mint: new web3_js_1.PublicKey(mintAddress) }); const associatedAddress = await (0, spl_token_1.getAssociatedTokenAddress)(new web3_js_1.PublicKey(mintAddress), new web3_js_1.PublicKey(userPubKey), true); const targetAccount = tokenAccounts.value.filter((account) => account.pubkey.equals(associatedAddress))[0] || tokenAccounts.value[0]; return targetAccount; }; exports.getTokenAccount = getTokenAccount; const createTokenAccountIx = async (owner, mintAddress, payer) => { if (!payer) { payer = owner; } const associatedAddress = await (0, spl_token_1.getAssociatedTokenAddress)(mintAddress, owner, true); const createAtaIx = await (0, spl_token_1.createAssociatedTokenAccountInstruction)(payer, associatedAddress, owner, mintAddress); return createAtaIx; }; exports.createTokenAccountIx = createTokenAccountIx; //# sourceMappingURL=token.js.map