@thespidercode/openbook-swap
Version:
Ready-to-use swap tool using Openbook DEX
57 lines (56 loc) • 2.75 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAssociatedTokenAddress = exports.getOrCreateTokenAccount = void 0;
const spl_token_1 = require("@solana/spl-token");
const web3_js_1 = require("@solana/web3.js");
const token_instructions_1 = require("./serum/token-instructions");
const getOrCreateTokenAccount = async (owner, mint, transaction, connection, lamports = 0) => {
try {
const tokenAccounts = await connection.getParsedTokenAccountsByOwner(owner, {
mint
});
if (mint.toString() === spl_token_1.NATIVE_MINT.toString()) {
const wrappedSolAccount = new web3_js_1.Keypair();
lamports = Math.max(lamports, 0) + 1e7;
transaction.add(web3_js_1.SystemProgram.createAccount({
fromPubkey: owner,
newAccountPubkey: wrappedSolAccount.publicKey,
lamports: lamports,
space: 165,
programId: spl_token_1.TOKEN_PROGRAM_ID,
}));
transaction.add((0, token_instructions_1.initializeAccount)({
account: wrappedSolAccount.publicKey,
mint: spl_token_1.NATIVE_MINT,
owner: owner,
}));
return wrappedSolAccount;
}
if (tokenAccounts.value && tokenAccounts.value.length > 0 &&
tokenAccounts.value.length === 1) {
return tokenAccounts.value[0].pubkey;
}
else if (tokenAccounts.value.length == 0) {
const newTokenAccount = await (0, exports.getAssociatedTokenAddress)(mint, owner);
transaction.add((0, spl_token_1.createAssociatedTokenAccountInstruction)(owner, newTokenAccount, owner, mint, spl_token_1.TOKEN_PROGRAM_ID, spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID));
return newTokenAccount;
}
else {
// TODO: SEE IF MULTIPLE TOKEN ACCOUNTS
console.log('Multiple token account for base mint');
}
return undefined;
}
catch (error) {
console.log(error);
return undefined;
}
};
exports.getOrCreateTokenAccount = getOrCreateTokenAccount;
const getAssociatedTokenAddress = async (mint, owner, allowOwnerOffCurve = false, programId = spl_token_1.TOKEN_PROGRAM_ID, associatedTokenProgramId = spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID) => {
if (!allowOwnerOffCurve && !web3_js_1.PublicKey.isOnCurve(owner.toBuffer()))
throw new Error('TokenOwnerOffCurveError');
const [address, number] = web3_js_1.PublicKey.findProgramAddressSync([owner.toBuffer(), programId.toBuffer(), mint.toBuffer()], associatedTokenProgramId);
return address;
};
exports.getAssociatedTokenAddress = getAssociatedTokenAddress;