import { ConfirmOptions, TransactionInstruction } from "@solana/web3.js"; import * as anchor from "@project-serum/anchor"; import { Connection, PublicKey, TransactionSignature, Transaction, Signer, AccountInfo, sendAndConfirmRawTransaction, SystemProgram, Keypair, } from "@solana/web3.js"; import { TOKEN_PROGRAM_ID, AccountLayout as TokenAccountLayout, getMinimumBalanceForRentExemptAccount, getAssociatedTokenAddress, createInitializeAccountInstruction, createCloseAccountInstruction, createAssociatedTokenAccountInstruction, getAccount, } from "@solana/spl-token"; import BufferLayout from "buffer-layout"; import { Program } from "./program"; import { flexIdlErrors, vaultIdlErrors } from "./errors"; import { SOL_PUBKEY, PUBKEY_TO_UNDERLYINGS_MAP, UNDERLYINGS_TO_PUBKEY_MAP, } from "./constants"; import { TokenAccount, TransactionMethodReturnData } from "./types"; import { Network } from "./network"; export async function sleep(ms: number) { await new Promise((resolve) => setTimeout(resolve, ms, undefined)); } export function defaultCommitment(): ConfirmOptions { return { skipPreflight: false, preflightCommitment: "processed", commitment: "processed", }; } const uint64 = (property = "uint64") => { return BufferLayout.blob(8, property); }; const int64 = (property = "int64") => { return BufferLayout.blob(8, property); }; // https://github.com/nodejs/node/blob/v14.17.0/lib/internal/errors.js#L758 export const ERR_BUFFER_OUT_OF_BOUNDS = () => new Error("Attempt to access memory outside buffer bounds"); // https://github.com/nodejs/node/blob/v14.17.0/lib/internal/errors.js#L968 export const ERR_INVALID_ARG_TYPE = ( name: string, expected: string, actual: string ) => new Error( `The "${name}" argument must be of type ${expected}. Received ${actual}` ); // https://github.com/nodejs/node/blob/v14.17.0/lib/internal/errors.js#L1262 export const ERR_OUT_OF_RANGE = ( str: string, range: string, received: number ) => new Error( `The value of "${str} is out of range. It must be ${range}. Received ${received}` ); // https://github.com/nodejs/node/blob/v14.17.0/lib/internal/validators.js#L127-L130 export function validateNumber(value: number, name: string) { if (typeof value !== "number") throw ERR_INVALID_ARG_TYPE(name, "number", value); } // https://github.com/nodejs/node/blob/v14.17.0/lib/internal/buffer.js#L68-L80 export function boundsError(value: number, length: number) { if (Math.floor(value) !== value) { validateNumber(value, "offset"); throw ERR_OUT_OF_RANGE("offset", "an integer", value); } if (length < 0) throw ERR_BUFFER_OUT_OF_BOUNDS(); throw ERR_OUT_OF_RANGE("offset", `>= 0 and <= ${length}`, value); } export function readBigInt64LE(buffer: Uint8Array, offset = 0) { validateNumber(offset, "offset"); const first = buffer[offset]; const last = buffer[offset + 7]; if (first === undefined || last === undefined) boundsError(offset, buffer.length - 8); const val = buffer[offset + 4] + buffer[offset + 5] * 2 ** 8 + buffer[offset + 6] * 2 ** 16 + (last << 24); // Overflow return ( (BigInt(val) << BigInt(32)) + BigInt( first + buffer[++offset] * 2 ** 8 + buffer[++offset] * 2 ** 16 + buffer[++offset] * 2 ** 24 ) ); } const SystemClockLayout = BufferLayout.struct([ uint64("slot"), int64("epochStartTimestamp"), uint64("epoch"), uint64("leaderScheduleEpoch"), int64("unixTimestamp"), ]); export function getClockTimestamp(accountInfo: AccountInfo): number { let info = SystemClockLayout.decode(accountInfo.data); return Number(readBigInt64LE(info.unixTimestamp, 0)); } export async function processTransaction( program: Program, provider: anchor.AnchorProvider, tx: Transaction, signers?: Array, opts?: ConfirmOptions, returnInstructions: boolean = false ): Promise { // Return instructions and signers if requested if (returnInstructions) { return { ixs: tx.instructions, signers, }; } // otherwise, send and confirm const blockhash = await provider.connection.getLatestBlockhash(); tx.recentBlockhash = blockhash.blockhash; tx.feePayer = provider.wallet.publicKey; tx = await provider.wallet.signTransaction(tx); if (signers === undefined) { signers = []; } signers .filter((s) => s !== undefined) .forEach((kp) => { tx.partialSign(kp); }); try { let txSig = await sendAndConfirmRawTransaction( provider.connection, tx.serialize(), opts || defaultCommitment() ); return txSig; } catch (err) { let translatedErr = anchor.ProgramError.parse( err, program == Program.FLEX ? flexIdlErrors : vaultIdlErrors ); if (translatedErr !== null) { throw translatedErr; } throw err; } } export async function createWrappedNativeAccount( connection: Connection, owner: PublicKey, payer: PublicKey, amount: number ): Promise<[Transaction, Keypair]> { // Allocate memory for the account const balanceNeeded = await getMinimumBalanceForRentExemptAccount(connection); // Create a new account const newAccount = Keypair.generate(); const transaction = new Transaction(); transaction.add( SystemProgram.createAccount({ fromPubkey: payer, newAccountPubkey: newAccount.publicKey, lamports: balanceNeeded, space: TokenAccountLayout.span, programId: TOKEN_PROGRAM_ID, }) ); // Send lamports to it (these will be wrapped into native tokens by the token program) transaction.add( SystemProgram.transfer({ fromPubkey: payer, toPubkey: newAccount.publicKey, lamports: amount, }) ); // Assign the new account to the native token mint. // the account will be initialized with a balance equal to the native token balance. // (i.e. amount) transaction.add( createInitializeAccountInstruction(newAccount.publicKey, SOL_PUBKEY, owner) ); // Send the three instructions return [transaction, newAccount]; } export async function getTokenAccountsForMint( connection: Connection, mint: PublicKey ): Promise { const accounts = await connection.getParsedProgramAccounts(TOKEN_PROGRAM_ID, { filters: [ { dataSize: 165, // number of bytes }, { memcmp: { offset: 0, // number of bytes bytes: mint.toBase58(), // base58 encoded string }, }, ], }); return accounts.map((acc) => { return { mint: new PublicKey(acc.account.data["parsed"].info.mint), owner: new PublicKey(acc.account.data["parsed"].info.owner), amount: new anchor.BN(acc.account.data["parsed"].info.tokenAmount.amount), decimals: acc.account.data["parsed"].info.tokenAmount.decimals, }; }); } export function getUnderlyingMapping( network: Network, tokenAddress: PublicKey ): string { let underlying = PUBKEY_TO_UNDERLYINGS_MAP[network][tokenAddress.toString()]; return underlying != undefined ? underlying : tokenAddress.toString(); } export function getUnderlyingToKeyMapping( network: Network, underlyingString: string ): PublicKey { let pubkey = UNDERLYINGS_TO_PUBKEY_MAP[network][underlyingString]; if (pubkey == undefined) { throw Error("Underlying does not exist in constants"); } return new PublicKey(pubkey); } export function bigIntToBN(bigInt: bigint): anchor.BN { return new anchor.BN(bigInt.toString()); } export function BNtoBigInt(bn: anchor.BN): bigint { return BigInt(bn.toString()); } export function combineIxsForTx(...ixs: TransactionInstruction[]): Transaction { let tx = new Transaction(); tx.add(...ixs.reduce((acc, v) => acc.concat(v), [])); return tx; } export async function createTokenAccountInstructions( connection: Connection, mint: PublicKey, owner: PublicKey, payer: PublicKey, amount: number, closeNative: boolean ): Promise< [TransactionInstruction[], TransactionInstruction[], Keypair, PublicKey] > { let preIxs: TransactionInstruction[] = []; let postIxs: TransactionInstruction[] = []; let wrappedAccKeypair: Keypair = undefined; let userTokenAddress: PublicKey = undefined; if (mint.equals(SOL_PUBKEY)) { console.log("Mint is native wrapped SOL."); let [_tx, _keypair] = await createWrappedNativeAccount( connection, owner, payer, amount ); preIxs.push(..._tx.instructions); wrappedAccKeypair = _keypair; userTokenAddress = _keypair.publicKey; if (closeNative) { postIxs.push( createCloseAccountInstruction(userTokenAddress, payer, owner) ); } } else { userTokenAddress = await getAssociatedTokenAddress(mint, owner, true); try { await getAccount(connection, userTokenAddress); } catch (e) { preIxs.push( createAssociatedTokenAccountInstruction( payer, userTokenAddress, owner, mint ) ); } } return [preIxs, postIxs, wrappedAccKeypair, userTokenAddress]; }