import { PublicKey, Transaction } from '@solana/web3.js'; // @internal export namespace TransactionBuilder { const LOW_VALUE = 127; // 0x7f const HIGH_VALUE = 16383; // 0x3fff const MAX_TRANSACTION_SIZE = 1232; /** * Compact u16 array header size * @param n elements in the compact array * @returns size in bytes of array header */ const compactHeader = (n: number) => n <= LOW_VALUE ? 1 : n <= HIGH_VALUE ? 2 : 3; /** * Compact u16 array size * @param n elements in the compact array * @param size bytes per each element * @returns size in bytes of array */ const compactArraySize = (n: number, size: number) => compactHeader(n) + n * size; /** * Calculate txsize * @param transaction a solana transaction * @param feePayer the publicKey of the signer * @returns size in bytes of the transaction */ export const calculateTxSize = ( transaction: Transaction, feePayer: PublicKey, ): number => { const feePayerPk = [feePayer.toBase58()]; const signers = new Set(feePayerPk); const accounts = new Set(feePayerPk); const ixsSize = transaction.instructions.reduce((acc, ix) => { ix.keys.forEach(({ pubkey, isSigner }) => { const pk = pubkey.toBase58(); if (isSigner) signers.add(pk); accounts.add(pk); }); accounts.add(ix.programId.toBase58()); const nIndexes = ix.keys.length; const opaqueData = ix.data.length; return ( acc + 1 + // PID index compactArraySize(nIndexes, 1) + compactArraySize(opaqueData, 1) ); }, 0); return ( compactArraySize(signers.size, 64) + // signatures 3 + // header compactArraySize(accounts.size, 32) + // accounts 32 + // blockhash compactHeader(transaction.instructions.length) + // instructions ixsSize ); }; /** * Is max transaction size * @param transaction a solana transaction * @param feePayer the publicKey of the signer * @returns size in bytes of the transaction */ export const isOverTransactionSize = ( transaction: Transaction, feePayer: PublicKey, ): boolean => { return calculateTxSize(transaction, feePayer) > MAX_TRANSACTION_SIZE; }; }