@lightprotocol/compressed-token 0.22.1-alpha.3 → 0.22.1-alpha.5

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.
@@ -1 +0,0 @@
1
- {"version":3,"file":"types-Drp6Yu8A.js","sources":["../../../../../src/constants.ts","../../../../../src/utils/get-token-pool-infos.ts","../../../../../src/utils/select-input-accounts.ts","../../../../../src/utils/pack-compressed-token-accounts.ts","../../../../../src/utils/validation.ts","../../../../../src/layout.ts","../../../../../src/program.ts","../../../../../src/v3/derivation.ts","../../../../../src/v3/layout/layout-mint-action.ts","../../../../../src/v3/instructions/create-mint.ts","../../../../../src/v3/instructions/update-mint.ts","../../../../../src/v3/instructions/update-metadata.ts","../../../../../src/v3/instructions/create-associated-ctoken.ts","../../../../../src/v3/ata-utils.ts","../../../../../src/v3/instructions/create-ata-interface.ts","../../../../../src/v3/instructions/mint-to.ts","../../../../../src/v3/instructions/mint-to-compressed.ts","../../../../../src/v3/instructions/mint-to-interface.ts","../../../../../src/v3/instructions/transfer-interface.ts","../../../../../src/v3/layout/layout-transfer2.ts","../../../../../src/v3/instructions/create-decompress-interface-instruction.ts","../../../../../node_modules/.pnpm/bn.js@5.2.1/node_modules/bn.js/lib/bn.js","../../../../../src/v3/get-account-interface.ts","../../../../../src/v3/get-associated-token-address-interface.ts","../../../../../src/v3/instructions/wrap.ts","../../../../../src/v3/actions/load-ata.ts","../../../../../src/v3/instructions/create-load-accounts-params.ts","../../../../../src/actions/create-mint.ts","../../../../../src/v3/actions/create-mint-interface.ts","../../../../../node_modules/.pnpm/@solana+buffer-layout@4.0.1/node_modules/@solana/buffer-layout/lib/Layout.js","../../../../../node_modules/.pnpm/@solana+buffer-layout-utils@0.2.0_bufferutil@4.0.8_typescript@5.9.2_utf-8-validate@5.0.10/node_modules/@solana/buffer-layout-utils/lib/esm/base.mjs","../../../../../src/v3/layout/layout-mint.ts","../../../../../node_modules/.pnpm/@solana+buffer-layout-utils@0.2.0_bufferutil@4.0.8_typescript@5.9.2_utf-8-validate@5.0.10/node_modules/@solana/buffer-layout-utils/lib/esm/web3.mjs","../../../../../src/v3/get-mint-interface.ts","../../../../../src/v3/actions/update-mint.ts","../../../../../src/v3/actions/update-metadata.ts","../../../../../src/v3/actions/create-ata-interface.ts","../../../../../src/v3/actions/mint-to.ts","../../../../../src/v3/actions/mint-to-compressed.ts","../../../../../src/v3/actions/mint-to-interface.ts","../../../../../src/v3/actions/get-or-create-ata-interface.ts","../../../../../src/v3/actions/transfer-interface.ts","../../../../../src/v3/actions/decompress-interface.ts","../../../../../src/v3/actions/wrap.ts","../../../../../src/v3/layout/layout-token-metadata.ts","../../../../../src/v3/layout/serde.ts","../../../../../src/actions/approve.ts","../../../../../src/actions/approve-and-mint-to.ts","../../../../../src/actions/compress.ts","../../../../../src/actions/compress-spl-token-account.ts","../../../../../src/actions/create-token-pool.ts","../../../../../src/actions/create-token-program-lookup-table.ts","../../../../../src/actions/decompress.ts","../../../../../src/actions/merge-token-accounts.ts","../../../../../src/actions/mint-to.ts","../../../../../src/actions/revoke.ts","../../../../../src/actions/transfer.ts","../../../../../src/actions/transfer-delegated.ts","../../../../../src/actions/decompress-delegated.ts","../../../../../src/idl.ts","../../../../../src/types.ts"],"sourcesContent":["import { Buffer } from 'buffer';\n\n/**\n * Token data version enum - mirrors Rust TokenDataVersion\n * Used for compressed token account hashing strategy\n */\nexport enum TokenDataVersion {\n /** V1: Poseidon hash with little-endian amount, discriminator [2,0,0,0,0,0,0,0] */\n V1 = 1,\n /** V2: Poseidon hash with big-endian amount, discriminator [0,0,0,0,0,0,0,3] */\n V2 = 2,\n /** ShaFlat: SHA256 hash of borsh-serialized data, discriminator [0,0,0,0,0,0,0,4] */\n ShaFlat = 3,\n}\n\nexport const POOL_SEED = Buffer.from('pool');\n\nexport const CPI_AUTHORITY_SEED = Buffer.from('cpi_authority');\n\nexport const SPL_TOKEN_MINT_RENT_EXEMPT_BALANCE = 1461600;\n\nexport const CREATE_TOKEN_POOL_DISCRIMINATOR = Buffer.from([\n 23, 169, 27, 122, 147, 169, 209, 152,\n]);\nexport const MINT_TO_DISCRIMINATOR = Buffer.from([\n 241, 34, 48, 186, 37, 179, 123, 192,\n]);\nexport const BATCH_COMPRESS_DISCRIMINATOR = Buffer.from([\n 65, 206, 101, 37, 147, 42, 221, 144,\n]);\nexport const TRANSFER_DISCRIMINATOR = Buffer.from([\n 163, 52, 200, 231, 140, 3, 69, 186,\n]);\nexport const COMPRESS_SPL_TOKEN_ACCOUNT_DISCRIMINATOR = Buffer.from([\n 112, 230, 105, 101, 145, 202, 157, 97,\n]);\n\nexport const APPROVE_DISCRIMINATOR = Buffer.from([\n 69, 74, 217, 36, 115, 117, 97, 76,\n]);\nexport const REVOKE_DISCRIMINATOR = Buffer.from([\n 170, 23, 31, 34, 133, 173, 93, 242,\n]);\nexport const ADD_TOKEN_POOL_DISCRIMINATOR = Buffer.from([\n 114, 143, 210, 73, 96, 115, 1, 228,\n]);\n\nexport const DECOMPRESS_ACCOUNTS_IDEMPOTENT_DISCRIMINATOR = Buffer.from([107]);\n","import { Commitment, PublicKey } from '@solana/web3.js';\nimport { unpackAccount } from '@solana/spl-token';\nimport { CompressedTokenProgram } from '../program';\nimport { bn, Rpc } from '@lightprotocol/stateless.js';\nimport BN from 'bn.js';\n\n/**\n * SPL interface PDA info.\n */\nexport type SplInterfaceInfo = {\n /**\n * The mint of the SPL interface\n */\n mint: PublicKey;\n /**\n * The SPL interface address\n */\n splInterfacePda: PublicKey;\n /**\n * The token program of the SPL interface\n */\n tokenProgram: PublicKey;\n /**\n * count of txs and volume in the past 60 seconds.\n */\n activity?: {\n txs: number;\n amountAdded: BN;\n amountRemoved: BN;\n };\n /**\n * Whether the SPL interface is initialized\n */\n isInitialized: boolean;\n /**\n * The balance of the SPL interface\n */\n balance: BN;\n /**\n * The index of the SPL interface\n */\n poolIndex: number;\n /**\n * The bump used to derive the SPL interface PDA\n */\n bump: number;\n};\n\n/**\n * @deprecated Use {@link SplInterfaceInfo} instead.\n * This type maintains backward compatibility by including both tokenPoolPda and splInterfacePda.\n * Both properties point to the same PublicKey value.\n */\nexport type TokenPoolInfo = {\n /**\n * The mint of the SPL interface\n */\n mint: PublicKey;\n /**\n * @deprecated Use splInterfacePda instead.\n */\n tokenPoolPda: PublicKey;\n /**\n * The SPL interface address (new name).\n * For backward compatibility, tokenPoolPda is also available.\n */\n splInterfacePda: PublicKey;\n /**\n * The token program of the SPL interface\n */\n tokenProgram: PublicKey;\n /**\n * count of txs and volume in the past 60 seconds.\n */\n activity?: {\n txs: number;\n amountAdded: BN;\n amountRemoved: BN;\n };\n /**\n * Whether the SPL interface is initialized\n */\n isInitialized: boolean;\n /**\n * The balance of the SPL interface\n */\n balance: BN;\n /**\n * The index of the SPL interface\n */\n poolIndex: number;\n /**\n * The bump used to derive the SPL interface PDA\n */\n bump: number;\n};\n\n/**\n * Convert SplInterfaceInfo to TokenPoolInfo for backward compatibility.\n * @internal\n */\nexport function toTokenPoolInfo(info: SplInterfaceInfo): TokenPoolInfo {\n return {\n mint: info.mint,\n tokenPoolPda: info.splInterfacePda,\n splInterfacePda: info.splInterfacePda,\n tokenProgram: info.tokenProgram,\n activity: info.activity,\n isInitialized: info.isInitialized,\n balance: info.balance,\n poolIndex: info.poolIndex,\n bump: info.bump,\n };\n}\n\n/**\n * Convert TokenPoolInfo to SplInterfaceInfo.\n * @internal\n */\nfunction toSplInterfaceInfo(info: TokenPoolInfo): SplInterfaceInfo {\n return {\n mint: info.mint,\n splInterfacePda: info.tokenPoolPda ?? info.splInterfacePda,\n tokenProgram: info.tokenProgram,\n activity: info.activity,\n isInitialized: info.isInitialized,\n balance: info.balance,\n poolIndex: info.poolIndex,\n bump: info.bump,\n };\n}\n\n/**\n * Derive SplInterfaceInfo for an SPL interface that will be initialized in the\n * same transaction. Use this when you need to create an SPL interface and\n * compress in a single transaction.\n *\n * @param mint The mint of the SPL interface\n * @param tokenProgramId The token program (TOKEN_PROGRAM_ID or TOKEN_2022_PROGRAM_ID)\n * @param poolIndex The pool index. Default 0.\n *\n * @returns SplInterfaceInfo for the to-be-initialized interface\n */\nexport function deriveSplInterfaceInfo(\n mint: PublicKey,\n tokenProgramId: PublicKey,\n poolIndex = 0,\n): SplInterfaceInfo {\n const [splInterfacePda, bump] =\n CompressedTokenProgram.deriveSplInterfacePdaWithIndex(mint, poolIndex);\n\n return {\n mint,\n splInterfacePda,\n tokenProgram: tokenProgramId,\n activity: undefined,\n balance: bn(0),\n isInitialized: true,\n poolIndex,\n bump,\n };\n}\n\n/**\n * Check if the SPL interface info is initialized and has a balance.\n * @param mint The mint of the SPL interface\n * @param splInterfaceInfo The SPL interface info (or TokenPoolInfo for backward compatibility)\n * @returns True if the SPL interface info is initialized and has a balance\n */\nexport function checkSplInterfaceInfo(\n splInterfaceInfo: SplInterfaceInfo | TokenPoolInfo,\n mint: PublicKey,\n): boolean {\n // Handle backward compatibility with TokenPoolInfo\n // TokenPoolInfo has both tokenPoolPda and splInterfacePda, so we can use either\n const info: SplInterfaceInfo =\n 'tokenPoolPda' in splInterfaceInfo\n ? toSplInterfaceInfo(splInterfaceInfo as TokenPoolInfo)\n : (splInterfaceInfo as SplInterfaceInfo);\n\n if (!info.mint.equals(mint)) {\n throw new Error(`SplInterface mint does not match the provided mint.`);\n }\n\n if (!info.isInitialized) {\n throw new Error(\n `SplInterface is not initialized. Please create an SPL interface for mint: ${mint.toBase58()} via createSplInterface().`,\n );\n }\n return true;\n}\n\n/**\n * Get the SPL interface infos for a given mint.\n * @param rpc The RPC client\n * @param mint The mint of the SPL interface\n * @param commitment The commitment to use\n *\n * @returns The SPL interface infos\n */\nexport async function getSplInterfaceInfos(\n rpc: Rpc,\n mint: PublicKey,\n commitment?: Commitment,\n): Promise<SplInterfaceInfo[]> {\n const addressesAndBumps = Array.from({ length: 5 }, (_, i) =>\n CompressedTokenProgram.deriveSplInterfacePdaWithIndex(mint, i),\n );\n\n const accountInfos = await rpc.getMultipleAccountsInfo(\n addressesAndBumps.map(addressAndBump => addressAndBump[0]),\n commitment,\n );\n\n if (accountInfos[0] === null) {\n throw new Error(\n `SplInterface not found. Please create an SPL interface for mint: ${mint.toBase58()} via createSplInterface().`,\n );\n }\n\n const parsedInfos = addressesAndBumps.map((addressAndBump, i) =>\n accountInfos[i]\n ? unpackAccount(\n addressAndBump[0],\n accountInfos[i],\n accountInfos[i].owner,\n )\n : null,\n );\n\n const tokenProgram = accountInfos[0].owner;\n return parsedInfos.map((parsedInfo, i) => {\n if (!parsedInfo) {\n return {\n mint,\n splInterfacePda: addressesAndBumps[i][0],\n tokenProgram,\n activity: undefined,\n balance: bn(0),\n isInitialized: false,\n poolIndex: i,\n bump: addressesAndBumps[i][1],\n };\n }\n\n return {\n mint,\n splInterfacePda: parsedInfo.address,\n tokenProgram,\n activity: undefined,\n balance: bn(parsedInfo.amount.toString()),\n isInitialized: true,\n poolIndex: i,\n bump: addressesAndBumps[i][1],\n };\n });\n}\n\nexport type SplInterfaceActivity = {\n signature: string;\n amount: BN;\n action: Action;\n};\n\n/**\n * @internal\n */\nexport enum Action {\n Compress = 1,\n Decompress = 2,\n Transfer = 3,\n}\n\n/**\n * @internal\n */\nconst shuffleArray = <T>(array: T[]): T[] => {\n for (let i = array.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * (i + 1));\n [array[i], array[j]] = [array[j], array[i]];\n }\n return array;\n};\n\n/**\n * For `compress` and `mintTo` instructions only.\n * Select a random SPL interface info from the SPL interface infos.\n *\n * For `decompress`, use {@link selectSplInterfaceInfosForDecompression} instead.\n *\n * @param infos The SPL interface infos\n *\n * @returns A random SPL interface info\n */\nexport function selectSplInterfaceInfo(\n infos: SplInterfaceInfo[],\n): SplInterfaceInfo {\n const shuffledInfos = shuffleArray(infos);\n\n // filter only infos that are initialized\n const filteredInfos = shuffledInfos.filter(info => info.isInitialized);\n\n if (filteredInfos.length === 0) {\n throw new Error(\n 'Please pass at least one initialized SPL interface info.',\n );\n }\n\n // Return a single random SPL interface info\n return filteredInfos[0];\n}\n\n/**\n * Select one or multiple SPL interface infos from the SPL interface infos.\n *\n * Use this function for `decompress`.\n *\n * For `compress`, `mintTo` use {@link selectSplInterfaceInfo} instead.\n *\n * @param infos The SPL interface infos\n * @param decompressAmount The amount of tokens to withdraw\n *\n * @returns Array with one or more SPL interface infos.\n */\nexport function selectSplInterfaceInfosForDecompression(\n infos: SplInterfaceInfo[],\n decompressAmount: number | BN,\n): SplInterfaceInfo[] {\n if (infos.length === 0) {\n throw new Error('Please pass at least one SPL interface info.');\n }\n\n infos = shuffleArray(infos);\n // Find the first info where balance is 10x the requested amount\n const sufficientBalanceInfo = infos.find(info =>\n info.balance.gte(bn(decompressAmount).mul(bn(10))),\n );\n\n // filter only infos that are initialized\n infos = infos\n .filter(info => info.isInitialized)\n .sort((a, b) => a.poolIndex - b.poolIndex);\n\n const allBalancesZero = infos.every(info => info.balance.isZero());\n if (allBalancesZero) {\n throw new Error(\n 'All provided SPL interface balances are zero. Please pass recent SPL interface infos.',\n );\n }\n\n // If none found, return all infos\n return sufficientBalanceInfo ? [sufficientBalanceInfo] : infos;\n}\n\n// =============================================================================\n// DEPRECATED TYPES AND FUNCTIONS - Use the new SplInterface* names instead\n// =============================================================================\n\n/**\n * @deprecated Use {@link SplInterfaceActivity} instead.\n */\nexport type TokenPoolActivity = SplInterfaceActivity;\n\n/**\n * @deprecated Use {@link deriveSplInterfaceInfo} instead.\n */\nexport function deriveTokenPoolInfo(\n mint: PublicKey,\n tokenProgramId: PublicKey,\n poolIndex = 0,\n): TokenPoolInfo {\n const info = deriveSplInterfaceInfo(mint, tokenProgramId, poolIndex);\n return toTokenPoolInfo(info);\n}\n\n/**\n * @deprecated Use {@link checkSplInterfaceInfo} instead.\n */\nexport function checkTokenPoolInfo(\n tokenPoolInfo: TokenPoolInfo,\n mint: PublicKey,\n): boolean {\n return checkSplInterfaceInfo(toSplInterfaceInfo(tokenPoolInfo), mint);\n}\n\n/**\n * @deprecated Use {@link getSplInterfaceInfos} instead.\n */\nexport async function getTokenPoolInfos(\n rpc: Rpc,\n mint: PublicKey,\n commitment?: Commitment,\n): Promise<TokenPoolInfo[]> {\n const infos = await getSplInterfaceInfos(rpc, mint, commitment);\n return infos.map(toTokenPoolInfo);\n}\n\n/**\n * @deprecated Use {@link selectSplInterfaceInfo} instead.\n */\nexport function selectTokenPoolInfo(infos: TokenPoolInfo[]): TokenPoolInfo {\n const splInfos = infos.map(toSplInterfaceInfo);\n const selected = selectSplInterfaceInfo(splInfos);\n return toTokenPoolInfo(selected);\n}\n\n/**\n * @deprecated Use {@link selectSplInterfaceInfosForDecompression} instead.\n */\nexport function selectTokenPoolInfosForDecompression(\n infos: TokenPoolInfo[],\n decompressAmount: number | BN,\n): TokenPoolInfo[] {\n const splInfos = infos.map(toSplInterfaceInfo);\n const selected = selectSplInterfaceInfosForDecompression(\n splInfos,\n decompressAmount,\n );\n return selected.map(toTokenPoolInfo);\n}\n","import { bn, ParsedTokenAccount } from '@lightprotocol/stateless.js';\n\nimport BN from 'bn.js';\n\nexport const ERROR_NO_ACCOUNTS_FOUND =\n 'Could not find accounts to select for transfer.';\n\n/**\n * Selects token accounts for approval, first trying to find an exact match, then falling back to minimum selection.\n *\n * @param {ParsedTokenAccount[]} accounts - Token accounts to choose from.\n * @param {BN} approveAmount - Amount to approve.\n * @param {number} [maxInputs=4] - Max accounts to select when falling back to minimum selection.\n * @returns {[\n * selectedAccounts: ParsedTokenAccount[],\n * total: BN,\n * totalLamports: BN | null,\n * maxPossibleAmount: BN\n * ]} - Returns:\n * - selectedAccounts: Accounts chosen for approval.\n * - total: Total amount from selected accounts.\n * - totalLamports: Total lamports from selected accounts.\n * - maxPossibleAmount: Max approvable amount given maxInputs.\n */\nexport function selectTokenAccountsForApprove(\n accounts: ParsedTokenAccount[],\n approveAmount: BN,\n maxInputs: number = 4,\n): [\n selectedAccounts: ParsedTokenAccount[],\n total: BN,\n totalLamports: BN | null,\n maxPossibleAmount: BN,\n] {\n // First try to find an exact match\n const exactMatch = accounts.find(account =>\n account.parsed.amount.eq(approveAmount),\n );\n if (exactMatch) {\n return [\n [exactMatch],\n exactMatch.parsed.amount,\n exactMatch.compressedAccount.lamports,\n exactMatch.parsed.amount,\n ];\n }\n\n // If no exact match, fall back to minimum selection\n return selectMinCompressedTokenAccountsForTransfer(\n accounts,\n approveAmount,\n maxInputs,\n );\n}\n\n/**\n * Selects the minimum number of compressed token accounts required for a\n * decompress instruction, up to a specified maximum.\n *\n * @param {ParsedTokenAccount[]} accounts Token accounts to choose from.\n * @param {BN} amount Amount to decompress.\n * @param {number} [maxInputs=4] Max accounts to select. Default\n * is 4.\n *\n * @returns Returns selected accounts and their totals.\n */\nexport function selectMinCompressedTokenAccountsForDecompression(\n accounts: ParsedTokenAccount[],\n amount: BN,\n maxInputs: number = 4,\n): {\n selectedAccounts: ParsedTokenAccount[];\n total: BN;\n totalLamports: BN | null;\n maxPossibleAmount: BN;\n} {\n const [selectedAccounts, total, totalLamports, maxPossibleAmount] =\n selectMinCompressedTokenAccountsForTransfer(\n accounts,\n amount,\n maxInputs,\n );\n return { selectedAccounts, total, totalLamports, maxPossibleAmount };\n}\n\n/**\n * Selects the minimum number of compressed token accounts required for a\n * transfer or decompression instruction, up to a specified maximum.\n *\n * @param {ParsedTokenAccount[]} accounts Token accounts to choose from.\n * @param {BN} transferAmount Amount to transfer or decompress.\n * @param {number} [maxInputs=4] Max accounts to select. Default\n * is 4.\n *\n * @returns Returns selected accounts and their totals. [\n * selectedAccounts: ParsedTokenAccount[],\n * total: BN,\n * totalLamports: BN | null,\n * maxPossibleAmount: BN\n * ]\n */\nexport function selectMinCompressedTokenAccountsForTransfer(\n accounts: ParsedTokenAccount[],\n transferAmount: BN,\n maxInputs: number = 4,\n): [\n selectedAccounts: ParsedTokenAccount[],\n total: BN,\n totalLamports: BN | null,\n maxPossibleAmount: BN,\n] {\n const [\n selectedAccounts,\n accumulatedAmount,\n accumulatedLamports,\n maxPossibleAmount,\n ] = selectMinCompressedTokenAccountsForTransferOrPartial(\n accounts,\n transferAmount,\n maxInputs,\n );\n\n if (accumulatedAmount.lt(bn(transferAmount))) {\n const totalBalance = accounts.reduce(\n (acc, account) => acc.add(account.parsed.amount),\n bn(0),\n );\n if (selectedAccounts.length >= maxInputs) {\n throw new Error(\n `Account limit exceeded: max ${maxPossibleAmount.toString()} (${maxInputs} accounts) per transaction. Total balance: ${totalBalance.toString()} (${accounts.length} accounts). Consider multiple transfers to spend full balance.`,\n );\n } else {\n throw new Error(\n `Insufficient balance for transfer. Required: ${transferAmount.toString()}, available: ${totalBalance.toString()}.`,\n );\n }\n }\n\n if (selectedAccounts.length === 0) {\n throw new Error(ERROR_NO_ACCOUNTS_FOUND);\n }\n\n return [\n selectedAccounts,\n accumulatedAmount,\n accumulatedLamports,\n maxPossibleAmount,\n ];\n}\n\n/**\n * Executes {@link selectMinCompressedTokenAccountsForTransfer} strategy,\n * returns partial amounts if insufficient accounts are found instead of\n * throwing an error.\n */\nexport function selectMinCompressedTokenAccountsForTransferOrPartial(\n accounts: ParsedTokenAccount[],\n transferAmount: BN,\n maxInputs: number = 4,\n): [\n selectedAccounts: ParsedTokenAccount[],\n total: BN,\n totalLamports: BN | null,\n maxPossibleAmount: BN,\n] {\n if (accounts.length === 0) {\n throw new Error(ERROR_NO_ACCOUNTS_FOUND);\n }\n\n let accumulatedAmount = bn(0);\n let accumulatedLamports = bn(0);\n let maxPossibleAmount = bn(0);\n\n const selectedAccounts: ParsedTokenAccount[] = [];\n\n accounts.sort((a, b) => b.parsed.amount.cmp(a.parsed.amount));\n\n for (const account of accounts) {\n if (selectedAccounts.length >= maxInputs) break;\n if (accumulatedAmount.gte(bn(transferAmount))) break;\n\n if (\n !account.parsed.amount.isZero() ||\n !account.compressedAccount.lamports.isZero()\n ) {\n accumulatedAmount = accumulatedAmount.add(account.parsed.amount);\n accumulatedLamports = accumulatedLamports.add(\n account.compressedAccount.lamports,\n );\n selectedAccounts.push(account);\n }\n }\n\n // Max, considering maxInputs\n maxPossibleAmount = accounts\n .slice(0, maxInputs)\n .reduce((total, account) => total.add(account.parsed.amount), bn(0));\n\n if (accumulatedAmount.lt(bn(transferAmount))) {\n console.log(\n `Insufficient balance for transfer. Requested: ${transferAmount.toString()}, Returns max available: ${maxPossibleAmount.toString()}.`,\n );\n }\n\n if (selectedAccounts.length === 0) {\n throw new Error(ERROR_NO_ACCOUNTS_FOUND);\n }\n\n return [\n selectedAccounts,\n accumulatedAmount,\n accumulatedLamports,\n maxPossibleAmount,\n ];\n}\n\n/**\n * Selects compressed token accounts for a transfer, ensuring one extra account\n * if possible, up to maxInputs.\n *\n * 1. Sorts accounts by amount (desc)\n * 2. Selects accounts until transfer amount is met or maxInputs is reached,\n * attempting to add one extra account if possible.\n *\n * @param {ParsedTokenAccount[]} accounts - The list of token accounts to select from.\n * @param {BN} transferAmount - The token amount to be transferred.\n * @param {number} [maxInputs=4] - The maximum number of accounts to select. Default: 4.\n * @returns {[\n * selectedAccounts: ParsedTokenAccount[],\n * total: BN,\n * totalLamports: BN | null,\n * maxPossibleAmount: BN\n * ]} - An array containing:\n * - selectedAccounts: The accounts selected for the transfer.\n * - total: The total amount accumulated from the selected accounts.\n * - totalLamports: The total lamports accumulated from the selected accounts.\n * - maxPossibleAmount: The maximum possible amount that can be transferred considering maxInputs.\n *\n * @example\n * const accounts = [\n * { parsed: { amount: new BN(100) }, compressedAccount: { lamports: new BN(10) } },\n * { parsed: { amount: new BN(50) }, compressedAccount: { lamports: new BN(5) } },\n * { parsed: { amount: new BN(25) }, compressedAccount: { lamports: new BN(2) } },\n * ];\n * const transferAmount = new BN(75);\n * const maxInputs = 2;\n *\n * const [selectedAccounts, total, totalLamports, maxPossibleAmount] =\n * selectSmartCompressedTokenAccountsForTransfer(accounts, transferAmount, maxInputs);\n *\n * console.log(selectedAccounts.length); // 2\n * console.log(total.toString()); // '150'\n * console.log(totalLamports!.toString()); // '15'\n * console.log(maxPossibleAmount.toString()); // '150'\n */\nexport function selectSmartCompressedTokenAccountsForTransfer(\n accounts: ParsedTokenAccount[],\n transferAmount: BN,\n maxInputs: number = 4,\n): [\n selectedAccounts: ParsedTokenAccount[],\n total: BN,\n totalLamports: BN | null,\n maxPossibleAmount: BN,\n] {\n const [\n selectedAccounts,\n accumulatedAmount,\n accumulatedLamports,\n maxPossibleAmount,\n ] = selectSmartCompressedTokenAccountsForTransferOrPartial(\n accounts,\n transferAmount,\n maxInputs,\n );\n\n if (accumulatedAmount.lt(bn(transferAmount))) {\n const totalBalance = accounts.reduce(\n (acc, account) => acc.add(account.parsed.amount),\n bn(0),\n );\n if (selectedAccounts.length >= maxInputs) {\n throw new Error(\n `Account limit exceeded: max ${maxPossibleAmount.toString()} (${maxInputs} accounts) per transaction. Total balance: ${totalBalance.toString()} (${accounts.length} accounts). Consider multiple transfers to spend full balance.`,\n );\n } else {\n throw new Error(\n `Insufficient balance. Required: ${transferAmount.toString()}, available: ${totalBalance.toString()}.`,\n );\n }\n }\n\n if (selectedAccounts.length === 0) {\n throw new Error(ERROR_NO_ACCOUNTS_FOUND);\n }\n\n return [\n selectedAccounts,\n accumulatedAmount,\n accumulatedLamports,\n maxPossibleAmount,\n ];\n}\n\n/**\n * Executes {@link selectMinCompressedTokenAccountsForTransfer} strategy,\n * returns partial amounts if insufficient accounts are found instead of\n * throwing an error.\n */\nexport function selectSmartCompressedTokenAccountsForTransferOrPartial(\n accounts: ParsedTokenAccount[],\n transferAmount: BN,\n maxInputs: number = 4,\n): [\n selectedAccounts: ParsedTokenAccount[],\n total: BN,\n totalLamports: BN | null,\n maxPossibleAmount: BN,\n] {\n if (accounts.length === 0) {\n throw new Error(ERROR_NO_ACCOUNTS_FOUND);\n }\n\n let accumulatedAmount = bn(0);\n let accumulatedLamports = bn(0);\n\n const selectedAccounts: ParsedTokenAccount[] = [];\n\n // we can ignore zero value accounts.\n const nonZeroAccounts = accounts.filter(\n account =>\n !account.parsed.amount.isZero() ||\n !account.compressedAccount.lamports.isZero(),\n );\n\n nonZeroAccounts.sort((a, b) => b.parsed.amount.cmp(a.parsed.amount));\n\n for (const account of nonZeroAccounts) {\n if (selectedAccounts.length >= maxInputs) break;\n accumulatedAmount = accumulatedAmount.add(account.parsed.amount);\n accumulatedLamports = accumulatedLamports.add(\n account.compressedAccount.lamports,\n );\n selectedAccounts.push(account);\n\n if (accumulatedAmount.gte(bn(transferAmount))) {\n // Select smallest additional account if maxInputs not reached\n const remainingAccounts = nonZeroAccounts.slice(\n selectedAccounts.length,\n );\n if (remainingAccounts.length > 0) {\n const smallestAccount = remainingAccounts.reduce((min, acc) =>\n acc.parsed.amount.lt(min.parsed.amount) ? acc : min,\n );\n if (selectedAccounts.length < maxInputs) {\n selectedAccounts.push(smallestAccount);\n accumulatedAmount = accumulatedAmount.add(\n smallestAccount.parsed.amount,\n );\n accumulatedLamports = accumulatedLamports.add(\n smallestAccount.compressedAccount.lamports,\n );\n }\n }\n break;\n }\n }\n\n const maxPossibleAmount = nonZeroAccounts\n .slice(0, maxInputs)\n .reduce((max, account) => max.add(account.parsed.amount), bn(0));\n\n if (selectedAccounts.length === 0) {\n throw new Error(ERROR_NO_ACCOUNTS_FOUND);\n }\n\n return [\n selectedAccounts,\n accumulatedAmount,\n accumulatedLamports,\n maxPossibleAmount,\n ];\n}\n","import {\n ParsedTokenAccount,\n InputTokenDataWithContext,\n getIndexOrAdd,\n bn,\n padOutputStateMerkleTrees,\n TreeType,\n featureFlags,\n TreeInfo,\n} from '@lightprotocol/stateless.js';\nimport { PublicKey, AccountMeta } from '@solana/web3.js';\nimport {\n PackedTokenTransferOutputData,\n TokenTransferOutputData,\n} from '../types';\n\nexport type PackCompressedTokenAccountsParams = {\n /** Input state to be consumed */\n inputCompressedTokenAccounts: ParsedTokenAccount[];\n /**\n * State trees that the output should be inserted into. Defaults to the 0th\n * state tree of the input state. Gets padded to the length of\n * outputCompressedAccounts.\n */\n outputStateTreeInfo?: TreeInfo;\n /** Optional remaining accounts to append to */\n remainingAccounts?: PublicKey[];\n /**\n * Root indices that are used on-chain to fetch the correct root\n * from the state Merkle tree account for validity proof verification.\n */\n rootIndices: number[];\n tokenTransferOutputs: TokenTransferOutputData[];\n};\n\n/**\n * Packs Compressed Token Accounts.\n */\nexport function packCompressedTokenAccounts(\n params: PackCompressedTokenAccountsParams,\n): {\n inputTokenDataWithContext: InputTokenDataWithContext[];\n remainingAccountMetas: AccountMeta[];\n packedOutputTokenData: PackedTokenTransferOutputData[];\n} {\n const {\n inputCompressedTokenAccounts,\n outputStateTreeInfo,\n remainingAccounts = [],\n rootIndices,\n tokenTransferOutputs,\n } = params;\n\n const _remainingAccounts = remainingAccounts.slice();\n let delegateIndex: number | null = null;\n\n if (\n inputCompressedTokenAccounts.length > 0 &&\n inputCompressedTokenAccounts[0].parsed.delegate\n ) {\n delegateIndex = getIndexOrAdd(\n _remainingAccounts,\n inputCompressedTokenAccounts[0].parsed.delegate,\n );\n }\n\n const packedInputTokenData: InputTokenDataWithContext[] = [];\n /// pack inputs\n inputCompressedTokenAccounts.forEach(\n (account: ParsedTokenAccount, index) => {\n const merkleTreePubkeyIndex = getIndexOrAdd(\n _remainingAccounts,\n account.compressedAccount.treeInfo.tree,\n );\n\n const queuePubkeyIndex = getIndexOrAdd(\n _remainingAccounts,\n account.compressedAccount.treeInfo.queue,\n );\n\n packedInputTokenData.push({\n amount: account.parsed.amount,\n delegateIndex,\n merkleContext: {\n merkleTreePubkeyIndex,\n queuePubkeyIndex,\n leafIndex: account.compressedAccount.leafIndex,\n proveByIndex: account.compressedAccount.proveByIndex,\n },\n rootIndex: rootIndices[index],\n lamports: account.compressedAccount.lamports.eq(bn(0))\n ? null\n : account.compressedAccount.lamports,\n tlv: null,\n });\n },\n );\n\n if (inputCompressedTokenAccounts.length > 0 && outputStateTreeInfo) {\n throw new Error(\n 'Cannot specify both input accounts and outputStateTreeInfo',\n );\n }\n\n let treeInfo: TreeInfo;\n if (inputCompressedTokenAccounts.length > 0) {\n treeInfo = inputCompressedTokenAccounts[0].compressedAccount.treeInfo;\n } else if (outputStateTreeInfo) {\n treeInfo = outputStateTreeInfo;\n } else {\n throw new Error(\n 'Neither input accounts nor outputStateTreeInfo are available',\n );\n }\n\n // Use next tree if available, otherwise fall back to current tree.\n // `nextTreeInfo` always takes precedence.\n const activeTreeInfo = treeInfo.nextTreeInfo || treeInfo;\n let activeTreeOrQueue = activeTreeInfo.tree;\n\n if (activeTreeInfo.treeType === TreeType.StateV2) {\n if (featureFlags.isV2()) {\n activeTreeOrQueue = activeTreeInfo.queue;\n } else throw new Error('V2 trees are not supported yet');\n }\n\n // Pack output state trees\n const paddedOutputStateMerkleTrees = padOutputStateMerkleTrees(\n activeTreeOrQueue,\n tokenTransferOutputs.length,\n );\n const packedOutputTokenData: PackedTokenTransferOutputData[] = [];\n paddedOutputStateMerkleTrees.forEach((account, index) => {\n const merkleTreeIndex = getIndexOrAdd(_remainingAccounts, account);\n packedOutputTokenData.push({\n owner: tokenTransferOutputs[index].owner,\n amount: tokenTransferOutputs[index].amount,\n lamports: tokenTransferOutputs[index].lamports?.eq(bn(0))\n ? null\n : tokenTransferOutputs[index].lamports,\n merkleTreeIndex,\n tlv: null,\n });\n });\n // to meta\n const remainingAccountMetas = _remainingAccounts.map(\n (account): AccountMeta => ({\n pubkey: account,\n isWritable: true,\n isSigner: false,\n }),\n );\n\n return {\n inputTokenDataWithContext: packedInputTokenData,\n remainingAccountMetas,\n packedOutputTokenData,\n };\n}\n","import { ParsedTokenAccount } from '@lightprotocol/stateless.js';\nimport { PublicKey } from '@solana/web3.js';\n\n/**\n * Check if all input accounts belong to the same mint.\n *\n * @param compressedTokenAccounts The compressed token accounts\n * @param mint The mint of the token pool\n * @returns True if all input accounts belong to the same mint\n */\nexport function checkMint(\n compressedTokenAccounts: ParsedTokenAccount[],\n mint: PublicKey,\n): boolean {\n if (\n !compressedTokenAccounts.every(account =>\n account.parsed.mint.equals(mint),\n )\n ) {\n throw new Error(`All input accounts must belong to the same mint`);\n }\n\n return true;\n}\n","import {\n struct,\n option,\n vec,\n bool,\n u64,\n u8,\n publicKey,\n array,\n u32,\n u16,\n vecU8,\n} from '@coral-xyz/borsh';\nimport { AccountMeta, PublicKey } from '@solana/web3.js';\nimport { CompressedTokenProgram } from './program';\nimport {\n BatchCompressInstructionData,\n CompressedTokenInstructionDataApprove,\n CompressedTokenInstructionDataRevoke,\n CompressedTokenInstructionDataTransfer,\n CompressSplTokenAccountInstructionData,\n MintToInstructionData,\n} from './types';\nimport {\n APPROVE_DISCRIMINATOR,\n BATCH_COMPRESS_DISCRIMINATOR,\n COMPRESS_SPL_TOKEN_ACCOUNT_DISCRIMINATOR,\n MINT_TO_DISCRIMINATOR,\n REVOKE_DISCRIMINATOR,\n TRANSFER_DISCRIMINATOR,\n} from './constants';\nimport { Buffer } from 'buffer';\nimport { ValidityProof } from '@lightprotocol/stateless.js';\n\nconst CompressedProofLayout = struct([\n array(u8(), 32, 'a'),\n array(u8(), 64, 'b'),\n array(u8(), 32, 'c'),\n]);\n\nconst PackedTokenTransferOutputDataLayout = struct([\n publicKey('owner'),\n u64('amount'),\n option(u64(), 'lamports'),\n u8('merkleTreeIndex'),\n option(vecU8(), 'tlv'),\n]);\n\nconst InputTokenDataWithContextLayout = struct([\n u64('amount'),\n option(u8(), 'delegateIndex'),\n struct(\n [\n u8('merkleTreePubkeyIndex'),\n u8('queuePubkeyIndex'),\n u32('leafIndex'),\n bool('proveByIndex'),\n ],\n 'merkleContext',\n ),\n u16('rootIndex'),\n option(u64(), 'lamports'),\n option(vecU8(), 'tlv'),\n]);\n\nexport const DelegatedTransferLayout = struct([\n publicKey('owner'),\n option(u8(), 'delegateChangeAccountIndex'),\n]);\n\nexport const CpiContextLayout = struct([\n bool('setContext'),\n bool('firstSetContext'),\n u8('cpiContextAccountIndex'),\n]);\n\nexport const CompressedTokenInstructionDataTransferLayout = struct([\n option(CompressedProofLayout, 'proof'),\n publicKey('mint'),\n option(DelegatedTransferLayout, 'delegatedTransfer'),\n vec(InputTokenDataWithContextLayout, 'inputTokenDataWithContext'),\n vec(PackedTokenTransferOutputDataLayout, 'outputCompressedAccounts'),\n bool('isCompress'),\n option(u64(), 'compressOrDecompressAmount'),\n option(CpiContextLayout, 'cpiContext'),\n option(u8(), 'lamportsChangeAccountMerkleTreeIndex'),\n]);\n\nexport const mintToLayout = struct([\n vec(publicKey(), 'recipients'),\n vec(u64(), 'amounts'),\n option(u64(), 'lamports'),\n]);\n\nexport const batchCompressLayout = struct([\n vec(publicKey(), 'pubkeys'),\n option(vec(u64(), 'amounts'), 'amounts'),\n option(u64(), 'lamports'),\n option(u64(), 'amount'),\n u8('index'),\n u8('bump'),\n]);\n\nexport const compressSplTokenAccountInstructionDataLayout = struct([\n publicKey('owner'),\n option(u64(), 'remainingAmount'),\n option(CpiContextLayout, 'cpiContext'),\n]);\n\nexport function encodeMintToInstructionData(\n data: MintToInstructionData,\n): Buffer {\n const buffer = Buffer.alloc(1000);\n const len = mintToLayout.encode(\n {\n recipients: data.recipients,\n amounts: data.amounts,\n lamports: data.lamports,\n },\n buffer,\n );\n\n return Buffer.concat([\n new Uint8Array(MINT_TO_DISCRIMINATOR),\n new Uint8Array(buffer.subarray(0, len)),\n ]);\n}\n\nexport function decodeMintToInstructionData(\n buffer: Buffer,\n): MintToInstructionData {\n return mintToLayout.decode(\n buffer.subarray(MINT_TO_DISCRIMINATOR.length),\n ) as MintToInstructionData;\n}\n\nexport function encodeBatchCompressInstructionData(\n data: BatchCompressInstructionData,\n): Buffer {\n const buffer = Buffer.alloc(1000);\n const len = batchCompressLayout.encode(data, buffer);\n\n const lengthBuffer = Buffer.alloc(4);\n lengthBuffer.writeUInt32LE(len, 0);\n\n const dataBuffer = buffer.subarray(0, len);\n return Buffer.concat([\n new Uint8Array(BATCH_COMPRESS_DISCRIMINATOR),\n new Uint8Array(lengthBuffer),\n new Uint8Array(dataBuffer),\n ]);\n}\n\nexport function decodeBatchCompressInstructionData(\n buffer: Buffer,\n): BatchCompressInstructionData {\n return batchCompressLayout.decode(\n buffer.subarray(BATCH_COMPRESS_DISCRIMINATOR.length + 4),\n ) as BatchCompressInstructionData;\n}\n\nexport function encodeCompressSplTokenAccountInstructionData(\n data: CompressSplTokenAccountInstructionData,\n): Buffer {\n const buffer = Buffer.alloc(1000);\n const len = compressSplTokenAccountInstructionDataLayout.encode(\n {\n owner: data.owner,\n remainingAmount: data.remainingAmount,\n cpiContext: data.cpiContext,\n },\n buffer,\n );\n\n return Buffer.concat([\n new Uint8Array(COMPRESS_SPL_TOKEN_ACCOUNT_DISCRIMINATOR),\n new Uint8Array(buffer.subarray(0, len)),\n ]);\n}\n\nexport function decodeCompressSplTokenAccountInstructionData(\n buffer: Buffer,\n): CompressSplTokenAccountInstructionData {\n const data = compressSplTokenAccountInstructionDataLayout.decode(\n buffer.subarray(COMPRESS_SPL_TOKEN_ACCOUNT_DISCRIMINATOR.length),\n ) as CompressSplTokenAccountInstructionData;\n return {\n owner: data.owner,\n remainingAmount: data.remainingAmount,\n cpiContext: data.cpiContext,\n };\n}\nexport function encodeTransferInstructionData(\n data: CompressedTokenInstructionDataTransfer,\n): Buffer {\n const buffer = Buffer.alloc(1000);\n\n const len = CompressedTokenInstructionDataTransferLayout.encode(\n data,\n buffer,\n );\n\n const lengthBuffer = Buffer.alloc(4);\n lengthBuffer.writeUInt32LE(len, 0);\n\n const dataBuffer = buffer.subarray(0, len);\n\n return Buffer.concat([\n new Uint8Array(TRANSFER_DISCRIMINATOR),\n new Uint8Array(lengthBuffer),\n new Uint8Array(dataBuffer),\n ]);\n}\n\nexport function decodeTransferInstructionData(\n buffer: Buffer,\n): CompressedTokenInstructionDataTransfer {\n return CompressedTokenInstructionDataTransferLayout.decode(\n buffer.slice(TRANSFER_DISCRIMINATOR.length + 4),\n ) as CompressedTokenInstructionDataTransfer;\n}\n\ninterface BaseAccountsLayoutParams {\n feePayer: PublicKey;\n authority: PublicKey;\n cpiAuthorityPda: PublicKey;\n lightSystemProgram: PublicKey;\n registeredProgramPda: PublicKey;\n noopProgram: PublicKey;\n accountCompressionAuthority: PublicKey;\n accountCompressionProgram: PublicKey;\n selfProgram: PublicKey;\n systemProgram: PublicKey;\n}\nexport type createTokenPoolAccountsLayoutParams = {\n feePayer: PublicKey;\n tokenPoolPda: PublicKey;\n systemProgram: PublicKey;\n mint: PublicKey;\n tokenProgram: PublicKey;\n cpiAuthorityPda: PublicKey;\n};\n\nexport type addTokenPoolAccountsLayoutParams =\n createTokenPoolAccountsLayoutParams & {\n existingTokenPoolPda: PublicKey;\n };\n\nexport type mintToAccountsLayoutParams = BaseAccountsLayoutParams & {\n mint: PublicKey;\n tokenPoolPda: PublicKey;\n tokenProgram: PublicKey;\n merkleTree: PublicKey;\n solPoolPda: PublicKey | null;\n};\nexport type transferAccountsLayoutParams = BaseAccountsLayoutParams & {\n tokenPoolPda?: PublicKey;\n compressOrDecompressTokenAccount?: PublicKey;\n tokenProgram?: PublicKey;\n};\nexport type approveAccountsLayoutParams = BaseAccountsLayoutParams;\nexport type revokeAccountsLayoutParams = approveAccountsLayoutParams;\nexport type freezeAccountsLayoutParams = BaseAccountsLayoutParams & {\n mint: PublicKey;\n};\nexport type thawAccountsLayoutParams = freezeAccountsLayoutParams;\n\nexport const createTokenPoolAccountsLayout = (\n accounts: createTokenPoolAccountsLayoutParams,\n): AccountMeta[] => {\n const {\n feePayer,\n tokenPoolPda,\n systemProgram,\n mint,\n tokenProgram,\n cpiAuthorityPda,\n } = accounts;\n return [\n { pubkey: feePayer, isSigner: true, isWritable: true },\n { pubkey: tokenPoolPda, isSigner: false, isWritable: true },\n { pubkey: systemProgram, isSigner: false, isWritable: false },\n { pubkey: mint, isSigner: false, isWritable: true },\n { pubkey: tokenProgram, isSigner: false, isWritable: false },\n { pubkey: cpiAuthorityPda, isSigner: false, isWritable: false },\n ];\n};\n\nexport const addTokenPoolAccountsLayout = (\n accounts: addTokenPoolAccountsLayoutParams,\n): AccountMeta[] => {\n const {\n feePayer,\n tokenPoolPda,\n systemProgram,\n mint,\n tokenProgram,\n cpiAuthorityPda,\n existingTokenPoolPda,\n } = accounts;\n return [\n { pubkey: feePayer, isSigner: true, isWritable: true },\n { pubkey: tokenPoolPda, isSigner: false, isWritable: true },\n { pubkey: existingTokenPoolPda, isSigner: false, isWritable: false },\n { pubkey: systemProgram, isSigner: false, isWritable: false },\n { pubkey: mint, isSigner: false, isWritable: true },\n { pubkey: tokenProgram, isSigner: false, isWritable: false },\n { pubkey: cpiAuthorityPda, isSigner: false, isWritable: false },\n ];\n};\n\nexport const mintToAccountsLayout = (\n accounts: mintToAccountsLayoutParams,\n): AccountMeta[] => {\n const defaultPubkey = CompressedTokenProgram.programId;\n const {\n feePayer,\n authority,\n cpiAuthorityPda,\n mint,\n tokenPoolPda,\n tokenProgram,\n lightSystemProgram,\n registeredProgramPda,\n noopProgram,\n accountCompressionAuthority,\n accountCompressionProgram,\n merkleTree,\n selfProgram,\n systemProgram,\n solPoolPda,\n } = accounts;\n\n const accountsList: AccountMeta[] = [\n { pubkey: feePayer, isSigner: true, isWritable: true },\n { pubkey: authority, isSigner: true, isWritable: false },\n { pubkey: cpiAuthorityPda, isSigner: false, isWritable: false },\n { pubkey: mint, isSigner: false, isWritable: true },\n { pubkey: tokenPoolPda, isSigner: false, isWritable: true },\n { pubkey: tokenProgram, isSigner: false, isWritable: false },\n { pubkey: lightSystemProgram, isSigner: false, isWritable: false },\n { pubkey: registeredProgramPda, isSigner: false, isWritable: false },\n { pubkey: noopProgram, isSigner: false, isWritable: false },\n {\n pubkey: accountCompressionAuthority,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: accountCompressionProgram,\n isSigner: false,\n isWritable: false,\n },\n { pubkey: merkleTree, isSigner: false, isWritable: true },\n { pubkey: selfProgram, isSigner: false, isWritable: false },\n { pubkey: systemProgram, isSigner: false, isWritable: false },\n {\n pubkey: solPoolPda ?? defaultPubkey,\n isSigner: false,\n isWritable: true,\n },\n ];\n\n return accountsList;\n};\n\nexport const transferAccountsLayout = (\n accounts: transferAccountsLayoutParams,\n): AccountMeta[] => {\n const defaultPubkey = CompressedTokenProgram.programId;\n const {\n feePayer,\n authority,\n cpiAuthorityPda,\n lightSystemProgram,\n registeredProgramPda,\n noopProgram,\n accountCompressionAuthority,\n accountCompressionProgram,\n selfProgram,\n tokenPoolPda,\n compressOrDecompressTokenAccount,\n tokenProgram,\n systemProgram,\n } = accounts;\n\n const accountsList: AccountMeta[] = [\n { pubkey: feePayer, isSigner: true, isWritable: true },\n { pubkey: authority, isSigner: true, isWritable: false },\n { pubkey: cpiAuthorityPda, isSigner: false, isWritable: false },\n { pubkey: lightSystemProgram, isSigner: false, isWritable: false },\n { pubkey: registeredProgramPda, isSigner: false, isWritable: false },\n { pubkey: noopProgram, isSigner: false, isWritable: false },\n {\n pubkey: accountCompressionAuthority,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: accountCompressionProgram,\n isSigner: false,\n isWritable: false,\n },\n { pubkey: selfProgram, isSigner: false, isWritable: false },\n {\n pubkey: tokenPoolPda ?? defaultPubkey,\n isSigner: false,\n isWritable: true,\n },\n {\n pubkey: compressOrDecompressTokenAccount ?? defaultPubkey,\n isSigner: false,\n isWritable: true,\n },\n {\n pubkey: tokenProgram ?? defaultPubkey,\n isSigner: false,\n isWritable: false,\n },\n { pubkey: systemProgram, isSigner: false, isWritable: false },\n ];\n\n return accountsList;\n};\n\nexport const approveAccountsLayout = (\n accounts: approveAccountsLayoutParams,\n): AccountMeta[] => {\n const {\n feePayer,\n authority,\n cpiAuthorityPda,\n lightSystemProgram,\n registeredProgramPda,\n noopProgram,\n accountCompressionAuthority,\n accountCompressionProgram,\n selfProgram,\n systemProgram,\n } = accounts;\n\n return [\n { pubkey: feePayer, isSigner: true, isWritable: true },\n { pubkey: authority, isSigner: true, isWritable: false },\n { pubkey: cpiAuthorityPda, isSigner: false, isWritable: false },\n { pubkey: lightSystemProgram, isSigner: false, isWritable: false },\n { pubkey: registeredProgramPda, isSigner: false, isWritable: false },\n { pubkey: noopProgram, isSigner: false, isWritable: false },\n {\n pubkey: accountCompressionAuthority,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: accountCompressionProgram,\n isSigner: false,\n isWritable: false,\n },\n { pubkey: selfProgram, isSigner: false, isWritable: false },\n { pubkey: systemProgram, isSigner: false, isWritable: false },\n ];\n};\n\nexport const revokeAccountsLayout = approveAccountsLayout;\n\nexport const freezeAccountsLayout = (\n accounts: freezeAccountsLayoutParams,\n): AccountMeta[] => {\n const {\n feePayer,\n authority,\n cpiAuthorityPda,\n lightSystemProgram,\n registeredProgramPda,\n noopProgram,\n accountCompressionAuthority,\n accountCompressionProgram,\n selfProgram,\n systemProgram,\n mint,\n } = accounts;\n\n return [\n { pubkey: feePayer, isSigner: true, isWritable: true },\n { pubkey: authority, isSigner: true, isWritable: false },\n { pubkey: cpiAuthorityPda, isSigner: false, isWritable: false },\n { pubkey: lightSystemProgram, isSigner: false, isWritable: false },\n { pubkey: registeredProgramPda, isSigner: false, isWritable: false },\n { pubkey: noopProgram, isSigner: false, isWritable: false },\n {\n pubkey: accountCompressionAuthority,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: accountCompressionProgram,\n isSigner: false,\n isWritable: false,\n },\n { pubkey: selfProgram, isSigner: false, isWritable: false },\n { pubkey: systemProgram, isSigner: false, isWritable: false },\n { pubkey: mint, isSigner: false, isWritable: false },\n ];\n};\n\nexport const thawAccountsLayout = freezeAccountsLayout;\n\nexport const CompressedTokenInstructionDataApproveLayout = struct([\n struct(\n [array(u8(), 32, 'a'), array(u8(), 64, 'b'), array(u8(), 32, 'c')],\n 'proof',\n ),\n publicKey('mint'),\n vec(InputTokenDataWithContextLayout, 'inputTokenDataWithContext'),\n option(CpiContextLayout, 'cpiContext'),\n publicKey('delegate'),\n u64('delegatedAmount'),\n u8('delegateMerkleTreeIndex'),\n u8('changeAccountMerkleTreeIndex'),\n option(u64(), 'delegateLamports'),\n]);\n\nexport const CompressedTokenInstructionDataRevokeLayout = struct([\n struct(\n [array(u8(), 32, 'a'), array(u8(), 64, 'b'), array(u8(), 32, 'c')],\n 'proof',\n ),\n publicKey('mint'),\n vec(InputTokenDataWithContextLayout, 'inputTokenDataWithContext'),\n option(CpiContextLayout, 'cpiContext'),\n u8('outputAccountMerkleTreeIndex'),\n]);\n\n// Approve and revoke instuctions do not support optional proof yet.\nconst emptyProof: ValidityProof = {\n a: new Array(32).fill(0),\n b: new Array(64).fill(0),\n c: new Array(32).fill(0),\n};\n\nfunction isEmptyProof(proof: ValidityProof): boolean {\n return (\n proof.a.every(a => a === 0) &&\n proof.b.every(b => b === 0) &&\n proof.c.every(c => c === 0)\n );\n}\n\nexport function encodeApproveInstructionData(\n data: CompressedTokenInstructionDataApprove,\n): Buffer {\n const buffer = Buffer.alloc(1000);\n\n const proofOption = data.proof ?? emptyProof;\n\n const len = CompressedTokenInstructionDataApproveLayout.encode(\n {\n ...data,\n proof: proofOption,\n },\n buffer,\n );\n\n const lengthBuffer = Buffer.alloc(4);\n lengthBuffer.writeUInt32LE(len, 0);\n\n const dataBuffer = buffer.subarray(0, len);\n\n return Buffer.concat([\n new Uint8Array(APPROVE_DISCRIMINATOR),\n new Uint8Array(lengthBuffer),\n new Uint8Array(dataBuffer),\n ]);\n}\n\nexport function decodeApproveInstructionData(\n buffer: Buffer,\n): CompressedTokenInstructionDataApprove {\n const data = CompressedTokenInstructionDataApproveLayout.decode(\n buffer.subarray(APPROVE_DISCRIMINATOR.length),\n ) as CompressedTokenInstructionDataApprove;\n return {\n ...data,\n proof: isEmptyProof(data.proof!) ? null : data.proof!,\n };\n}\n\nexport function encodeRevokeInstructionData(\n data: CompressedTokenInstructionDataRevoke,\n): Buffer {\n const buffer = Buffer.alloc(1000);\n\n const proofOption = data.proof ?? emptyProof;\n\n const len = CompressedTokenInstructionDataRevokeLayout.encode(\n {\n ...data,\n proof: proofOption,\n },\n buffer,\n );\n\n const lengthBuffer = Buffer.alloc(4);\n lengthBuffer.writeUInt32LE(len, 0);\n\n const dataBuffer = buffer.subarray(0, len);\n\n return Buffer.concat([\n new Uint8Array(REVOKE_DISCRIMINATOR),\n new Uint8Array(lengthBuffer),\n new Uint8Array(dataBuffer),\n ]);\n}\n\nexport function decodeRevokeInstructionData(\n buffer: Buffer,\n): CompressedTokenInstructionDataRevoke {\n const data = CompressedTokenInstructionDataRevokeLayout.decode(\n buffer.subarray(REVOKE_DISCRIMINATOR.length),\n ) as CompressedTokenInstructionDataRevoke;\n return {\n ...data,\n proof: isEmptyProof(data.proof!) ? null : data.proof!,\n };\n}\n","import {\n PublicKey,\n TransactionInstruction,\n SystemProgram,\n Connection,\n AddressLookupTableProgram,\n AccountMeta,\n ComputeBudgetProgram,\n} from '@solana/web3.js';\nimport BN from 'bn.js';\nimport { Buffer } from 'buffer';\nimport {\n ValidityProof,\n LightSystemProgram,\n ParsedTokenAccount,\n bn,\n defaultStaticAccountsStruct,\n sumUpLamports,\n toArray,\n validateSameOwner,\n validateSufficientBalance,\n defaultTestStateTreeAccounts,\n TreeInfo,\n CompressedProof,\n featureFlags,\n TreeType,\n} from '@lightprotocol/stateless.js';\nimport {\n MINT_SIZE,\n TOKEN_2022_PROGRAM_ID,\n TOKEN_PROGRAM_ID,\n createInitializeMint2Instruction,\n createMintToInstruction,\n} from '@solana/spl-token';\nimport {\n CPI_AUTHORITY_SEED,\n POOL_SEED,\n CREATE_TOKEN_POOL_DISCRIMINATOR,\n ADD_TOKEN_POOL_DISCRIMINATOR,\n} from './constants';\nimport { checkMint, packCompressedTokenAccounts } from './utils';\nimport {\n encodeTransferInstructionData,\n encodeCompressSplTokenAccountInstructionData,\n encodeMintToInstructionData,\n createTokenPoolAccountsLayout,\n mintToAccountsLayout,\n transferAccountsLayout,\n approveAccountsLayout,\n revokeAccountsLayout,\n encodeApproveInstructionData,\n encodeRevokeInstructionData,\n addTokenPoolAccountsLayout,\n encodeBatchCompressInstructionData,\n} from './layout';\nimport {\n BatchCompressInstructionData,\n CompressedTokenInstructionDataApprove,\n CompressedTokenInstructionDataRevoke,\n CompressedTokenInstructionDataTransfer,\n DelegatedTransfer,\n TokenTransferOutputData,\n} from './types';\nimport {\n checkSplInterfaceInfo,\n SplInterfaceInfo,\n // Deprecated aliases\n checkTokenPoolInfo,\n TokenPoolInfo,\n} from './utils/get-token-pool-infos';\n\n/**\n * Helper to get the PDA from either TokenPoolInfo or SplInterfaceInfo\n * @internal\n */\nfunction getTokenPoolPda(info: TokenPoolInfo | SplInterfaceInfo): PublicKey {\n if ('tokenPoolPda' in info) {\n return info.tokenPoolPda ?? info.splInterfacePda;\n }\n return info.splInterfacePda;\n}\n\nexport type CompressParams = {\n /**\n * Fee payer\n */\n payer: PublicKey;\n /**\n * Owner of uncompressed token account\n */\n owner: PublicKey;\n /**\n * Source SPL Token account address\n */\n source: PublicKey;\n /**\n * Recipient address(es)\n */\n toAddress: PublicKey | PublicKey[];\n /**\n * Token amount(s) to compress\n */\n amount: number | BN | number[] | BN[];\n /**\n * SPL Token mint address\n */\n mint: PublicKey;\n /**\n * State tree to write to\n */\n outputStateTreeInfo: TreeInfo;\n /**\n * Token pool\n */\n tokenPoolInfo: TokenPoolInfo | SplInterfaceInfo;\n};\n\nexport type CompressSplTokenAccountParams = {\n /**\n * Fee payer\n */\n feePayer: PublicKey;\n /**\n * SPL Token account owner\n */\n authority: PublicKey;\n /**\n * SPL Token account to compress\n */\n tokenAccount: PublicKey;\n /**\n * SPL Token mint address\n */\n mint: PublicKey;\n /**\n * Amount to leave in token account\n */\n remainingAmount?: BN;\n /**\n * State tree to write to\n */\n outputStateTreeInfo: TreeInfo;\n /**\n * Token pool\n */\n tokenPoolInfo: TokenPoolInfo | SplInterfaceInfo;\n};\n\nexport type DecompressParams = {\n /**\n * Fee payer\n */\n payer: PublicKey;\n /**\n * Source compressed token accounts\n */\n inputCompressedTokenAccounts: ParsedTokenAccount[];\n /**\n * Destination uncompressed token account\n */\n toAddress: PublicKey;\n /**\n * Token amount to decompress\n */\n amount: number | BN;\n /**\n * Validity proof for input state\n */\n recentValidityProof: ValidityProof | CompressedProof | null;\n /**\n * Recent state root indices\n */\n recentInputStateRootIndices: number[];\n /**\n * Token pool(s)\n */\n tokenPoolInfos:\n | TokenPoolInfo\n | TokenPoolInfo[]\n | SplInterfaceInfo\n | SplInterfaceInfo[];\n};\n\nexport type TransferParams = {\n /**\n * Fee payer\n */\n payer: PublicKey;\n /**\n * Source compressed token accounts\n */\n inputCompressedTokenAccounts: ParsedTokenAccount[];\n /**\n * Recipient address\n */\n toAddress: PublicKey;\n /**\n * Token amount to transfer\n */\n amount: BN | number;\n /**\n * Validity proof for input state\n */\n recentValidityProof: ValidityProof | CompressedProof | null;\n /**\n * Recent state root indices\n */\n recentInputStateRootIndices: number[];\n};\n\nexport type ApproveParams = {\n /**\n * Fee payer\n */\n payer: PublicKey;\n /**\n * Source compressed token accounts\n */\n inputCompressedTokenAccounts: ParsedTokenAccount[];\n /**\n * Recipient address\n */\n toAddress: PublicKey;\n /**\n * Token amount to approve\n */\n amount: BN | number;\n /**\n * Validity proof for input state\n */\n recentValidityProof: ValidityProof | CompressedProof | null;\n /**\n * Recent state root indices\n */\n recentInputStateRootIndices: number[];\n};\n\nexport type RevokeParams = {\n /**\n * Fee payer\n */\n payer: PublicKey;\n /**\n * Input compressed token accounts\n */\n inputCompressedTokenAccounts: ParsedTokenAccount[];\n /**\n * Validity proof for input state\n */\n recentValidityProof: ValidityProof | CompressedProof | null;\n /**\n * Recent state root indices\n */\n recentInputStateRootIndices: number[];\n};\n\n/**\n * Create Mint account for compressed Tokens\n */\nexport type CreateMintParams = {\n /**\n * Fee payer\n */\n feePayer: PublicKey;\n /**\n * SPL Mint address\n */\n mint: PublicKey;\n /**\n * Mint authority\n */\n authority: PublicKey;\n /**\n * Optional: freeze authority\n */\n freezeAuthority: PublicKey | null;\n /**\n * Mint decimals\n */\n decimals: number;\n /**\n * lamport amount for mint account rent exemption\n */\n rentExemptBalance: number;\n /**\n * Optional: The token program ID. Default: SPL Token Program ID\n */\n tokenProgramId?: PublicKey;\n /**\n * Optional: Mint size to use, defaults to MINT_SIZE\n */\n mintSize?: number;\n};\n\n/**\n * Parameters for merging compressed token accounts\n */\nexport type MergeTokenAccountsParams = {\n /**\n * Fee payer\n */\n payer: PublicKey;\n /**\n * Owner of the compressed token accounts to be merged\n */\n owner: PublicKey;\n /**\n * SPL Token mint address\n */\n mint: PublicKey;\n /**\n * Array of compressed token accounts to merge\n */\n inputCompressedTokenAccounts: ParsedTokenAccount[];\n /**\n * Validity proof for state inclusion\n */\n recentValidityProof: ValidityProof | CompressedProof | null;\n /**\n * State root indices of the input state\n */\n recentInputStateRootIndices: number[];\n};\n\n/**\n * Create compressed token accounts\n */\nexport type MintToParams = {\n /**\n * Fee payer\n */\n feePayer: PublicKey;\n /**\n * Token mint address\n */\n mint: PublicKey;\n /**\n * Mint authority\n */\n authority: PublicKey;\n /**\n * Recipient address(es)\n */\n toPubkey: PublicKey[] | PublicKey;\n /**\n * Token amount(s) to mint\n */\n amount: BN | BN[] | number | number[];\n /**\n * State tree for minted tokens\n */\n outputStateTreeInfo: TreeInfo;\n /**\n * Token pool\n */\n tokenPoolInfo: TokenPoolInfo | SplInterfaceInfo;\n};\n\n/**\n * Register an existing SPL mint account to the compressed token program.\n * Creates an omnibus account (SPL interface) for the mint.\n */\nexport type CreateSplInterfaceParams = {\n /**\n * Fee payer\n */\n feePayer: PublicKey;\n /**\n * SPL Mint address\n */\n mint: PublicKey;\n /**\n * Optional: The token program ID. Default: SPL Token Program ID\n */\n tokenProgramId?: PublicKey;\n};\n\n/**\n * @deprecated Use {@link CreateSplInterfaceParams} instead.\n */\nexport type CreateTokenPoolParams = CreateSplInterfaceParams;\n\nexport type AddSplInterfaceParams = {\n /**\n * Fee payer\n */\n feePayer: PublicKey;\n /**\n * Token mint address\n */\n mint: PublicKey;\n /**\n * SPL interface pool index\n */\n poolIndex: number;\n /**\n * Optional: Token program ID. Default: SPL Token Program ID\n */\n tokenProgramId?: PublicKey;\n};\n\n/**\n * @deprecated Use {@link AddSplInterfaceParams} instead.\n */\nexport type AddTokenPoolParams = AddSplInterfaceParams;\n\n/**\n * Mint from existing SPL mint to compressed token accounts\n */\nexport type ApproveAndMintToParams = {\n /**\n * Fee payer\n */\n feePayer: PublicKey;\n /**\n * SPL Mint address\n */\n mint: PublicKey;\n /**\n * Mint authority\n */\n authority: PublicKey;\n /**\n * Mint authority (associated) token account\n */\n authorityTokenAccount: PublicKey;\n /**\n * Recipient address\n */\n toPubkey: PublicKey;\n /**\n * Token amount to mint\n */\n amount: BN | number;\n /**\n * State tree to write to\n */\n outputStateTreeInfo: TreeInfo;\n /**\n * Token pool\n */\n tokenPoolInfo: TokenPoolInfo | SplInterfaceInfo;\n};\n\nexport type CreateTokenProgramLookupTableParams = {\n /**\n * Fee payer\n */\n payer: PublicKey;\n /**\n * Authority of the transaction\n */\n authority: PublicKey;\n /**\n * Optional Mint addresses to store in the lookup table\n */\n mints?: PublicKey[];\n /**\n * Recently finalized Solana slot\n */\n recentSlot: number;\n /**\n * Optional additional addresses to store in the lookup table\n */\n remainingAccounts?: PublicKey[];\n};\n\n/**\n * Sum up the token amounts of the compressed token accounts\n */\nexport const sumUpTokenAmount = (accounts: ParsedTokenAccount[]): BN => {\n return accounts.reduce(\n (acc, account: ParsedTokenAccount) => acc.add(account.parsed.amount),\n bn(0),\n );\n};\n\n/**\n * Validate that all the compressed token accounts are owned by the same owner.\n */\nexport const validateSameTokenOwner = (accounts: ParsedTokenAccount[]) => {\n const owner = accounts[0].parsed.owner;\n accounts.forEach(acc => {\n if (!acc.parsed.owner.equals(owner)) {\n throw new Error('Token accounts must be owned by the same owner');\n }\n });\n};\n\n/**\n * Parse compressed token accounts to get the mint, current owner and delegate.\n */\nexport const parseTokenData = (\n compressedTokenAccounts: ParsedTokenAccount[],\n) => {\n const mint = compressedTokenAccounts[0].parsed.mint;\n const currentOwner = compressedTokenAccounts[0].parsed.owner;\n const delegate = compressedTokenAccounts[0].parsed.delegate;\n\n return { mint, currentOwner, delegate };\n};\n\nexport const parseMaybeDelegatedTransfer = (\n inputs: ParsedTokenAccount[],\n outputs: TokenTransferOutputData[],\n): { delegatedTransfer: DelegatedTransfer | null; authority: PublicKey } => {\n if (inputs.length < 1)\n throw new Error('Must supply at least one input token account.');\n\n const owner = inputs[0].parsed.owner;\n\n const delegatedAccountsIndex = inputs.findIndex(a => a.parsed.delegate);\n\n /// Fast path: no delegated account used\n if (delegatedAccountsIndex === -1)\n return { delegatedTransfer: null, authority: owner };\n\n const delegate = inputs[delegatedAccountsIndex].parsed.delegate;\n const delegateChangeAccountIndex = outputs.length <= 1 ? null : 0;\n\n return {\n delegatedTransfer: {\n owner,\n delegateChangeAccountIndex,\n },\n authority: delegate!,\n };\n};\n\n/**\n * Create the output state for a transfer transaction.\n * @param inputCompressedTokenAccounts Input state\n * @param toAddress Recipient address\n * @param amount Amount of tokens to transfer\n * @returns Output token data for the transfer\n * instruction\n */\nexport function createTransferOutputState(\n inputCompressedTokenAccounts: ParsedTokenAccount[],\n toAddress: PublicKey,\n amount: number | BN,\n): TokenTransferOutputData[] {\n amount = bn(amount);\n const inputAmount = sumUpTokenAmount(inputCompressedTokenAccounts);\n const inputLamports = sumUpLamports(\n inputCompressedTokenAccounts.map(acc => acc.compressedAccount),\n );\n\n const changeAmount = inputAmount.sub(amount);\n\n validateSufficientBalance(changeAmount);\n\n if (changeAmount.eq(bn(0)) && inputLamports.eq(bn(0))) {\n return [\n {\n owner: toAddress,\n amount,\n lamports: inputLamports,\n tlv: null,\n },\n ];\n }\n\n /// validates token program\n validateSameOwner(\n inputCompressedTokenAccounts.map(acc => acc.compressedAccount),\n );\n validateSameTokenOwner(inputCompressedTokenAccounts);\n\n const outputCompressedAccounts: TokenTransferOutputData[] = [\n {\n owner: inputCompressedTokenAccounts[0].parsed.owner,\n amount: changeAmount,\n lamports: inputLamports,\n tlv: null,\n },\n {\n owner: toAddress,\n amount,\n lamports: bn(0),\n tlv: null,\n },\n ];\n return outputCompressedAccounts;\n}\n\n/**\n * Create the output state for a compress transaction.\n * @param inputCompressedTokenAccounts Input state\n * @param amount Amount of tokens to compress\n * @returns Output token data for the compress\n * instruction\n */\nexport function createDecompressOutputState(\n inputCompressedTokenAccounts: ParsedTokenAccount[],\n amount: number | BN,\n): TokenTransferOutputData[] {\n amount = bn(amount);\n const inputLamports = sumUpLamports(\n inputCompressedTokenAccounts.map(acc => acc.compressedAccount),\n );\n const inputAmount = sumUpTokenAmount(inputCompressedTokenAccounts);\n const changeAmount = inputAmount.sub(amount);\n\n validateSufficientBalance(changeAmount);\n\n /// lamports gets decompressed\n if (changeAmount.eq(bn(0)) && inputLamports.eq(bn(0))) {\n return [];\n }\n\n validateSameOwner(\n inputCompressedTokenAccounts.map(acc => acc.compressedAccount),\n );\n validateSameTokenOwner(inputCompressedTokenAccounts);\n\n const tokenTransferOutputs: TokenTransferOutputData[] = [\n {\n owner: inputCompressedTokenAccounts[0].parsed.owner,\n amount: changeAmount,\n lamports: inputLamports,\n tlv: null,\n },\n ];\n return tokenTransferOutputs;\n}\n\nexport class CompressedTokenProgram {\n /**\n * @internal\n */\n constructor() {}\n\n /**\n * Public key that identifies the CompressedPda program\n */\n static programId: PublicKey = new PublicKey(\n 'cTokenmWW8bLPjZEBAUgYy3zKxQZW6VKi7bqNFEVv3m',\n );\n\n /**\n * Set a custom programId via PublicKey or base58 encoded string.\n * This method is not required for regular usage.\n *\n * Use this only if you know what you are doing.\n */\n static setProgramId(programId: PublicKey | string) {\n this.programId =\n typeof programId === 'string'\n ? new PublicKey(programId)\n : programId;\n }\n\n /**\n * Derive the SPL interface PDA.\n * To derive the SPL interface PDA with bump, use {@link deriveSplInterfacePdaWithIndex}.\n *\n * @param mint The mint of the SPL interface\n *\n * @returns The SPL interface PDA\n */\n static deriveSplInterfacePda(mint: PublicKey): PublicKey {\n const seeds = [POOL_SEED, mint.toBuffer()];\n const [address, _] = PublicKey.findProgramAddressSync(\n seeds,\n this.programId,\n );\n return address;\n }\n\n /**\n * @deprecated Use {@link deriveSplInterfacePda} instead.\n */\n static deriveTokenPoolPda(mint: PublicKey): PublicKey {\n return this.deriveSplInterfacePda(mint);\n }\n\n /**\n * Find the index and bump for a given SPL interface PDA and mint.\n *\n * @param poolPda The SPL interface PDA to find the index and bump for\n * @param mint The mint of the SPL interface\n *\n * @returns The index and bump number.\n */\n static findSplInterfaceIndexAndBump(\n poolPda: PublicKey,\n mint: PublicKey,\n ): [number, number] {\n for (let index = 0; index < 5; index++) {\n const derivedPda =\n CompressedTokenProgram.deriveSplInterfacePdaWithIndex(\n mint,\n index,\n );\n if (derivedPda[0].equals(poolPda)) {\n return [index, derivedPda[1]];\n }\n }\n throw new Error('SPL interface not found');\n }\n\n /**\n * @deprecated Use {@link findSplInterfaceIndexAndBump} instead.\n */\n static findTokenPoolIndexAndBump(\n poolPda: PublicKey,\n mint: PublicKey,\n ): [number, number] {\n return this.findSplInterfaceIndexAndBump(poolPda, mint);\n }\n\n /**\n * Derive the SPL interface PDA with index.\n *\n * @param mint The mint of the SPL interface\n * @param index Index. starts at 0. The Protocol supports 4 indexes aka SPL interfaces\n * per mint.\n *\n * @returns The SPL interface PDA and bump.\n */\n static deriveSplInterfacePdaWithIndex(\n mint: PublicKey,\n index: number,\n ): [PublicKey, number] {\n let seeds: Buffer[] = [];\n if (index === 0) {\n seeds = [Buffer.from('pool'), mint.toBuffer(), Buffer.from([])]; // legacy, 1st\n } else {\n seeds = [\n Buffer.from('pool'),\n mint.toBuffer(),\n Buffer.from([index]),\n ];\n }\n const [address, bump] = PublicKey.findProgramAddressSync(\n seeds,\n this.programId,\n );\n return [address, bump];\n }\n\n /**\n * @deprecated Use {@link deriveSplInterfacePdaWithIndex} instead.\n */\n static deriveTokenPoolPdaWithIndex(\n mint: PublicKey,\n index: number,\n ): [PublicKey, number] {\n return this.deriveSplInterfacePdaWithIndex(mint, index);\n }\n\n /** @internal */\n static get deriveCpiAuthorityPda(): PublicKey {\n const [address, _] = PublicKey.findProgramAddressSync(\n [CPI_AUTHORITY_SEED],\n this.programId,\n );\n return address;\n }\n\n /**\n * Construct createMint instruction for SPL tokens.\n *\n * @param feePayer Fee payer.\n * @param mint SPL Mint address.\n * @param authority Mint authority.\n * @param freezeAuthority Optional: freeze authority.\n * @param decimals Decimals.\n * @param rentExemptBalance Lamport amount for mint account rent exemption.\n * @param tokenProgramId Optional: Token program ID. Default: SPL Token Program ID\n * @param mintSize Optional: mint size. Default: MINT_SIZE\n *\n * @returns [createMintAccountInstruction, initializeMintInstruction,\n * createTokenPoolInstruction]\n *\n * Note that `createTokenPoolInstruction` must be executed after\n * `initializeMintInstruction`.\n */\n static async createMint({\n feePayer,\n mint,\n authority,\n freezeAuthority,\n decimals,\n rentExemptBalance,\n tokenProgramId,\n mintSize,\n }: CreateMintParams): Promise<TransactionInstruction[]> {\n const tokenProgram = tokenProgramId ?? TOKEN_PROGRAM_ID;\n\n /// Create and initialize SPL Mint account\n const createMintAccountInstruction = SystemProgram.createAccount({\n fromPubkey: feePayer,\n lamports: rentExemptBalance,\n newAccountPubkey: mint,\n programId: tokenProgram,\n space: mintSize ?? MINT_SIZE,\n });\n\n const initializeMintInstruction = createInitializeMint2Instruction(\n mint,\n decimals,\n authority,\n freezeAuthority,\n tokenProgram,\n );\n\n const createTokenPoolInstruction = await this.createTokenPool({\n feePayer,\n mint,\n tokenProgramId: tokenProgram,\n });\n\n return [\n createMintAccountInstruction,\n initializeMintInstruction,\n createTokenPoolInstruction,\n ];\n }\n\n /**\n * Enable compression for an existing SPL mint, creating an omnibus account.\n * For new mints, use `CompressedTokenProgram.createMint`.\n *\n * @param feePayer Fee payer.\n * @param mint SPL Mint address.\n * @param tokenProgramId Optional: Token program ID. Default: SPL\n * Token Program ID\n *\n * @returns The createTokenPool instruction\n */\n static async createTokenPool({\n feePayer,\n mint,\n tokenProgramId,\n }: CreateSplInterfaceParams): Promise<TransactionInstruction> {\n const tokenProgram = tokenProgramId ?? TOKEN_PROGRAM_ID;\n\n const splInterfacePda = this.deriveSplInterfacePdaWithIndex(mint, 0);\n\n const keys = createTokenPoolAccountsLayout({\n mint,\n feePayer,\n tokenPoolPda: splInterfacePda[0],\n tokenProgram,\n cpiAuthorityPda: this.deriveCpiAuthorityPda,\n systemProgram: SystemProgram.programId,\n });\n\n return new TransactionInstruction({\n programId: this.programId,\n keys,\n data: CREATE_TOKEN_POOL_DISCRIMINATOR,\n });\n }\n\n /**\n * Add a token pool to an existing SPL mint. For new mints, use\n * {@link createTokenPool}.\n *\n * @param feePayer Fee payer.\n * @param mint SPL Mint address.\n * @param poolIndex Pool index.\n * @param tokenProgramId Optional: Token program ID. Default: SPL\n * Token Program ID\n *\n * @returns The addTokenPool instruction\n */\n static async addTokenPool({\n feePayer,\n mint,\n poolIndex,\n tokenProgramId,\n }: AddSplInterfaceParams): Promise<TransactionInstruction> {\n if (poolIndex <= 0) {\n throw new Error(\n 'Pool index must be greater than 0. For 0, use CreateTokenPool instead.',\n );\n }\n if (poolIndex > 3) {\n throw new Error(\n `Invalid poolIndex ${poolIndex}. Max 4 pools per mint.`,\n );\n }\n\n const tokenProgram = tokenProgramId ?? TOKEN_PROGRAM_ID;\n\n const existingSplInterfacePda = this.deriveSplInterfacePdaWithIndex(\n mint,\n poolIndex - 1,\n );\n const splInterfacePda = this.deriveSplInterfacePdaWithIndex(\n mint,\n poolIndex,\n );\n\n const keys = addTokenPoolAccountsLayout({\n mint,\n feePayer,\n tokenPoolPda: splInterfacePda[0],\n existingTokenPoolPda: existingSplInterfacePda[0],\n tokenProgram,\n cpiAuthorityPda: this.deriveCpiAuthorityPda,\n systemProgram: SystemProgram.programId,\n });\n\n return new TransactionInstruction({\n programId: this.programId,\n keys,\n data: Buffer.concat([\n new Uint8Array(ADD_TOKEN_POOL_DISCRIMINATOR),\n new Uint8Array(Buffer.from([poolIndex])),\n ]),\n });\n }\n\n /**\n * Construct mintTo instruction for compressed tokens\n *\n * @param feePayer Fee payer.\n * @param mint SPL Mint address.\n * @param authority Mint authority.\n * @param toPubkey Recipient owner address.\n * @param amount Amount of tokens to mint.\n * @param outputStateTreeInfo State tree to write to.\n * @param tokenPoolInfo Token pool info.\n *\n * @returns The mintTo instruction\n */\n static async mintTo({\n feePayer,\n mint,\n authority,\n toPubkey,\n amount,\n outputStateTreeInfo,\n tokenPoolInfo,\n }: MintToParams): Promise<TransactionInstruction> {\n const systemKeys = defaultStaticAccountsStruct();\n const tokenProgram = tokenPoolInfo.tokenProgram;\n checkSplInterfaceInfo(tokenPoolInfo, mint);\n\n const amounts = toArray<BN | number>(amount).map(amount => bn(amount));\n const toPubkeys = toArray(toPubkey);\n\n if (amounts.length !== toPubkeys.length) {\n throw new Error(\n 'Amount and toPubkey arrays must have the same length',\n );\n }\n\n const keys = mintToAccountsLayout({\n mint,\n feePayer,\n authority,\n cpiAuthorityPda: this.deriveCpiAuthorityPda,\n tokenProgram,\n tokenPoolPda: getTokenPoolPda(tokenPoolInfo),\n lightSystemProgram: LightSystemProgram.programId,\n registeredProgramPda: systemKeys.registeredProgramPda,\n noopProgram: systemKeys.noopProgram,\n accountCompressionAuthority: systemKeys.accountCompressionAuthority,\n accountCompressionProgram: systemKeys.accountCompressionProgram,\n merkleTree:\n outputStateTreeInfo.treeType === TreeType.StateV2\n ? outputStateTreeInfo.queue\n : outputStateTreeInfo.tree,\n selfProgram: this.programId,\n systemProgram: SystemProgram.programId,\n solPoolPda: null,\n });\n\n const data = encodeMintToInstructionData({\n recipients: toPubkeys,\n amounts,\n lamports: null,\n });\n\n return new TransactionInstruction({\n programId: this.programId,\n keys,\n data,\n });\n }\n\n /**\n * Mint tokens from registered SPL mint account to a compressed account\n *\n * @param feePayer Fee payer.\n * @param mint SPL Mint address.\n * @param authority Mint authority.\n * @param authorityTokenAccount The mint authority's associated token\n * account (ATA).\n * @param toPubkey Recipient owner address.\n * @param amount Amount of tokens to mint.\n * @param outputStateTreeInfo State tree to write to.\n * @param tokenPoolInfo Token pool info.\n *\n * @returns The mintTo instruction\n */\n static async approveAndMintTo({\n feePayer,\n mint,\n authority,\n authorityTokenAccount,\n toPubkey,\n amount,\n outputStateTreeInfo,\n tokenPoolInfo,\n }: ApproveAndMintToParams) {\n const amountBigInt: bigint = BigInt(amount.toString());\n\n /// 1. Mint to existing ATA of mintAuthority.\n const splMintToInstruction = createMintToInstruction(\n mint,\n authorityTokenAccount,\n authority,\n amountBigInt,\n [],\n tokenPoolInfo.tokenProgram,\n );\n\n /// 2. Compress from mint authority ATA to recipient compressed account\n const compressInstruction = await this.compress({\n payer: feePayer,\n owner: authority,\n source: authorityTokenAccount,\n toAddress: toPubkey,\n mint,\n amount,\n outputStateTreeInfo,\n tokenPoolInfo,\n });\n\n return [splMintToInstruction, compressInstruction];\n }\n\n /**\n * Construct transfer instruction for compressed tokens\n *\n * @param payer Fee payer.\n * @param inputCompressedTokenAccounts Source compressed token accounts.\n * @param toAddress Recipient owner address.\n * @param amount Amount of tokens to transfer.\n * @param recentValidityProof Recent validity proof.\n * @param recentInputStateRootIndices Recent state root indices.\n *\n * @returns The transfer instruction\n */\n static async transfer({\n payer,\n inputCompressedTokenAccounts,\n toAddress,\n amount,\n recentValidityProof,\n recentInputStateRootIndices,\n }: TransferParams): Promise<TransactionInstruction> {\n const tokenTransferOutputs: TokenTransferOutputData[] =\n createTransferOutputState(\n inputCompressedTokenAccounts,\n toAddress,\n amount,\n );\n\n const {\n inputTokenDataWithContext,\n packedOutputTokenData,\n remainingAccountMetas,\n } = packCompressedTokenAccounts({\n inputCompressedTokenAccounts,\n rootIndices: recentInputStateRootIndices,\n tokenTransferOutputs,\n });\n\n const { mint } = parseTokenData(inputCompressedTokenAccounts);\n\n const { delegatedTransfer, authority } = parseMaybeDelegatedTransfer(\n inputCompressedTokenAccounts,\n tokenTransferOutputs,\n );\n\n const rawData: CompressedTokenInstructionDataTransfer = {\n proof: recentValidityProof,\n mint,\n delegatedTransfer,\n inputTokenDataWithContext,\n outputCompressedAccounts: packedOutputTokenData,\n compressOrDecompressAmount: null,\n isCompress: false,\n cpiContext: null,\n lamportsChangeAccountMerkleTreeIndex: null,\n };\n const data = encodeTransferInstructionData(rawData);\n\n const {\n accountCompressionAuthority,\n noopProgram,\n registeredProgramPda,\n accountCompressionProgram,\n } = defaultStaticAccountsStruct();\n const keys = transferAccountsLayout({\n feePayer: payer,\n authority,\n cpiAuthorityPda: this.deriveCpiAuthorityPda,\n lightSystemProgram: LightSystemProgram.programId,\n registeredProgramPda: registeredProgramPda,\n noopProgram: noopProgram,\n accountCompressionAuthority: accountCompressionAuthority,\n accountCompressionProgram: accountCompressionProgram,\n selfProgram: this.programId,\n tokenPoolPda: undefined,\n compressOrDecompressTokenAccount: undefined,\n tokenProgram: undefined,\n systemProgram: SystemProgram.programId,\n });\n\n keys.push(...remainingAccountMetas);\n\n return new TransactionInstruction({\n programId: this.programId,\n keys,\n data,\n });\n }\n\n /**\n * Create lookup table instructions for the token program's default\n * accounts.\n *\n * @param payer Fee payer.\n * @param authority Authority.\n * @param mints Mints.\n * @param recentSlot Recent slot.\n * @param remainingAccounts Remaining accounts.\n *\n * @returns [createInstruction, extendInstruction, option(extendInstruction2)]\n */\n static async createTokenProgramLookupTable({\n payer,\n authority,\n mints,\n recentSlot,\n remainingAccounts,\n }: CreateTokenProgramLookupTableParams) {\n const [createInstruction, lookupTableAddress] =\n AddressLookupTableProgram.createLookupTable({\n authority,\n payer: authority,\n recentSlot,\n });\n\n let optionalMintKeys: PublicKey[] = [];\n if (mints) {\n optionalMintKeys = [\n ...mints,\n ...mints.map(mint => this.deriveSplInterfacePda(mint)),\n ];\n }\n\n const extendInstruction = AddressLookupTableProgram.extendLookupTable({\n payer,\n authority,\n lookupTable: lookupTableAddress,\n addresses: [\n SystemProgram.programId,\n ComputeBudgetProgram.programId,\n this.deriveCpiAuthorityPda,\n LightSystemProgram.programId,\n CompressedTokenProgram.programId,\n defaultStaticAccountsStruct().registeredProgramPda,\n defaultStaticAccountsStruct().noopProgram,\n defaultStaticAccountsStruct().accountCompressionAuthority,\n defaultStaticAccountsStruct().accountCompressionProgram,\n defaultTestStateTreeAccounts().merkleTree,\n defaultTestStateTreeAccounts().nullifierQueue,\n defaultTestStateTreeAccounts().addressTree,\n defaultTestStateTreeAccounts().addressQueue,\n this.programId,\n TOKEN_PROGRAM_ID,\n TOKEN_2022_PROGRAM_ID,\n authority,\n ...optionalMintKeys,\n ],\n });\n\n const instructions = [createInstruction, extendInstruction];\n\n if (remainingAccounts && remainingAccounts.length > 0) {\n for (let i = 0; i < remainingAccounts.length; i += 25) {\n const chunk = remainingAccounts.slice(i, i + 25);\n const extendIx = AddressLookupTableProgram.extendLookupTable({\n payer,\n authority,\n lookupTable: lookupTableAddress,\n addresses: chunk,\n });\n instructions.push(extendIx);\n }\n }\n\n return {\n instructions,\n address: lookupTableAddress,\n };\n }\n\n /**\n * Create compress instruction\n *\n * @param payer Fee payer.\n * @param owner Owner of uncompressed token account.\n * @param source Source SPL Token account address.\n * @param toAddress Recipient owner address(es).\n * @param amount Amount of tokens to compress.\n * @param mint SPL Token mint address.\n * @param outputStateTreeInfo State tree to write to.\n * @param tokenPoolInfo Token pool info.\n *\n * @returns The compress instruction\n */\n static async compress({\n payer,\n owner,\n source,\n toAddress,\n amount,\n mint,\n outputStateTreeInfo,\n tokenPoolInfo,\n }: CompressParams): Promise<TransactionInstruction> {\n let tokenTransferOutputs: TokenTransferOutputData[];\n\n const amountArray = toArray<BN | number>(amount);\n const toAddressArray = toArray(toAddress);\n\n checkSplInterfaceInfo(tokenPoolInfo, mint);\n\n if (amountArray.length !== toAddressArray.length) {\n throw new Error(\n 'Amount and toAddress arrays must have the same length',\n );\n }\n if (featureFlags.isV2()) {\n const [index, bump] = this.findSplInterfaceIndexAndBump(\n getTokenPoolPda(tokenPoolInfo),\n mint,\n );\n const rawData: BatchCompressInstructionData = {\n pubkeys: toAddressArray,\n amounts:\n amountArray.length > 1\n ? amountArray.map(amt => bn(amt))\n : null,\n lamports: null,\n amount: amountArray.length === 1 ? bn(amountArray[0]) : null,\n index,\n bump,\n };\n\n const data = encodeBatchCompressInstructionData(rawData);\n const keys = mintToAccountsLayout({\n mint,\n feePayer: payer,\n authority: owner,\n cpiAuthorityPda: this.deriveCpiAuthorityPda,\n tokenProgram: tokenPoolInfo.tokenProgram,\n tokenPoolPda: getTokenPoolPda(tokenPoolInfo),\n lightSystemProgram: LightSystemProgram.programId,\n ...defaultStaticAccountsStruct(),\n merkleTree: outputStateTreeInfo.queue,\n selfProgram: this.programId,\n systemProgram: SystemProgram.programId,\n solPoolPda: null,\n });\n keys.push({\n pubkey: source,\n isWritable: true,\n isSigner: false,\n });\n\n return new TransactionInstruction({\n programId: this.programId,\n keys,\n data,\n });\n } else {\n tokenTransferOutputs = amountArray.map((amt, index) => {\n const amountBN = bn(amt);\n return {\n owner: toAddressArray[index],\n amount: amountBN,\n lamports: null,\n tlv: null,\n };\n });\n\n const {\n inputTokenDataWithContext,\n packedOutputTokenData,\n remainingAccountMetas,\n } = packCompressedTokenAccounts({\n inputCompressedTokenAccounts: [],\n outputStateTreeInfo,\n rootIndices: [],\n tokenTransferOutputs,\n });\n\n const rawData: CompressedTokenInstructionDataTransfer = {\n proof: null,\n mint,\n delegatedTransfer: null,\n inputTokenDataWithContext,\n outputCompressedAccounts: packedOutputTokenData,\n compressOrDecompressAmount: Array.isArray(amount)\n ? amount\n .map(amt => bn(amt))\n .reduce((sum, amt) => sum.add(amt), bn(0))\n : bn(amount),\n isCompress: true,\n cpiContext: null,\n lamportsChangeAccountMerkleTreeIndex: null,\n };\n const data = encodeTransferInstructionData(rawData);\n const keys = transferAccountsLayout({\n ...defaultStaticAccountsStruct(),\n feePayer: payer,\n authority: owner,\n cpiAuthorityPda: this.deriveCpiAuthorityPda,\n lightSystemProgram: LightSystemProgram.programId,\n selfProgram: this.programId,\n systemProgram: SystemProgram.programId,\n tokenPoolPda: getTokenPoolPda(tokenPoolInfo),\n compressOrDecompressTokenAccount: source,\n tokenProgram: tokenPoolInfo.tokenProgram,\n });\n keys.push(...remainingAccountMetas);\n\n return new TransactionInstruction({\n programId: this.programId,\n keys,\n data,\n });\n }\n }\n\n /**\n * Construct decompress instruction\n *\n * @param payer Fee payer.\n * @param inputCompressedTokenAccounts Source compressed token accounts.\n * @param toAddress Destination **uncompressed** token\n * account address. (ATA)\n * @param amount Amount of tokens to decompress.\n * @param recentValidityProof Recent validity proof.\n * @param recentInputStateRootIndices Recent state root indices.\n * @param tokenPoolInfos Token pool info.\n *\n * @returns The decompress instruction\n */\n static async decompress({\n payer,\n inputCompressedTokenAccounts,\n toAddress,\n amount,\n recentValidityProof,\n recentInputStateRootIndices,\n tokenPoolInfos,\n }: DecompressParams): Promise<TransactionInstruction> {\n const amountBN = bn(amount);\n const tokenPoolInfosArray = toArray(tokenPoolInfos);\n\n const tokenTransferOutputs = createDecompressOutputState(\n inputCompressedTokenAccounts,\n amountBN,\n );\n\n /// Pack\n const {\n inputTokenDataWithContext,\n packedOutputTokenData,\n remainingAccountMetas,\n } = packCompressedTokenAccounts({\n inputCompressedTokenAccounts,\n rootIndices: recentInputStateRootIndices,\n tokenTransferOutputs: tokenTransferOutputs,\n remainingAccounts: tokenPoolInfosArray\n .slice(1)\n .map(info =>\n getTokenPoolPda(info as TokenPoolInfo | SplInterfaceInfo),\n ),\n });\n\n const { mint } = parseTokenData(inputCompressedTokenAccounts);\n const { delegatedTransfer, authority } = parseMaybeDelegatedTransfer(\n inputCompressedTokenAccounts,\n tokenTransferOutputs,\n );\n\n const rawData: CompressedTokenInstructionDataTransfer = {\n proof: recentValidityProof,\n mint,\n delegatedTransfer,\n inputTokenDataWithContext,\n outputCompressedAccounts: packedOutputTokenData,\n compressOrDecompressAmount: amountBN,\n isCompress: false,\n cpiContext: null,\n lamportsChangeAccountMerkleTreeIndex: null,\n };\n const data = encodeTransferInstructionData(rawData);\n const tokenProgram = tokenPoolInfosArray[0].tokenProgram;\n\n const {\n accountCompressionAuthority,\n noopProgram,\n registeredProgramPda,\n accountCompressionProgram,\n } = defaultStaticAccountsStruct();\n\n const keys = transferAccountsLayout({\n feePayer: payer,\n authority: authority,\n cpiAuthorityPda: this.deriveCpiAuthorityPda,\n lightSystemProgram: LightSystemProgram.programId,\n registeredProgramPda: registeredProgramPda,\n noopProgram: noopProgram,\n accountCompressionAuthority: accountCompressionAuthority,\n accountCompressionProgram: accountCompressionProgram,\n selfProgram: this.programId,\n tokenPoolPda: getTokenPoolPda(tokenPoolInfosArray[0]),\n compressOrDecompressTokenAccount: toAddress,\n tokenProgram,\n systemProgram: SystemProgram.programId,\n });\n keys.push(...remainingAccountMetas);\n\n return new TransactionInstruction({\n programId: this.programId,\n keys,\n data,\n });\n }\n\n /**\n * Create `mergeTokenAccounts` instruction\n *\n * @param payer Fee payer.\n * @param owner Owner of the compressed token\n * accounts to be merged.\n * @param inputCompressedTokenAccounts Source compressed token accounts.\n * @param mint SPL Token mint address.\n * @param recentValidityProof Recent validity proof.\n * @param recentInputStateRootIndices Recent state root indices.\n *\n * @returns instruction\n */\n static async mergeTokenAccounts({\n payer,\n owner,\n inputCompressedTokenAccounts,\n mint,\n recentValidityProof,\n recentInputStateRootIndices,\n }: MergeTokenAccountsParams): Promise<TransactionInstruction[]> {\n if (inputCompressedTokenAccounts.length > 4) {\n throw new Error('Cannot merge more than 4 token accounts at once');\n }\n\n checkMint(inputCompressedTokenAccounts, mint);\n\n const ix = await this.transfer({\n payer,\n inputCompressedTokenAccounts,\n toAddress: owner,\n amount: inputCompressedTokenAccounts.reduce(\n (sum, account) => sum.add(account.parsed.amount),\n bn(0),\n ),\n recentInputStateRootIndices,\n recentValidityProof,\n });\n\n return [ix];\n }\n\n /**\n * Create `compressSplTokenAccount` instruction\n *\n * @param feePayer Fee payer.\n * @param authority SPL Token account owner.\n * @param tokenAccount SPL Token account to compress.\n * @param mint SPL Token mint address.\n * @param remainingAmount Optional: Amount to leave in token account.\n * @param outputStateTreeInfo State tree to write to.\n * @param tokenPoolInfo Token pool info.\n *\n * @returns instruction\n */\n static async compressSplTokenAccount({\n feePayer,\n authority,\n tokenAccount,\n mint,\n remainingAmount,\n outputStateTreeInfo,\n tokenPoolInfo,\n }: CompressSplTokenAccountParams): Promise<TransactionInstruction> {\n checkSplInterfaceInfo(tokenPoolInfo, mint);\n const remainingAccountMetas: AccountMeta[] = [\n {\n pubkey:\n outputStateTreeInfo.treeType === TreeType.StateV2\n ? outputStateTreeInfo.queue\n : outputStateTreeInfo.tree,\n isSigner: false,\n isWritable: true,\n },\n ];\n\n const data = encodeCompressSplTokenAccountInstructionData({\n owner: authority,\n remainingAmount: remainingAmount ?? null,\n cpiContext: null,\n });\n const {\n accountCompressionAuthority,\n noopProgram,\n registeredProgramPda,\n accountCompressionProgram,\n } = defaultStaticAccountsStruct();\n\n const keys = transferAccountsLayout({\n feePayer,\n authority,\n cpiAuthorityPda: this.deriveCpiAuthorityPda,\n lightSystemProgram: LightSystemProgram.programId,\n registeredProgramPda: registeredProgramPda,\n noopProgram: noopProgram,\n accountCompressionAuthority: accountCompressionAuthority,\n accountCompressionProgram: accountCompressionProgram,\n selfProgram: this.programId,\n tokenPoolPda: getTokenPoolPda(tokenPoolInfo),\n compressOrDecompressTokenAccount: tokenAccount,\n tokenProgram: tokenPoolInfo.tokenProgram,\n systemProgram: SystemProgram.programId,\n });\n\n keys.push(...remainingAccountMetas);\n\n return new TransactionInstruction({\n programId: this.programId,\n keys,\n data,\n });\n }\n\n /**\n * Get the program ID for a mint\n *\n * @param mint SPL Token mint address.\n * @param connection Connection.\n *\n * @returns program ID\n */\n static async getMintProgramId(\n mint: PublicKey,\n connection: Connection,\n ): Promise<PublicKey | undefined> {\n return (await connection.getAccountInfo(mint))?.owner;\n }\n\n /**\n * Create `approve` instruction to delegate compressed tokens.\n *\n * @param payer Fee payer.\n * @param inputCompressedTokenAccounts Source compressed token accounts.\n * @param toAddress Owner to delegate to.\n * @param amount Amount of tokens to delegate.\n * @param recentValidityProof Recent validity proof.\n * @param recentInputStateRootIndices Recent state root indices.\n *\n * @returns instruction\n */\n static async approve({\n payer,\n inputCompressedTokenAccounts,\n toAddress,\n amount,\n recentValidityProof,\n recentInputStateRootIndices,\n }: ApproveParams): Promise<TransactionInstruction> {\n const { inputTokenDataWithContext, remainingAccountMetas } =\n packCompressedTokenAccounts({\n inputCompressedTokenAccounts,\n rootIndices: recentInputStateRootIndices,\n tokenTransferOutputs: [],\n });\n\n const { mint, currentOwner } = parseTokenData(\n inputCompressedTokenAccounts,\n );\n\n const CHANGE_INDEX =\n inputCompressedTokenAccounts[0].compressedAccount.treeInfo\n .treeType === TreeType.StateV2\n ? 1\n : 0;\n\n const rawData: CompressedTokenInstructionDataApprove = {\n proof: recentValidityProof,\n mint,\n inputTokenDataWithContext,\n cpiContext: null,\n delegate: toAddress,\n delegatedAmount: bn(amount),\n delegateMerkleTreeIndex: CHANGE_INDEX,\n changeAccountMerkleTreeIndex: CHANGE_INDEX,\n delegateLamports: null,\n };\n\n const data = encodeApproveInstructionData(rawData);\n\n const {\n accountCompressionAuthority,\n noopProgram,\n registeredProgramPda,\n accountCompressionProgram,\n } = defaultStaticAccountsStruct();\n\n const keys = approveAccountsLayout({\n feePayer: payer,\n authority: currentOwner,\n cpiAuthorityPda: this.deriveCpiAuthorityPda,\n lightSystemProgram: LightSystemProgram.programId,\n registeredProgramPda: registeredProgramPda,\n noopProgram: noopProgram,\n accountCompressionAuthority: accountCompressionAuthority,\n accountCompressionProgram: accountCompressionProgram,\n selfProgram: this.programId,\n systemProgram: SystemProgram.programId,\n });\n\n keys.push(...remainingAccountMetas);\n\n return new TransactionInstruction({\n programId: this.programId,\n keys,\n data,\n });\n }\n\n /**\n * Create `revoke` instruction to revoke delegation of compressed tokens.\n *\n * @param payer Fee payer.\n * @param inputCompressedTokenAccounts Source compressed token accounts.\n * @param recentValidityProof Recent validity proof.\n * @param recentInputStateRootIndices Recent state root indices.\n *\n * @returns instruction\n */\n static async revoke({\n payer,\n inputCompressedTokenAccounts,\n recentValidityProof,\n recentInputStateRootIndices,\n }: RevokeParams): Promise<TransactionInstruction> {\n validateSameTokenOwner(inputCompressedTokenAccounts);\n\n const { inputTokenDataWithContext, remainingAccountMetas } =\n packCompressedTokenAccounts({\n inputCompressedTokenAccounts,\n rootIndices: recentInputStateRootIndices,\n tokenTransferOutputs: [],\n });\n\n const { mint, currentOwner } = parseTokenData(\n inputCompressedTokenAccounts,\n );\n\n const rawData: CompressedTokenInstructionDataRevoke = {\n proof: recentValidityProof,\n mint,\n inputTokenDataWithContext,\n cpiContext: null,\n outputAccountMerkleTreeIndex:\n inputCompressedTokenAccounts[0].compressedAccount.treeInfo\n .treeType === TreeType.StateV2\n ? 2\n : 1,\n };\n const data = encodeRevokeInstructionData(rawData);\n\n const {\n accountCompressionAuthority,\n noopProgram,\n registeredProgramPda,\n accountCompressionProgram,\n } = defaultStaticAccountsStruct();\n const keys = revokeAccountsLayout({\n feePayer: payer,\n authority: currentOwner,\n cpiAuthorityPda: this.deriveCpiAuthorityPda,\n lightSystemProgram: LightSystemProgram.programId,\n registeredProgramPda: registeredProgramPda,\n noopProgram: noopProgram,\n accountCompressionAuthority: accountCompressionAuthority,\n accountCompressionProgram: accountCompressionProgram,\n selfProgram: this.programId,\n systemProgram: SystemProgram.programId,\n });\n\n keys.push(...remainingAccountMetas);\n\n return new TransactionInstruction({\n programId: this.programId,\n keys,\n data,\n });\n }\n}\n","import {\n CTOKEN_PROGRAM_ID,\n deriveAddressV2,\n TreeInfo,\n} from '@lightprotocol/stateless.js';\nimport { PublicKey } from '@solana/web3.js';\nimport { Buffer } from 'buffer';\n\n/**\n * Returns the compressed mint address as bytes.\n */\nexport function deriveCMintAddress(\n mintSeed: PublicKey,\n addressTreeInfo: TreeInfo,\n) {\n // find_cmint_address returns [CMint, bump], we want CMint\n // In JS, just use the mintSeed directly as the CMint address\n const address = deriveAddressV2(\n findMintAddress(mintSeed)[0].toBytes(),\n addressTreeInfo.tree,\n CTOKEN_PROGRAM_ID,\n );\n return Array.from(address.toBytes());\n}\n\n/// b\"compressed_mint\"\nexport const COMPRESSED_MINT_SEED: Buffer = Buffer.from([\n 99, 111, 109, 112, 114, 101, 115, 115, 101, 100, 95, 109, 105, 110, 116,\n]);\n\n/**\n * Finds the SPL mint PDA for a c-token mint.\n * @param mintSeed The mint seed public key.\n * @returns [PDA, bump]\n */\nexport function findMintAddress(mintSigner: PublicKey): [PublicKey, number] {\n const [address, bump] = PublicKey.findProgramAddressSync(\n [COMPRESSED_MINT_SEED, mintSigner.toBuffer()],\n CTOKEN_PROGRAM_ID,\n );\n return [address, bump];\n}\n\n/// Same as \"getAssociatedTokenAddress\" but returns the bump as well.\n/// Uses c-token program ID.\nexport function getAssociatedCTokenAddressAndBump(\n owner: PublicKey,\n mint: PublicKey,\n) {\n return PublicKey.findProgramAddressSync(\n [owner.toBuffer(), CTOKEN_PROGRAM_ID.toBuffer(), mint.toBuffer()],\n CTOKEN_PROGRAM_ID,\n );\n}\n\n/// Same as \"getAssociatedTokenAddress\" but with c-token program ID.\nexport function getAssociatedCTokenAddress(owner: PublicKey, mint: PublicKey) {\n return PublicKey.findProgramAddressSync(\n [owner.toBuffer(), CTOKEN_PROGRAM_ID.toBuffer(), mint.toBuffer()],\n CTOKEN_PROGRAM_ID,\n )[0];\n}\n","/**\n * Borsh layouts for MintAction instruction data\n *\n * These layouts match the Rust structs in:\n * program-libs/ctoken-types/src/instructions/mint_action/\n *\n * @module mint-action-layout\n */\nimport { PublicKey } from '@solana/web3.js';\nimport { Buffer } from 'buffer';\nimport {\n struct,\n option,\n vec,\n bool,\n u8,\n u16,\n u32,\n u64,\n array,\n vecU8,\n publicKey,\n rustEnum,\n} from '@coral-xyz/borsh';\nimport { bn } from '@lightprotocol/stateless.js';\n\nexport const MINT_ACTION_DISCRIMINATOR = Buffer.from([103]);\n\nexport const RecipientLayout = struct([publicKey('recipient'), u64('amount')]);\n\nexport const MintToCompressedActionLayout = struct([\n u8('tokenAccountVersion'),\n vec(RecipientLayout, 'recipients'),\n]);\n\nexport const UpdateAuthorityLayout = struct([\n option(publicKey(), 'newAuthority'),\n]);\n\nexport const CreateSplMintActionLayout = struct([u8('mintBump')]);\n\nexport const MintToCTokenActionLayout = struct([\n u8('accountIndex'),\n u64('amount'),\n]);\n\nexport const UpdateMetadataFieldActionLayout = struct([\n u8('extensionIndex'),\n u8('fieldType'),\n vecU8('key'),\n vecU8('value'),\n]);\n\nexport const UpdateMetadataAuthorityActionLayout = struct([\n u8('extensionIndex'),\n publicKey('newAuthority'),\n]);\n\nexport const RemoveMetadataKeyActionLayout = struct([\n u8('extensionIndex'),\n vecU8('key'),\n u8('idempotent'),\n]);\n\nexport const ActionLayout = rustEnum([\n MintToCompressedActionLayout.replicate('mintToCompressed'),\n UpdateAuthorityLayout.replicate('updateMintAuthority'),\n UpdateAuthorityLayout.replicate('updateFreezeAuthority'),\n CreateSplMintActionLayout.replicate('createSplMint'),\n MintToCTokenActionLayout.replicate('mintToCToken'),\n UpdateMetadataFieldActionLayout.replicate('updateMetadataField'),\n UpdateMetadataAuthorityActionLayout.replicate('updateMetadataAuthority'),\n RemoveMetadataKeyActionLayout.replicate('removeMetadataKey'),\n]);\n\nexport const CompressedProofLayout = struct([\n array(u8(), 32, 'a'),\n array(u8(), 64, 'b'),\n array(u8(), 32, 'c'),\n]);\n\nexport const CpiContextLayout = struct([\n bool('setContext'),\n bool('firstSetContext'),\n u8('inTreeIndex'),\n u8('inQueueIndex'),\n u8('outQueueIndex'),\n u8('tokenOutQueueIndex'),\n u8('assignedAccountIndex'),\n array(u8(), 4, 'readOnlyAddressTrees'),\n array(u8(), 32, 'addressTreePubkey'),\n]);\n\nexport const CreateMintLayout = struct([\n array(u8(), 4, 'readOnlyAddressTrees'),\n array(u16(), 4, 'readOnlyAddressTreeRootIndices'),\n]);\n\nexport const AdditionalMetadataLayout = struct([vecU8('key'), vecU8('value')]);\n\nexport const TokenMetadataInstructionDataLayout = struct([\n option(publicKey(), 'updateAuthority'),\n vecU8('name'),\n vecU8('symbol'),\n vecU8('uri'),\n option(vec(AdditionalMetadataLayout), 'additionalMetadata'),\n]);\n\nconst PlaceholderLayout = struct([]);\n\nexport const ExtensionInstructionDataLayout = rustEnum([\n PlaceholderLayout.replicate('placeholder0'),\n PlaceholderLayout.replicate('placeholder1'),\n PlaceholderLayout.replicate('placeholder2'),\n PlaceholderLayout.replicate('placeholder3'),\n PlaceholderLayout.replicate('placeholder4'),\n PlaceholderLayout.replicate('placeholder5'),\n PlaceholderLayout.replicate('placeholder6'),\n PlaceholderLayout.replicate('placeholder7'),\n PlaceholderLayout.replicate('placeholder8'),\n PlaceholderLayout.replicate('placeholder9'),\n PlaceholderLayout.replicate('placeholder10'),\n PlaceholderLayout.replicate('placeholder11'),\n PlaceholderLayout.replicate('placeholder12'),\n PlaceholderLayout.replicate('placeholder13'),\n PlaceholderLayout.replicate('placeholder14'),\n PlaceholderLayout.replicate('placeholder15'),\n PlaceholderLayout.replicate('placeholder16'),\n PlaceholderLayout.replicate('placeholder17'),\n PlaceholderLayout.replicate('placeholder18'),\n TokenMetadataInstructionDataLayout.replicate('tokenMetadata'),\n]);\n\nexport const CompressedMintMetadataLayout = struct([\n u8('version'),\n bool('splMintInitialized'),\n publicKey('mint'),\n]);\n\nexport const CompressedMintInstructionDataLayout = struct([\n u64('supply'),\n u8('decimals'),\n CompressedMintMetadataLayout.replicate('metadata'),\n option(publicKey(), 'mintAuthority'),\n option(publicKey(), 'freezeAuthority'),\n option(vec(ExtensionInstructionDataLayout), 'extensions'),\n]);\n\nexport const MintActionCompressedInstructionDataLayout = struct([\n u32('leafIndex'),\n bool('proveByIndex'),\n u16('rootIndex'),\n array(u8(), 32, 'compressedAddress'),\n u8('tokenPoolBump'),\n u8('tokenPoolIndex'),\n u16('maxTopUp'),\n option(CreateMintLayout, 'createMint'),\n vec(ActionLayout, 'actions'),\n option(CompressedProofLayout, 'proof'),\n option(CpiContextLayout, 'cpiContext'),\n CompressedMintInstructionDataLayout.replicate('mint'),\n]);\n\nexport interface ValidityProof {\n a: number[];\n b: number[];\n c: number[];\n}\n\nexport interface Recipient {\n recipient: PublicKey;\n amount: bigint;\n}\n\nexport interface MintToCompressedAction {\n tokenAccountVersion: number;\n recipients: Recipient[];\n}\n\nexport interface UpdateAuthority {\n newAuthority: PublicKey | null;\n}\n\nexport interface CreateSplMintAction {\n mintBump: number;\n}\n\nexport interface MintToCTokenAction {\n accountIndex: number;\n amount: bigint;\n}\n\nexport interface UpdateMetadataFieldAction {\n extensionIndex: number;\n fieldType: number;\n key: Buffer;\n value: Buffer;\n}\n\nexport interface UpdateMetadataAuthorityAction {\n extensionIndex: number;\n newAuthority: PublicKey;\n}\n\nexport interface RemoveMetadataKeyAction {\n extensionIndex: number;\n key: Buffer;\n idempotent: number;\n}\n\nexport type Action =\n | { mintToCompressed: MintToCompressedAction }\n | { updateMintAuthority: UpdateAuthority }\n | { updateFreezeAuthority: UpdateAuthority }\n | { createSplMint: CreateSplMintAction }\n | { mintToCToken: MintToCTokenAction }\n | { updateMetadataField: UpdateMetadataFieldAction }\n | { updateMetadataAuthority: UpdateMetadataAuthorityAction }\n | { removeMetadataKey: RemoveMetadataKeyAction };\n\nexport interface CpiContext {\n setContext: boolean;\n firstSetContext: boolean;\n inTreeIndex: number;\n inQueueIndex: number;\n outQueueIndex: number;\n tokenOutQueueIndex: number;\n assignedAccountIndex: number;\n readOnlyAddressTrees: number[];\n addressTreePubkey: number[];\n}\n\nexport interface CreateMint {\n readOnlyAddressTrees: number[];\n readOnlyAddressTreeRootIndices: number[];\n}\n\nexport interface AdditionalMetadata {\n key: Buffer;\n value: Buffer;\n}\n\nexport interface TokenMetadataLayoutData {\n updateAuthority: PublicKey | null;\n name: Buffer;\n symbol: Buffer;\n uri: Buffer;\n additionalMetadata: AdditionalMetadata[] | null;\n}\n\nexport type ExtensionInstructionData = {\n tokenMetadata: TokenMetadataLayoutData;\n};\n\nexport interface CompressedMintMetadata {\n version: number;\n splMintInitialized: boolean;\n mint: PublicKey;\n}\n\nexport interface CompressedMintInstructionData {\n supply: bigint;\n decimals: number;\n metadata: CompressedMintMetadata;\n mintAuthority: PublicKey | null;\n freezeAuthority: PublicKey | null;\n extensions: ExtensionInstructionData[] | null;\n}\n\nexport interface MintActionCompressedInstructionData {\n leafIndex: number;\n proveByIndex: boolean;\n rootIndex: number;\n compressedAddress: number[];\n tokenPoolBump: number;\n tokenPoolIndex: number;\n maxTopUp: number;\n createMint: CreateMint | null;\n actions: Action[];\n proof: ValidityProof | null;\n cpiContext: CpiContext | null;\n mint: CompressedMintInstructionData;\n}\n\n/**\n * Encode MintActionCompressedInstructionData to buffer\n *\n * @param data - The instruction data to encode\n * @returns Encoded buffer with discriminator prepended\n */\nexport function encodeMintActionInstructionData(\n data: MintActionCompressedInstructionData,\n): Buffer {\n // Convert bigint fields to BN for Borsh encoding\n const encodableData = {\n ...data,\n mint: {\n ...data.mint,\n supply: bn(data.mint.supply.toString()),\n },\n actions: data.actions.map(action => {\n // Handle MintToCompressed action with recipients\n if ('mintToCompressed' in action && action.mintToCompressed) {\n return {\n mintToCompressed: {\n ...action.mintToCompressed,\n recipients: action.mintToCompressed.recipients.map(\n r => ({\n ...r,\n amount: bn(r.amount.toString()),\n }),\n ),\n },\n };\n }\n // Handle MintToCToken action (c-token mint-to)\n if ('mintToCToken' in action && action.mintToCToken) {\n return {\n mintToCToken: {\n ...action.mintToCToken,\n amount: bn(action.mintToCToken.amount.toString()),\n },\n };\n }\n return action;\n }),\n };\n\n const buffer = Buffer.alloc(10000); // Generous allocation\n const len = MintActionCompressedInstructionDataLayout.encode(\n encodableData,\n buffer,\n );\n\n return Buffer.concat([MINT_ACTION_DISCRIMINATOR, buffer.subarray(0, len)]);\n}\n\n/**\n * Decode MintActionCompressedInstructionData from buffer\n *\n * @param buffer - The buffer to decode (including discriminator)\n * @returns Decoded instruction data\n */\nexport function decodeMintActionInstructionData(\n buffer: Buffer,\n): MintActionCompressedInstructionData {\n return MintActionCompressedInstructionDataLayout.decode(\n buffer.subarray(MINT_ACTION_DISCRIMINATOR.length),\n ) as MintActionCompressedInstructionData;\n}\n","import {\n PublicKey,\n SystemProgram,\n TransactionInstruction,\n} from '@solana/web3.js';\nimport { Buffer } from 'buffer';\nimport {\n ValidityProofWithContext,\n CTOKEN_PROGRAM_ID,\n LightSystemProgram,\n defaultStaticAccountsStruct,\n deriveAddressV2,\n TreeInfo,\n AddressTreeInfo,\n ValidityProof,\n} from '@lightprotocol/stateless.js';\nimport { CompressedTokenProgram } from '../../program';\nimport { findMintAddress } from '../derivation';\nimport {\n AdditionalMetadata,\n encodeMintActionInstructionData,\n MintActionCompressedInstructionData,\n TokenMetadataLayoutData as TokenMetadataBorshData,\n} from '../layout/layout-mint-action';\nimport { TokenDataVersion } from '../../constants';\n\n/**\n * Token metadata for creating a c-token mint.\n */\nexport interface TokenMetadataInstructionData {\n name: string;\n symbol: string;\n uri: string;\n updateAuthority?: PublicKey | null;\n additionalMetadata: AdditionalMetadata[] | null;\n}\n\nexport interface EncodeCreateMintInstructionParams {\n mintSigner: PublicKey;\n mintAuthority: PublicKey;\n freezeAuthority: PublicKey | null;\n decimals: number;\n addressTree: PublicKey;\n outputQueue: PublicKey;\n rootIndex: number;\n proof: ValidityProof | null;\n metadata?: TokenMetadataInstructionData;\n}\n\nexport function createTokenMetadata(\n name: string,\n symbol: string,\n uri: string,\n updateAuthority?: PublicKey | null,\n additionalMetadata: AdditionalMetadata[] | null = null,\n): TokenMetadataInstructionData {\n return {\n name,\n symbol,\n uri,\n updateAuthority: updateAuthority ?? null,\n additionalMetadata: additionalMetadata ?? null,\n };\n}\n\n/**\n * Validate and normalize proof arrays to ensure correct sizes for Borsh serialization.\n * The compressed proof must have exactly: a[32], b[64], c[32] bytes.\n */\nfunction validateProofArrays(\n proof: ValidityProof | null,\n): ValidityProof | null {\n if (!proof) return null;\n\n // Validate array sizes\n if (proof.a.length !== 32) {\n throw new Error(\n `Invalid proof.a length: expected 32, got ${proof.a.length}`,\n );\n }\n if (proof.b.length !== 64) {\n throw new Error(\n `Invalid proof.b length: expected 64, got ${proof.b.length}`,\n );\n }\n if (proof.c.length !== 32) {\n throw new Error(\n `Invalid proof.c length: expected 32, got ${proof.c.length}`,\n );\n }\n\n return proof;\n}\n\nexport function encodeCreateMintInstructionData(\n params: EncodeCreateMintInstructionParams,\n): Buffer {\n const [splMintPda] = findMintAddress(params.mintSigner);\n const compressedAddress = deriveAddressV2(\n splMintPda.toBytes(),\n params.addressTree,\n CTOKEN_PROGRAM_ID,\n );\n\n // Build extensions if metadata present\n let extensions: { tokenMetadata: TokenMetadataBorshData }[] | null = null;\n if (params.metadata) {\n extensions = [\n {\n tokenMetadata: {\n updateAuthority: params.metadata.updateAuthority ?? null,\n name: Buffer.from(params.metadata.name),\n symbol: Buffer.from(params.metadata.symbol),\n uri: Buffer.from(params.metadata.uri),\n additionalMetadata: params.metadata.additionalMetadata,\n },\n },\n ];\n }\n\n // Validate proof arrays before encoding\n const validatedProof = validateProofArrays(params.proof);\n\n /** TODO: check leafIndex */\n const instructionData: MintActionCompressedInstructionData = {\n leafIndex: 0,\n proveByIndex: false,\n rootIndex: params.rootIndex,\n compressedAddress: Array.from(compressedAddress.toBytes()),\n tokenPoolBump: 0,\n tokenPoolIndex: 0,\n maxTopUp: 0,\n createMint: {\n readOnlyAddressTrees: [0, 0, 0, 0],\n readOnlyAddressTreeRootIndices: [0, 0, 0, 0],\n },\n actions: [], // No actions for create mint\n proof: validatedProof,\n cpiContext: null,\n mint: {\n supply: BigInt(0),\n decimals: params.decimals,\n metadata: {\n version: TokenDataVersion.ShaFlat,\n splMintInitialized: false,\n mint: splMintPda,\n },\n mintAuthority: params.mintAuthority,\n freezeAuthority: params.freezeAuthority,\n extensions,\n },\n };\n\n return encodeMintActionInstructionData(instructionData);\n}\n\n// Keep old interface type for backwards compatibility export\nexport interface CreateMintInstructionParams {\n mintSigner: PublicKey;\n decimals: number;\n mintAuthority: PublicKey;\n freezeAuthority: PublicKey | null;\n payer: PublicKey;\n validityProof: ValidityProofWithContext;\n metadata?: TokenMetadataInstructionData;\n addressTreeInfo: AddressTreeInfo;\n outputStateTreeInfo: TreeInfo;\n}\n\n/**\n * Create instruction for initializing a c-token mint.\n *\n * @param mintSigner Mint signer keypair public key.\n * @param decimals Number of decimals for the mint.\n * @param mintAuthority Mint authority public key.\n * @param freezeAuthority Optional freeze authority public key.\n * @param payer Fee payer public key.\n * @param validityProof Validity proof for the mint account.\n * @param addressTreeInfo Address tree info for the mint.\n * @param outputStateTreeInfo Output state tree info.\n * @param metadata Optional token metadata.\n */\nexport function createMintInstruction(\n mintSigner: PublicKey,\n decimals: number,\n mintAuthority: PublicKey,\n freezeAuthority: PublicKey | null,\n payer: PublicKey,\n validityProof: ValidityProofWithContext,\n addressTreeInfo: AddressTreeInfo,\n outputStateTreeInfo: TreeInfo,\n metadata?: TokenMetadataInstructionData,\n): TransactionInstruction {\n const data = encodeCreateMintInstructionData({\n mintSigner,\n mintAuthority,\n freezeAuthority,\n decimals,\n addressTree: addressTreeInfo.tree,\n outputQueue: outputStateTreeInfo.queue,\n rootIndex: validityProof.rootIndices[0],\n proof: validityProof.compressedProof,\n metadata,\n });\n\n const sys = defaultStaticAccountsStruct();\n const keys = [\n {\n pubkey: LightSystemProgram.programId,\n isSigner: false,\n isWritable: false,\n },\n { pubkey: mintSigner, isSigner: true, isWritable: false },\n { pubkey: mintAuthority, isSigner: true, isWritable: false },\n { pubkey: payer, isSigner: true, isWritable: true },\n {\n pubkey: CompressedTokenProgram.deriveCpiAuthorityPda,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: sys.registeredProgramPda,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: sys.accountCompressionAuthority,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: sys.accountCompressionProgram,\n isSigner: false,\n isWritable: false,\n },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n {\n pubkey: outputStateTreeInfo.queue,\n isSigner: false,\n isWritable: true,\n },\n {\n pubkey: addressTreeInfo.tree,\n isSigner: false,\n isWritable: true,\n },\n ];\n\n return new TransactionInstruction({\n programId: CTOKEN_PROGRAM_ID,\n keys,\n data,\n });\n}\n","import {\n PublicKey,\n SystemProgram,\n TransactionInstruction,\n} from '@solana/web3.js';\nimport { Buffer } from 'buffer';\nimport {\n ValidityProofWithContext,\n CTOKEN_PROGRAM_ID,\n LightSystemProgram,\n defaultStaticAccountsStruct,\n deriveAddressV2,\n getDefaultAddressTreeInfo,\n getOutputQueue,\n} from '@lightprotocol/stateless.js';\nimport { CompressedTokenProgram } from '../../program';\nimport { MintInterface } from '../get-mint-interface';\nimport {\n encodeMintActionInstructionData,\n MintActionCompressedInstructionData,\n Action,\n ExtensionInstructionData,\n} from '../layout/layout-mint-action';\n\ninterface EncodeUpdateMintInstructionParams {\n splMint: PublicKey;\n addressTree: PublicKey;\n leafIndex: number;\n proveByIndex: boolean;\n rootIndex: number;\n proof: { a: number[]; b: number[]; c: number[] } | null;\n mintInterface: MintInterface;\n newAuthority: PublicKey | null;\n actionType: 'mintAuthority' | 'freezeAuthority';\n}\n\nfunction encodeUpdateMintInstructionData(\n params: EncodeUpdateMintInstructionParams,\n): Buffer {\n const compressedAddress = deriveAddressV2(\n params.splMint.toBytes(),\n params.addressTree,\n CTOKEN_PROGRAM_ID,\n );\n\n // Build action\n const action: Action =\n params.actionType === 'mintAuthority'\n ? { updateMintAuthority: { newAuthority: params.newAuthority } }\n : { updateFreezeAuthority: { newAuthority: params.newAuthority } };\n\n // Build extensions if metadata present\n let extensions: ExtensionInstructionData[] | null = null;\n if (params.mintInterface.tokenMetadata) {\n extensions = [\n {\n tokenMetadata: {\n updateAuthority:\n params.mintInterface.tokenMetadata.updateAuthority ??\n null,\n name: Buffer.from(params.mintInterface.tokenMetadata.name),\n symbol: Buffer.from(\n params.mintInterface.tokenMetadata.symbol,\n ),\n uri: Buffer.from(params.mintInterface.tokenMetadata.uri),\n additionalMetadata: null,\n },\n },\n ];\n }\n\n const instructionData: MintActionCompressedInstructionData = {\n leafIndex: params.leafIndex,\n proveByIndex: params.proveByIndex,\n rootIndex: params.rootIndex,\n compressedAddress: Array.from(compressedAddress.toBytes()),\n tokenPoolBump: 0,\n tokenPoolIndex: 0,\n maxTopUp: 0,\n createMint: null,\n actions: [action],\n proof: params.proof,\n cpiContext: null,\n mint: {\n supply: params.mintInterface.mint.supply,\n decimals: params.mintInterface.mint.decimals,\n metadata: {\n version: params.mintInterface.mintContext!.version,\n splMintInitialized:\n params.mintInterface.mintContext!.splMintInitialized,\n mint: params.mintInterface.mintContext!.splMint,\n },\n mintAuthority: params.mintInterface.mint.mintAuthority,\n freezeAuthority: params.mintInterface.mint.freezeAuthority,\n extensions,\n },\n };\n\n return encodeMintActionInstructionData(instructionData);\n}\n\n/**\n * Create instruction for updating a compressed mint's mint authority.\n *\n * @param mintInterface MintInterface from getMintInterface() - must have merkleContext\n * @param currentMintAuthority Current mint authority public key (must sign)\n * @param newMintAuthority New mint authority (or null to revoke)\n * @param payer Fee payer public key\n * @param validityProof Validity proof for the compressed mint\n */\nexport function createUpdateMintAuthorityInstruction(\n mintInterface: MintInterface,\n currentMintAuthority: PublicKey,\n newMintAuthority: PublicKey | null,\n payer: PublicKey,\n validityProof: ValidityProofWithContext,\n): TransactionInstruction {\n if (!mintInterface.merkleContext) {\n throw new Error(\n 'MintInterface must have merkleContext for compressed mint operations',\n );\n }\n if (!mintInterface.mintContext) {\n throw new Error(\n 'MintInterface must have mintContext for compressed mint operations',\n );\n }\n\n const merkleContext = mintInterface.merkleContext;\n const outputQueue = getOutputQueue(merkleContext);\n\n const addressTreeInfo = getDefaultAddressTreeInfo();\n const data = encodeUpdateMintInstructionData({\n splMint: mintInterface.mintContext.splMint,\n addressTree: addressTreeInfo.tree,\n leafIndex: merkleContext.leafIndex,\n proveByIndex: true,\n rootIndex: validityProof.rootIndices[0],\n proof: validityProof.compressedProof,\n mintInterface,\n newAuthority: newMintAuthority,\n actionType: 'mintAuthority',\n });\n\n const sys = defaultStaticAccountsStruct();\n const keys = [\n {\n pubkey: LightSystemProgram.programId,\n isSigner: false,\n isWritable: false,\n },\n { pubkey: currentMintAuthority, isSigner: true, isWritable: false },\n { pubkey: payer, isSigner: true, isWritable: true },\n {\n pubkey: CompressedTokenProgram.deriveCpiAuthorityPda,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: sys.registeredProgramPda,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: sys.accountCompressionAuthority,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: sys.accountCompressionProgram,\n isSigner: false,\n isWritable: false,\n },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n { pubkey: outputQueue, isSigner: false, isWritable: true },\n {\n pubkey: merkleContext.treeInfo.tree,\n isSigner: false,\n isWritable: true,\n },\n {\n pubkey: merkleContext.treeInfo.queue,\n isSigner: false,\n isWritable: true,\n },\n ];\n\n return new TransactionInstruction({\n programId: CTOKEN_PROGRAM_ID,\n keys,\n data,\n });\n}\n\n/**\n * Create instruction for updating a compressed mint's freeze authority.\n *\n * Output queue is automatically derived from mintInterface.merkleContext.treeInfo\n * (preferring nextTreeInfo.queue if available for rollover support).\n *\n * @param mintInterface MintInterface from getMintInterface() - must have merkleContext\n * @param currentFreezeAuthority Current freeze authority public key (must sign)\n * @param newFreezeAuthority New freeze authority (or null to revoke)\n * @param payer Fee payer public key\n * @param validityProof Validity proof for the compressed mint\n */\nexport function createUpdateFreezeAuthorityInstruction(\n mintInterface: MintInterface,\n currentFreezeAuthority: PublicKey,\n newFreezeAuthority: PublicKey | null,\n payer: PublicKey,\n validityProof: ValidityProofWithContext,\n): TransactionInstruction {\n if (!mintInterface.merkleContext) {\n throw new Error(\n 'MintInterface must have merkleContext for compressed mint operations',\n );\n }\n if (!mintInterface.mintContext) {\n throw new Error(\n 'MintInterface must have mintContext for compressed mint operations',\n );\n }\n\n const merkleContext = mintInterface.merkleContext;\n const outputQueue = getOutputQueue(merkleContext);\n\n const addressTreeInfo = getDefaultAddressTreeInfo();\n const data = encodeUpdateMintInstructionData({\n splMint: mintInterface.mintContext.splMint,\n addressTree: addressTreeInfo.tree,\n leafIndex: merkleContext.leafIndex,\n proveByIndex: true,\n rootIndex: validityProof.rootIndices[0],\n proof: validityProof.compressedProof,\n mintInterface,\n newAuthority: newFreezeAuthority,\n actionType: 'freezeAuthority',\n });\n\n const sys = defaultStaticAccountsStruct();\n const keys = [\n {\n pubkey: LightSystemProgram.programId,\n isSigner: false,\n isWritable: false,\n },\n { pubkey: currentFreezeAuthority, isSigner: true, isWritable: false },\n { pubkey: payer, isSigner: true, isWritable: true },\n {\n pubkey: CompressedTokenProgram.deriveCpiAuthorityPda,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: sys.registeredProgramPda,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: sys.accountCompressionAuthority,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: sys.accountCompressionProgram,\n isSigner: false,\n isWritable: false,\n },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n { pubkey: outputQueue, isSigner: false, isWritable: true },\n {\n pubkey: merkleContext.treeInfo.tree,\n isSigner: false,\n isWritable: true,\n },\n {\n pubkey: merkleContext.treeInfo.queue,\n isSigner: false,\n isWritable: true,\n },\n ];\n\n return new TransactionInstruction({\n programId: CTOKEN_PROGRAM_ID,\n keys,\n data,\n });\n}\n","import {\n PublicKey,\n SystemProgram,\n TransactionInstruction,\n} from '@solana/web3.js';\nimport { Buffer } from 'buffer';\nimport {\n ValidityProofWithContext,\n CTOKEN_PROGRAM_ID,\n LightSystemProgram,\n defaultStaticAccountsStruct,\n deriveAddressV2,\n getDefaultAddressTreeInfo,\n getOutputQueue,\n} from '@lightprotocol/stateless.js';\nimport { CompressedTokenProgram } from '../../program';\nimport { MintInterface } from '../get-mint-interface';\nimport {\n encodeMintActionInstructionData,\n MintActionCompressedInstructionData,\n Action,\n} from '../layout/layout-mint-action';\n\ntype UpdateMetadataAction =\n | {\n type: 'updateField';\n extensionIndex: number;\n fieldType: number;\n key: string;\n value: string;\n }\n | {\n type: 'updateAuthority';\n extensionIndex: number;\n newAuthority: PublicKey;\n }\n | {\n type: 'removeKey';\n extensionIndex: number;\n key: string;\n idempotent: boolean;\n };\n\ninterface EncodeUpdateMetadataInstructionParams {\n splMint: PublicKey;\n addressTree: PublicKey;\n leafIndex: number;\n rootIndex: number;\n proof: { a: number[]; b: number[]; c: number[] } | null;\n mintInterface: MintInterface;\n action: UpdateMetadataAction;\n}\n\nfunction convertActionToBorsh(action: UpdateMetadataAction): Action {\n if (action.type === 'updateField') {\n return {\n updateMetadataField: {\n extensionIndex: action.extensionIndex,\n fieldType: action.fieldType,\n key: Buffer.from(action.key),\n value: Buffer.from(action.value),\n },\n };\n } else if (action.type === 'updateAuthority') {\n return {\n updateMetadataAuthority: {\n extensionIndex: action.extensionIndex,\n newAuthority: action.newAuthority,\n },\n };\n } else {\n return {\n removeMetadataKey: {\n extensionIndex: action.extensionIndex,\n key: Buffer.from(action.key),\n idempotent: action.idempotent ? 1 : 0,\n },\n };\n }\n}\n\nfunction encodeUpdateMetadataInstructionData(\n params: EncodeUpdateMetadataInstructionParams,\n): Buffer {\n const compressedAddress = deriveAddressV2(\n params.splMint.toBytes(),\n params.addressTree,\n CTOKEN_PROGRAM_ID,\n );\n\n const mintInterface = params.mintInterface;\n\n if (!mintInterface.tokenMetadata) {\n throw new Error(\n 'MintInterface must have tokenMetadata for metadata operations',\n );\n }\n\n const instructionData: MintActionCompressedInstructionData = {\n leafIndex: params.leafIndex,\n proveByIndex: params.proof === null,\n rootIndex: params.rootIndex,\n compressedAddress: Array.from(compressedAddress.toBytes()),\n tokenPoolBump: 0,\n tokenPoolIndex: 0,\n maxTopUp: 0,\n createMint: null,\n actions: [convertActionToBorsh(params.action)],\n proof: params.proof,\n cpiContext: null,\n mint: {\n supply: mintInterface.mint.supply,\n decimals: mintInterface.mint.decimals,\n metadata: {\n version: mintInterface.mintContext!.version,\n splMintInitialized:\n mintInterface.mintContext!.splMintInitialized,\n mint: mintInterface.mintContext!.splMint,\n },\n mintAuthority: mintInterface.mint.mintAuthority,\n freezeAuthority: mintInterface.mint.freezeAuthority,\n extensions: [\n {\n tokenMetadata: {\n updateAuthority:\n mintInterface.tokenMetadata.updateAuthority ?? null,\n name: Buffer.from(mintInterface.tokenMetadata.name),\n symbol: Buffer.from(mintInterface.tokenMetadata.symbol),\n uri: Buffer.from(mintInterface.tokenMetadata.uri),\n additionalMetadata: null,\n },\n },\n ],\n },\n };\n\n return encodeMintActionInstructionData(instructionData);\n}\n\nfunction createUpdateMetadataInstruction(\n mintInterface: MintInterface,\n authority: PublicKey,\n payer: PublicKey,\n validityProof: ValidityProofWithContext,\n action: UpdateMetadataAction,\n): TransactionInstruction {\n if (!mintInterface.merkleContext) {\n throw new Error(\n 'MintInterface must have merkleContext for compressed mint operations',\n );\n }\n if (!mintInterface.mintContext) {\n throw new Error(\n 'MintInterface must have mintContext for compressed mint operations',\n );\n }\n if (!mintInterface.tokenMetadata) {\n throw new Error(\n 'MintInterface must have tokenMetadata for metadata operations',\n );\n }\n\n const merkleContext = mintInterface.merkleContext;\n const outputQueue = getOutputQueue(merkleContext);\n\n const addressTreeInfo = getDefaultAddressTreeInfo();\n const data = encodeUpdateMetadataInstructionData({\n splMint: mintInterface.mintContext.splMint,\n addressTree: addressTreeInfo.tree,\n leafIndex: merkleContext.leafIndex,\n rootIndex: validityProof.rootIndices[0],\n proof: validityProof.compressedProof,\n mintInterface,\n action,\n });\n\n const sys = defaultStaticAccountsStruct();\n const keys = [\n {\n pubkey: LightSystemProgram.programId,\n isSigner: false,\n isWritable: false,\n },\n { pubkey: authority, isSigner: true, isWritable: false },\n { pubkey: payer, isSigner: true, isWritable: true },\n {\n pubkey: CompressedTokenProgram.deriveCpiAuthorityPda,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: sys.registeredProgramPda,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: sys.accountCompressionAuthority,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: sys.accountCompressionProgram,\n isSigner: false,\n isWritable: false,\n },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n { pubkey: outputQueue, isSigner: false, isWritable: true },\n {\n pubkey: merkleContext.treeInfo.tree,\n isSigner: false,\n isWritable: true,\n },\n {\n pubkey: merkleContext.treeInfo.queue,\n isSigner: false,\n isWritable: true,\n },\n ];\n\n return new TransactionInstruction({\n programId: CTOKEN_PROGRAM_ID,\n keys,\n data,\n });\n}\n\n/**\n * Create instruction for updating a compressed mint's metadata field.\n *\n * Output queue is automatically derived from mintInterface.merkleContext.treeInfo\n * (preferring nextTreeInfo.queue if available for rollover support).\n *\n * @param mintInterface MintInterface from getMintInterface() - must have merkleContext and tokenMetadata\n * @param authority Metadata update authority public key (must sign)\n * @param payer Fee payer public key\n * @param validityProof Validity proof for the compressed mint\n * @param fieldType Field to update: 'name', 'symbol', 'uri', or 'custom'\n * @param value New value for the field\n * @param customKey Custom key name (required if fieldType is 'custom')\n * @param extensionIndex Extension index (default: 0)\n */\nexport function createUpdateMetadataFieldInstruction(\n mintInterface: MintInterface,\n authority: PublicKey,\n payer: PublicKey,\n validityProof: ValidityProofWithContext,\n fieldType: 'name' | 'symbol' | 'uri' | 'custom',\n value: string,\n customKey?: string,\n extensionIndex: number = 0,\n): TransactionInstruction {\n const action: UpdateMetadataAction = {\n type: 'updateField',\n extensionIndex,\n fieldType:\n fieldType === 'name'\n ? 0\n : fieldType === 'symbol'\n ? 1\n : fieldType === 'uri'\n ? 2\n : 3,\n key: customKey || '',\n value,\n };\n\n return createUpdateMetadataInstruction(\n mintInterface,\n authority,\n payer,\n validityProof,\n action,\n );\n}\n\n/**\n * Create instruction for updating a compressed mint's metadata authority.\n *\n * Output queue is automatically derived from mintInterface.merkleContext.treeInfo\n * (preferring nextTreeInfo.queue if available for rollover support).\n *\n * @param mintInterface MintInterface from getMintInterface() - must have merkleContext and tokenMetadata\n * @param currentAuthority Current metadata update authority public key (must sign)\n * @param newAuthority New metadata update authority public key\n * @param payer Fee payer public key\n * @param validityProof Validity proof for the compressed mint\n * @param extensionIndex Extension index (default: 0)\n */\nexport function createUpdateMetadataAuthorityInstruction(\n mintInterface: MintInterface,\n currentAuthority: PublicKey,\n newAuthority: PublicKey,\n payer: PublicKey,\n validityProof: ValidityProofWithContext,\n extensionIndex: number = 0,\n): TransactionInstruction {\n const action: UpdateMetadataAction = {\n type: 'updateAuthority',\n extensionIndex,\n newAuthority,\n };\n\n return createUpdateMetadataInstruction(\n mintInterface,\n currentAuthority,\n payer,\n validityProof,\n action,\n );\n}\n\n/**\n * Create instruction for removing a metadata key from a compressed mint.\n *\n * Output queue is automatically derived from mintInterface.merkleContext.treeInfo\n * (preferring nextTreeInfo.queue if available for rollover support).\n *\n * @param mintInterface MintInterface from getMintInterface() - must have merkleContext and tokenMetadata\n * @param authority Metadata update authority public key (must sign)\n * @param payer Fee payer public key\n * @param validityProof Validity proof for the compressed mint\n * @param key Metadata key to remove\n * @param idempotent If true, don't error if key doesn't exist (default: false)\n * @param extensionIndex Extension index (default: 0)\n */\nexport function createRemoveMetadataKeyInstruction(\n mintInterface: MintInterface,\n authority: PublicKey,\n payer: PublicKey,\n validityProof: ValidityProofWithContext,\n key: string,\n idempotent: boolean = false,\n extensionIndex: number = 0,\n): TransactionInstruction {\n const action: UpdateMetadataAction = {\n type: 'removeKey',\n extensionIndex,\n key,\n idempotent,\n };\n\n return createUpdateMetadataInstruction(\n mintInterface,\n authority,\n payer,\n validityProof,\n action,\n );\n}\n","import {\n PublicKey,\n SystemProgram,\n TransactionInstruction,\n} from '@solana/web3.js';\nimport { Buffer } from 'buffer';\nimport { CTOKEN_PROGRAM_ID } from '@lightprotocol/stateless.js';\nimport { struct, u8, u32, option, vec, array } from '@coral-xyz/borsh';\n\nconst CREATE_ASSOCIATED_TOKEN_ACCOUNT_DISCRIMINATOR = Buffer.from([100]);\nconst CREATE_ASSOCIATED_TOKEN_ACCOUNT_IDEMPOTENT_DISCRIMINATOR = Buffer.from([\n 102,\n]);\n\n// Matches Rust CompressToPubkey struct\nconst CompressToPubkeyLayout = struct([\n u8('bump'),\n array(u8(), 32, 'programId'),\n vec(vec(u8()), 'seeds'),\n]);\n\n// Matches Rust CompressibleExtensionInstructionData struct\nconst CompressibleExtensionInstructionDataLayout = struct([\n u8('tokenAccountVersion'),\n u8('rentPayment'),\n u8('hasTopUp'),\n u8('compressionOnly'),\n u32('writeTopUp'),\n option(CompressToPubkeyLayout, 'compressToAccountPubkey'),\n]);\n\nconst CreateAssociatedTokenAccountInstructionDataLayout = struct([\n u8('bump'),\n option(CompressibleExtensionInstructionDataLayout, 'compressibleConfig'),\n]);\n\nexport interface CompressToPubkey {\n bump: number;\n programId: number[];\n seeds: number[][];\n}\n\nexport interface CompressibleConfig {\n tokenAccountVersion: number;\n rentPayment: number;\n hasTopUp: number;\n compressionOnly: number;\n writeTopUp: number;\n compressToAccountPubkey?: CompressToPubkey | null;\n}\n\nexport interface CreateAssociatedCTokenAccountParams {\n bump: number;\n compressibleConfig?: CompressibleConfig;\n}\n\nfunction getAssociatedCTokenAddressAndBump(\n owner: PublicKey,\n mint: PublicKey,\n): [PublicKey, number] {\n return PublicKey.findProgramAddressSync(\n [owner.toBuffer(), CTOKEN_PROGRAM_ID.toBuffer(), mint.toBuffer()],\n CTOKEN_PROGRAM_ID,\n );\n}\n\nfunction encodeCreateAssociatedCTokenAccountData(\n params: CreateAssociatedCTokenAccountParams,\n idempotent: boolean,\n): Buffer {\n const buffer = Buffer.alloc(2000);\n const len = CreateAssociatedTokenAccountInstructionDataLayout.encode(\n {\n bump: params.bump,\n compressibleConfig: params.compressibleConfig || null,\n },\n buffer,\n );\n\n const discriminator = idempotent\n ? CREATE_ASSOCIATED_TOKEN_ACCOUNT_IDEMPOTENT_DISCRIMINATOR\n : CREATE_ASSOCIATED_TOKEN_ACCOUNT_DISCRIMINATOR;\n\n return Buffer.concat([discriminator, buffer.subarray(0, len)]);\n}\n\nexport interface CreateAssociatedCTokenAccountInstructionParams {\n feePayer: PublicKey;\n owner: PublicKey;\n mint: PublicKey;\n compressibleConfig?: CompressibleConfig;\n configAccount?: PublicKey;\n rentPayerPda?: PublicKey;\n}\n\n/**\n * Create instruction for creating an associated compressed token account.\n *\n * @param feePayer Fee payer public key.\n * @param owner Owner of the associated token account.\n * @param mint Mint address.\n * @param compressibleConfig Optional compressible configuration.\n * @param configAccount Optional config account.\n * @param rentPayerPda Optional rent payer PDA.\n */\n// TODO: use createAssociatedCTokenAccount2.\nexport function createAssociatedCTokenAccountInstruction(\n feePayer: PublicKey,\n owner: PublicKey,\n mint: PublicKey,\n compressibleConfig?: CompressibleConfig,\n configAccount?: PublicKey,\n rentPayerPda?: PublicKey,\n): TransactionInstruction {\n const [associatedTokenAccount, bump] = getAssociatedCTokenAddressAndBump(\n owner,\n mint,\n );\n\n const data = encodeCreateAssociatedCTokenAccountData(\n {\n bump,\n compressibleConfig,\n },\n false,\n );\n\n // Account order per Rust processor:\n // 0. owner (non-mut, non-signer)\n // 1. mint (non-mut, non-signer)\n // 2. fee_payer (signer, mut)\n // 3. associated_token_account (mut)\n // 4. system_program\n // 5. optional accounts (config, rent_payer, etc.)\n const keys = [\n { pubkey: owner, isSigner: false, isWritable: false },\n { pubkey: mint, isSigner: false, isWritable: false },\n { pubkey: feePayer, isSigner: true, isWritable: true },\n {\n pubkey: associatedTokenAccount,\n isSigner: false,\n isWritable: true,\n },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n ];\n\n if (compressibleConfig && configAccount && rentPayerPda) {\n keys.push(\n { pubkey: configAccount, isSigner: false, isWritable: false },\n { pubkey: rentPayerPda, isSigner: false, isWritable: true },\n );\n }\n\n return new TransactionInstruction({\n programId: CTOKEN_PROGRAM_ID,\n keys,\n data,\n });\n}\n\n/**\n * Create idempotent instruction for creating an associated compressed token account.\n *\n * @param feePayer Fee payer public key.\n * @param owner Owner of the associated token account.\n * @param mint Mint address.\n * @param compressibleConfig Optional compressible configuration.\n * @param configAccount Optional config account.\n * @param rentPayerPda Optional rent payer PDA.\n */\nexport function createAssociatedCTokenAccountIdempotentInstruction(\n feePayer: PublicKey,\n owner: PublicKey,\n mint: PublicKey,\n compressibleConfig?: CompressibleConfig,\n configAccount?: PublicKey,\n rentPayerPda?: PublicKey,\n): TransactionInstruction {\n const [associatedTokenAccount, bump] = getAssociatedCTokenAddressAndBump(\n owner,\n mint,\n );\n\n const data = encodeCreateAssociatedCTokenAccountData(\n {\n bump,\n compressibleConfig,\n },\n true,\n );\n\n const keys = [\n { pubkey: owner, isSigner: false, isWritable: false },\n { pubkey: mint, isSigner: false, isWritable: false },\n { pubkey: feePayer, isSigner: true, isWritable: true },\n {\n pubkey: associatedTokenAccount,\n isSigner: false,\n isWritable: true,\n },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n ];\n\n if (compressibleConfig && configAccount && rentPayerPda) {\n keys.push(\n { pubkey: configAccount, isSigner: false, isWritable: false },\n { pubkey: rentPayerPda, isSigner: false, isWritable: true },\n );\n }\n\n return new TransactionInstruction({\n programId: CTOKEN_PROGRAM_ID,\n keys,\n data,\n });\n}\n","import {\n ASSOCIATED_TOKEN_PROGRAM_ID,\n TOKEN_PROGRAM_ID,\n TOKEN_2022_PROGRAM_ID,\n getAssociatedTokenAddressSync,\n} from '@solana/spl-token';\nimport { CTOKEN_PROGRAM_ID } from '@lightprotocol/stateless.js';\nimport { PublicKey } from '@solana/web3.js';\n\n/**\n * Get ATA program ID for a token program ID\n * @param tokenProgramId Token program ID\n * @returns ATA program ID\n */\nexport function getAtaProgramId(tokenProgramId: PublicKey): PublicKey {\n if (tokenProgramId.equals(CTOKEN_PROGRAM_ID)) {\n return CTOKEN_PROGRAM_ID;\n }\n return ASSOCIATED_TOKEN_PROGRAM_ID;\n}\n\n/** ATA type for validation result */\nexport type AtaType = 'spl' | 'token2022' | 'ctoken';\n\n/** Result of ATA validation */\nexport interface AtaValidationResult {\n valid: true;\n type: AtaType;\n programId: PublicKey;\n}\n\n/**\n * Check if an ATA address matches the expected derivation from mint+owner.\n *\n * Pass programId for fast path.\n *\n * @param ata ATA address to check\n * @param mint Mint address\n * @param owner Owner address\n * @param programId Optional: if known, only check this program's ATA\n * @returns Result with detected type, or throws on mismatch\n */\nexport function checkAtaAddress(\n ata: PublicKey,\n mint: PublicKey,\n owner: PublicKey,\n programId?: PublicKey,\n): AtaValidationResult {\n // fast path\n if (programId) {\n const expected = getAssociatedTokenAddressSync(\n mint,\n owner,\n false,\n programId,\n getAtaProgramId(programId),\n );\n if (ata.equals(expected)) {\n return {\n valid: true,\n type: programIdToAtaType(programId),\n programId,\n };\n }\n throw new Error(\n `ATA address mismatch for ${programId.toBase58()}. ` +\n `Expected: ${expected.toBase58()}, got: ${ata.toBase58()}`,\n );\n }\n\n let ctokenExpected: PublicKey;\n let splExpected: PublicKey;\n let t22Expected: PublicKey;\n\n // c-token\n ctokenExpected = getAssociatedTokenAddressSync(\n mint,\n owner,\n false,\n CTOKEN_PROGRAM_ID,\n getAtaProgramId(CTOKEN_PROGRAM_ID),\n );\n if (ata.equals(ctokenExpected)) {\n return {\n valid: true,\n type: 'ctoken',\n programId: CTOKEN_PROGRAM_ID,\n };\n }\n\n // SPL\n splExpected = getAssociatedTokenAddressSync(\n mint,\n owner,\n false,\n TOKEN_PROGRAM_ID,\n getAtaProgramId(TOKEN_PROGRAM_ID),\n );\n if (ata.equals(splExpected)) {\n return { valid: true, type: 'spl', programId: TOKEN_PROGRAM_ID };\n }\n\n // T22\n t22Expected = getAssociatedTokenAddressSync(\n mint,\n owner,\n false,\n TOKEN_2022_PROGRAM_ID,\n getAtaProgramId(TOKEN_2022_PROGRAM_ID),\n );\n\n if (ata.equals(t22Expected)) {\n return {\n valid: true,\n type: 'token2022',\n programId: TOKEN_2022_PROGRAM_ID,\n };\n }\n\n throw new Error(\n `ATA address does not match any valid derivation from mint+owner. ` +\n `Got: ${ata.toBase58()}, expected one of: ` +\n `c-token=${ctokenExpected.toBase58()}, ` +\n `SPL=${splExpected.toBase58()}, ` +\n `T22=${t22Expected.toBase58()}`,\n );\n}\n\n/**\n * Convert programId to AtaType\n */\nfunction programIdToAtaType(programId: PublicKey): AtaType {\n if (programId.equals(CTOKEN_PROGRAM_ID)) return 'ctoken';\n if (programId.equals(TOKEN_PROGRAM_ID)) return 'spl';\n if (programId.equals(TOKEN_2022_PROGRAM_ID)) return 'token2022';\n throw new Error(`Unknown program ID: ${programId.toBase58()}`);\n}\n","import { PublicKey, TransactionInstruction } from '@solana/web3.js';\nimport {\n TOKEN_PROGRAM_ID,\n createAssociatedTokenAccountInstruction as createSplAssociatedTokenAccountInstruction,\n createAssociatedTokenAccountIdempotentInstruction as createSplAssociatedTokenAccountIdempotentInstruction,\n} from '@solana/spl-token';\nimport { CTOKEN_PROGRAM_ID } from '@lightprotocol/stateless.js';\nimport { getAtaProgramId } from '../ata-utils';\nimport {\n createAssociatedCTokenAccountInstruction,\n createAssociatedCTokenAccountIdempotentInstruction,\n CompressibleConfig,\n} from './create-associated-ctoken';\n\n/**\n * c-token-specific config for createAssociatedTokenAccountInterfaceInstruction\n */\nexport interface CTokenConfig {\n compressibleConfig?: CompressibleConfig;\n configAccount?: PublicKey;\n rentPayerPda?: PublicKey;\n}\n\n// Keep old interface type for backwards compatibility export\nexport interface CreateAssociatedTokenAccountInterfaceInstructionParams {\n payer: PublicKey;\n associatedToken: PublicKey;\n owner: PublicKey;\n mint: PublicKey;\n programId?: PublicKey;\n associatedTokenProgramId?: PublicKey;\n compressibleConfig?: CompressibleConfig;\n configAccount?: PublicKey;\n rentPayerPda?: PublicKey;\n}\n\n/**\n * Create instruction for creating an associated token account (SPL, Token-2022,\n * or c-token). Follows SPL Token API signature with optional c-token config at the\n * end.\n *\n * @param payer Fee payer public key.\n * @param associatedToken Associated token account address.\n * @param owner Owner of the associated token account.\n * @param mint Mint address.\n * @param programId Token program ID (default: TOKEN_PROGRAM_ID).\n * @param associatedTokenProgramId Associated token program ID.\n * @param ctokenConfig Optional c-token-specific configuration.\n */\nexport function createAssociatedTokenAccountInterfaceInstruction(\n payer: PublicKey,\n associatedToken: PublicKey,\n owner: PublicKey,\n mint: PublicKey,\n programId: PublicKey = TOKEN_PROGRAM_ID,\n associatedTokenProgramId?: PublicKey,\n ctokenConfig?: CTokenConfig,\n): TransactionInstruction {\n const effectiveAssociatedTokenProgramId =\n associatedTokenProgramId ?? getAtaProgramId(programId);\n\n if (programId.equals(CTOKEN_PROGRAM_ID)) {\n return createAssociatedCTokenAccountInstruction(\n payer,\n owner,\n mint,\n ctokenConfig?.compressibleConfig,\n ctokenConfig?.configAccount,\n ctokenConfig?.rentPayerPda,\n );\n } else {\n return createSplAssociatedTokenAccountInstruction(\n payer,\n associatedToken,\n owner,\n mint,\n programId,\n effectiveAssociatedTokenProgramId,\n );\n }\n}\n\n/**\n * Create idempotent instruction for creating an associated token account (SPL,\n * Token-2022, or c-token). Follows SPL Token API signature with optional c-token\n * config at the end.\n *\n * @param payer Fee payer public key.\n * @param associatedToken Associated token account address.\n * @param owner Owner of the associated token account.\n * @param mint Mint address.\n * @param programId Token program ID (default: TOKEN_PROGRAM_ID).\n * @param associatedTokenProgramId Associated token program ID.\n * @param ctokenConfig Optional c-token-specific configuration.\n */\nexport function createAssociatedTokenAccountInterfaceIdempotentInstruction(\n payer: PublicKey,\n associatedToken: PublicKey,\n owner: PublicKey,\n mint: PublicKey,\n programId: PublicKey = TOKEN_PROGRAM_ID,\n associatedTokenProgramId?: PublicKey,\n ctokenConfig?: CTokenConfig,\n): TransactionInstruction {\n const effectiveAssociatedTokenProgramId =\n associatedTokenProgramId ?? getAtaProgramId(programId);\n\n if (programId.equals(CTOKEN_PROGRAM_ID)) {\n return createAssociatedCTokenAccountIdempotentInstruction(\n payer,\n owner,\n mint,\n ctokenConfig?.compressibleConfig,\n ctokenConfig?.configAccount,\n ctokenConfig?.rentPayerPda,\n );\n } else {\n return createSplAssociatedTokenAccountIdempotentInstruction(\n payer,\n associatedToken,\n owner,\n mint,\n programId,\n effectiveAssociatedTokenProgramId,\n );\n }\n}\n\n/**\n * Short alias for createAssociatedTokenAccountInterfaceIdempotentInstruction.\n */\nexport const createAtaInterfaceIdempotentInstruction =\n createAssociatedTokenAccountInterfaceIdempotentInstruction;\n","import {\n PublicKey,\n SystemProgram,\n TransactionInstruction,\n} from '@solana/web3.js';\nimport { Buffer } from 'buffer';\nimport {\n ValidityProofWithContext,\n CTOKEN_PROGRAM_ID,\n LightSystemProgram,\n defaultStaticAccountsStruct,\n deriveAddressV2,\n getDefaultAddressTreeInfo,\n MerkleContext,\n TreeInfo,\n} from '@lightprotocol/stateless.js';\nimport { CompressedTokenProgram } from '../../program';\nimport { MintInstructionData } from '../layout/layout-mint';\nimport {\n encodeMintActionInstructionData,\n MintActionCompressedInstructionData,\n} from '../layout/layout-mint-action';\n\ninterface EncodeMintToCTokenInstructionParams {\n addressTree: PublicKey;\n leafIndex: number;\n rootIndex: number;\n proof: { a: number[]; b: number[]; c: number[] } | null;\n mintData: MintInstructionData;\n recipientAccountIndex: number;\n amount: number | bigint;\n}\n\nfunction encodeMintToCTokenInstructionData(\n params: EncodeMintToCTokenInstructionParams,\n): Buffer {\n const compressedAddress = deriveAddressV2(\n params.mintData.splMint.toBytes(),\n params.addressTree,\n CTOKEN_PROGRAM_ID,\n );\n\n // TokenMetadata extension not supported in mintTo instruction\n if (params.mintData.metadata) {\n throw new Error(\n 'TokenMetadata extension not supported in mintTo instruction',\n );\n }\n\n const instructionData: MintActionCompressedInstructionData = {\n leafIndex: params.leafIndex,\n proveByIndex: true,\n rootIndex: params.rootIndex,\n compressedAddress: Array.from(compressedAddress.toBytes()),\n tokenPoolBump: 0,\n tokenPoolIndex: 0,\n maxTopUp: 0,\n createMint: null,\n actions: [\n {\n mintToCToken: {\n accountIndex: params.recipientAccountIndex,\n amount: BigInt(params.amount.toString()),\n },\n },\n ],\n proof: params.proof,\n cpiContext: null,\n mint: {\n supply: params.mintData.supply,\n decimals: params.mintData.decimals,\n metadata: {\n version: params.mintData.version,\n splMintInitialized: params.mintData.splMintInitialized,\n mint: params.mintData.splMint,\n },\n mintAuthority: params.mintData.mintAuthority,\n freezeAuthority: params.mintData.freezeAuthority,\n extensions: null,\n },\n };\n\n return encodeMintActionInstructionData(instructionData);\n}\n\n// Keep old interface type for backwards compatibility export\nexport interface CreateMintToInstructionParams {\n mintSigner: PublicKey;\n authority: PublicKey;\n payer: PublicKey;\n validityProof: ValidityProofWithContext;\n merkleContext: MerkleContext;\n mintData: MintInstructionData;\n outputStateTreeInfo: TreeInfo;\n tokensOutQueue: PublicKey;\n recipientAccount: PublicKey;\n amount: number | bigint;\n}\n\n/**\n * Create instruction for minting compressed tokens to an onchain token account.\n *\n * @param authority Mint authority public key.\n * @param payer Fee payer public key.\n * @param validityProof Validity proof for the compressed mint.\n * @param merkleContext Merkle context of the compressed mint.\n * @param mintData Mint instruction data.\n * @param outputStateTreeInfo Output state tree info.\n * @param recipientAccount Recipient onchain token account address.\n * @param amount Amount to mint.\n */\nexport function createMintToInstruction(\n authority: PublicKey,\n payer: PublicKey,\n validityProof: ValidityProofWithContext,\n merkleContext: MerkleContext,\n mintData: MintInstructionData,\n outputStateTreeInfo: TreeInfo,\n recipientAccount: PublicKey,\n amount: number | bigint,\n): TransactionInstruction {\n const addressTreeInfo = getDefaultAddressTreeInfo();\n const data = encodeMintToCTokenInstructionData({\n addressTree: addressTreeInfo.tree,\n leafIndex: merkleContext.leafIndex,\n rootIndex: validityProof.rootIndices[0],\n proof: validityProof.compressedProof,\n mintData,\n recipientAccountIndex: 0,\n amount,\n });\n\n const sys = defaultStaticAccountsStruct();\n const keys = [\n {\n pubkey: LightSystemProgram.programId,\n isSigner: false,\n isWritable: false,\n },\n { pubkey: authority, isSigner: true, isWritable: false },\n { pubkey: payer, isSigner: true, isWritable: true },\n {\n pubkey: CompressedTokenProgram.deriveCpiAuthorityPda,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: sys.registeredProgramPda,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: sys.accountCompressionAuthority,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: sys.accountCompressionProgram,\n isSigner: false,\n isWritable: false,\n },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n {\n pubkey: outputStateTreeInfo.queue,\n isSigner: false,\n isWritable: true,\n },\n {\n pubkey: merkleContext.treeInfo.tree,\n isSigner: false,\n isWritable: true,\n },\n {\n pubkey: merkleContext.treeInfo.queue,\n isSigner: false,\n isWritable: true,\n },\n // Note: tokensOutQueue is NOT included for MintToCToken-only actions.\n // MintToCToken mints to existing decompressed accounts, doesn't create\n // new compressed outputs so Rust expects no tokens_out_queue account.\n ];\n\n keys.push({ pubkey: recipientAccount, isSigner: false, isWritable: true });\n\n return new TransactionInstruction({\n programId: CTOKEN_PROGRAM_ID,\n keys,\n data,\n });\n}\n","import {\n PublicKey,\n SystemProgram,\n TransactionInstruction,\n} from '@solana/web3.js';\nimport { Buffer } from 'buffer';\nimport {\n ValidityProofWithContext,\n CTOKEN_PROGRAM_ID,\n LightSystemProgram,\n defaultStaticAccountsStruct,\n deriveAddressV2,\n getDefaultAddressTreeInfo,\n MerkleContext,\n TreeInfo,\n getOutputQueue,\n} from '@lightprotocol/stateless.js';\nimport { CompressedTokenProgram } from '../../program';\nimport { MintInstructionData } from '../layout/layout-mint';\nimport {\n encodeMintActionInstructionData,\n MintActionCompressedInstructionData,\n} from '../layout/layout-mint-action';\nimport { TokenDataVersion } from '../../constants';\n\ninterface EncodeCompressedMintToInstructionParams {\n addressTree: PublicKey;\n leafIndex: number;\n rootIndex: number;\n proof: { a: number[]; b: number[]; c: number[] } | null;\n mintData: MintInstructionData;\n recipients: Array<{ recipient: PublicKey; amount: number | bigint }>;\n tokenAccountVersion: number;\n}\n\nfunction encodeCompressedMintToInstructionData(\n params: EncodeCompressedMintToInstructionParams,\n): Buffer {\n const compressedAddress = deriveAddressV2(\n params.mintData.splMint.toBytes(),\n params.addressTree,\n CTOKEN_PROGRAM_ID,\n );\n\n // TokenMetadata extension not supported in mintTo instruction\n if (params.mintData.metadata) {\n throw new Error(\n 'TokenMetadata extension not supported in mintTo instruction',\n );\n }\n\n const instructionData: MintActionCompressedInstructionData = {\n leafIndex: params.leafIndex,\n proveByIndex: true,\n rootIndex: params.rootIndex,\n compressedAddress: Array.from(compressedAddress.toBytes()),\n tokenPoolBump: 0,\n tokenPoolIndex: 0,\n maxTopUp: 0,\n createMint: null,\n actions: [\n {\n mintToCompressed: {\n tokenAccountVersion: params.tokenAccountVersion,\n recipients: params.recipients.map(r => ({\n recipient: r.recipient,\n amount: BigInt(r.amount.toString()),\n })),\n },\n },\n ],\n proof: params.proof,\n cpiContext: null,\n mint: {\n supply: params.mintData.supply,\n decimals: params.mintData.decimals,\n metadata: {\n version: params.mintData.version,\n splMintInitialized: params.mintData.splMintInitialized,\n mint: params.mintData.splMint,\n },\n mintAuthority: params.mintData.mintAuthority,\n freezeAuthority: params.mintData.freezeAuthority,\n extensions: null,\n },\n };\n\n return encodeMintActionInstructionData(instructionData);\n}\n\n// Keep old interface type for backwards compatibility export\nexport interface CreateMintToCompressedInstructionParams {\n mintSigner: PublicKey;\n authority: PublicKey;\n payer: PublicKey;\n validityProof: ValidityProofWithContext;\n merkleContext: MerkleContext;\n mintData: MintInstructionData;\n recipients: Array<{ recipient: PublicKey; amount: number | bigint }>;\n outputStateTreeInfo?: TreeInfo;\n tokenAccountVersion?: TokenDataVersion;\n}\n\n/**\n * Create instruction for minting tokens from a c-mint to compressed accounts.\n * To mint to onchain token accounts across SPL/T22/c-mints, use\n * {@link createMintToInterfaceInstruction} instead.\n *\n * @param authority Mint authority public key.\n * @param payer Fee payer public key.\n * @param validityProof Validity proof for the compressed mint.\n * @param merkleContext Merkle context of the compressed mint.\n * @param mintData Mint instruction data.\n * @param recipients Array of recipients with amounts.\n * @param outputStateTreeInfo Optional output state tree info. Uses merkle\n * context queue if not provided.\n * @param tokenAccountVersion Token account version (default:\n * TokenDataVersion.ShaFlat).\n */\nexport function createMintToCompressedInstruction(\n authority: PublicKey,\n payer: PublicKey,\n validityProof: ValidityProofWithContext,\n merkleContext: MerkleContext,\n mintData: MintInstructionData,\n recipients: Array<{ recipient: PublicKey; amount: number | bigint }>,\n outputStateTreeInfo?: TreeInfo,\n tokenAccountVersion: TokenDataVersion = TokenDataVersion.ShaFlat,\n): TransactionInstruction {\n const addressTreeInfo = getDefaultAddressTreeInfo();\n const data = encodeCompressedMintToInstructionData({\n addressTree: addressTreeInfo.tree,\n leafIndex: merkleContext.leafIndex,\n rootIndex: validityProof.rootIndices[0],\n proof: validityProof.compressedProof,\n mintData,\n recipients,\n tokenAccountVersion,\n });\n\n // Use outputStateTreeInfo.queue if provided, otherwise derive from merkleContext\n const outputQueue =\n outputStateTreeInfo?.queue ?? getOutputQueue(merkleContext);\n\n const sys = defaultStaticAccountsStruct();\n const keys = [\n {\n pubkey: LightSystemProgram.programId,\n isSigner: false,\n isWritable: false,\n },\n { pubkey: authority, isSigner: true, isWritable: false },\n { pubkey: payer, isSigner: true, isWritable: true },\n {\n pubkey: CompressedTokenProgram.deriveCpiAuthorityPda,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: sys.registeredProgramPda,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: sys.accountCompressionAuthority,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: sys.accountCompressionProgram,\n isSigner: false,\n isWritable: false,\n },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n { pubkey: outputQueue, isSigner: false, isWritable: true },\n {\n pubkey: merkleContext.treeInfo.tree,\n isSigner: false,\n isWritable: true,\n },\n {\n pubkey: merkleContext.treeInfo.queue,\n isSigner: false,\n isWritable: true,\n },\n // Use same queue for tokens out\n { pubkey: outputQueue, isSigner: false, isWritable: true },\n ];\n\n return new TransactionInstruction({\n programId: CTOKEN_PROGRAM_ID,\n keys,\n data,\n });\n}\n","import { PublicKey, TransactionInstruction } from '@solana/web3.js';\nimport {\n getOutputTreeInfo,\n ValidityProofWithContext,\n} from '@lightprotocol/stateless.js';\nimport { createMintToInstruction as createSplMintToInstruction } from '@solana/spl-token';\nimport { createMintToInstruction as createCtokenMintToInstruction } from './mint-to';\nimport { MintInterface } from '../get-mint-interface';\n\n// Keep old interface type for backwards compatibility export\nexport interface CreateMintToInterfaceInstructionParams {\n mintInterface: MintInterface;\n destination: PublicKey;\n authority: PublicKey;\n payer: PublicKey;\n amount: number | bigint;\n validityProof?: ValidityProofWithContext;\n multiSigners?: PublicKey[];\n}\n\n/**\n * Create mint-to instruction for SPL, Token-2022, or compressed token mints.\n * This instruction ONLY mints to decompressed/onchain token accounts.\n *\n * @param mintInterface Mint interface (SPL, Token-2022, or compressed).\n * @param destination Destination onchain token account address.\n * @param authority Mint authority public key.\n * @param payer Fee payer public key.\n * @param amount Amount to mint.\n * @param validityProof Validity proof (required for compressed mints).\n * @param multiSigners Multi-signature signer public keys.\n */\nexport function createMintToInterfaceInstruction(\n mintInterface: MintInterface,\n destination: PublicKey,\n authority: PublicKey,\n payer: PublicKey,\n amount: number | bigint,\n validityProof?: ValidityProofWithContext,\n multiSigners: PublicKey[] = [],\n): TransactionInstruction {\n const mint = mintInterface.mint.address;\n const programId = mintInterface.programId;\n\n // SPL/T22\n if (!mintInterface.merkleContext) {\n return createSplMintToInstruction(\n mint,\n destination,\n authority,\n BigInt(amount.toString()),\n multiSigners,\n programId,\n );\n }\n\n if (!validityProof) {\n throw new Error('Validity proof required for c-token mint-to');\n }\n if (!mintInterface.mintContext) {\n throw new Error('mintContext required for c-token mint-to');\n }\n\n const mintData = {\n supply: mintInterface.mint.supply,\n decimals: mintInterface.mint.decimals,\n mintAuthority: mintInterface.mint.mintAuthority,\n freezeAuthority: mintInterface.mint.freezeAuthority,\n splMint: mintInterface.mintContext.splMint,\n splMintInitialized: mintInterface.mintContext.splMintInitialized,\n version: mintInterface.mintContext.version,\n metadata: mintInterface.tokenMetadata\n ? {\n updateAuthority:\n mintInterface.tokenMetadata.updateAuthority || null,\n name: mintInterface.tokenMetadata.name,\n symbol: mintInterface.tokenMetadata.symbol,\n uri: mintInterface.tokenMetadata.uri,\n }\n : undefined,\n };\n\n return createCtokenMintToInstruction(\n authority,\n payer,\n validityProof,\n mintInterface.merkleContext,\n mintData,\n getOutputTreeInfo(mintInterface.merkleContext),\n destination,\n amount,\n );\n}\n","import { PublicKey, Signer, TransactionInstruction } from '@solana/web3.js';\nimport { CTOKEN_PROGRAM_ID } from '@lightprotocol/stateless.js';\nimport {\n TOKEN_2022_PROGRAM_ID,\n TOKEN_PROGRAM_ID,\n createTransferInstruction as createSplTransferInstruction,\n} from '@solana/spl-token';\n\n/**\n * c-token transfer instruction discriminator\n */\nconst CTOKEN_TRANSFER_DISCRIMINATOR = 3;\n\n/**\n * Create a c-token transfer instruction.\n *\n * @param source Source c-token account\n * @param destination Destination c-token account\n * @param owner Owner of the source account (signer)\n * @param amount Amount to transfer\n * @param payer Payer for compressible extension top-up (optional)\n * @returns Transaction instruction for c-token transfer\n */\nexport function createCTokenTransferInstruction(\n source: PublicKey,\n destination: PublicKey,\n owner: PublicKey,\n amount: number | bigint,\n payer?: PublicKey,\n): TransactionInstruction {\n // Instruction data format (from CTOKEN_TRANSFER.md):\n // byte 0: discriminator (3)\n // byte 1: padding (0)\n // bytes 2-9: amount (u64 LE) - SPL TokenInstruction::Transfer format\n const data = Buffer.alloc(10);\n data.writeUInt8(CTOKEN_TRANSFER_DISCRIMINATOR, 0);\n data.writeUInt8(0, 1); // padding\n data.writeBigUInt64LE(BigInt(amount), 2);\n\n const keys = [\n { pubkey: source, isSigner: false, isWritable: true },\n { pubkey: destination, isSigner: false, isWritable: true },\n { pubkey: owner, isSigner: true, isWritable: false },\n ];\n\n // Add payer as 4th account if provided and different from owner\n // (for compressible extension top-up)\n if (payer && !payer.equals(owner)) {\n keys.push({ pubkey: payer, isSigner: true, isWritable: true });\n }\n\n return new TransactionInstruction({\n programId: CTOKEN_PROGRAM_ID,\n keys,\n data,\n });\n}\n\n/**\n * Construct a transfer instruction for SPL/T22/c-token. Defaults to c-token\n * program. For cross-program transfers (SPL <> c-token), use `wrap`/`unwrap`.\n *\n * @param source Source token account\n * @param destination Destination token account\n * @param owner Owner of the source account (signer)\n * @param amount Amount to transfer\n * @param payer Payer for compressible top-up (optional)\n * @returns instruction for c-token transfer\n */\nexport function createTransferInterfaceInstruction(\n source: PublicKey,\n destination: PublicKey,\n owner: PublicKey,\n amount: number | bigint,\n multiSigners: (Signer | PublicKey)[] = [],\n programId: PublicKey = CTOKEN_PROGRAM_ID,\n payer?: PublicKey,\n): TransactionInstruction {\n if (programId.equals(CTOKEN_PROGRAM_ID)) {\n if (multiSigners.length > 0) {\n throw new Error(\n 'c-token transfer does not support multi-signers. Use a single owner.',\n );\n }\n return createCTokenTransferInstruction(\n source,\n destination,\n owner,\n amount,\n payer,\n );\n }\n\n if (\n programId.equals(TOKEN_PROGRAM_ID) ||\n programId.equals(TOKEN_2022_PROGRAM_ID)\n ) {\n return createSplTransferInstruction(\n source,\n destination,\n owner,\n amount,\n multiSigners.map(pk =>\n pk instanceof PublicKey ? pk : pk.publicKey,\n ),\n programId,\n );\n }\n\n throw new Error(`Unsupported program ID: ${programId.toBase58()}`);\n}\n","import {\n struct,\n option,\n vec,\n bool,\n u64,\n u8,\n u16,\n u32,\n array,\n} from '@coral-xyz/borsh';\nimport { Buffer } from 'buffer';\nimport { bn } from '@lightprotocol/stateless.js';\n\n// Transfer2 discriminator = 101\nexport const TRANSFER2_DISCRIMINATOR = Buffer.from([101]);\n\n// CompressionMode enum values\nexport const COMPRESSION_MODE_COMPRESS = 0;\nexport const COMPRESSION_MODE_DECOMPRESS = 1;\nexport const COMPRESSION_MODE_COMPRESS_AND_CLOSE = 2;\n\n/**\n * Compression struct for Transfer2 instruction\n */\nexport interface Compression {\n mode: number;\n amount: bigint;\n mint: number;\n sourceOrRecipient: number;\n authority: number;\n poolAccountIndex: number;\n poolIndex: number;\n bump: number;\n decimals: number;\n}\n\n/**\n * Packed merkle context for compressed accounts\n */\nexport interface PackedMerkleContext {\n merkleTreePubkeyIndex: number;\n queuePubkeyIndex: number;\n leafIndex: number;\n proveByIndex: boolean;\n}\n\n/**\n * Input token data with context for Transfer2\n */\nexport interface MultiInputTokenDataWithContext {\n owner: number;\n amount: bigint;\n hasDelegate: boolean;\n delegate: number;\n mint: number;\n version: number;\n merkleContext: PackedMerkleContext;\n rootIndex: number;\n}\n\n/**\n * Output token data for Transfer2\n */\nexport interface MultiTokenTransferOutputData {\n owner: number;\n amount: bigint;\n hasDelegate: boolean;\n delegate: number;\n mint: number;\n version: number;\n}\n\n/**\n * CPI context for Transfer2\n */\nexport interface CompressedCpiContext {\n setContext: boolean;\n firstSetContext: boolean;\n cpiContextAccountIndex: number;\n}\n\n/**\n * Full Transfer2 instruction data\n */\nexport interface Transfer2InstructionData {\n withTransactionHash: boolean;\n withLamportsChangeAccountMerkleTreeIndex: boolean;\n lamportsChangeAccountMerkleTreeIndex: number;\n lamportsChangeAccountOwnerIndex: number;\n outputQueue: number;\n maxTopUp: number;\n cpiContext: CompressedCpiContext | null;\n compressions: Compression[] | null;\n proof: { a: number[]; b: number[]; c: number[] } | null;\n inTokenData: MultiInputTokenDataWithContext[];\n outTokenData: MultiTokenTransferOutputData[];\n inLamports: bigint[] | null;\n outLamports: bigint[] | null;\n inTlv: number[][] | null;\n outTlv: number[][] | null;\n}\n\n// Borsh layouts\nconst CompressionLayout = struct([\n u8('mode'),\n u64('amount'),\n u8('mint'),\n u8('sourceOrRecipient'),\n u8('authority'),\n u8('poolAccountIndex'),\n u8('poolIndex'),\n u8('bump'),\n u8('decimals'),\n]);\n\nconst PackedMerkleContextLayout = struct([\n u8('merkleTreePubkeyIndex'),\n u8('queuePubkeyIndex'),\n u32('leafIndex'),\n bool('proveByIndex'),\n]);\n\nconst MultiInputTokenDataWithContextLayout = struct([\n u8('owner'),\n u64('amount'),\n bool('hasDelegate'),\n u8('delegate'),\n u8('mint'),\n u8('version'),\n PackedMerkleContextLayout.replicate('merkleContext'),\n u16('rootIndex'),\n]);\n\nconst MultiTokenTransferOutputDataLayout = struct([\n u8('owner'),\n u64('amount'),\n bool('hasDelegate'),\n u8('delegate'),\n u8('mint'),\n u8('version'),\n]);\n\nconst CompressedCpiContextLayout = struct([\n bool('setContext'),\n bool('firstSetContext'),\n u8('cpiContextAccountIndex'),\n]);\n\nconst CompressedProofLayout = struct([\n array(u8(), 32, 'a'),\n array(u8(), 64, 'b'),\n array(u8(), 32, 'c'),\n]);\n\nconst Transfer2InstructionDataLayout = struct([\n bool('withTransactionHash'),\n bool('withLamportsChangeAccountMerkleTreeIndex'),\n u8('lamportsChangeAccountMerkleTreeIndex'),\n u8('lamportsChangeAccountOwnerIndex'),\n u8('outputQueue'),\n u16('maxTopUp'),\n option(CompressedCpiContextLayout, 'cpiContext'),\n option(vec(CompressionLayout), 'compressions'),\n option(CompressedProofLayout, 'proof'),\n vec(MultiInputTokenDataWithContextLayout, 'inTokenData'),\n vec(MultiTokenTransferOutputDataLayout, 'outTokenData'),\n option(vec(u64()), 'inLamports'),\n option(vec(u64()), 'outLamports'),\n option(vec(vec(u8())), 'inTlv'),\n option(vec(vec(u8())), 'outTlv'),\n]);\n\n/**\n * Encode Transfer2 instruction data using Borsh\n */\nexport function encodeTransfer2InstructionData(\n data: Transfer2InstructionData,\n): Buffer {\n // Convert bigint values to BN for Borsh encoding\n const encodableData = {\n ...data,\n compressions:\n data.compressions?.map(c => ({\n ...c,\n amount: bn(c.amount.toString()),\n })) ?? null,\n inTokenData: data.inTokenData.map(t => ({\n ...t,\n amount: bn(t.amount.toString()),\n })),\n outTokenData: data.outTokenData.map(t => ({\n ...t,\n amount: bn(t.amount.toString()),\n })),\n inLamports: data.inLamports?.map(v => bn(v.toString())) ?? null,\n outLamports: data.outLamports?.map(v => bn(v.toString())) ?? null,\n };\n\n const buffer = Buffer.alloc(2000); // Allocate enough space\n const len = Transfer2InstructionDataLayout.encode(encodableData, buffer);\n return Buffer.concat([TRANSFER2_DISCRIMINATOR, buffer.subarray(0, len)]);\n}\n\n/**\n * Create a compression struct for wrapping SPL tokens to c-token\n * (compress from SPL ATA)\n */\nexport function createCompressSpl(\n amount: bigint,\n mintIndex: number,\n sourceIndex: number,\n authorityIndex: number,\n poolAccountIndex: number,\n poolIndex: number,\n bump: number,\n): Compression {\n return {\n mode: COMPRESSION_MODE_COMPRESS,\n amount,\n mint: mintIndex,\n sourceOrRecipient: sourceIndex,\n authority: authorityIndex,\n poolAccountIndex,\n poolIndex,\n bump,\n decimals: 0,\n };\n}\n\n/**\n * Create a compression struct for decompressing to c-token ATA\n * @param amount - Amount to decompress\n * @param mintIndex - Index of mint in packed accounts\n * @param recipientIndex - Index of recipient c-token account in packed accounts\n * @param tokenProgramIndex - Index of c-token program in packed accounts (for CPI)\n */\nexport function createDecompressCtoken(\n amount: bigint,\n mintIndex: number,\n recipientIndex: number,\n tokenProgramIndex?: number,\n): Compression {\n return {\n mode: COMPRESSION_MODE_DECOMPRESS,\n amount,\n mint: mintIndex,\n sourceOrRecipient: recipientIndex,\n authority: 0,\n poolAccountIndex: tokenProgramIndex ?? 0,\n poolIndex: 0,\n bump: 0,\n decimals: 0,\n };\n}\n\n/**\n * Create a compression struct for compressing c-token (burn from c-token ATA)\n * Used in unwrap flow: c-token ATA -> pool -> SPL ATA\n * @param amount - Amount to compress (burn from c-token)\n * @param mintIndex - Index of mint in packed accounts\n * @param sourceIndex - Index of source c-token account in packed accounts\n * @param authorityIndex - Index of authority/owner in packed accounts (must sign)\n * @param tokenProgramIndex - Index of c-token program in packed accounts (for CPI)\n */\nexport function createCompressCtoken(\n amount: bigint,\n mintIndex: number,\n sourceIndex: number,\n authorityIndex: number,\n tokenProgramIndex?: number,\n): Compression {\n return {\n mode: COMPRESSION_MODE_COMPRESS,\n amount,\n mint: mintIndex,\n sourceOrRecipient: sourceIndex,\n authority: authorityIndex,\n poolAccountIndex: tokenProgramIndex ?? 0,\n poolIndex: 0,\n bump: 0,\n decimals: 0,\n };\n}\n\n/**\n * Create a compression struct for decompressing SPL tokens\n */\nexport function createDecompressSpl(\n amount: bigint,\n mintIndex: number,\n recipientIndex: number,\n poolAccountIndex: number,\n poolIndex: number,\n bump: number,\n): Compression {\n return {\n mode: COMPRESSION_MODE_DECOMPRESS,\n amount,\n mint: mintIndex,\n sourceOrRecipient: recipientIndex,\n authority: 0,\n poolAccountIndex,\n poolIndex,\n bump,\n decimals: 0,\n };\n}\n","import {\n PublicKey,\n TransactionInstruction,\n SystemProgram,\n} from '@solana/web3.js';\nimport {\n CTOKEN_PROGRAM_ID,\n LightSystemProgram,\n defaultStaticAccountsStruct,\n ParsedTokenAccount,\n ValidityProofWithContext,\n} from '@lightprotocol/stateless.js';\nimport { CompressedTokenProgram } from '../../program';\nimport {\n encodeTransfer2InstructionData,\n Transfer2InstructionData,\n MultiInputTokenDataWithContext,\n COMPRESSION_MODE_DECOMPRESS,\n Compression,\n} from '../layout/layout-transfer2';\nimport { TokenDataVersion } from '../../constants';\nimport { SplInterfaceInfo } from '../../utils/get-token-pool-infos';\n\n/**\n * Get token data version from compressed account discriminator.\n */\nfunction getVersionFromDiscriminator(\n discriminator: number[] | undefined,\n): number {\n if (!discriminator || discriminator.length < 8) {\n // Default to ShaFlat for new accounts without discriminator\n return TokenDataVersion.ShaFlat;\n }\n\n // V1 has discriminator[0] = 2\n if (discriminator[0] === 2) {\n return TokenDataVersion.V1;\n }\n\n // V2 and ShaFlat have version in discriminator[7]\n const versionByte = discriminator[7];\n if (versionByte === 3) {\n return TokenDataVersion.V2;\n }\n if (versionByte === 4) {\n return TokenDataVersion.ShaFlat;\n }\n\n // Default to ShaFlat\n return TokenDataVersion.ShaFlat;\n}\n\n/**\n * Build input token data for Transfer2 from parsed token accounts\n */\nfunction buildInputTokenData(\n accounts: ParsedTokenAccount[],\n rootIndices: number[],\n packedAccountIndices: Map<string, number>,\n): MultiInputTokenDataWithContext[] {\n return accounts.map((acc, i) => {\n const ownerKey = acc.parsed.owner.toBase58();\n const mintKey = acc.parsed.mint.toBase58();\n\n const version = getVersionFromDiscriminator(\n acc.compressedAccount.data?.discriminator,\n );\n\n return {\n owner: packedAccountIndices.get(ownerKey)!,\n amount: BigInt(acc.parsed.amount.toString()),\n hasDelegate: acc.parsed.delegate !== null,\n delegate: acc.parsed.delegate\n ? (packedAccountIndices.get(acc.parsed.delegate.toBase58()) ??\n 0)\n : 0,\n mint: packedAccountIndices.get(mintKey)!,\n version,\n merkleContext: {\n merkleTreePubkeyIndex: packedAccountIndices.get(\n acc.compressedAccount.treeInfo.tree.toBase58(),\n )!,\n queuePubkeyIndex: packedAccountIndices.get(\n acc.compressedAccount.treeInfo.queue.toBase58(),\n )!,\n leafIndex: acc.compressedAccount.leafIndex,\n proveByIndex: acc.compressedAccount.proveByIndex,\n },\n rootIndex: rootIndices[i],\n };\n });\n}\n\n/**\n * Create decompressInterface instruction using Transfer2.\n *\n * Supports decompressing to both c-token accounts and SPL token accounts:\n * - For c-token destinations: No splInterfaceInfo needed\n * - For SPL destinations: Provide splInterfaceInfo (token pool info)\n *\n * @param payer Fee payer public key\n * @param inputCompressedTokenAccounts Input compressed token accounts\n * @param toAddress Destination token account address (c-token or SPL ATA)\n * @param amount Amount to decompress\n * @param validityProof Validity proof (contains compressedProof and rootIndices)\n * @param splInterfaceInfo Optional: SPL interface info for SPL destinations\n * @returns TransactionInstruction\n */\nexport function createDecompressInterfaceInstruction(\n payer: PublicKey,\n inputCompressedTokenAccounts: ParsedTokenAccount[],\n toAddress: PublicKey,\n amount: bigint,\n validityProof: ValidityProofWithContext,\n splInterfaceInfo?: SplInterfaceInfo,\n): TransactionInstruction {\n if (inputCompressedTokenAccounts.length === 0) {\n throw new Error('No input compressed token accounts provided');\n }\n\n const mint = inputCompressedTokenAccounts[0].parsed.mint;\n const owner = inputCompressedTokenAccounts[0].parsed.owner;\n\n // Build packed accounts map\n // Order: trees/queues first, then mint, owner, c-token account, c-token program\n const packedAccountIndices = new Map<string, number>();\n const packedAccounts: PublicKey[] = [];\n\n // Collect unique trees and queues\n const treeSet = new Set<string>();\n const queueSet = new Set<string>();\n for (const acc of inputCompressedTokenAccounts) {\n treeSet.add(acc.compressedAccount.treeInfo.tree.toBase58());\n queueSet.add(acc.compressedAccount.treeInfo.queue.toBase58());\n }\n\n // Add trees first (owned by account compression program)\n for (const tree of treeSet) {\n packedAccountIndices.set(tree, packedAccounts.length);\n packedAccounts.push(new PublicKey(tree));\n }\n\n let firstQueueIndex = 0;\n let isFirstQueue = true;\n for (const queue of queueSet) {\n if (isFirstQueue) {\n firstQueueIndex = packedAccounts.length;\n isFirstQueue = false;\n }\n packedAccountIndices.set(queue, packedAccounts.length);\n packedAccounts.push(new PublicKey(queue));\n }\n\n // Add mint\n const mintIndex = packedAccounts.length;\n packedAccountIndices.set(mint.toBase58(), mintIndex);\n packedAccounts.push(mint);\n\n // Add owner\n const ownerIndex = packedAccounts.length;\n packedAccountIndices.set(owner.toBase58(), ownerIndex);\n packedAccounts.push(owner);\n\n // Add destination token account (c-token or SPL)\n const destinationIndex = packedAccounts.length;\n packedAccountIndices.set(toAddress.toBase58(), destinationIndex);\n packedAccounts.push(toAddress);\n\n // For SPL decompression, add pool account and token program\n let poolAccountIndex = 0;\n let poolIndex = 0;\n let poolBump = 0;\n let tokenProgramIndex = 0;\n\n if (splInterfaceInfo) {\n // Add SPL interface PDA (token pool)\n poolAccountIndex = packedAccounts.length;\n packedAccountIndices.set(\n splInterfaceInfo.splInterfacePda.toBase58(),\n poolAccountIndex,\n );\n packedAccounts.push(splInterfaceInfo.splInterfacePda);\n\n // Add SPL token program\n tokenProgramIndex = packedAccounts.length;\n packedAccountIndices.set(\n splInterfaceInfo.tokenProgram.toBase58(),\n tokenProgramIndex,\n );\n packedAccounts.push(splInterfaceInfo.tokenProgram);\n\n poolIndex = splInterfaceInfo.poolIndex;\n poolBump = splInterfaceInfo.bump;\n }\n\n // Build input token data\n const inTokenData = buildInputTokenData(\n inputCompressedTokenAccounts,\n validityProof.rootIndices,\n packedAccountIndices,\n );\n\n // Calculate total input amount and change\n const totalInputAmount = inputCompressedTokenAccounts.reduce(\n (sum, acc) => sum + BigInt(acc.parsed.amount.toString()),\n BigInt(0),\n );\n const changeAmount = totalInputAmount - amount;\n\n const outTokenData: {\n owner: number;\n amount: bigint;\n hasDelegate: boolean;\n delegate: number;\n mint: number;\n version: number;\n }[] = [];\n\n if (changeAmount > 0) {\n const version = getVersionFromDiscriminator(\n inputCompressedTokenAccounts[0].compressedAccount.data\n ?.discriminator,\n );\n\n outTokenData.push({\n owner: ownerIndex,\n amount: changeAmount,\n hasDelegate: false,\n delegate: 0,\n mint: mintIndex,\n version,\n });\n }\n\n // Build decompress compression\n // For c-token: pool values are 0 (unused)\n // For SPL: pool values point to SPL interface PDA\n const compressions: Compression[] = [\n {\n mode: COMPRESSION_MODE_DECOMPRESS,\n amount,\n mint: mintIndex,\n sourceOrRecipient: destinationIndex,\n authority: 0, // Not needed for decompress\n poolAccountIndex: splInterfaceInfo ? poolAccountIndex : 0,\n poolIndex: splInterfaceInfo ? poolIndex : 0,\n bump: splInterfaceInfo ? poolBump : 0,\n decimals: 0,\n },\n ];\n\n // Build Transfer2 instruction data\n const instructionData: Transfer2InstructionData = {\n withTransactionHash: false,\n withLamportsChangeAccountMerkleTreeIndex: false,\n lamportsChangeAccountMerkleTreeIndex: 0,\n lamportsChangeAccountOwnerIndex: 0,\n outputQueue: firstQueueIndex, // First queue in packed accounts\n maxTopUp: 0,\n cpiContext: null,\n compressions,\n proof: validityProof.compressedProof\n ? {\n a: Array.from(validityProof.compressedProof.a),\n b: Array.from(validityProof.compressedProof.b),\n c: Array.from(validityProof.compressedProof.c),\n }\n : null,\n inTokenData,\n outTokenData,\n inLamports: null,\n outLamports: null,\n inTlv: null,\n outTlv: null,\n };\n\n const data = encodeTransfer2InstructionData(instructionData);\n\n // Build accounts for Transfer2 with compressed accounts (full path)\n const {\n accountCompressionAuthority,\n registeredProgramPda,\n accountCompressionProgram,\n } = defaultStaticAccountsStruct();\n\n const keys = [\n // 0: light_system_program (non-mutable)\n {\n pubkey: LightSystemProgram.programId,\n isSigner: false,\n isWritable: false,\n },\n // 1: fee_payer (signer, mutable)\n { pubkey: payer, isSigner: true, isWritable: true },\n // 2: cpi_authority_pda\n {\n pubkey: CompressedTokenProgram.deriveCpiAuthorityPda,\n isSigner: false,\n isWritable: false,\n },\n // 3: registered_program_pda\n {\n pubkey: registeredProgramPda,\n isSigner: false,\n isWritable: false,\n },\n // 4: account_compression_authority\n {\n pubkey: accountCompressionAuthority,\n isSigner: false,\n isWritable: false,\n },\n // 5: account_compression_program\n {\n pubkey: accountCompressionProgram,\n isSigner: false,\n isWritable: false,\n },\n // 6: system_program\n {\n pubkey: SystemProgram.programId,\n isSigner: false,\n isWritable: false,\n },\n // 7+: packed_accounts (trees/queues come first)\n ...packedAccounts.map((pubkey, i) => {\n // Trees need to be writable\n const isTreeOrQueue = i < treeSet.size + queueSet.size;\n // Destination account needs to be writable\n const isDestination = pubkey.equals(toAddress);\n // SPL interface PDA (pool) needs to be writable for SPL decompression\n const isPool =\n splInterfaceInfo !== undefined &&\n pubkey.equals(splInterfaceInfo.splInterfacePda);\n // Owner must be marked as signer in packed accounts\n const isOwner = i === ownerIndex;\n return {\n pubkey,\n isSigner: isOwner,\n isWritable: isTreeOrQueue || isDestination || isPool,\n };\n }),\n ];\n\n return new TransactionInstruction({\n programId: CompressedTokenProgram.programId,\n keys,\n data,\n });\n}\n","(function (module, exports) {\n 'use strict';\n\n // Utils\n function assert (val, msg) {\n if (!val) throw new Error(msg || 'Assertion failed');\n }\n\n // Could use `inherits` module, but don't want to move from single file\n // architecture yet.\n function inherits (ctor, superCtor) {\n ctor.super_ = superCtor;\n var TempCtor = function () {};\n TempCtor.prototype = superCtor.prototype;\n ctor.prototype = new TempCtor();\n ctor.prototype.constructor = ctor;\n }\n\n // BN\n\n function BN (number, base, endian) {\n if (BN.isBN(number)) {\n return number;\n }\n\n this.negative = 0;\n this.words = null;\n this.length = 0;\n\n // Reduction context\n this.red = null;\n\n if (number !== null) {\n if (base === 'le' || base === 'be') {\n endian = base;\n base = 10;\n }\n\n this._init(number || 0, base || 10, endian || 'be');\n }\n }\n if (typeof module === 'object') {\n module.exports = BN;\n } else {\n exports.BN = BN;\n }\n\n BN.BN = BN;\n BN.wordSize = 26;\n\n var Buffer;\n try {\n if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {\n Buffer = window.Buffer;\n } else {\n Buffer = require('buffer').Buffer;\n }\n } catch (e) {\n }\n\n BN.isBN = function isBN (num) {\n if (num instanceof BN) {\n return true;\n }\n\n return num !== null && typeof num === 'object' &&\n num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);\n };\n\n BN.max = function max (left, right) {\n if (left.cmp(right) > 0) return left;\n return right;\n };\n\n BN.min = function min (left, right) {\n if (left.cmp(right) < 0) return left;\n return right;\n };\n\n BN.prototype._init = function init (number, base, endian) {\n if (typeof number === 'number') {\n return this._initNumber(number, base, endian);\n }\n\n if (typeof number === 'object') {\n return this._initArray(number, base, endian);\n }\n\n if (base === 'hex') {\n base = 16;\n }\n assert(base === (base | 0) && base >= 2 && base <= 36);\n\n number = number.toString().replace(/\\s+/g, '');\n var start = 0;\n if (number[0] === '-') {\n start++;\n this.negative = 1;\n }\n\n if (start < number.length) {\n if (base === 16) {\n this._parseHex(number, start, endian);\n } else {\n this._parseBase(number, base, start);\n if (endian === 'le') {\n this._initArray(this.toArray(), base, endian);\n }\n }\n }\n };\n\n BN.prototype._initNumber = function _initNumber (number, base, endian) {\n if (number < 0) {\n this.negative = 1;\n number = -number;\n }\n if (number < 0x4000000) {\n this.words = [number & 0x3ffffff];\n this.length = 1;\n } else if (number < 0x10000000000000) {\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff\n ];\n this.length = 2;\n } else {\n assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff,\n 1\n ];\n this.length = 3;\n }\n\n if (endian !== 'le') return;\n\n // Reverse the bytes\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initArray = function _initArray (number, base, endian) {\n // Perhaps a Uint8Array\n assert(typeof number.length === 'number');\n if (number.length <= 0) {\n this.words = [0];\n this.length = 1;\n return this;\n }\n\n this.length = Math.ceil(number.length / 3);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n var off = 0;\n if (endian === 'be') {\n for (i = number.length - 1, j = 0; i >= 0; i -= 3) {\n w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n } else if (endian === 'le') {\n for (i = 0, j = 0; i < number.length; i += 3) {\n w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n }\n return this._strip();\n };\n\n function parseHex4Bits (string, index) {\n var c = string.charCodeAt(index);\n // '0' - '9'\n if (c >= 48 && c <= 57) {\n return c - 48;\n // 'A' - 'F'\n } else if (c >= 65 && c <= 70) {\n return c - 55;\n // 'a' - 'f'\n } else if (c >= 97 && c <= 102) {\n return c - 87;\n } else {\n assert(false, 'Invalid character in ' + string);\n }\n }\n\n function parseHexByte (string, lowerBound, index) {\n var r = parseHex4Bits(string, index);\n if (index - 1 >= lowerBound) {\n r |= parseHex4Bits(string, index - 1) << 4;\n }\n return r;\n }\n\n BN.prototype._parseHex = function _parseHex (number, start, endian) {\n // Create possibly bigger array to ensure that it fits the number\n this.length = Math.ceil((number.length - start) / 6);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n // 24-bits chunks\n var off = 0;\n var j = 0;\n\n var w;\n if (endian === 'be') {\n for (i = number.length - 1; i >= start; i -= 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n } else {\n var parseLength = number.length - start;\n for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n }\n\n this._strip();\n };\n\n function parseBase (str, start, end, mul) {\n var r = 0;\n var b = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r *= mul;\n\n // 'a'\n if (c >= 49) {\n b = c - 49 + 0xa;\n\n // 'A'\n } else if (c >= 17) {\n b = c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n b = c;\n }\n assert(c >= 0 && b < mul, 'Invalid character');\n r += b;\n }\n return r;\n }\n\n BN.prototype._parseBase = function _parseBase (number, base, start) {\n // Initialize as zero\n this.words = [0];\n this.length = 1;\n\n // Find length of limb in base\n for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {\n limbLen++;\n }\n limbLen--;\n limbPow = (limbPow / base) | 0;\n\n var total = number.length - start;\n var mod = total % limbLen;\n var end = Math.min(total, total - mod) + start;\n\n var word = 0;\n for (var i = start; i < end; i += limbLen) {\n word = parseBase(number, i, i + limbLen, base);\n\n this.imuln(limbPow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n if (mod !== 0) {\n var pow = 1;\n word = parseBase(number, i, number.length, base);\n\n for (i = 0; i < mod; i++) {\n pow *= base;\n }\n\n this.imuln(pow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n this._strip();\n };\n\n BN.prototype.copy = function copy (dest) {\n dest.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n dest.words[i] = this.words[i];\n }\n dest.length = this.length;\n dest.negative = this.negative;\n dest.red = this.red;\n };\n\n function move (dest, src) {\n dest.words = src.words;\n dest.length = src.length;\n dest.negative = src.negative;\n dest.red = src.red;\n }\n\n BN.prototype._move = function _move (dest) {\n move(dest, this);\n };\n\n BN.prototype.clone = function clone () {\n var r = new BN(null);\n this.copy(r);\n return r;\n };\n\n BN.prototype._expand = function _expand (size) {\n while (this.length < size) {\n this.words[this.length++] = 0;\n }\n return this;\n };\n\n // Remove leading `0` from `this`\n BN.prototype._strip = function strip () {\n while (this.length > 1 && this.words[this.length - 1] === 0) {\n this.length--;\n }\n return this._normSign();\n };\n\n BN.prototype._normSign = function _normSign () {\n // -0 = 0\n if (this.length === 1 && this.words[0] === 0) {\n this.negative = 0;\n }\n return this;\n };\n\n // Check Symbol.for because not everywhere where Symbol defined\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility\n if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') {\n try {\n BN.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspect;\n } catch (e) {\n BN.prototype.inspect = inspect;\n }\n } else {\n BN.prototype.inspect = inspect;\n }\n\n function inspect () {\n return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';\n }\n\n /*\n\n var zeros = [];\n var groupSizes = [];\n var groupBases = [];\n\n var s = '';\n var i = -1;\n while (++i < BN.wordSize) {\n zeros[i] = s;\n s += '0';\n }\n groupSizes[0] = 0;\n groupSizes[1] = 0;\n groupBases[0] = 0;\n groupBases[1] = 0;\n var base = 2 - 1;\n while (++base < 36 + 1) {\n var groupSize = 0;\n var groupBase = 1;\n while (groupBase < (1 << BN.wordSize) / base) {\n groupBase *= base;\n groupSize += 1;\n }\n groupSizes[base] = groupSize;\n groupBases[base] = groupBase;\n }\n\n */\n\n var zeros = [\n '',\n '0',\n '00',\n '000',\n '0000',\n '00000',\n '000000',\n '0000000',\n '00000000',\n '000000000',\n '0000000000',\n '00000000000',\n '000000000000',\n '0000000000000',\n '00000000000000',\n '000000000000000',\n '0000000000000000',\n '00000000000000000',\n '000000000000000000',\n '0000000000000000000',\n '00000000000000000000',\n '000000000000000000000',\n '0000000000000000000000',\n '00000000000000000000000',\n '000000000000000000000000',\n '0000000000000000000000000'\n ];\n\n var groupSizes = [\n 0, 0,\n 25, 16, 12, 11, 10, 9, 8,\n 8, 7, 7, 7, 7, 6, 6,\n 6, 6, 6, 6, 6, 5, 5,\n 5, 5, 5, 5, 5, 5, 5,\n 5, 5, 5, 5, 5, 5, 5\n ];\n\n var groupBases = [\n 0, 0,\n 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,\n 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,\n 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,\n 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,\n 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176\n ];\n\n BN.prototype.toString = function toString (base, padding) {\n base = base || 10;\n padding = padding | 0 || 1;\n\n var out;\n if (base === 16 || base === 'hex') {\n out = '';\n var off = 0;\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = this.words[i];\n var word = (((w << off) | carry) & 0xffffff).toString(16);\n carry = (w >>> (24 - off)) & 0xffffff;\n off += 2;\n if (off >= 26) {\n off -= 26;\n i--;\n }\n if (carry !== 0 || i !== this.length - 1) {\n out = zeros[6 - word.length] + word + out;\n } else {\n out = word + out;\n }\n }\n if (carry !== 0) {\n out = carry.toString(16) + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n if (base === (base | 0) && base >= 2 && base <= 36) {\n // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));\n var groupSize = groupSizes[base];\n // var groupBase = Math.pow(base, groupSize);\n var groupBase = groupBases[base];\n out = '';\n var c = this.clone();\n c.negative = 0;\n while (!c.isZero()) {\n var r = c.modrn(groupBase).toString(base);\n c = c.idivn(groupBase);\n\n if (!c.isZero()) {\n out = zeros[groupSize - r.length] + r + out;\n } else {\n out = r + out;\n }\n }\n if (this.isZero()) {\n out = '0' + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n assert(false, 'Base should be between 2 and 36');\n };\n\n BN.prototype.toNumber = function toNumber () {\n var ret = this.words[0];\n if (this.length === 2) {\n ret += this.words[1] * 0x4000000;\n } else if (this.length === 3 && this.words[2] === 0x01) {\n // NOTE: at this stage it is known that the top bit is set\n ret += 0x10000000000000 + (this.words[1] * 0x4000000);\n } else if (this.length > 2) {\n assert(false, 'Number can only safely store up to 53 bits');\n }\n return (this.negative !== 0) ? -ret : ret;\n };\n\n BN.prototype.toJSON = function toJSON () {\n return this.toString(16, 2);\n };\n\n if (Buffer) {\n BN.prototype.toBuffer = function toBuffer (endian, length) {\n return this.toArrayLike(Buffer, endian, length);\n };\n }\n\n BN.prototype.toArray = function toArray (endian, length) {\n return this.toArrayLike(Array, endian, length);\n };\n\n var allocate = function allocate (ArrayType, size) {\n if (ArrayType.allocUnsafe) {\n return ArrayType.allocUnsafe(size);\n }\n return new ArrayType(size);\n };\n\n BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {\n this._strip();\n\n var byteLength = this.byteLength();\n var reqLength = length || Math.max(1, byteLength);\n assert(byteLength <= reqLength, 'byte array longer than desired length');\n assert(reqLength > 0, 'Requested array length <= 0');\n\n var res = allocate(ArrayType, reqLength);\n var postfix = endian === 'le' ? 'LE' : 'BE';\n this['_toArrayLike' + postfix](res, byteLength);\n return res;\n };\n\n BN.prototype._toArrayLikeLE = function _toArrayLikeLE (res, byteLength) {\n var position = 0;\n var carry = 0;\n\n for (var i = 0, shift = 0; i < this.length; i++) {\n var word = (this.words[i] << shift) | carry;\n\n res[position++] = word & 0xff;\n if (position < res.length) {\n res[position++] = (word >> 8) & 0xff;\n }\n if (position < res.length) {\n res[position++] = (word >> 16) & 0xff;\n }\n\n if (shift === 6) {\n if (position < res.length) {\n res[position++] = (word >> 24) & 0xff;\n }\n carry = 0;\n shift = 0;\n } else {\n carry = word >>> 24;\n shift += 2;\n }\n }\n\n if (position < res.length) {\n res[position++] = carry;\n\n while (position < res.length) {\n res[position++] = 0;\n }\n }\n };\n\n BN.prototype._toArrayLikeBE = function _toArrayLikeBE (res, byteLength) {\n var position = res.length - 1;\n var carry = 0;\n\n for (var i = 0, shift = 0; i < this.length; i++) {\n var word = (this.words[i] << shift) | carry;\n\n res[position--] = word & 0xff;\n if (position >= 0) {\n res[position--] = (word >> 8) & 0xff;\n }\n if (position >= 0) {\n res[position--] = (word >> 16) & 0xff;\n }\n\n if (shift === 6) {\n if (position >= 0) {\n res[position--] = (word >> 24) & 0xff;\n }\n carry = 0;\n shift = 0;\n } else {\n carry = word >>> 24;\n shift += 2;\n }\n }\n\n if (position >= 0) {\n res[position--] = carry;\n\n while (position >= 0) {\n res[position--] = 0;\n }\n }\n };\n\n if (Math.clz32) {\n BN.prototype._countBits = function _countBits (w) {\n return 32 - Math.clz32(w);\n };\n } else {\n BN.prototype._countBits = function _countBits (w) {\n var t = w;\n var r = 0;\n if (t >= 0x1000) {\n r += 13;\n t >>>= 13;\n }\n if (t >= 0x40) {\n r += 7;\n t >>>= 7;\n }\n if (t >= 0x8) {\n r += 4;\n t >>>= 4;\n }\n if (t >= 0x02) {\n r += 2;\n t >>>= 2;\n }\n return r + t;\n };\n }\n\n BN.prototype._zeroBits = function _zeroBits (w) {\n // Short-cut\n if (w === 0) return 26;\n\n var t = w;\n var r = 0;\n if ((t & 0x1fff) === 0) {\n r += 13;\n t >>>= 13;\n }\n if ((t & 0x7f) === 0) {\n r += 7;\n t >>>= 7;\n }\n if ((t & 0xf) === 0) {\n r += 4;\n t >>>= 4;\n }\n if ((t & 0x3) === 0) {\n r += 2;\n t >>>= 2;\n }\n if ((t & 0x1) === 0) {\n r++;\n }\n return r;\n };\n\n // Return number of used bits in a BN\n BN.prototype.bitLength = function bitLength () {\n var w = this.words[this.length - 1];\n var hi = this._countBits(w);\n return (this.length - 1) * 26 + hi;\n };\n\n function toBitArray (num) {\n var w = new Array(num.bitLength());\n\n for (var bit = 0; bit < w.length; bit++) {\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n w[bit] = (num.words[off] >>> wbit) & 0x01;\n }\n\n return w;\n }\n\n // Number of trailing zero bits\n BN.prototype.zeroBits = function zeroBits () {\n if (this.isZero()) return 0;\n\n var r = 0;\n for (var i = 0; i < this.length; i++) {\n var b = this._zeroBits(this.words[i]);\n r += b;\n if (b !== 26) break;\n }\n return r;\n };\n\n BN.prototype.byteLength = function byteLength () {\n return Math.ceil(this.bitLength() / 8);\n };\n\n BN.prototype.toTwos = function toTwos (width) {\n if (this.negative !== 0) {\n return this.abs().inotn(width).iaddn(1);\n }\n return this.clone();\n };\n\n BN.prototype.fromTwos = function fromTwos (width) {\n if (this.testn(width - 1)) {\n return this.notn(width).iaddn(1).ineg();\n }\n return this.clone();\n };\n\n BN.prototype.isNeg = function isNeg () {\n return this.negative !== 0;\n };\n\n // Return negative clone of `this`\n BN.prototype.neg = function neg () {\n return this.clone().ineg();\n };\n\n BN.prototype.ineg = function ineg () {\n if (!this.isZero()) {\n this.negative ^= 1;\n }\n\n return this;\n };\n\n // Or `num` with `this` in-place\n BN.prototype.iuor = function iuor (num) {\n while (this.length < num.length) {\n this.words[this.length++] = 0;\n }\n\n for (var i = 0; i < num.length; i++) {\n this.words[i] = this.words[i] | num.words[i];\n }\n\n return this._strip();\n };\n\n BN.prototype.ior = function ior (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuor(num);\n };\n\n // Or `num` with `this`\n BN.prototype.or = function or (num) {\n if (this.length > num.length) return this.clone().ior(num);\n return num.clone().ior(this);\n };\n\n BN.prototype.uor = function uor (num) {\n if (this.length > num.length) return this.clone().iuor(num);\n return num.clone().iuor(this);\n };\n\n // And `num` with `this` in-place\n BN.prototype.iuand = function iuand (num) {\n // b = min-length(num, this)\n var b;\n if (this.length > num.length) {\n b = num;\n } else {\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = this.words[i] & num.words[i];\n }\n\n this.length = b.length;\n\n return this._strip();\n };\n\n BN.prototype.iand = function iand (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuand(num);\n };\n\n // And `num` with `this`\n BN.prototype.and = function and (num) {\n if (this.length > num.length) return this.clone().iand(num);\n return num.clone().iand(this);\n };\n\n BN.prototype.uand = function uand (num) {\n if (this.length > num.length) return this.clone().iuand(num);\n return num.clone().iuand(this);\n };\n\n // Xor `num` with `this` in-place\n BN.prototype.iuxor = function iuxor (num) {\n // a.length > b.length\n var a;\n var b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = a.words[i] ^ b.words[i];\n }\n\n if (this !== a) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = a.length;\n\n return this._strip();\n };\n\n BN.prototype.ixor = function ixor (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuxor(num);\n };\n\n // Xor `num` with `this`\n BN.prototype.xor = function xor (num) {\n if (this.length > num.length) return this.clone().ixor(num);\n return num.clone().ixor(this);\n };\n\n BN.prototype.uxor = function uxor (num) {\n if (this.length > num.length) return this.clone().iuxor(num);\n return num.clone().iuxor(this);\n };\n\n // Not ``this`` with ``width`` bitwidth\n BN.prototype.inotn = function inotn (width) {\n assert(typeof width === 'number' && width >= 0);\n\n var bytesNeeded = Math.ceil(width / 26) | 0;\n var bitsLeft = width % 26;\n\n // Extend the buffer with leading zeroes\n this._expand(bytesNeeded);\n\n if (bitsLeft > 0) {\n bytesNeeded--;\n }\n\n // Handle complete words\n for (var i = 0; i < bytesNeeded; i++) {\n this.words[i] = ~this.words[i] & 0x3ffffff;\n }\n\n // Handle the residue\n if (bitsLeft > 0) {\n this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));\n }\n\n // And remove leading zeroes\n return this._strip();\n };\n\n BN.prototype.notn = function notn (width) {\n return this.clone().inotn(width);\n };\n\n // Set `bit` of `this`\n BN.prototype.setn = function setn (bit, val) {\n assert(typeof bit === 'number' && bit >= 0);\n\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n this._expand(off + 1);\n\n if (val) {\n this.words[off] = this.words[off] | (1 << wbit);\n } else {\n this.words[off] = this.words[off] & ~(1 << wbit);\n }\n\n return this._strip();\n };\n\n // Add `num` to `this` in-place\n BN.prototype.iadd = function iadd (num) {\n var r;\n\n // negative + positive\n if (this.negative !== 0 && num.negative === 0) {\n this.negative = 0;\n r = this.isub(num);\n this.negative ^= 1;\n return this._normSign();\n\n // positive + negative\n } else if (this.negative === 0 && num.negative !== 0) {\n num.negative = 0;\n r = this.isub(num);\n num.negative = 1;\n return r._normSign();\n }\n\n // a.length > b.length\n var a, b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) + (b.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n\n this.length = a.length;\n if (carry !== 0) {\n this.words[this.length] = carry;\n this.length++;\n // Copy the rest of the words\n } else if (a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n return this;\n };\n\n // Add `num` to `this`\n BN.prototype.add = function add (num) {\n var res;\n if (num.negative !== 0 && this.negative === 0) {\n num.negative = 0;\n res = this.sub(num);\n num.negative ^= 1;\n return res;\n } else if (num.negative === 0 && this.negative !== 0) {\n this.negative = 0;\n res = num.sub(this);\n this.negative = 1;\n return res;\n }\n\n if (this.length > num.length) return this.clone().iadd(num);\n\n return num.clone().iadd(this);\n };\n\n // Subtract `num` from `this` in-place\n BN.prototype.isub = function isub (num) {\n // this - (-num) = this + num\n if (num.negative !== 0) {\n num.negative = 0;\n var r = this.iadd(num);\n num.negative = 1;\n return r._normSign();\n\n // -this - num = -(this + num)\n } else if (this.negative !== 0) {\n this.negative = 0;\n this.iadd(num);\n this.negative = 1;\n return this._normSign();\n }\n\n // At this point both numbers are positive\n var cmp = this.cmp(num);\n\n // Optimization - zeroify\n if (cmp === 0) {\n this.negative = 0;\n this.length = 1;\n this.words[0] = 0;\n return this;\n }\n\n // a > b\n var a, b;\n if (cmp > 0) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) - (b.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n\n // Copy rest of the words\n if (carry === 0 && i < a.length && a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = Math.max(this.length, i);\n\n if (a !== this) {\n this.negative = 1;\n }\n\n return this._strip();\n };\n\n // Subtract `num` from `this`\n BN.prototype.sub = function sub (num) {\n return this.clone().isub(num);\n };\n\n function smallMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n var len = (self.length + num.length) | 0;\n out.length = len;\n len = (len - 1) | 0;\n\n // Peel one iteration (compiler can't do it, because of code complexity)\n var a = self.words[0] | 0;\n var b = num.words[0] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n var carry = (r / 0x4000000) | 0;\n out.words[0] = lo;\n\n for (var k = 1; k < len; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = carry >>> 26;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = (k - j) | 0;\n a = self.words[i] | 0;\n b = num.words[j] | 0;\n r = a * b + rword;\n ncarry += (r / 0x4000000) | 0;\n rword = r & 0x3ffffff;\n }\n out.words[k] = rword | 0;\n carry = ncarry | 0;\n }\n if (carry !== 0) {\n out.words[k] = carry | 0;\n } else {\n out.length--;\n }\n\n return out._strip();\n }\n\n // TODO(indutny): it may be reasonable to omit it for users who don't need\n // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit\n // multiplication (like elliptic secp256k1).\n var comb10MulTo = function comb10MulTo (self, num, out) {\n var a = self.words;\n var b = num.words;\n var o = out.words;\n var c = 0;\n var lo;\n var mid;\n var hi;\n var a0 = a[0] | 0;\n var al0 = a0 & 0x1fff;\n var ah0 = a0 >>> 13;\n var a1 = a[1] | 0;\n var al1 = a1 & 0x1fff;\n var ah1 = a1 >>> 13;\n var a2 = a[2] | 0;\n var al2 = a2 & 0x1fff;\n var ah2 = a2 >>> 13;\n var a3 = a[3] | 0;\n var al3 = a3 & 0x1fff;\n var ah3 = a3 >>> 13;\n var a4 = a[4] | 0;\n var al4 = a4 & 0x1fff;\n var ah4 = a4 >>> 13;\n var a5 = a[5] | 0;\n var al5 = a5 & 0x1fff;\n var ah5 = a5 >>> 13;\n var a6 = a[6] | 0;\n var al6 = a6 & 0x1fff;\n var ah6 = a6 >>> 13;\n var a7 = a[7] | 0;\n var al7 = a7 & 0x1fff;\n var ah7 = a7 >>> 13;\n var a8 = a[8] | 0;\n var al8 = a8 & 0x1fff;\n var ah8 = a8 >>> 13;\n var a9 = a[9] | 0;\n var al9 = a9 & 0x1fff;\n var ah9 = a9 >>> 13;\n var b0 = b[0] | 0;\n var bl0 = b0 & 0x1fff;\n var bh0 = b0 >>> 13;\n var b1 = b[1] | 0;\n var bl1 = b1 & 0x1fff;\n var bh1 = b1 >>> 13;\n var b2 = b[2] | 0;\n var bl2 = b2 & 0x1fff;\n var bh2 = b2 >>> 13;\n var b3 = b[3] | 0;\n var bl3 = b3 & 0x1fff;\n var bh3 = b3 >>> 13;\n var b4 = b[4] | 0;\n var bl4 = b4 & 0x1fff;\n var bh4 = b4 >>> 13;\n var b5 = b[5] | 0;\n var bl5 = b5 & 0x1fff;\n var bh5 = b5 >>> 13;\n var b6 = b[6] | 0;\n var bl6 = b6 & 0x1fff;\n var bh6 = b6 >>> 13;\n var b7 = b[7] | 0;\n var bl7 = b7 & 0x1fff;\n var bh7 = b7 >>> 13;\n var b8 = b[8] | 0;\n var bl8 = b8 & 0x1fff;\n var bh8 = b8 >>> 13;\n var b9 = b[9] | 0;\n var bl9 = b9 & 0x1fff;\n var bh9 = b9 >>> 13;\n\n out.negative = self.negative ^ num.negative;\n out.length = 19;\n /* k = 0 */\n lo = Math.imul(al0, bl0);\n mid = Math.imul(al0, bh0);\n mid = (mid + Math.imul(ah0, bl0)) | 0;\n hi = Math.imul(ah0, bh0);\n var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;\n w0 &= 0x3ffffff;\n /* k = 1 */\n lo = Math.imul(al1, bl0);\n mid = Math.imul(al1, bh0);\n mid = (mid + Math.imul(ah1, bl0)) | 0;\n hi = Math.imul(ah1, bh0);\n lo = (lo + Math.imul(al0, bl1)) | 0;\n mid = (mid + Math.imul(al0, bh1)) | 0;\n mid = (mid + Math.imul(ah0, bl1)) | 0;\n hi = (hi + Math.imul(ah0, bh1)) | 0;\n var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;\n w1 &= 0x3ffffff;\n /* k = 2 */\n lo = Math.imul(al2, bl0);\n mid = Math.imul(al2, bh0);\n mid = (mid + Math.imul(ah2, bl0)) | 0;\n hi = Math.imul(ah2, bh0);\n lo = (lo + Math.imul(al1, bl1)) | 0;\n mid = (mid + Math.imul(al1, bh1)) | 0;\n mid = (mid + Math.imul(ah1, bl1)) | 0;\n hi = (hi + Math.imul(ah1, bh1)) | 0;\n lo = (lo + Math.imul(al0, bl2)) | 0;\n mid = (mid + Math.imul(al0, bh2)) | 0;\n mid = (mid + Math.imul(ah0, bl2)) | 0;\n hi = (hi + Math.imul(ah0, bh2)) | 0;\n var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;\n w2 &= 0x3ffffff;\n /* k = 3 */\n lo = Math.imul(al3, bl0);\n mid = Math.imul(al3, bh0);\n mid = (mid + Math.imul(ah3, bl0)) | 0;\n hi = Math.imul(ah3, bh0);\n lo = (lo + Math.imul(al2, bl1)) | 0;\n mid = (mid + Math.imul(al2, bh1)) | 0;\n mid = (mid + Math.imul(ah2, bl1)) | 0;\n hi = (hi + Math.imul(ah2, bh1)) | 0;\n lo = (lo + Math.imul(al1, bl2)) | 0;\n mid = (mid + Math.imul(al1, bh2)) | 0;\n mid = (mid + Math.imul(ah1, bl2)) | 0;\n hi = (hi + Math.imul(ah1, bh2)) | 0;\n lo = (lo + Math.imul(al0, bl3)) | 0;\n mid = (mid + Math.imul(al0, bh3)) | 0;\n mid = (mid + Math.imul(ah0, bl3)) | 0;\n hi = (hi + Math.imul(ah0, bh3)) | 0;\n var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;\n w3 &= 0x3ffffff;\n /* k = 4 */\n lo = Math.imul(al4, bl0);\n mid = Math.imul(al4, bh0);\n mid = (mid + Math.imul(ah4, bl0)) | 0;\n hi = Math.imul(ah4, bh0);\n lo = (lo + Math.imul(al3, bl1)) | 0;\n mid = (mid + Math.imul(al3, bh1)) | 0;\n mid = (mid + Math.imul(ah3, bl1)) | 0;\n hi = (hi + Math.imul(ah3, bh1)) | 0;\n lo = (lo + Math.imul(al2, bl2)) | 0;\n mid = (mid + Math.imul(al2, bh2)) | 0;\n mid = (mid + Math.imul(ah2, bl2)) | 0;\n hi = (hi + Math.imul(ah2, bh2)) | 0;\n lo = (lo + Math.imul(al1, bl3)) | 0;\n mid = (mid + Math.imul(al1, bh3)) | 0;\n mid = (mid + Math.imul(ah1, bl3)) | 0;\n hi = (hi + Math.imul(ah1, bh3)) | 0;\n lo = (lo + Math.imul(al0, bl4)) | 0;\n mid = (mid + Math.imul(al0, bh4)) | 0;\n mid = (mid + Math.imul(ah0, bl4)) | 0;\n hi = (hi + Math.imul(ah0, bh4)) | 0;\n var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;\n w4 &= 0x3ffffff;\n /* k = 5 */\n lo = Math.imul(al5, bl0);\n mid = Math.imul(al5, bh0);\n mid = (mid + Math.imul(ah5, bl0)) | 0;\n hi = Math.imul(ah5, bh0);\n lo = (lo + Math.imul(al4, bl1)) | 0;\n mid = (mid + Math.imul(al4, bh1)) | 0;\n mid = (mid + Math.imul(ah4, bl1)) | 0;\n hi = (hi + Math.imul(ah4, bh1)) | 0;\n lo = (lo + Math.imul(al3, bl2)) | 0;\n mid = (mid + Math.imul(al3, bh2)) | 0;\n mid = (mid + Math.imul(ah3, bl2)) | 0;\n hi = (hi + Math.imul(ah3, bh2)) | 0;\n lo = (lo + Math.imul(al2, bl3)) | 0;\n mid = (mid + Math.imul(al2, bh3)) | 0;\n mid = (mid + Math.imul(ah2, bl3)) | 0;\n hi = (hi + Math.imul(ah2, bh3)) | 0;\n lo = (lo + Math.imul(al1, bl4)) | 0;\n mid = (mid + Math.imul(al1, bh4)) | 0;\n mid = (mid + Math.imul(ah1, bl4)) | 0;\n hi = (hi + Math.imul(ah1, bh4)) | 0;\n lo = (lo + Math.imul(al0, bl5)) | 0;\n mid = (mid + Math.imul(al0, bh5)) | 0;\n mid = (mid + Math.imul(ah0, bl5)) | 0;\n hi = (hi + Math.imul(ah0, bh5)) | 0;\n var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;\n w5 &= 0x3ffffff;\n /* k = 6 */\n lo = Math.imul(al6, bl0);\n mid = Math.imul(al6, bh0);\n mid = (mid + Math.imul(ah6, bl0)) | 0;\n hi = Math.imul(ah6, bh0);\n lo = (lo + Math.imul(al5, bl1)) | 0;\n mid = (mid + Math.imul(al5, bh1)) | 0;\n mid = (mid + Math.imul(ah5, bl1)) | 0;\n hi = (hi + Math.imul(ah5, bh1)) | 0;\n lo = (lo + Math.imul(al4, bl2)) | 0;\n mid = (mid + Math.imul(al4, bh2)) | 0;\n mid = (mid + Math.imul(ah4, bl2)) | 0;\n hi = (hi + Math.imul(ah4, bh2)) | 0;\n lo = (lo + Math.imul(al3, bl3)) | 0;\n mid = (mid + Math.imul(al3, bh3)) | 0;\n mid = (mid + Math.imul(ah3, bl3)) | 0;\n hi = (hi + Math.imul(ah3, bh3)) | 0;\n lo = (lo + Math.imul(al2, bl4)) | 0;\n mid = (mid + Math.imul(al2, bh4)) | 0;\n mid = (mid + Math.imul(ah2, bl4)) | 0;\n hi = (hi + Math.imul(ah2, bh4)) | 0;\n lo = (lo + Math.imul(al1, bl5)) | 0;\n mid = (mid + Math.imul(al1, bh5)) | 0;\n mid = (mid + Math.imul(ah1, bl5)) | 0;\n hi = (hi + Math.imul(ah1, bh5)) | 0;\n lo = (lo + Math.imul(al0, bl6)) | 0;\n mid = (mid + Math.imul(al0, bh6)) | 0;\n mid = (mid + Math.imul(ah0, bl6)) | 0;\n hi = (hi + Math.imul(ah0, bh6)) | 0;\n var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;\n w6 &= 0x3ffffff;\n /* k = 7 */\n lo = Math.imul(al7, bl0);\n mid = Math.imul(al7, bh0);\n mid = (mid + Math.imul(ah7, bl0)) | 0;\n hi = Math.imul(ah7, bh0);\n lo = (lo + Math.imul(al6, bl1)) | 0;\n mid = (mid + Math.imul(al6, bh1)) | 0;\n mid = (mid + Math.imul(ah6, bl1)) | 0;\n hi = (hi + Math.imul(ah6, bh1)) | 0;\n lo = (lo + Math.imul(al5, bl2)) | 0;\n mid = (mid + Math.imul(al5, bh2)) | 0;\n mid = (mid + Math.imul(ah5, bl2)) | 0;\n hi = (hi + Math.imul(ah5, bh2)) | 0;\n lo = (lo + Math.imul(al4, bl3)) | 0;\n mid = (mid + Math.imul(al4, bh3)) | 0;\n mid = (mid + Math.imul(ah4, bl3)) | 0;\n hi = (hi + Math.imul(ah4, bh3)) | 0;\n lo = (lo + Math.imul(al3, bl4)) | 0;\n mid = (mid + Math.imul(al3, bh4)) | 0;\n mid = (mid + Math.imul(ah3, bl4)) | 0;\n hi = (hi + Math.imul(ah3, bh4)) | 0;\n lo = (lo + Math.imul(al2, bl5)) | 0;\n mid = (mid + Math.imul(al2, bh5)) | 0;\n mid = (mid + Math.imul(ah2, bl5)) | 0;\n hi = (hi + Math.imul(ah2, bh5)) | 0;\n lo = (lo + Math.imul(al1, bl6)) | 0;\n mid = (mid + Math.imul(al1, bh6)) | 0;\n mid = (mid + Math.imul(ah1, bl6)) | 0;\n hi = (hi + Math.imul(ah1, bh6)) | 0;\n lo = (lo + Math.imul(al0, bl7)) | 0;\n mid = (mid + Math.imul(al0, bh7)) | 0;\n mid = (mid + Math.imul(ah0, bl7)) | 0;\n hi = (hi + Math.imul(ah0, bh7)) | 0;\n var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;\n w7 &= 0x3ffffff;\n /* k = 8 */\n lo = Math.imul(al8, bl0);\n mid = Math.imul(al8, bh0);\n mid = (mid + Math.imul(ah8, bl0)) | 0;\n hi = Math.imul(ah8, bh0);\n lo = (lo + Math.imul(al7, bl1)) | 0;\n mid = (mid + Math.imul(al7, bh1)) | 0;\n mid = (mid + Math.imul(ah7, bl1)) | 0;\n hi = (hi + Math.imul(ah7, bh1)) | 0;\n lo = (lo + Math.imul(al6, bl2)) | 0;\n mid = (mid + Math.imul(al6, bh2)) | 0;\n mid = (mid + Math.imul(ah6, bl2)) | 0;\n hi = (hi + Math.imul(ah6, bh2)) | 0;\n lo = (lo + Math.imul(al5, bl3)) | 0;\n mid = (mid + Math.imul(al5, bh3)) | 0;\n mid = (mid + Math.imul(ah5, bl3)) | 0;\n hi = (hi + Math.imul(ah5, bh3)) | 0;\n lo = (lo + Math.imul(al4, bl4)) | 0;\n mid = (mid + Math.imul(al4, bh4)) | 0;\n mid = (mid + Math.imul(ah4, bl4)) | 0;\n hi = (hi + Math.imul(ah4, bh4)) | 0;\n lo = (lo + Math.imul(al3, bl5)) | 0;\n mid = (mid + Math.imul(al3, bh5)) | 0;\n mid = (mid + Math.imul(ah3, bl5)) | 0;\n hi = (hi + Math.imul(ah3, bh5)) | 0;\n lo = (lo + Math.imul(al2, bl6)) | 0;\n mid = (mid + Math.imul(al2, bh6)) | 0;\n mid = (mid + Math.imul(ah2, bl6)) | 0;\n hi = (hi + Math.imul(ah2, bh6)) | 0;\n lo = (lo + Math.imul(al1, bl7)) | 0;\n mid = (mid + Math.imul(al1, bh7)) | 0;\n mid = (mid + Math.imul(ah1, bl7)) | 0;\n hi = (hi + Math.imul(ah1, bh7)) | 0;\n lo = (lo + Math.imul(al0, bl8)) | 0;\n mid = (mid + Math.imul(al0, bh8)) | 0;\n mid = (mid + Math.imul(ah0, bl8)) | 0;\n hi = (hi + Math.imul(ah0, bh8)) | 0;\n var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;\n w8 &= 0x3ffffff;\n /* k = 9 */\n lo = Math.imul(al9, bl0);\n mid = Math.imul(al9, bh0);\n mid = (mid + Math.imul(ah9, bl0)) | 0;\n hi = Math.imul(ah9, bh0);\n lo = (lo + Math.imul(al8, bl1)) | 0;\n mid = (mid + Math.imul(al8, bh1)) | 0;\n mid = (mid + Math.imul(ah8, bl1)) | 0;\n hi = (hi + Math.imul(ah8, bh1)) | 0;\n lo = (lo + Math.imul(al7, bl2)) | 0;\n mid = (mid + Math.imul(al7, bh2)) | 0;\n mid = (mid + Math.imul(ah7, bl2)) | 0;\n hi = (hi + Math.imul(ah7, bh2)) | 0;\n lo = (lo + Math.imul(al6, bl3)) | 0;\n mid = (mid + Math.imul(al6, bh3)) | 0;\n mid = (mid + Math.imul(ah6, bl3)) | 0;\n hi = (hi + Math.imul(ah6, bh3)) | 0;\n lo = (lo + Math.imul(al5, bl4)) | 0;\n mid = (mid + Math.imul(al5, bh4)) | 0;\n mid = (mid + Math.imul(ah5, bl4)) | 0;\n hi = (hi + Math.imul(ah5, bh4)) | 0;\n lo = (lo + Math.imul(al4, bl5)) | 0;\n mid = (mid + Math.imul(al4, bh5)) | 0;\n mid = (mid + Math.imul(ah4, bl5)) | 0;\n hi = (hi + Math.imul(ah4, bh5)) | 0;\n lo = (lo + Math.imul(al3, bl6)) | 0;\n mid = (mid + Math.imul(al3, bh6)) | 0;\n mid = (mid + Math.imul(ah3, bl6)) | 0;\n hi = (hi + Math.imul(ah3, bh6)) | 0;\n lo = (lo + Math.imul(al2, bl7)) | 0;\n mid = (mid + Math.imul(al2, bh7)) | 0;\n mid = (mid + Math.imul(ah2, bl7)) | 0;\n hi = (hi + Math.imul(ah2, bh7)) | 0;\n lo = (lo + Math.imul(al1, bl8)) | 0;\n mid = (mid + Math.imul(al1, bh8)) | 0;\n mid = (mid + Math.imul(ah1, bl8)) | 0;\n hi = (hi + Math.imul(ah1, bh8)) | 0;\n lo = (lo + Math.imul(al0, bl9)) | 0;\n mid = (mid + Math.imul(al0, bh9)) | 0;\n mid = (mid + Math.imul(ah0, bl9)) | 0;\n hi = (hi + Math.imul(ah0, bh9)) | 0;\n var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;\n w9 &= 0x3ffffff;\n /* k = 10 */\n lo = Math.imul(al9, bl1);\n mid = Math.imul(al9, bh1);\n mid = (mid + Math.imul(ah9, bl1)) | 0;\n hi = Math.imul(ah9, bh1);\n lo = (lo + Math.imul(al8, bl2)) | 0;\n mid = (mid + Math.imul(al8, bh2)) | 0;\n mid = (mid + Math.imul(ah8, bl2)) | 0;\n hi = (hi + Math.imul(ah8, bh2)) | 0;\n lo = (lo + Math.imul(al7, bl3)) | 0;\n mid = (mid + Math.imul(al7, bh3)) | 0;\n mid = (mid + Math.imul(ah7, bl3)) | 0;\n hi = (hi + Math.imul(ah7, bh3)) | 0;\n lo = (lo + Math.imul(al6, bl4)) | 0;\n mid = (mid + Math.imul(al6, bh4)) | 0;\n mid = (mid + Math.imul(ah6, bl4)) | 0;\n hi = (hi + Math.imul(ah6, bh4)) | 0;\n lo = (lo + Math.imul(al5, bl5)) | 0;\n mid = (mid + Math.imul(al5, bh5)) | 0;\n mid = (mid + Math.imul(ah5, bl5)) | 0;\n hi = (hi + Math.imul(ah5, bh5)) | 0;\n lo = (lo + Math.imul(al4, bl6)) | 0;\n mid = (mid + Math.imul(al4, bh6)) | 0;\n mid = (mid + Math.imul(ah4, bl6)) | 0;\n hi = (hi + Math.imul(ah4, bh6)) | 0;\n lo = (lo + Math.imul(al3, bl7)) | 0;\n mid = (mid + Math.imul(al3, bh7)) | 0;\n mid = (mid + Math.imul(ah3, bl7)) | 0;\n hi = (hi + Math.imul(ah3, bh7)) | 0;\n lo = (lo + Math.imul(al2, bl8)) | 0;\n mid = (mid + Math.imul(al2, bh8)) | 0;\n mid = (mid + Math.imul(ah2, bl8)) | 0;\n hi = (hi + Math.imul(ah2, bh8)) | 0;\n lo = (lo + Math.imul(al1, bl9)) | 0;\n mid = (mid + Math.imul(al1, bh9)) | 0;\n mid = (mid + Math.imul(ah1, bl9)) | 0;\n hi = (hi + Math.imul(ah1, bh9)) | 0;\n var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;\n w10 &= 0x3ffffff;\n /* k = 11 */\n lo = Math.imul(al9, bl2);\n mid = Math.imul(al9, bh2);\n mid = (mid + Math.imul(ah9, bl2)) | 0;\n hi = Math.imul(ah9, bh2);\n lo = (lo + Math.imul(al8, bl3)) | 0;\n mid = (mid + Math.imul(al8, bh3)) | 0;\n mid = (mid + Math.imul(ah8, bl3)) | 0;\n hi = (hi + Math.imul(ah8, bh3)) | 0;\n lo = (lo + Math.imul(al7, bl4)) | 0;\n mid = (mid + Math.imul(al7, bh4)) | 0;\n mid = (mid + Math.imul(ah7, bl4)) | 0;\n hi = (hi + Math.imul(ah7, bh4)) | 0;\n lo = (lo + Math.imul(al6, bl5)) | 0;\n mid = (mid + Math.imul(al6, bh5)) | 0;\n mid = (mid + Math.imul(ah6, bl5)) | 0;\n hi = (hi + Math.imul(ah6, bh5)) | 0;\n lo = (lo + Math.imul(al5, bl6)) | 0;\n mid = (mid + Math.imul(al5, bh6)) | 0;\n mid = (mid + Math.imul(ah5, bl6)) | 0;\n hi = (hi + Math.imul(ah5, bh6)) | 0;\n lo = (lo + Math.imul(al4, bl7)) | 0;\n mid = (mid + Math.imul(al4, bh7)) | 0;\n mid = (mid + Math.imul(ah4, bl7)) | 0;\n hi = (hi + Math.imul(ah4, bh7)) | 0;\n lo = (lo + Math.imul(al3, bl8)) | 0;\n mid = (mid + Math.imul(al3, bh8)) | 0;\n mid = (mid + Math.imul(ah3, bl8)) | 0;\n hi = (hi + Math.imul(ah3, bh8)) | 0;\n lo = (lo + Math.imul(al2, bl9)) | 0;\n mid = (mid + Math.imul(al2, bh9)) | 0;\n mid = (mid + Math.imul(ah2, bl9)) | 0;\n hi = (hi + Math.imul(ah2, bh9)) | 0;\n var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;\n w11 &= 0x3ffffff;\n /* k = 12 */\n lo = Math.imul(al9, bl3);\n mid = Math.imul(al9, bh3);\n mid = (mid + Math.imul(ah9, bl3)) | 0;\n hi = Math.imul(ah9, bh3);\n lo = (lo + Math.imul(al8, bl4)) | 0;\n mid = (mid + Math.imul(al8, bh4)) | 0;\n mid = (mid + Math.imul(ah8, bl4)) | 0;\n hi = (hi + Math.imul(ah8, bh4)) | 0;\n lo = (lo + Math.imul(al7, bl5)) | 0;\n mid = (mid + Math.imul(al7, bh5)) | 0;\n mid = (mid + Math.imul(ah7, bl5)) | 0;\n hi = (hi + Math.imul(ah7, bh5)) | 0;\n lo = (lo + Math.imul(al6, bl6)) | 0;\n mid = (mid + Math.imul(al6, bh6)) | 0;\n mid = (mid + Math.imul(ah6, bl6)) | 0;\n hi = (hi + Math.imul(ah6, bh6)) | 0;\n lo = (lo + Math.imul(al5, bl7)) | 0;\n mid = (mid + Math.imul(al5, bh7)) | 0;\n mid = (mid + Math.imul(ah5, bl7)) | 0;\n hi = (hi + Math.imul(ah5, bh7)) | 0;\n lo = (lo + Math.imul(al4, bl8)) | 0;\n mid = (mid + Math.imul(al4, bh8)) | 0;\n mid = (mid + Math.imul(ah4, bl8)) | 0;\n hi = (hi + Math.imul(ah4, bh8)) | 0;\n lo = (lo + Math.imul(al3, bl9)) | 0;\n mid = (mid + Math.imul(al3, bh9)) | 0;\n mid = (mid + Math.imul(ah3, bl9)) | 0;\n hi = (hi + Math.imul(ah3, bh9)) | 0;\n var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;\n w12 &= 0x3ffffff;\n /* k = 13 */\n lo = Math.imul(al9, bl4);\n mid = Math.imul(al9, bh4);\n mid = (mid + Math.imul(ah9, bl4)) | 0;\n hi = Math.imul(ah9, bh4);\n lo = (lo + Math.imul(al8, bl5)) | 0;\n mid = (mid + Math.imul(al8, bh5)) | 0;\n mid = (mid + Math.imul(ah8, bl5)) | 0;\n hi = (hi + Math.imul(ah8, bh5)) | 0;\n lo = (lo + Math.imul(al7, bl6)) | 0;\n mid = (mid + Math.imul(al7, bh6)) | 0;\n mid = (mid + Math.imul(ah7, bl6)) | 0;\n hi = (hi + Math.imul(ah7, bh6)) | 0;\n lo = (lo + Math.imul(al6, bl7)) | 0;\n mid = (mid + Math.imul(al6, bh7)) | 0;\n mid = (mid + Math.imul(ah6, bl7)) | 0;\n hi = (hi + Math.imul(ah6, bh7)) | 0;\n lo = (lo + Math.imul(al5, bl8)) | 0;\n mid = (mid + Math.imul(al5, bh8)) | 0;\n mid = (mid + Math.imul(ah5, bl8)) | 0;\n hi = (hi + Math.imul(ah5, bh8)) | 0;\n lo = (lo + Math.imul(al4, bl9)) | 0;\n mid = (mid + Math.imul(al4, bh9)) | 0;\n mid = (mid + Math.imul(ah4, bl9)) | 0;\n hi = (hi + Math.imul(ah4, bh9)) | 0;\n var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;\n w13 &= 0x3ffffff;\n /* k = 14 */\n lo = Math.imul(al9, bl5);\n mid = Math.imul(al9, bh5);\n mid = (mid + Math.imul(ah9, bl5)) | 0;\n hi = Math.imul(ah9, bh5);\n lo = (lo + Math.imul(al8, bl6)) | 0;\n mid = (mid + Math.imul(al8, bh6)) | 0;\n mid = (mid + Math.imul(ah8, bl6)) | 0;\n hi = (hi + Math.imul(ah8, bh6)) | 0;\n lo = (lo + Math.imul(al7, bl7)) | 0;\n mid = (mid + Math.imul(al7, bh7)) | 0;\n mid = (mid + Math.imul(ah7, bl7)) | 0;\n hi = (hi + Math.imul(ah7, bh7)) | 0;\n lo = (lo + Math.imul(al6, bl8)) | 0;\n mid = (mid + Math.imul(al6, bh8)) | 0;\n mid = (mid + Math.imul(ah6, bl8)) | 0;\n hi = (hi + Math.imul(ah6, bh8)) | 0;\n lo = (lo + Math.imul(al5, bl9)) | 0;\n mid = (mid + Math.imul(al5, bh9)) | 0;\n mid = (mid + Math.imul(ah5, bl9)) | 0;\n hi = (hi + Math.imul(ah5, bh9)) | 0;\n var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;\n w14 &= 0x3ffffff;\n /* k = 15 */\n lo = Math.imul(al9, bl6);\n mid = Math.imul(al9, bh6);\n mid = (mid + Math.imul(ah9, bl6)) | 0;\n hi = Math.imul(ah9, bh6);\n lo = (lo + Math.imul(al8, bl7)) | 0;\n mid = (mid + Math.imul(al8, bh7)) | 0;\n mid = (mid + Math.imul(ah8, bl7)) | 0;\n hi = (hi + Math.imul(ah8, bh7)) | 0;\n lo = (lo + Math.imul(al7, bl8)) | 0;\n mid = (mid + Math.imul(al7, bh8)) | 0;\n mid = (mid + Math.imul(ah7, bl8)) | 0;\n hi = (hi + Math.imul(ah7, bh8)) | 0;\n lo = (lo + Math.imul(al6, bl9)) | 0;\n mid = (mid + Math.imul(al6, bh9)) | 0;\n mid = (mid + Math.imul(ah6, bl9)) | 0;\n hi = (hi + Math.imul(ah6, bh9)) | 0;\n var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;\n w15 &= 0x3ffffff;\n /* k = 16 */\n lo = Math.imul(al9, bl7);\n mid = Math.imul(al9, bh7);\n mid = (mid + Math.imul(ah9, bl7)) | 0;\n hi = Math.imul(ah9, bh7);\n lo = (lo + Math.imul(al8, bl8)) | 0;\n mid = (mid + Math.imul(al8, bh8)) | 0;\n mid = (mid + Math.imul(ah8, bl8)) | 0;\n hi = (hi + Math.imul(ah8, bh8)) | 0;\n lo = (lo + Math.imul(al7, bl9)) | 0;\n mid = (mid + Math.imul(al7, bh9)) | 0;\n mid = (mid + Math.imul(ah7, bl9)) | 0;\n hi = (hi + Math.imul(ah7, bh9)) | 0;\n var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;\n w16 &= 0x3ffffff;\n /* k = 17 */\n lo = Math.imul(al9, bl8);\n mid = Math.imul(al9, bh8);\n mid = (mid + Math.imul(ah9, bl8)) | 0;\n hi = Math.imul(ah9, bh8);\n lo = (lo + Math.imul(al8, bl9)) | 0;\n mid = (mid + Math.imul(al8, bh9)) | 0;\n mid = (mid + Math.imul(ah8, bl9)) | 0;\n hi = (hi + Math.imul(ah8, bh9)) | 0;\n var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;\n w17 &= 0x3ffffff;\n /* k = 18 */\n lo = Math.imul(al9, bl9);\n mid = Math.imul(al9, bh9);\n mid = (mid + Math.imul(ah9, bl9)) | 0;\n hi = Math.imul(ah9, bh9);\n var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;\n w18 &= 0x3ffffff;\n o[0] = w0;\n o[1] = w1;\n o[2] = w2;\n o[3] = w3;\n o[4] = w4;\n o[5] = w5;\n o[6] = w6;\n o[7] = w7;\n o[8] = w8;\n o[9] = w9;\n o[10] = w10;\n o[11] = w11;\n o[12] = w12;\n o[13] = w13;\n o[14] = w14;\n o[15] = w15;\n o[16] = w16;\n o[17] = w17;\n o[18] = w18;\n if (c !== 0) {\n o[19] = c;\n out.length++;\n }\n return out;\n };\n\n // Polyfill comb\n if (!Math.imul) {\n comb10MulTo = smallMulTo;\n }\n\n function bigMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n out.length = self.length + num.length;\n\n var carry = 0;\n var hncarry = 0;\n for (var k = 0; k < out.length - 1; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = hncarry;\n hncarry = 0;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = k - j;\n var a = self.words[i] | 0;\n var b = num.words[j] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;\n lo = (lo + rword) | 0;\n rword = lo & 0x3ffffff;\n ncarry = (ncarry + (lo >>> 26)) | 0;\n\n hncarry += ncarry >>> 26;\n ncarry &= 0x3ffffff;\n }\n out.words[k] = rword;\n carry = ncarry;\n ncarry = hncarry;\n }\n if (carry !== 0) {\n out.words[k] = carry;\n } else {\n out.length--;\n }\n\n return out._strip();\n }\n\n function jumboMulTo (self, num, out) {\n // Temporary disable, see https://github.com/indutny/bn.js/issues/211\n // var fftm = new FFTM();\n // return fftm.mulp(self, num, out);\n return bigMulTo(self, num, out);\n }\n\n BN.prototype.mulTo = function mulTo (num, out) {\n var res;\n var len = this.length + num.length;\n if (this.length === 10 && num.length === 10) {\n res = comb10MulTo(this, num, out);\n } else if (len < 63) {\n res = smallMulTo(this, num, out);\n } else if (len < 1024) {\n res = bigMulTo(this, num, out);\n } else {\n res = jumboMulTo(this, num, out);\n }\n\n return res;\n };\n\n // Cooley-Tukey algorithm for FFT\n // slightly revisited to rely on looping instead of recursion\n\n function FFTM (x, y) {\n this.x = x;\n this.y = y;\n }\n\n FFTM.prototype.makeRBT = function makeRBT (N) {\n var t = new Array(N);\n var l = BN.prototype._countBits(N) - 1;\n for (var i = 0; i < N; i++) {\n t[i] = this.revBin(i, l, N);\n }\n\n return t;\n };\n\n // Returns binary-reversed representation of `x`\n FFTM.prototype.revBin = function revBin (x, l, N) {\n if (x === 0 || x === N - 1) return x;\n\n var rb = 0;\n for (var i = 0; i < l; i++) {\n rb |= (x & 1) << (l - i - 1);\n x >>= 1;\n }\n\n return rb;\n };\n\n // Performs \"tweedling\" phase, therefore 'emulating'\n // behaviour of the recursive algorithm\n FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {\n for (var i = 0; i < N; i++) {\n rtws[i] = rws[rbt[i]];\n itws[i] = iws[rbt[i]];\n }\n };\n\n FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {\n this.permute(rbt, rws, iws, rtws, itws, N);\n\n for (var s = 1; s < N; s <<= 1) {\n var l = s << 1;\n\n var rtwdf = Math.cos(2 * Math.PI / l);\n var itwdf = Math.sin(2 * Math.PI / l);\n\n for (var p = 0; p < N; p += l) {\n var rtwdf_ = rtwdf;\n var itwdf_ = itwdf;\n\n for (var j = 0; j < s; j++) {\n var re = rtws[p + j];\n var ie = itws[p + j];\n\n var ro = rtws[p + j + s];\n var io = itws[p + j + s];\n\n var rx = rtwdf_ * ro - itwdf_ * io;\n\n io = rtwdf_ * io + itwdf_ * ro;\n ro = rx;\n\n rtws[p + j] = re + ro;\n itws[p + j] = ie + io;\n\n rtws[p + j + s] = re - ro;\n itws[p + j + s] = ie - io;\n\n /* jshint maxdepth : false */\n if (j !== l) {\n rx = rtwdf * rtwdf_ - itwdf * itwdf_;\n\n itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;\n rtwdf_ = rx;\n }\n }\n }\n }\n };\n\n FFTM.prototype.guessLen13b = function guessLen13b (n, m) {\n var N = Math.max(m, n) | 1;\n var odd = N & 1;\n var i = 0;\n for (N = N / 2 | 0; N; N = N >>> 1) {\n i++;\n }\n\n return 1 << i + 1 + odd;\n };\n\n FFTM.prototype.conjugate = function conjugate (rws, iws, N) {\n if (N <= 1) return;\n\n for (var i = 0; i < N / 2; i++) {\n var t = rws[i];\n\n rws[i] = rws[N - i - 1];\n rws[N - i - 1] = t;\n\n t = iws[i];\n\n iws[i] = -iws[N - i - 1];\n iws[N - i - 1] = -t;\n }\n };\n\n FFTM.prototype.normalize13b = function normalize13b (ws, N) {\n var carry = 0;\n for (var i = 0; i < N / 2; i++) {\n var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +\n Math.round(ws[2 * i] / N) +\n carry;\n\n ws[i] = w & 0x3ffffff;\n\n if (w < 0x4000000) {\n carry = 0;\n } else {\n carry = w / 0x4000000 | 0;\n }\n }\n\n return ws;\n };\n\n FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {\n var carry = 0;\n for (var i = 0; i < len; i++) {\n carry = carry + (ws[i] | 0);\n\n rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;\n rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;\n }\n\n // Pad with zeroes\n for (i = 2 * len; i < N; ++i) {\n rws[i] = 0;\n }\n\n assert(carry === 0);\n assert((carry & ~0x1fff) === 0);\n };\n\n FFTM.prototype.stub = function stub (N) {\n var ph = new Array(N);\n for (var i = 0; i < N; i++) {\n ph[i] = 0;\n }\n\n return ph;\n };\n\n FFTM.prototype.mulp = function mulp (x, y, out) {\n var N = 2 * this.guessLen13b(x.length, y.length);\n\n var rbt = this.makeRBT(N);\n\n var _ = this.stub(N);\n\n var rws = new Array(N);\n var rwst = new Array(N);\n var iwst = new Array(N);\n\n var nrws = new Array(N);\n var nrwst = new Array(N);\n var niwst = new Array(N);\n\n var rmws = out.words;\n rmws.length = N;\n\n this.convert13b(x.words, x.length, rws, N);\n this.convert13b(y.words, y.length, nrws, N);\n\n this.transform(rws, _, rwst, iwst, N, rbt);\n this.transform(nrws, _, nrwst, niwst, N, rbt);\n\n for (var i = 0; i < N; i++) {\n var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];\n iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];\n rwst[i] = rx;\n }\n\n this.conjugate(rwst, iwst, N);\n this.transform(rwst, iwst, rmws, _, N, rbt);\n this.conjugate(rmws, _, N);\n this.normalize13b(rmws, N);\n\n out.negative = x.negative ^ y.negative;\n out.length = x.length + y.length;\n return out._strip();\n };\n\n // Multiply `this` by `num`\n BN.prototype.mul = function mul (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return this.mulTo(num, out);\n };\n\n // Multiply employing FFT\n BN.prototype.mulf = function mulf (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return jumboMulTo(this, num, out);\n };\n\n // In-place Multiplication\n BN.prototype.imul = function imul (num) {\n return this.clone().mulTo(num, this);\n };\n\n BN.prototype.imuln = function imuln (num) {\n var isNegNum = num < 0;\n if (isNegNum) num = -num;\n\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n\n // Carry\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = (this.words[i] | 0) * num;\n var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);\n carry >>= 26;\n carry += (w / 0x4000000) | 0;\n // NOTE: lo is 27bit maximum\n carry += lo >>> 26;\n this.words[i] = lo & 0x3ffffff;\n }\n\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n\n return isNegNum ? this.ineg() : this;\n };\n\n BN.prototype.muln = function muln (num) {\n return this.clone().imuln(num);\n };\n\n // `this` * `this`\n BN.prototype.sqr = function sqr () {\n return this.mul(this);\n };\n\n // `this` * `this` in-place\n BN.prototype.isqr = function isqr () {\n return this.imul(this.clone());\n };\n\n // Math.pow(`this`, `num`)\n BN.prototype.pow = function pow (num) {\n var w = toBitArray(num);\n if (w.length === 0) return new BN(1);\n\n // Skip leading zeroes\n var res = this;\n for (var i = 0; i < w.length; i++, res = res.sqr()) {\n if (w[i] !== 0) break;\n }\n\n if (++i < w.length) {\n for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {\n if (w[i] === 0) continue;\n\n res = res.mul(q);\n }\n }\n\n return res;\n };\n\n // Shift-left in-place\n BN.prototype.iushln = function iushln (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);\n var i;\n\n if (r !== 0) {\n var carry = 0;\n\n for (i = 0; i < this.length; i++) {\n var newCarry = this.words[i] & carryMask;\n var c = ((this.words[i] | 0) - newCarry) << r;\n this.words[i] = c | carry;\n carry = newCarry >>> (26 - r);\n }\n\n if (carry) {\n this.words[i] = carry;\n this.length++;\n }\n }\n\n if (s !== 0) {\n for (i = this.length - 1; i >= 0; i--) {\n this.words[i + s] = this.words[i];\n }\n\n for (i = 0; i < s; i++) {\n this.words[i] = 0;\n }\n\n this.length += s;\n }\n\n return this._strip();\n };\n\n BN.prototype.ishln = function ishln (bits) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushln(bits);\n };\n\n // Shift-right in-place\n // NOTE: `hint` is a lowest bit before trailing zeroes\n // NOTE: if `extended` is present - it will be filled with destroyed bits\n BN.prototype.iushrn = function iushrn (bits, hint, extended) {\n assert(typeof bits === 'number' && bits >= 0);\n var h;\n if (hint) {\n h = (hint - (hint % 26)) / 26;\n } else {\n h = 0;\n }\n\n var r = bits % 26;\n var s = Math.min((bits - r) / 26, this.length);\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n var maskedWords = extended;\n\n h -= s;\n h = Math.max(0, h);\n\n // Extended mode, copy masked part\n if (maskedWords) {\n for (var i = 0; i < s; i++) {\n maskedWords.words[i] = this.words[i];\n }\n maskedWords.length = s;\n }\n\n if (s === 0) {\n // No-op, we should not move anything at all\n } else if (this.length > s) {\n this.length -= s;\n for (i = 0; i < this.length; i++) {\n this.words[i] = this.words[i + s];\n }\n } else {\n this.words[0] = 0;\n this.length = 1;\n }\n\n var carry = 0;\n for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {\n var word = this.words[i] | 0;\n this.words[i] = (carry << (26 - r)) | (word >>> r);\n carry = word & mask;\n }\n\n // Push carried bits as a mask\n if (maskedWords && carry !== 0) {\n maskedWords.words[maskedWords.length++] = carry;\n }\n\n if (this.length === 0) {\n this.words[0] = 0;\n this.length = 1;\n }\n\n return this._strip();\n };\n\n BN.prototype.ishrn = function ishrn (bits, hint, extended) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushrn(bits, hint, extended);\n };\n\n // Shift-left\n BN.prototype.shln = function shln (bits) {\n return this.clone().ishln(bits);\n };\n\n BN.prototype.ushln = function ushln (bits) {\n return this.clone().iushln(bits);\n };\n\n // Shift-right\n BN.prototype.shrn = function shrn (bits) {\n return this.clone().ishrn(bits);\n };\n\n BN.prototype.ushrn = function ushrn (bits) {\n return this.clone().iushrn(bits);\n };\n\n // Test if n bit is set\n BN.prototype.testn = function testn (bit) {\n assert(typeof bit === 'number' && bit >= 0);\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) return false;\n\n // Check bit and return\n var w = this.words[s];\n\n return !!(w & q);\n };\n\n // Return only lowers bits of number (in-place)\n BN.prototype.imaskn = function imaskn (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n\n assert(this.negative === 0, 'imaskn works only with positive numbers');\n\n if (this.length <= s) {\n return this;\n }\n\n if (r !== 0) {\n s++;\n }\n this.length = Math.min(s, this.length);\n\n if (r !== 0) {\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n this.words[this.length - 1] &= mask;\n }\n\n return this._strip();\n };\n\n // Return only lowers bits of number\n BN.prototype.maskn = function maskn (bits) {\n return this.clone().imaskn(bits);\n };\n\n // Add plain number `num` to `this`\n BN.prototype.iaddn = function iaddn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.isubn(-num);\n\n // Possible sign change\n if (this.negative !== 0) {\n if (this.length === 1 && (this.words[0] | 0) <= num) {\n this.words[0] = num - (this.words[0] | 0);\n this.negative = 0;\n return this;\n }\n\n this.negative = 0;\n this.isubn(num);\n this.negative = 1;\n return this;\n }\n\n // Add without checks\n return this._iaddn(num);\n };\n\n BN.prototype._iaddn = function _iaddn (num) {\n this.words[0] += num;\n\n // Carry\n for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {\n this.words[i] -= 0x4000000;\n if (i === this.length - 1) {\n this.words[i + 1] = 1;\n } else {\n this.words[i + 1]++;\n }\n }\n this.length = Math.max(this.length, i + 1);\n\n return this;\n };\n\n // Subtract plain number `num` from `this`\n BN.prototype.isubn = function isubn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.iaddn(-num);\n\n if (this.negative !== 0) {\n this.negative = 0;\n this.iaddn(num);\n this.negative = 1;\n return this;\n }\n\n this.words[0] -= num;\n\n if (this.length === 1 && this.words[0] < 0) {\n this.words[0] = -this.words[0];\n this.negative = 1;\n } else {\n // Carry\n for (var i = 0; i < this.length && this.words[i] < 0; i++) {\n this.words[i] += 0x4000000;\n this.words[i + 1] -= 1;\n }\n }\n\n return this._strip();\n };\n\n BN.prototype.addn = function addn (num) {\n return this.clone().iaddn(num);\n };\n\n BN.prototype.subn = function subn (num) {\n return this.clone().isubn(num);\n };\n\n BN.prototype.iabs = function iabs () {\n this.negative = 0;\n\n return this;\n };\n\n BN.prototype.abs = function abs () {\n return this.clone().iabs();\n };\n\n BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {\n var len = num.length + shift;\n var i;\n\n this._expand(len);\n\n var w;\n var carry = 0;\n for (i = 0; i < num.length; i++) {\n w = (this.words[i + shift] | 0) + carry;\n var right = (num.words[i] | 0) * mul;\n w -= right & 0x3ffffff;\n carry = (w >> 26) - ((right / 0x4000000) | 0);\n this.words[i + shift] = w & 0x3ffffff;\n }\n for (; i < this.length - shift; i++) {\n w = (this.words[i + shift] | 0) + carry;\n carry = w >> 26;\n this.words[i + shift] = w & 0x3ffffff;\n }\n\n if (carry === 0) return this._strip();\n\n // Subtraction overflow\n assert(carry === -1);\n carry = 0;\n for (i = 0; i < this.length; i++) {\n w = -(this.words[i] | 0) + carry;\n carry = w >> 26;\n this.words[i] = w & 0x3ffffff;\n }\n this.negative = 1;\n\n return this._strip();\n };\n\n BN.prototype._wordDiv = function _wordDiv (num, mode) {\n var shift = this.length - num.length;\n\n var a = this.clone();\n var b = num;\n\n // Normalize\n var bhi = b.words[b.length - 1] | 0;\n var bhiBits = this._countBits(bhi);\n shift = 26 - bhiBits;\n if (shift !== 0) {\n b = b.ushln(shift);\n a.iushln(shift);\n bhi = b.words[b.length - 1] | 0;\n }\n\n // Initialize quotient\n var m = a.length - b.length;\n var q;\n\n if (mode !== 'mod') {\n q = new BN(null);\n q.length = m + 1;\n q.words = new Array(q.length);\n for (var i = 0; i < q.length; i++) {\n q.words[i] = 0;\n }\n }\n\n var diff = a.clone()._ishlnsubmul(b, 1, m);\n if (diff.negative === 0) {\n a = diff;\n if (q) {\n q.words[m] = 1;\n }\n }\n\n for (var j = m - 1; j >= 0; j--) {\n var qj = (a.words[b.length + j] | 0) * 0x4000000 +\n (a.words[b.length + j - 1] | 0);\n\n // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max\n // (0x7ffffff)\n qj = Math.min((qj / bhi) | 0, 0x3ffffff);\n\n a._ishlnsubmul(b, qj, j);\n while (a.negative !== 0) {\n qj--;\n a.negative = 0;\n a._ishlnsubmul(b, 1, j);\n if (!a.isZero()) {\n a.negative ^= 1;\n }\n }\n if (q) {\n q.words[j] = qj;\n }\n }\n if (q) {\n q._strip();\n }\n a._strip();\n\n // Denormalize\n if (mode !== 'div' && shift !== 0) {\n a.iushrn(shift);\n }\n\n return {\n div: q || null,\n mod: a\n };\n };\n\n // NOTE: 1) `mode` can be set to `mod` to request mod only,\n // to `div` to request div only, or be absent to\n // request both div & mod\n // 2) `positive` is true if unsigned mod is requested\n BN.prototype.divmod = function divmod (num, mode, positive) {\n assert(!num.isZero());\n\n if (this.isZero()) {\n return {\n div: new BN(0),\n mod: new BN(0)\n };\n }\n\n var div, mod, res;\n if (this.negative !== 0 && num.negative === 0) {\n res = this.neg().divmod(num, mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.iadd(num);\n }\n }\n\n return {\n div: div,\n mod: mod\n };\n }\n\n if (this.negative === 0 && num.negative !== 0) {\n res = this.divmod(num.neg(), mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n return {\n div: div,\n mod: res.mod\n };\n }\n\n if ((this.negative & num.negative) !== 0) {\n res = this.neg().divmod(num.neg(), mode);\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.isub(num);\n }\n }\n\n return {\n div: res.div,\n mod: mod\n };\n }\n\n // Both numbers are positive at this point\n\n // Strip both numbers to approximate shift value\n if (num.length > this.length || this.cmp(num) < 0) {\n return {\n div: new BN(0),\n mod: this\n };\n }\n\n // Very short reduction\n if (num.length === 1) {\n if (mode === 'div') {\n return {\n div: this.divn(num.words[0]),\n mod: null\n };\n }\n\n if (mode === 'mod') {\n return {\n div: null,\n mod: new BN(this.modrn(num.words[0]))\n };\n }\n\n return {\n div: this.divn(num.words[0]),\n mod: new BN(this.modrn(num.words[0]))\n };\n }\n\n return this._wordDiv(num, mode);\n };\n\n // Find `this` / `num`\n BN.prototype.div = function div (num) {\n return this.divmod(num, 'div', false).div;\n };\n\n // Find `this` % `num`\n BN.prototype.mod = function mod (num) {\n return this.divmod(num, 'mod', false).mod;\n };\n\n BN.prototype.umod = function umod (num) {\n return this.divmod(num, 'mod', true).mod;\n };\n\n // Find Round(`this` / `num`)\n BN.prototype.divRound = function divRound (num) {\n var dm = this.divmod(num);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;\n\n var half = num.ushrn(1);\n var r2 = num.andln(1);\n var cmp = mod.cmp(half);\n\n // Round down\n if (cmp < 0 || (r2 === 1 && cmp === 0)) return dm.div;\n\n // Round up\n return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);\n };\n\n BN.prototype.modrn = function modrn (num) {\n var isNegNum = num < 0;\n if (isNegNum) num = -num;\n\n assert(num <= 0x3ffffff);\n var p = (1 << 26) % num;\n\n var acc = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n acc = (p * acc + (this.words[i] | 0)) % num;\n }\n\n return isNegNum ? -acc : acc;\n };\n\n // WARNING: DEPRECATED\n BN.prototype.modn = function modn (num) {\n return this.modrn(num);\n };\n\n // In-place division by number\n BN.prototype.idivn = function idivn (num) {\n var isNegNum = num < 0;\n if (isNegNum) num = -num;\n\n assert(num <= 0x3ffffff);\n\n var carry = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var w = (this.words[i] | 0) + carry * 0x4000000;\n this.words[i] = (w / num) | 0;\n carry = w % num;\n }\n\n this._strip();\n return isNegNum ? this.ineg() : this;\n };\n\n BN.prototype.divn = function divn (num) {\n return this.clone().idivn(num);\n };\n\n BN.prototype.egcd = function egcd (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var x = this;\n var y = p.clone();\n\n if (x.negative !== 0) {\n x = x.umod(p);\n } else {\n x = x.clone();\n }\n\n // A * x + B * y = x\n var A = new BN(1);\n var B = new BN(0);\n\n // C * x + D * y = y\n var C = new BN(0);\n var D = new BN(1);\n\n var g = 0;\n\n while (x.isEven() && y.isEven()) {\n x.iushrn(1);\n y.iushrn(1);\n ++g;\n }\n\n var yp = y.clone();\n var xp = x.clone();\n\n while (!x.isZero()) {\n for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n x.iushrn(i);\n while (i-- > 0) {\n if (A.isOdd() || B.isOdd()) {\n A.iadd(yp);\n B.isub(xp);\n }\n\n A.iushrn(1);\n B.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n y.iushrn(j);\n while (j-- > 0) {\n if (C.isOdd() || D.isOdd()) {\n C.iadd(yp);\n D.isub(xp);\n }\n\n C.iushrn(1);\n D.iushrn(1);\n }\n }\n\n if (x.cmp(y) >= 0) {\n x.isub(y);\n A.isub(C);\n B.isub(D);\n } else {\n y.isub(x);\n C.isub(A);\n D.isub(B);\n }\n }\n\n return {\n a: C,\n b: D,\n gcd: y.iushln(g)\n };\n };\n\n // This is reduced incarnation of the binary EEA\n // above, designated to invert members of the\n // _prime_ fields F(p) at a maximal speed\n BN.prototype._invmp = function _invmp (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var a = this;\n var b = p.clone();\n\n if (a.negative !== 0) {\n a = a.umod(p);\n } else {\n a = a.clone();\n }\n\n var x1 = new BN(1);\n var x2 = new BN(0);\n\n var delta = b.clone();\n\n while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {\n for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n a.iushrn(i);\n while (i-- > 0) {\n if (x1.isOdd()) {\n x1.iadd(delta);\n }\n\n x1.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n b.iushrn(j);\n while (j-- > 0) {\n if (x2.isOdd()) {\n x2.iadd(delta);\n }\n\n x2.iushrn(1);\n }\n }\n\n if (a.cmp(b) >= 0) {\n a.isub(b);\n x1.isub(x2);\n } else {\n b.isub(a);\n x2.isub(x1);\n }\n }\n\n var res;\n if (a.cmpn(1) === 0) {\n res = x1;\n } else {\n res = x2;\n }\n\n if (res.cmpn(0) < 0) {\n res.iadd(p);\n }\n\n return res;\n };\n\n BN.prototype.gcd = function gcd (num) {\n if (this.isZero()) return num.abs();\n if (num.isZero()) return this.abs();\n\n var a = this.clone();\n var b = num.clone();\n a.negative = 0;\n b.negative = 0;\n\n // Remove common factor of two\n for (var shift = 0; a.isEven() && b.isEven(); shift++) {\n a.iushrn(1);\n b.iushrn(1);\n }\n\n do {\n while (a.isEven()) {\n a.iushrn(1);\n }\n while (b.isEven()) {\n b.iushrn(1);\n }\n\n var r = a.cmp(b);\n if (r < 0) {\n // Swap `a` and `b` to make `a` always bigger than `b`\n var t = a;\n a = b;\n b = t;\n } else if (r === 0 || b.cmpn(1) === 0) {\n break;\n }\n\n a.isub(b);\n } while (true);\n\n return b.iushln(shift);\n };\n\n // Invert number in the field F(num)\n BN.prototype.invm = function invm (num) {\n return this.egcd(num).a.umod(num);\n };\n\n BN.prototype.isEven = function isEven () {\n return (this.words[0] & 1) === 0;\n };\n\n BN.prototype.isOdd = function isOdd () {\n return (this.words[0] & 1) === 1;\n };\n\n // And first word and num\n BN.prototype.andln = function andln (num) {\n return this.words[0] & num;\n };\n\n // Increment at the bit position in-line\n BN.prototype.bincn = function bincn (bit) {\n assert(typeof bit === 'number');\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) {\n this._expand(s + 1);\n this.words[s] |= q;\n return this;\n }\n\n // Add bit and propagate, if needed\n var carry = q;\n for (var i = s; carry !== 0 && i < this.length; i++) {\n var w = this.words[i] | 0;\n w += carry;\n carry = w >>> 26;\n w &= 0x3ffffff;\n this.words[i] = w;\n }\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n return this;\n };\n\n BN.prototype.isZero = function isZero () {\n return this.length === 1 && this.words[0] === 0;\n };\n\n BN.prototype.cmpn = function cmpn (num) {\n var negative = num < 0;\n\n if (this.negative !== 0 && !negative) return -1;\n if (this.negative === 0 && negative) return 1;\n\n this._strip();\n\n var res;\n if (this.length > 1) {\n res = 1;\n } else {\n if (negative) {\n num = -num;\n }\n\n assert(num <= 0x3ffffff, 'Number is too big');\n\n var w = this.words[0] | 0;\n res = w === num ? 0 : w < num ? -1 : 1;\n }\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Compare two numbers and return:\n // 1 - if `this` > `num`\n // 0 - if `this` == `num`\n // -1 - if `this` < `num`\n BN.prototype.cmp = function cmp (num) {\n if (this.negative !== 0 && num.negative === 0) return -1;\n if (this.negative === 0 && num.negative !== 0) return 1;\n\n var res = this.ucmp(num);\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Unsigned comparison\n BN.prototype.ucmp = function ucmp (num) {\n // At this point both numbers have the same sign\n if (this.length > num.length) return 1;\n if (this.length < num.length) return -1;\n\n var res = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var a = this.words[i] | 0;\n var b = num.words[i] | 0;\n\n if (a === b) continue;\n if (a < b) {\n res = -1;\n } else if (a > b) {\n res = 1;\n }\n break;\n }\n return res;\n };\n\n BN.prototype.gtn = function gtn (num) {\n return this.cmpn(num) === 1;\n };\n\n BN.prototype.gt = function gt (num) {\n return this.cmp(num) === 1;\n };\n\n BN.prototype.gten = function gten (num) {\n return this.cmpn(num) >= 0;\n };\n\n BN.prototype.gte = function gte (num) {\n return this.cmp(num) >= 0;\n };\n\n BN.prototype.ltn = function ltn (num) {\n return this.cmpn(num) === -1;\n };\n\n BN.prototype.lt = function lt (num) {\n return this.cmp(num) === -1;\n };\n\n BN.prototype.lten = function lten (num) {\n return this.cmpn(num) <= 0;\n };\n\n BN.prototype.lte = function lte (num) {\n return this.cmp(num) <= 0;\n };\n\n BN.prototype.eqn = function eqn (num) {\n return this.cmpn(num) === 0;\n };\n\n BN.prototype.eq = function eq (num) {\n return this.cmp(num) === 0;\n };\n\n //\n // A reduce context, could be using montgomery or something better, depending\n // on the `m` itself.\n //\n BN.red = function red (num) {\n return new Red(num);\n };\n\n BN.prototype.toRed = function toRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n assert(this.negative === 0, 'red works only with positives');\n return ctx.convertTo(this)._forceRed(ctx);\n };\n\n BN.prototype.fromRed = function fromRed () {\n assert(this.red, 'fromRed works only with numbers in reduction context');\n return this.red.convertFrom(this);\n };\n\n BN.prototype._forceRed = function _forceRed (ctx) {\n this.red = ctx;\n return this;\n };\n\n BN.prototype.forceRed = function forceRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n return this._forceRed(ctx);\n };\n\n BN.prototype.redAdd = function redAdd (num) {\n assert(this.red, 'redAdd works only with red numbers');\n return this.red.add(this, num);\n };\n\n BN.prototype.redIAdd = function redIAdd (num) {\n assert(this.red, 'redIAdd works only with red numbers');\n return this.red.iadd(this, num);\n };\n\n BN.prototype.redSub = function redSub (num) {\n assert(this.red, 'redSub works only with red numbers');\n return this.red.sub(this, num);\n };\n\n BN.prototype.redISub = function redISub (num) {\n assert(this.red, 'redISub works only with red numbers');\n return this.red.isub(this, num);\n };\n\n BN.prototype.redShl = function redShl (num) {\n assert(this.red, 'redShl works only with red numbers');\n return this.red.shl(this, num);\n };\n\n BN.prototype.redMul = function redMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.mul(this, num);\n };\n\n BN.prototype.redIMul = function redIMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.imul(this, num);\n };\n\n BN.prototype.redSqr = function redSqr () {\n assert(this.red, 'redSqr works only with red numbers');\n this.red._verify1(this);\n return this.red.sqr(this);\n };\n\n BN.prototype.redISqr = function redISqr () {\n assert(this.red, 'redISqr works only with red numbers');\n this.red._verify1(this);\n return this.red.isqr(this);\n };\n\n // Square root over p\n BN.prototype.redSqrt = function redSqrt () {\n assert(this.red, 'redSqrt works only with red numbers');\n this.red._verify1(this);\n return this.red.sqrt(this);\n };\n\n BN.prototype.redInvm = function redInvm () {\n assert(this.red, 'redInvm works only with red numbers');\n this.red._verify1(this);\n return this.red.invm(this);\n };\n\n // Return negative clone of `this` % `red modulo`\n BN.prototype.redNeg = function redNeg () {\n assert(this.red, 'redNeg works only with red numbers');\n this.red._verify1(this);\n return this.red.neg(this);\n };\n\n BN.prototype.redPow = function redPow (num) {\n assert(this.red && !num.red, 'redPow(normalNum)');\n this.red._verify1(this);\n return this.red.pow(this, num);\n };\n\n // Prime numbers with efficient reduction\n var primes = {\n k256: null,\n p224: null,\n p192: null,\n p25519: null\n };\n\n // Pseudo-Mersenne prime\n function MPrime (name, p) {\n // P = 2 ^ N - K\n this.name = name;\n this.p = new BN(p, 16);\n this.n = this.p.bitLength();\n this.k = new BN(1).iushln(this.n).isub(this.p);\n\n this.tmp = this._tmp();\n }\n\n MPrime.prototype._tmp = function _tmp () {\n var tmp = new BN(null);\n tmp.words = new Array(Math.ceil(this.n / 13));\n return tmp;\n };\n\n MPrime.prototype.ireduce = function ireduce (num) {\n // Assumes that `num` is less than `P^2`\n // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)\n var r = num;\n var rlen;\n\n do {\n this.split(r, this.tmp);\n r = this.imulK(r);\n r = r.iadd(this.tmp);\n rlen = r.bitLength();\n } while (rlen > this.n);\n\n var cmp = rlen < this.n ? -1 : r.ucmp(this.p);\n if (cmp === 0) {\n r.words[0] = 0;\n r.length = 1;\n } else if (cmp > 0) {\n r.isub(this.p);\n } else {\n if (r.strip !== undefined) {\n // r is a BN v4 instance\n r.strip();\n } else {\n // r is a BN v5 instance\n r._strip();\n }\n }\n\n return r;\n };\n\n MPrime.prototype.split = function split (input, out) {\n input.iushrn(this.n, 0, out);\n };\n\n MPrime.prototype.imulK = function imulK (num) {\n return num.imul(this.k);\n };\n\n function K256 () {\n MPrime.call(\n this,\n 'k256',\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');\n }\n inherits(K256, MPrime);\n\n K256.prototype.split = function split (input, output) {\n // 256 = 9 * 26 + 22\n var mask = 0x3fffff;\n\n var outLen = Math.min(input.length, 9);\n for (var i = 0; i < outLen; i++) {\n output.words[i] = input.words[i];\n }\n output.length = outLen;\n\n if (input.length <= 9) {\n input.words[0] = 0;\n input.length = 1;\n return;\n }\n\n // Shift by 9 limbs\n var prev = input.words[9];\n output.words[output.length++] = prev & mask;\n\n for (i = 10; i < input.length; i++) {\n var next = input.words[i] | 0;\n input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);\n prev = next;\n }\n prev >>>= 22;\n input.words[i - 10] = prev;\n if (prev === 0 && input.length > 10) {\n input.length -= 10;\n } else {\n input.length -= 9;\n }\n };\n\n K256.prototype.imulK = function imulK (num) {\n // K = 0x1000003d1 = [ 0x40, 0x3d1 ]\n num.words[num.length] = 0;\n num.words[num.length + 1] = 0;\n num.length += 2;\n\n // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390\n var lo = 0;\n for (var i = 0; i < num.length; i++) {\n var w = num.words[i] | 0;\n lo += w * 0x3d1;\n num.words[i] = lo & 0x3ffffff;\n lo = w * 0x40 + ((lo / 0x4000000) | 0);\n }\n\n // Fast length reduction\n if (num.words[num.length - 1] === 0) {\n num.length--;\n if (num.words[num.length - 1] === 0) {\n num.length--;\n }\n }\n return num;\n };\n\n function P224 () {\n MPrime.call(\n this,\n 'p224',\n 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');\n }\n inherits(P224, MPrime);\n\n function P192 () {\n MPrime.call(\n this,\n 'p192',\n 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');\n }\n inherits(P192, MPrime);\n\n function P25519 () {\n // 2 ^ 255 - 19\n MPrime.call(\n this,\n '25519',\n '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');\n }\n inherits(P25519, MPrime);\n\n P25519.prototype.imulK = function imulK (num) {\n // K = 0x13\n var carry = 0;\n for (var i = 0; i < num.length; i++) {\n var hi = (num.words[i] | 0) * 0x13 + carry;\n var lo = hi & 0x3ffffff;\n hi >>>= 26;\n\n num.words[i] = lo;\n carry = hi;\n }\n if (carry !== 0) {\n num.words[num.length++] = carry;\n }\n return num;\n };\n\n // Exported mostly for testing purposes, use plain name instead\n BN._prime = function prime (name) {\n // Cached version of prime\n if (primes[name]) return primes[name];\n\n var prime;\n if (name === 'k256') {\n prime = new K256();\n } else if (name === 'p224') {\n prime = new P224();\n } else if (name === 'p192') {\n prime = new P192();\n } else if (name === 'p25519') {\n prime = new P25519();\n } else {\n throw new Error('Unknown prime ' + name);\n }\n primes[name] = prime;\n\n return prime;\n };\n\n //\n // Base reduction engine\n //\n function Red (m) {\n if (typeof m === 'string') {\n var prime = BN._prime(m);\n this.m = prime.p;\n this.prime = prime;\n } else {\n assert(m.gtn(1), 'modulus must be greater than 1');\n this.m = m;\n this.prime = null;\n }\n }\n\n Red.prototype._verify1 = function _verify1 (a) {\n assert(a.negative === 0, 'red works only with positives');\n assert(a.red, 'red works only with red numbers');\n };\n\n Red.prototype._verify2 = function _verify2 (a, b) {\n assert((a.negative | b.negative) === 0, 'red works only with positives');\n assert(a.red && a.red === b.red,\n 'red works only with red numbers');\n };\n\n Red.prototype.imod = function imod (a) {\n if (this.prime) return this.prime.ireduce(a)._forceRed(this);\n\n move(a, a.umod(this.m)._forceRed(this));\n return a;\n };\n\n Red.prototype.neg = function neg (a) {\n if (a.isZero()) {\n return a.clone();\n }\n\n return this.m.sub(a)._forceRed(this);\n };\n\n Red.prototype.add = function add (a, b) {\n this._verify2(a, b);\n\n var res = a.add(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.iadd = function iadd (a, b) {\n this._verify2(a, b);\n\n var res = a.iadd(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res;\n };\n\n Red.prototype.sub = function sub (a, b) {\n this._verify2(a, b);\n\n var res = a.sub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.isub = function isub (a, b) {\n this._verify2(a, b);\n\n var res = a.isub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res;\n };\n\n Red.prototype.shl = function shl (a, num) {\n this._verify1(a);\n return this.imod(a.ushln(num));\n };\n\n Red.prototype.imul = function imul (a, b) {\n this._verify2(a, b);\n return this.imod(a.imul(b));\n };\n\n Red.prototype.mul = function mul (a, b) {\n this._verify2(a, b);\n return this.imod(a.mul(b));\n };\n\n Red.prototype.isqr = function isqr (a) {\n return this.imul(a, a.clone());\n };\n\n Red.prototype.sqr = function sqr (a) {\n return this.mul(a, a);\n };\n\n Red.prototype.sqrt = function sqrt (a) {\n if (a.isZero()) return a.clone();\n\n var mod3 = this.m.andln(3);\n assert(mod3 % 2 === 1);\n\n // Fast case\n if (mod3 === 3) {\n var pow = this.m.add(new BN(1)).iushrn(2);\n return this.pow(a, pow);\n }\n\n // Tonelli-Shanks algorithm (Totally unoptimized and slow)\n //\n // Find Q and S, that Q * 2 ^ S = (P - 1)\n var q = this.m.subn(1);\n var s = 0;\n while (!q.isZero() && q.andln(1) === 0) {\n s++;\n q.iushrn(1);\n }\n assert(!q.isZero());\n\n var one = new BN(1).toRed(this);\n var nOne = one.redNeg();\n\n // Find quadratic non-residue\n // NOTE: Max is such because of generalized Riemann hypothesis.\n var lpow = this.m.subn(1).iushrn(1);\n var z = this.m.bitLength();\n z = new BN(2 * z * z).toRed(this);\n\n while (this.pow(z, lpow).cmp(nOne) !== 0) {\n z.redIAdd(nOne);\n }\n\n var c = this.pow(z, q);\n var r = this.pow(a, q.addn(1).iushrn(1));\n var t = this.pow(a, q);\n var m = s;\n while (t.cmp(one) !== 0) {\n var tmp = t;\n for (var i = 0; tmp.cmp(one) !== 0; i++) {\n tmp = tmp.redSqr();\n }\n assert(i < m);\n var b = this.pow(c, new BN(1).iushln(m - i - 1));\n\n r = r.redMul(b);\n c = b.redSqr();\n t = t.redMul(c);\n m = i;\n }\n\n return r;\n };\n\n Red.prototype.invm = function invm (a) {\n var inv = a._invmp(this.m);\n if (inv.negative !== 0) {\n inv.negative = 0;\n return this.imod(inv).redNeg();\n } else {\n return this.imod(inv);\n }\n };\n\n Red.prototype.pow = function pow (a, num) {\n if (num.isZero()) return new BN(1).toRed(this);\n if (num.cmpn(1) === 0) return a.clone();\n\n var windowSize = 4;\n var wnd = new Array(1 << windowSize);\n wnd[0] = new BN(1).toRed(this);\n wnd[1] = a;\n for (var i = 2; i < wnd.length; i++) {\n wnd[i] = this.mul(wnd[i - 1], a);\n }\n\n var res = wnd[0];\n var current = 0;\n var currentLen = 0;\n var start = num.bitLength() % 26;\n if (start === 0) {\n start = 26;\n }\n\n for (i = num.length - 1; i >= 0; i--) {\n var word = num.words[i];\n for (var j = start - 1; j >= 0; j--) {\n var bit = (word >> j) & 1;\n if (res !== wnd[0]) {\n res = this.sqr(res);\n }\n\n if (bit === 0 && current === 0) {\n currentLen = 0;\n continue;\n }\n\n current <<= 1;\n current |= bit;\n currentLen++;\n if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;\n\n res = this.mul(res, wnd[current]);\n currentLen = 0;\n current = 0;\n }\n start = 26;\n }\n\n return res;\n };\n\n Red.prototype.convertTo = function convertTo (num) {\n var r = num.umod(this.m);\n\n return r === num ? r.clone() : r;\n };\n\n Red.prototype.convertFrom = function convertFrom (num) {\n var res = num.clone();\n res.red = null;\n return res;\n };\n\n //\n // Montgomery method engine\n //\n\n BN.mont = function mont (num) {\n return new Mont(num);\n };\n\n function Mont (m) {\n Red.call(this, m);\n\n this.shift = this.m.bitLength();\n if (this.shift % 26 !== 0) {\n this.shift += 26 - (this.shift % 26);\n }\n\n this.r = new BN(1).iushln(this.shift);\n this.r2 = this.imod(this.r.sqr());\n this.rinv = this.r._invmp(this.m);\n\n this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);\n this.minv = this.minv.umod(this.r);\n this.minv = this.r.sub(this.minv);\n }\n inherits(Mont, Red);\n\n Mont.prototype.convertTo = function convertTo (num) {\n return this.imod(num.ushln(this.shift));\n };\n\n Mont.prototype.convertFrom = function convertFrom (num) {\n var r = this.imod(num.mul(this.rinv));\n r.red = null;\n return r;\n };\n\n Mont.prototype.imul = function imul (a, b) {\n if (a.isZero() || b.isZero()) {\n a.words[0] = 0;\n a.length = 1;\n return a;\n }\n\n var t = a.imul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.mul = function mul (a, b) {\n if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);\n\n var t = a.mul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.invm = function invm (a) {\n // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R\n var res = this.imod(a._invmp(this.m).mul(this.r2));\n return res._forceRed(this);\n };\n})(typeof module === 'undefined' || module, this);\n","import { AccountInfo, Commitment, PublicKey } from '@solana/web3.js';\nimport {\n TOKEN_PROGRAM_ID,\n TOKEN_2022_PROGRAM_ID,\n unpackAccount as unpackAccountSPL,\n TokenAccountNotFoundError,\n getAssociatedTokenAddressSync,\n AccountState,\n Account,\n} from '@solana/spl-token';\nimport {\n Rpc,\n CTOKEN_PROGRAM_ID,\n MerkleContext,\n CompressedAccountWithMerkleContext,\n deriveAddressV2,\n bn,\n getDefaultAddressTreeInfo,\n} from '@lightprotocol/stateless.js';\nimport { Buffer } from 'buffer';\nimport BN from 'bn.js';\nimport { getAtaProgramId, checkAtaAddress } from './ata-utils';\nexport { Account, AccountState } from '@solana/spl-token';\nexport { ParsedTokenAccount } from '@lightprotocol/stateless.js';\n\nexport const TokenAccountSourceType = {\n Spl: 'spl',\n Token2022: 'token2022',\n SplCold: 'spl-cold',\n Token2022Cold: 'token2022-cold',\n CTokenHot: 'ctoken-hot',\n CTokenCold: 'ctoken-cold',\n} as const;\n\nexport type TokenAccountSourceTypeValue =\n (typeof TokenAccountSourceType)[keyof typeof TokenAccountSourceType];\n\n/** @internal */\nexport interface TokenAccountSource {\n type: TokenAccountSourceTypeValue;\n address: PublicKey;\n amount: bigint;\n accountInfo: AccountInfo<Buffer>;\n loadContext?: MerkleContext;\n parsed: Account;\n}\n\nexport interface AccountInterface {\n accountInfo: AccountInfo<Buffer>;\n parsed: Account;\n isCold: boolean;\n loadContext?: MerkleContext;\n _sources?: TokenAccountSource[];\n _needsConsolidation?: boolean;\n _hasDelegate?: boolean;\n _anyFrozen?: boolean;\n /** True when fetched via getAtaInterface */\n _isAta?: boolean;\n /** ATA owner - set by getAtaInterface */\n _owner?: PublicKey;\n /** ATA mint - set by getAtaInterface */\n _mint?: PublicKey;\n}\n\n/** @internal */\nfunction parseTokenData(data: Buffer): {\n mint: PublicKey;\n owner: PublicKey;\n amount: BN;\n delegate: PublicKey | null;\n state: number;\n tlv: Buffer | null;\n} | null {\n if (!data || data.length === 0) return null;\n\n try {\n let offset = 0;\n const mint = new PublicKey(data.slice(offset, offset + 32));\n offset += 32;\n const owner = new PublicKey(data.slice(offset, offset + 32));\n offset += 32;\n const amount = new BN(data.slice(offset, offset + 8), 'le');\n offset += 8;\n const delegateOption = data[offset];\n offset += 1;\n const delegate = delegateOption\n ? new PublicKey(data.slice(offset, offset + 32))\n : null;\n offset += 32;\n const state = data[offset];\n offset += 1;\n const tlvOption = data[offset];\n offset += 1;\n const tlv = tlvOption ? data.slice(offset) : null;\n\n return {\n mint,\n owner,\n amount,\n delegate,\n state,\n tlv,\n };\n } catch (error) {\n console.error('Token data parsing error:', error);\n return null;\n }\n}\n\n/** @internal */\nexport function convertTokenDataToAccount(\n address: PublicKey,\n tokenData: {\n mint: PublicKey;\n owner: PublicKey;\n amount: BN;\n delegate: PublicKey | null;\n state: number;\n tlv: Buffer | null;\n },\n): Account {\n return {\n address,\n mint: tokenData.mint,\n owner: tokenData.owner,\n amount: BigInt(tokenData.amount.toString()),\n delegate: tokenData.delegate,\n delegatedAmount: BigInt(0),\n isInitialized: tokenData.state !== AccountState.Uninitialized,\n isFrozen: tokenData.state === AccountState.Frozen,\n isNative: false,\n rentExemptReserve: null,\n closeAuthority: null,\n tlvData: tokenData.tlv ? Buffer.from(tokenData.tlv) : Buffer.alloc(0),\n };\n}\n\n/** Convert compressed account to AccountInfo */\nexport function toAccountInfo(\n compressedAccount: CompressedAccountWithMerkleContext,\n): AccountInfo<Buffer> {\n const dataDiscriminatorBuffer: Buffer = Buffer.from(\n compressedAccount.data!.discriminator,\n );\n const dataBuffer: Buffer = Buffer.from(compressedAccount.data!.data);\n const data: Buffer = Buffer.concat([dataDiscriminatorBuffer, dataBuffer]);\n\n return {\n executable: false,\n owner: compressedAccount.owner,\n lamports: compressedAccount.lamports.toNumber(),\n data,\n rentEpoch: undefined,\n };\n}\n\n/** @internal */\nexport function parseCTokenHot(\n address: PublicKey,\n accountInfo: AccountInfo<Buffer>,\n): {\n accountInfo: AccountInfo<Buffer>;\n loadContext: undefined;\n parsed: Account;\n isCold: false;\n} {\n const parsed = parseTokenData(accountInfo.data);\n if (!parsed) throw new Error('Invalid token data');\n return {\n accountInfo,\n loadContext: undefined,\n parsed: convertTokenDataToAccount(address, parsed),\n isCold: false,\n };\n}\n\n/** @internal */\nexport function parseCTokenCold(\n address: PublicKey,\n compressedAccount: CompressedAccountWithMerkleContext,\n): {\n accountInfo: AccountInfo<Buffer>;\n loadContext: MerkleContext;\n parsed: Account;\n isCold: true;\n} {\n const parsed = parseTokenData(compressedAccount.data!.data);\n if (!parsed) throw new Error('Invalid token data');\n return {\n accountInfo: toAccountInfo(compressedAccount),\n loadContext: {\n treeInfo: compressedAccount.treeInfo,\n hash: compressedAccount.hash,\n leafIndex: compressedAccount.leafIndex,\n proveByIndex: compressedAccount.proveByIndex,\n },\n parsed: convertTokenDataToAccount(address, parsed),\n isCold: true,\n };\n}\n/**\n * Retrieve information about a token account of SPL/T22/c-token.\n *\n * @param rpc RPC connection to use\n * @param address Token account address\n * @param commitment Desired level of commitment for querying the state\n * @param programId Token program ID. If not provided, tries all programs concurrently.\n *\n * @return Token account information with compression context if applicable\n */\nexport async function getAccountInterface(\n rpc: Rpc,\n address: PublicKey,\n commitment?: Commitment,\n programId?: PublicKey,\n): Promise<AccountInterface> {\n return _getAccountInterface(rpc, address, commitment, programId, undefined);\n}\n\n/**\n * Retrieve associated token account for a given owner and mint.\n *\n * @param rpc RPC connection\n * @param ata Associated token address\n * @param owner Owner public key\n * @param mint Mint public key\n * @param commitment Optional commitment level\n * @param programId Optional program ID\n * @param wrap Include SPL/T22 balances (default: false)\n * @returns AccountInterface with ATA metadata\n */\nexport async function getAtaInterface(\n rpc: Rpc,\n ata: PublicKey,\n owner: PublicKey,\n mint: PublicKey,\n commitment?: Commitment,\n programId?: PublicKey,\n wrap = false,\n): Promise<AccountInterface> {\n // Invariant: ata MUST match a valid derivation from mint+owner.\n // Hot path: if programId provided, only validate against that program.\n // For wrap=true, additionally require c-token ATA.\n const validation = checkAtaAddress(ata, mint, owner, programId);\n\n if (wrap && validation.type !== 'ctoken') {\n throw new Error(\n `For wrap=true, ata must be the c-token ATA. Got ${validation.type} ATA instead.`,\n );\n }\n\n // Pass both ata address AND fetchByOwner for proper lookups:\n // - address is used for on-chain account fetching\n // - fetchByOwner is used for compressed token lookup by owner+mint\n const result = await _getAccountInterface(\n rpc,\n ata,\n commitment,\n programId,\n {\n owner,\n mint,\n },\n wrap,\n );\n result._isAta = true;\n result._owner = owner;\n result._mint = mint;\n return result;\n}\n\n/**\n * @internal\n */\nasync function _tryFetchSpl(\n rpc: Rpc,\n address: PublicKey,\n commitment?: Commitment,\n): Promise<{\n accountInfo: AccountInfo<Buffer>;\n parsed: Account;\n isCold: false;\n loadContext: undefined;\n}> {\n const info = await rpc.getAccountInfo(address, commitment);\n if (!info || !info.owner.equals(TOKEN_PROGRAM_ID)) {\n throw new Error('Not a TOKEN_PROGRAM_ID account');\n }\n const account = unpackAccountSPL(address, info, TOKEN_PROGRAM_ID);\n return {\n accountInfo: info,\n parsed: account,\n isCold: false,\n loadContext: undefined,\n };\n}\n\n/**\n * @internal\n */\nasync function _tryFetchToken2022(\n rpc: Rpc,\n address: PublicKey,\n commitment?: Commitment,\n): Promise<{\n accountInfo: AccountInfo<Buffer>;\n parsed: Account;\n isCold: false;\n loadContext: undefined;\n}> {\n const info = await rpc.getAccountInfo(address, commitment);\n if (!info || !info.owner.equals(TOKEN_2022_PROGRAM_ID)) {\n throw new Error('Not a TOKEN_2022_PROGRAM_ID account');\n }\n const account = unpackAccountSPL(address, info, TOKEN_2022_PROGRAM_ID);\n return {\n accountInfo: info,\n parsed: account,\n isCold: false,\n loadContext: undefined,\n };\n}\n\n/**\n * @internal\n */\nasync function _tryFetchCTokenHot(\n rpc: Rpc,\n address: PublicKey,\n commitment?: Commitment,\n): Promise<{\n accountInfo: AccountInfo<Buffer>;\n loadContext: undefined;\n parsed: Account;\n isCold: false;\n}> {\n const info = await rpc.getAccountInfo(address, commitment);\n if (!info || !info.owner.equals(CTOKEN_PROGRAM_ID)) {\n throw new Error('Not a CTOKEN onchain account');\n }\n return parseCTokenHot(address, info);\n}\n\n/**\n * @internal\n */\nasync function _tryFetchCTokenColdByOwner(\n rpc: Rpc,\n owner: PublicKey,\n mint: PublicKey,\n ataAddress: PublicKey,\n): Promise<{\n accountInfo: AccountInfo<Buffer>;\n loadContext: MerkleContext;\n parsed: Account;\n isCold: true;\n}> {\n const result = await rpc.getCompressedTokenAccountsByOwner(owner, {\n mint,\n });\n const compressedAccount =\n result.items.length > 0 ? result.items[0].compressedAccount : null;\n if (!compressedAccount?.data?.data.length) {\n throw new Error('Not a compressed token account');\n }\n if (!compressedAccount.owner.equals(CTOKEN_PROGRAM_ID)) {\n throw new Error('Invalid owner for compressed token');\n }\n return parseCTokenCold(ataAddress, compressedAccount);\n}\n\n/**\n * @internal\n * Fetch compressed token account by deriving its compressed address from the on-chain address.\n * Uses deriveAddressV2(address, addressTree, CTOKEN_PROGRAM_ID) to get the compressed address.\n *\n * Note: This only works for accounts that were **compressed from on-chain** (via compress_accounts_idempotent).\n * For tokens minted compressed (via mintTo), use getAtaInterface with owner+mint instead.\n */\nasync function _tryFetchCTokenColdByAddress(\n rpc: Rpc,\n address: PublicKey,\n): Promise<{\n accountInfo: AccountInfo<Buffer>;\n loadContext: MerkleContext;\n parsed: Account;\n isCold: true;\n}> {\n // Derive compressed address from on-chain token account address\n const addressTree = getDefaultAddressTreeInfo().tree;\n const compressedAddress = deriveAddressV2(\n address.toBytes(),\n addressTree,\n CTOKEN_PROGRAM_ID,\n );\n\n // Fetch by derived compressed address\n const compressedAccount = await rpc.getCompressedAccount(\n bn(compressedAddress.toBytes()),\n );\n\n if (!compressedAccount?.data?.data.length) {\n throw new Error(\n 'Compressed token account not found at derived address. ' +\n 'Note: getAccountInterface only finds compressed accounts that were ' +\n 'compressed from on-chain (via compress_accounts_idempotent). ' +\n 'For tokens minted compressed (via mintTo), use getAtaInterface with owner+mint.',\n );\n }\n if (!compressedAccount.owner.equals(CTOKEN_PROGRAM_ID)) {\n throw new Error('Invalid owner for compressed token');\n }\n return parseCTokenCold(address, compressedAccount);\n}\n\n/**\n * @internal\n * Retrieve information about a token account SPL/T22/c-token.\n */\nasync function _getAccountInterface(\n rpc: Rpc,\n address?: PublicKey,\n commitment?: Commitment,\n programId?: PublicKey,\n fetchByOwner?: {\n owner: PublicKey;\n mint: PublicKey;\n },\n wrap = false,\n): Promise<AccountInterface> {\n // At least one of address or fetchByOwner is required.\n // Both can be provided: address for on-chain lookup, fetchByOwner for\n // compressed token lookup by owner+mint (useful for PDA owners where\n // address derivation might not work with standard allowOwnerOffCurve=false).\n if (!address && !fetchByOwner) {\n throw new Error('One of address or fetchByOwner is required');\n }\n\n // Unified mode (auto-detect: c-token + optional SPL/T22)\n if (!programId) {\n return getUnifiedAccountInterface(\n rpc,\n address,\n commitment,\n fetchByOwner,\n wrap,\n );\n }\n\n // c-token-only mode\n if (programId.equals(CTOKEN_PROGRAM_ID)) {\n return getCTokenAccountInterface(\n rpc,\n address,\n commitment,\n fetchByOwner,\n );\n }\n\n // SPL / Token-2022 only\n if (\n programId.equals(TOKEN_PROGRAM_ID) ||\n programId.equals(TOKEN_2022_PROGRAM_ID)\n ) {\n return getSplOrToken2022AccountInterface(\n rpc,\n address,\n commitment,\n programId,\n fetchByOwner,\n );\n }\n\n throw new Error(`Unsupported program ID: ${programId.toBase58()}`);\n}\n\nasync function getUnifiedAccountInterface(\n rpc: Rpc,\n address: PublicKey | undefined,\n commitment: Commitment | undefined,\n fetchByOwner: { owner: PublicKey; mint: PublicKey } | undefined,\n wrap: boolean,\n): Promise<AccountInterface> {\n // Canonical address for unified mode is always the c-token ATA\n const cTokenAta =\n address ??\n getAssociatedTokenAddressSync(\n fetchByOwner!.mint,\n fetchByOwner!.owner,\n false,\n CTOKEN_PROGRAM_ID,\n getAtaProgramId(CTOKEN_PROGRAM_ID),\n );\n\n const fetchPromises: Promise<{\n accountInfo: AccountInfo<Buffer>;\n parsed: Account;\n isCold: boolean;\n loadContext?: MerkleContext;\n }>[] = [];\n const fetchTypes: TokenAccountSource['type'][] = [];\n const fetchAddresses: PublicKey[] = [];\n\n // c-token hot + cold\n fetchPromises.push(_tryFetchCTokenHot(rpc, cTokenAta, commitment));\n fetchTypes.push(TokenAccountSourceType.CTokenHot);\n fetchAddresses.push(cTokenAta);\n\n fetchPromises.push(\n fetchByOwner\n ? _tryFetchCTokenColdByOwner(\n rpc,\n fetchByOwner.owner,\n fetchByOwner.mint,\n cTokenAta,\n )\n : _tryFetchCTokenColdByAddress(rpc, address!),\n );\n fetchTypes.push(TokenAccountSourceType.CTokenCold);\n fetchAddresses.push(cTokenAta);\n\n // SPL / Token-2022 (only when wrap is enabled)\n if (wrap) {\n // Always derive SPL/T22 addresses from owner+mint, not from the passed\n // c-token address. SPL and T22 ATAs are different from c-token ATAs.\n if (!fetchByOwner) {\n throw new Error(\n 'fetchByOwner is required for wrap=true to derive SPL/T22 addresses',\n );\n }\n const splTokenAta = getAssociatedTokenAddressSync(\n fetchByOwner.mint,\n fetchByOwner.owner,\n false,\n TOKEN_PROGRAM_ID,\n getAtaProgramId(TOKEN_PROGRAM_ID),\n );\n const token2022Ata = getAssociatedTokenAddressSync(\n fetchByOwner.mint,\n fetchByOwner.owner,\n false,\n TOKEN_2022_PROGRAM_ID,\n getAtaProgramId(TOKEN_2022_PROGRAM_ID),\n );\n\n fetchPromises.push(_tryFetchSpl(rpc, splTokenAta, commitment));\n fetchTypes.push(TokenAccountSourceType.Spl);\n fetchAddresses.push(splTokenAta);\n\n fetchPromises.push(_tryFetchToken2022(rpc, token2022Ata, commitment));\n fetchTypes.push(TokenAccountSourceType.Token2022);\n fetchAddresses.push(token2022Ata);\n }\n\n const results = await Promise.allSettled(fetchPromises);\n\n // collect all successful results\n const sources: TokenAccountSource[] = [];\n\n for (let i = 0; i < results.length; i++) {\n const result = results[i];\n if (result.status === 'fulfilled') {\n const value = result.value;\n sources.push({\n type: fetchTypes[i],\n address: fetchAddresses[i],\n amount: value.parsed.amount,\n accountInfo: value.accountInfo,\n loadContext: value.loadContext,\n parsed: value.parsed,\n });\n }\n }\n\n // account not found\n if (sources.length === 0) {\n const triedPrograms = wrap\n ? 'TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, and CTOKEN_PROGRAM_ID (both onchain and compressed)'\n : 'CTOKEN_PROGRAM_ID (both onchain and compressed)';\n throw new Error(`Token account not found. Tried ${triedPrograms}.`);\n }\n\n // priority order: c-token hot > c-token cold > SPL/T22\n const priority: TokenAccountSource['type'][] = [\n TokenAccountSourceType.CTokenHot,\n TokenAccountSourceType.CTokenCold,\n TokenAccountSourceType.Spl,\n TokenAccountSourceType.Token2022,\n ];\n\n sources.sort((a, b) => {\n const aIdx = priority.indexOf(a.type);\n const bIdx = priority.indexOf(b.type);\n return aIdx - bIdx;\n });\n\n return buildAccountInterfaceFromSources(sources, cTokenAta);\n}\n\nasync function getCTokenAccountInterface(\n rpc: Rpc,\n address: PublicKey | undefined,\n commitment: Commitment | undefined,\n fetchByOwner?: { owner: PublicKey; mint: PublicKey },\n): Promise<AccountInterface> {\n // Derive address if not provided\n if (!address) {\n if (!fetchByOwner) {\n throw new Error('fetchByOwner is required');\n }\n address = getAssociatedTokenAddressSync(\n fetchByOwner.mint,\n fetchByOwner.owner,\n false,\n CTOKEN_PROGRAM_ID,\n getAtaProgramId(CTOKEN_PROGRAM_ID),\n );\n }\n\n const [onchainResult, compressedResult] = await Promise.allSettled([\n rpc.getAccountInfo(address, commitment),\n // Fetch compressed: by owner+mint for ATAs, by address for non-ATAs\n fetchByOwner\n ? rpc.getCompressedTokenAccountsByOwner(fetchByOwner.owner, {\n mint: fetchByOwner.mint,\n })\n : rpc.getCompressedTokenAccountsByOwner(address),\n ]);\n\n const onchainAccount =\n onchainResult.status === 'fulfilled' ? onchainResult.value : null;\n const compressedAccounts =\n compressedResult.status === 'fulfilled'\n ? compressedResult.value.items.map(item => item.compressedAccount)\n : [];\n\n const sources: TokenAccountSource[] = [];\n\n // Collect hot (decompressed) c-token account\n if (onchainAccount && onchainAccount.owner.equals(CTOKEN_PROGRAM_ID)) {\n const parsed = parseCTokenHot(address, onchainAccount);\n sources.push({\n type: TokenAccountSourceType.CTokenHot,\n address,\n amount: parsed.parsed.amount,\n accountInfo: onchainAccount,\n parsed: parsed.parsed,\n });\n }\n\n // Collect cold (compressed) c-token accounts\n for (const compressedAccount of compressedAccounts) {\n if (\n compressedAccount &&\n compressedAccount.data &&\n compressedAccount.data.data.length > 0 &&\n compressedAccount.owner.equals(CTOKEN_PROGRAM_ID)\n ) {\n const parsed = parseCTokenCold(address, compressedAccount);\n sources.push({\n type: TokenAccountSourceType.CTokenCold,\n address,\n amount: parsed.parsed.amount,\n accountInfo: parsed.accountInfo,\n loadContext: parsed.loadContext,\n parsed: parsed.parsed,\n });\n }\n }\n\n if (sources.length === 0) {\n throw new TokenAccountNotFoundError();\n }\n\n // Priority: hot > cold\n sources.sort((a, b) => {\n if (a.type === 'ctoken-hot' && b.type === 'ctoken-cold') return -1;\n if (a.type === 'ctoken-cold' && b.type === 'ctoken-hot') return 1;\n return 0;\n });\n\n return buildAccountInterfaceFromSources(sources, address);\n}\n\nasync function getSplOrToken2022AccountInterface(\n rpc: Rpc,\n address: PublicKey | undefined,\n commitment: Commitment | undefined,\n programId: PublicKey,\n fetchByOwner?: { owner: PublicKey; mint: PublicKey },\n): Promise<AccountInterface> {\n if (!address) {\n if (!fetchByOwner) {\n throw new Error('fetchByOwner is required');\n }\n address = getAssociatedTokenAddressSync(\n fetchByOwner.mint,\n fetchByOwner.owner,\n false,\n programId,\n getAtaProgramId(programId),\n );\n }\n\n const info = await rpc.getAccountInfo(address, commitment);\n if (!info) {\n throw new TokenAccountNotFoundError();\n }\n\n const account = unpackAccountSPL(address, info, programId);\n\n const hotType: TokenAccountSource['type'] = programId.equals(\n TOKEN_PROGRAM_ID,\n )\n ? TokenAccountSourceType.Spl\n : TokenAccountSourceType.Token2022;\n\n const sources: TokenAccountSource[] = [\n {\n type: hotType,\n address,\n amount: account.amount,\n accountInfo: info,\n parsed: account,\n },\n ];\n\n // For ATA-based calls (fetchByOwner present), also include cold (compressed) balances\n if (fetchByOwner) {\n const compressedResult = await rpc.getCompressedTokenAccountsByOwner(\n fetchByOwner.owner,\n {\n mint: fetchByOwner.mint,\n },\n );\n const compressedAccounts = compressedResult.items.map(\n item => item.compressedAccount,\n );\n\n const coldType: TokenAccountSource['type'] = programId.equals(\n TOKEN_PROGRAM_ID,\n )\n ? TokenAccountSourceType.SplCold\n : TokenAccountSourceType.Token2022Cold;\n\n for (const compressedAccount of compressedAccounts) {\n if (\n compressedAccount &&\n compressedAccount.data &&\n compressedAccount.data.data.length > 0 &&\n compressedAccount.owner.equals(CTOKEN_PROGRAM_ID)\n ) {\n // Represent cold supply as belonging to this SPL/T22 ATA\n const parsedCold = parseCTokenCold(address, compressedAccount);\n sources.push({\n type: coldType,\n address,\n amount: parsedCold.parsed.amount,\n accountInfo: parsedCold.accountInfo,\n loadContext: parsedCold.loadContext,\n parsed: parsedCold.parsed,\n });\n }\n }\n }\n\n return buildAccountInterfaceFromSources(sources, address);\n}\n\nfunction buildAccountInterfaceFromSources(\n sources: TokenAccountSource[],\n canonicalAddress: PublicKey,\n): AccountInterface {\n const totalAmount = sources.reduce(\n (sum, src) => sum + src.amount,\n BigInt(0),\n );\n\n const primarySource = sources[0];\n\n const hasDelegate = sources.some(src => src.parsed.delegate !== null);\n const anyFrozen = sources.some(src => src.parsed.isFrozen);\n const needsConsolidation = sources.length > 1;\n\n const unifiedAccount: Account = {\n ...primarySource.parsed,\n address: canonicalAddress,\n amount: totalAmount,\n };\n\n const coldTypes: TokenAccountSource['type'][] = [\n 'ctoken-cold',\n 'spl-cold',\n 'token2022-cold',\n ];\n\n return {\n accountInfo: primarySource.accountInfo!,\n parsed: unifiedAccount,\n isCold: coldTypes.includes(primarySource.type),\n loadContext: primarySource.loadContext,\n _sources: sources,\n _needsConsolidation: needsConsolidation,\n _hasDelegate: hasDelegate,\n _anyFrozen: anyFrozen,\n };\n}\n","import { PublicKey } from '@solana/web3.js';\nimport { getAssociatedTokenAddressSync } from '@solana/spl-token';\nimport { CTOKEN_PROGRAM_ID } from '@lightprotocol/stateless.js';\nimport { getAtaProgramId } from './ata-utils';\n\n/**\n * Derive the canonical associated token address for any of SPL/T22/c-token.\n * Defaults to using c-token as the canonical ATA.\n *\n * @param mint Mint public key\n * @param owner Owner public key\n * @param allowOwnerOffCurve Allow owner to be a PDA. Default false.\n * @param programId Token program ID. Default c-token.\n *\n * @param associatedTokenProgramId Associated token program ID. Default\n * auto-detected.\n * @returns Associated token address.\n */\nexport function getAssociatedTokenAddressInterface(\n mint: PublicKey,\n owner: PublicKey,\n allowOwnerOffCurve = false,\n programId: PublicKey = CTOKEN_PROGRAM_ID,\n associatedTokenProgramId?: PublicKey,\n): PublicKey {\n const effectiveAssociatedProgramId =\n associatedTokenProgramId ?? getAtaProgramId(programId);\n\n // by passing program id, user indicates preference for the canonical ATA.\n return getAssociatedTokenAddressSync(\n mint,\n owner,\n allowOwnerOffCurve,\n programId,\n effectiveAssociatedProgramId,\n );\n}\n","import { PublicKey, TransactionInstruction } from '@solana/web3.js';\nimport { CTOKEN_PROGRAM_ID } from '@lightprotocol/stateless.js';\nimport { CompressedTokenProgram } from '../../program';\nimport { SplInterfaceInfo } from '../../utils/get-token-pool-infos';\nimport {\n encodeTransfer2InstructionData,\n createCompressSpl,\n createDecompressCtoken,\n Transfer2InstructionData,\n Compression,\n} from '../layout/layout-transfer2';\n\n/**\n * Create a wrap instruction that moves tokens from an SPL/T22 account to a\n * c-token account.\n *\n * @param source Source SPL/T22 token account\n * @param destination Destination c-token account\n * @param owner Owner of the source account (signer)\n * @param mint Mint address\n * @param amount Amount to wrap,\n * @param splInterfaceInfo SPL interface info for the compression\n * @param payer Fee payer (defaults to owner)\n * @returns Instruction to wrap tokens\n */\nexport function createWrapInstruction(\n source: PublicKey,\n destination: PublicKey,\n owner: PublicKey,\n mint: PublicKey,\n amount: bigint,\n splInterfaceInfo: SplInterfaceInfo,\n payer: PublicKey = owner,\n): TransactionInstruction {\n const MINT_INDEX = 0;\n const OWNER_INDEX = 1;\n const SOURCE_INDEX = 2;\n const DESTINATION_INDEX = 3;\n const POOL_INDEX = 4;\n const _SPL_TOKEN_PROGRAM_INDEX = 5;\n const CTOKEN_PROGRAM_INDEX = 6;\n\n const compressions: Compression[] = [\n createCompressSpl(\n amount,\n MINT_INDEX,\n SOURCE_INDEX,\n OWNER_INDEX,\n POOL_INDEX,\n splInterfaceInfo.poolIndex,\n splInterfaceInfo.bump,\n ),\n createDecompressCtoken(\n amount,\n MINT_INDEX,\n DESTINATION_INDEX,\n CTOKEN_PROGRAM_INDEX,\n ),\n ];\n\n const instructionData: Transfer2InstructionData = {\n withTransactionHash: false,\n withLamportsChangeAccountMerkleTreeIndex: false,\n lamportsChangeAccountMerkleTreeIndex: 0,\n lamportsChangeAccountOwnerIndex: 0,\n outputQueue: 0,\n maxTopUp: 0,\n cpiContext: null,\n compressions,\n proof: null,\n inTokenData: [],\n outTokenData: [],\n inLamports: null,\n outLamports: null,\n inTlv: null,\n outTlv: null,\n };\n\n const data = encodeTransfer2InstructionData(instructionData);\n\n const keys = [\n {\n pubkey: CompressedTokenProgram.deriveCpiAuthorityPda,\n isSigner: false,\n isWritable: false,\n },\n { pubkey: payer, isSigner: true, isWritable: true },\n { pubkey: mint, isSigner: false, isWritable: false },\n { pubkey: owner, isSigner: true, isWritable: false },\n { pubkey: source, isSigner: false, isWritable: true },\n { pubkey: destination, isSigner: false, isWritable: true },\n {\n pubkey: splInterfaceInfo.splInterfacePda,\n isSigner: false,\n isWritable: true,\n },\n {\n pubkey: splInterfaceInfo.tokenProgram,\n isSigner: false,\n isWritable: false,\n },\n {\n pubkey: CTOKEN_PROGRAM_ID,\n isSigner: false,\n isWritable: false,\n },\n ];\n\n return new TransactionInstruction({\n programId: CompressedTokenProgram.programId,\n keys,\n data,\n });\n}\n","import {\n Rpc,\n CTOKEN_PROGRAM_ID,\n buildAndSignTx,\n sendAndConfirmTx,\n dedupeSigner,\n} from '@lightprotocol/stateless.js';\nimport {\n PublicKey,\n TransactionInstruction,\n Signer,\n TransactionSignature,\n ConfirmOptions,\n ComputeBudgetProgram,\n} from '@solana/web3.js';\nimport {\n TOKEN_PROGRAM_ID,\n TOKEN_2022_PROGRAM_ID,\n getAssociatedTokenAddressSync,\n createAssociatedTokenAccountIdempotentInstruction,\n} from '@solana/spl-token';\nimport {\n AccountInterface,\n getAtaInterface as _getAtaInterface,\n} from '../get-account-interface';\nimport { getAssociatedTokenAddressInterface } from '../get-associated-token-address-interface';\nimport { createAssociatedTokenAccountInterfaceIdempotentInstruction } from '../instructions/create-ata-interface';\nimport { createWrapInstruction } from '../instructions/wrap';\nimport { createDecompressInterfaceInstruction } from '../instructions/create-decompress-interface-instruction';\nimport {\n getSplInterfaceInfos,\n SplInterfaceInfo,\n} from '../../utils/get-token-pool-infos';\nimport { getAtaProgramId, checkAtaAddress, AtaType } from '../ata-utils';\nimport { InterfaceOptions } from './transfer-interface';\n\n// Re-export types moved to instructions\nexport {\n ParsedAccountInfoInterface,\n CompressibleAccountInput,\n PackedCompressedAccount,\n CompressibleLoadParams,\n LoadResult,\n createLoadAccountsParams,\n calculateCompressibleLoadComputeUnits,\n} from '../instructions/create-load-accounts-params';\n\n/**\n * Create instructions to load token balances into an ATA.\n *\n * Behavior depends on `wrap` parameter:\n * - wrap=false (standard): Decompress compressed tokens to the target ATA.\n * ATA can be SPL (via pool), T22 (via pool), or c-token (direct).\n * - wrap=true (unified): Wrap SPL/T22 + decompress all to c-token ATA.\n * ATA must be a c-token ATA.\n *\n * @param rpc RPC connection\n * @param ata Associated token address (SPL, T22, or c-token)\n * @param owner Owner public key\n * @param mint Mint public key\n * @param payer Fee payer (defaults to owner)\n * @param options Optional load options\n * @param wrap Unified mode: wrap SPL/T22 to c-token (default: false)\n * @returns Array of instructions (empty if nothing to load)\n */\nexport async function createLoadAtaInstructions(\n rpc: Rpc,\n ata: PublicKey,\n owner: PublicKey,\n mint: PublicKey,\n payer?: PublicKey,\n options?: InterfaceOptions,\n wrap = false,\n): Promise<TransactionInstruction[]> {\n payer ??= owner;\n\n // Validation happens inside getAtaInterface via checkAtaAddress helper:\n // - Always validates ata matches mint+owner derivation\n // - For wrap=true, additionally requires c-token ATA\n const ataInterface = await _getAtaInterface(\n rpc,\n ata,\n owner,\n mint,\n undefined,\n undefined,\n wrap,\n );\n return createLoadAtaInstructionsFromInterface(\n rpc,\n payer,\n ataInterface,\n options,\n wrap,\n ata,\n );\n}\n\n// Re-export AtaType for backwards compatibility\nexport { AtaType } from '../ata-utils';\n\n/**\n * Create instructions to load an ATA from its AccountInterface.\n *\n * Behavior depends on `wrap` parameter:\n * - wrap=false (standard): Decompress compressed tokens to the target ATA type\n * (SPL ATA via pool, T22 ATA via pool, or c-token ATA direct)\n * - wrap=true (unified): Wrap SPL/T22 + decompress all to c-token ATA\n *\n * @param rpc RPC connection\n * @param payer Fee payer\n * @param ata AccountInterface from getAtaInterface (must have _isAta, _owner, _mint)\n * @param options Optional load options\n * @param wrap Unified mode: wrap SPL/T22 to c-token (default: false)\n * @param targetAta Target ATA address (used for type detection in standard mode)\n * @returns Array of instructions (empty if nothing to load)\n */\nexport async function createLoadAtaInstructionsFromInterface(\n rpc: Rpc,\n payer: PublicKey,\n ata: AccountInterface,\n options?: InterfaceOptions,\n wrap = false,\n targetAta?: PublicKey,\n): Promise<TransactionInstruction[]> {\n if (!ata._isAta || !ata._owner || !ata._mint) {\n throw new Error(\n 'AccountInterface must be from getAtaInterface (requires _isAta, _owner, _mint)',\n );\n }\n\n const instructions: TransactionInstruction[] = [];\n const owner = ata._owner;\n const mint = ata._mint;\n const sources = ata._sources ?? [];\n\n // Derive addresses\n const ctokenAtaAddress = getAssociatedTokenAddressInterface(mint, owner);\n const splAta = getAssociatedTokenAddressSync(\n mint,\n owner,\n false,\n TOKEN_PROGRAM_ID,\n getAtaProgramId(TOKEN_PROGRAM_ID),\n );\n const t22Ata = getAssociatedTokenAddressSync(\n mint,\n owner,\n false,\n TOKEN_2022_PROGRAM_ID,\n getAtaProgramId(TOKEN_2022_PROGRAM_ID),\n );\n\n // Validate and detect target ATA type\n // If called via createLoadAtaInstructions, validation already happened in getAtaInterface.\n // If called directly, this validates the targetAta is correct.\n let ataType: AtaType = 'ctoken';\n if (targetAta) {\n const validation = checkAtaAddress(targetAta, mint, owner);\n ataType = validation.type;\n\n // For wrap=true, must be c-token ATA\n if (wrap && ataType !== 'ctoken') {\n throw new Error(\n `For wrap=true, targetAta must be c-token ATA. Got ${ataType} ATA.`,\n );\n }\n }\n\n // Check sources for balances\n const splSource = sources.find(s => s.type === 'spl');\n const t22Source = sources.find(s => s.type === 'token2022');\n const ctokenHotSource = sources.find(s => s.type === 'ctoken-hot');\n const ctokenColdSource = sources.find(s => s.type === 'ctoken-cold');\n\n const splBalance = splSource?.amount ?? BigInt(0);\n const t22Balance = t22Source?.amount ?? BigInt(0);\n const coldBalance = ctokenColdSource?.amount ?? BigInt(0);\n\n // Nothing to load\n if (\n splBalance === BigInt(0) &&\n t22Balance === BigInt(0) &&\n coldBalance === BigInt(0)\n ) {\n return [];\n }\n\n // Get SPL interface info (needed for wrapping or SPL/T22 decompression)\n let splInterfaceInfo: SplInterfaceInfo | undefined;\n const needsSplInfo =\n wrap ||\n ataType === 'spl' ||\n ataType === 'token2022' ||\n splBalance > BigInt(0) ||\n t22Balance > BigInt(0);\n\n if (needsSplInfo) {\n try {\n const splInterfaceInfos =\n options?.splInterfaceInfos ??\n (await getSplInterfaceInfos(rpc, mint));\n splInterfaceInfo = splInterfaceInfos.find(\n (info: SplInterfaceInfo) => info.isInitialized,\n );\n } catch {\n // No SPL interface exists\n }\n }\n\n if (wrap) {\n // UNIFIED MODE: Everything goes to c-token ATA\n\n // 1. Create c-token ATA if needed\n if (!ctokenHotSource) {\n instructions.push(\n createAssociatedTokenAccountInterfaceIdempotentInstruction(\n payer,\n ctokenAtaAddress,\n owner,\n mint,\n CTOKEN_PROGRAM_ID,\n ),\n );\n }\n\n // 2. Wrap SPL tokens to c-token\n if (splBalance > BigInt(0) && splInterfaceInfo) {\n instructions.push(\n createWrapInstruction(\n splAta,\n ctokenAtaAddress,\n owner,\n mint,\n splBalance,\n splInterfaceInfo,\n payer,\n ),\n );\n }\n\n // 3. Wrap T22 tokens to c-token\n if (t22Balance > BigInt(0) && splInterfaceInfo) {\n instructions.push(\n createWrapInstruction(\n t22Ata,\n ctokenAtaAddress,\n owner,\n mint,\n t22Balance,\n splInterfaceInfo,\n payer,\n ),\n );\n }\n\n // 4. Decompress compressed tokens to c-token ATA\n if (coldBalance > BigInt(0) && ctokenColdSource) {\n const compressedResult =\n await rpc.getCompressedTokenAccountsByOwner(owner, { mint });\n const compressedAccounts = compressedResult.items;\n\n if (compressedAccounts.length > 0) {\n const proof = await rpc.getValidityProofV0(\n compressedAccounts.map(acc => ({\n hash: acc.compressedAccount.hash,\n tree: acc.compressedAccount.treeInfo.tree,\n queue: acc.compressedAccount.treeInfo.queue,\n })),\n );\n\n instructions.push(\n createDecompressInterfaceInstruction(\n payer,\n compressedAccounts,\n ctokenAtaAddress,\n coldBalance,\n proof,\n ),\n );\n }\n }\n } else {\n // STANDARD MODE: Decompress to target ATA type\n\n if (coldBalance > BigInt(0) && ctokenColdSource) {\n const compressedResult =\n await rpc.getCompressedTokenAccountsByOwner(owner, { mint });\n const compressedAccounts = compressedResult.items;\n\n if (compressedAccounts.length > 0) {\n const proof = await rpc.getValidityProofV0(\n compressedAccounts.map(acc => ({\n hash: acc.compressedAccount.hash,\n tree: acc.compressedAccount.treeInfo.tree,\n queue: acc.compressedAccount.treeInfo.queue,\n })),\n );\n\n if (ataType === 'ctoken') {\n // Decompress to c-token ATA (direct)\n if (!ctokenHotSource) {\n instructions.push(\n createAssociatedTokenAccountInterfaceIdempotentInstruction(\n payer,\n ctokenAtaAddress,\n owner,\n mint,\n CTOKEN_PROGRAM_ID,\n ),\n );\n }\n instructions.push(\n createDecompressInterfaceInstruction(\n payer,\n compressedAccounts,\n ctokenAtaAddress,\n coldBalance,\n proof,\n ),\n );\n } else if (ataType === 'spl' && splInterfaceInfo) {\n // Decompress to SPL ATA via token pool\n // Create SPL ATA if needed\n if (!splSource) {\n instructions.push(\n createAssociatedTokenAccountIdempotentInstruction(\n payer,\n splAta,\n owner,\n mint,\n TOKEN_PROGRAM_ID,\n ),\n );\n }\n instructions.push(\n createDecompressInterfaceInstruction(\n payer,\n compressedAccounts,\n splAta,\n coldBalance,\n proof,\n splInterfaceInfo,\n ),\n );\n } else if (ataType === 'token2022' && splInterfaceInfo) {\n // Decompress to T22 ATA via token pool\n // Create T22 ATA if needed\n if (!t22Source) {\n instructions.push(\n createAssociatedTokenAccountIdempotentInstruction(\n payer,\n t22Ata,\n owner,\n mint,\n TOKEN_2022_PROGRAM_ID,\n ),\n );\n }\n instructions.push(\n createDecompressInterfaceInstruction(\n payer,\n compressedAccounts,\n t22Ata,\n coldBalance,\n proof,\n splInterfaceInfo,\n ),\n );\n }\n }\n }\n }\n\n return instructions;\n}\n\n/**\n * Load token balances into an ATA.\n *\n * Behavior depends on `wrap` parameter:\n * - wrap=false (standard): Decompress compressed tokens to the target ATA.\n * ATA can be SPL (via pool), T22 (via pool), or c-token (direct).\n * - wrap=true (unified): Wrap SPL/T22 + decompress all to c-token ATA.\n *\n * Idempotent: returns null if nothing to load.\n *\n * @param rpc RPC connection\n * @param ata Associated token address (SPL, T22, or c-token)\n * @param owner Owner of the tokens (signer)\n * @param mint Mint public key\n * @param payer Fee payer (signer, defaults to owner)\n * @param confirmOptions Optional confirm options\n * @param interfaceOptions Optional interface options\n * @param wrap Unified mode: wrap SPL/T22 to c-token (default: false)\n * @returns Transaction signature, or null if nothing to load\n */\nexport async function loadAta(\n rpc: Rpc,\n ata: PublicKey,\n owner: Signer,\n mint: PublicKey,\n payer?: Signer,\n confirmOptions?: ConfirmOptions,\n interfaceOptions?: InterfaceOptions,\n wrap = false,\n): Promise<TransactionSignature | null> {\n payer ??= owner;\n\n const ixs = await createLoadAtaInstructions(\n rpc,\n ata,\n owner.publicKey,\n mint,\n payer.publicKey,\n interfaceOptions,\n wrap,\n );\n\n if (ixs.length === 0) {\n return null;\n }\n\n const { blockhash } = await rpc.getLatestBlockhash();\n const additionalSigners = dedupeSigner(payer, [owner]);\n\n const tx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 500_000 }), ...ixs],\n payer,\n blockhash,\n additionalSigners,\n );\n\n return sendAndConfirmTx(rpc, tx, confirmOptions);\n}\n","import {\n Rpc,\n MerkleContext,\n ValidityProof,\n packDecompressAccountsIdempotent,\n} from '@lightprotocol/stateless.js';\nimport {\n PublicKey,\n AccountMeta,\n TransactionInstruction,\n} from '@solana/web3.js';\nimport { AccountInterface } from '../get-account-interface';\nimport { createLoadAtaInstructionsFromInterface } from '../actions/load-ata';\nimport { InterfaceOptions } from '../actions/transfer-interface';\n\n/**\n * Account info interface for compressible accounts.\n * Matches return structure of getAccountInterface/getAtaInterface.\n *\n * Integrating programs provide their own fetch/parse - this is just the data shape.\n */\nexport interface ParsedAccountInfoInterface<T = unknown> {\n /** Parsed account data (program-specific) */\n parsed: T;\n /** Load context - present if account is compressed (cold), undefined if hot */\n loadContext?: MerkleContext;\n}\n\n/**\n * Input for createLoadAccountsParams.\n * Supports both program PDAs and c-token vaults.\n *\n * The integrating program is responsible for fetching and parsing their accounts.\n * This helper just packs them for the decompressAccountsIdempotent instruction.\n */\nexport interface CompressibleAccountInput<T = unknown> {\n /** Account address */\n address: PublicKey;\n /**\n * Account type key for packing:\n * - For PDAs: program-specific type name (e.g., \"poolState\", \"observationState\")\n * - For c-token vaults: \"cTokenData\"\n */\n accountType: string;\n /**\n * Token variant - required when accountType is \"cTokenData\".\n * Examples: \"lpVault\", \"token0Vault\", \"token1Vault\"\n */\n tokenVariant?: string;\n /** Parsed account info (from program-specific fetch) */\n info: ParsedAccountInfoInterface<T>;\n}\n\n/**\n * Packed compressed account for decompressAccountsIdempotent instruction\n */\nexport interface PackedCompressedAccount {\n [key: string]: unknown;\n merkleContext: {\n merkleTreePubkeyIndex: number;\n queuePubkeyIndex: number;\n };\n}\n\n/**\n * Result from building load params\n */\nexport interface CompressibleLoadParams {\n /** Validity proof wrapped in option (null if all proveByIndex) */\n proofOption: { 0: ValidityProof | null };\n /** Packed compressed accounts data for instruction */\n compressedAccounts: PackedCompressedAccount[];\n /** Offset to system accounts in remainingAccounts */\n systemAccountsOffset: number;\n /** Account metas for remaining accounts */\n remainingAccounts: AccountMeta[];\n}\n\n/**\n * Result from createLoadAccountsParams\n */\nexport interface LoadResult {\n /** Params for decompressAccountsIdempotent (null if no program accounts need decompressing) */\n decompressParams: CompressibleLoadParams | null;\n /** Instructions to load ATAs (create ATA, wrap SPL/T22, decompressInterface) */\n ataInstructions: TransactionInstruction[];\n}\n\n/**\n * Create params for loading program accounts and ATAs.\n *\n * Returns:\n * - decompressParams: for a caller program's standardized\n * decompressAccountsIdempotent instruction\n * - ataInstructions: for loading user ATAs\n *\n * @param rpc RPC connection\n * @param payer Fee payer (needed for ATA instructions)\n * @param programId Program ID for decompressAccountsIdempotent\n * @param programAccounts PDAs and vaults (caller pre-fetches)\n * @param atas User ATAs (fetched via getAtaInterface)\n * @param options Optional load options\n * @returns LoadResult with decompressParams and ataInstructions\n *\n * @example\n * ```typescript\n * const poolInfo = await myProgram.fetchPoolState(rpc, poolAddress);\n * const vault0Ata = getAssociatedTokenAddressInterface(token0Mint, poolAddress);\n * const vault0Info = await getAtaInterface(rpc, vault0Ata, poolAddress, token0Mint, undefined, CTOKEN_PROGRAM_ID);\n * const userAta = getAssociatedTokenAddressInterface(tokenMint, userWallet);\n * const userAtaInfo = await getAtaInterface(rpc, userAta, userWallet, tokenMint);\n *\n * const result = await createLoadAccountsParams(\n * rpc,\n * payer.publicKey,\n * programId,\n * [\n * { address: poolAddress, accountType: 'poolState', info: poolInfo },\n * { address: vault0, accountType: 'cTokenData', tokenVariant: 'token0Vault', info: vault0Info },\n * ],\n * [userAta],\n * );\n *\n * // Build transaction with both program decompress and ATA load\n * const instructions = [...result.ataInstructions];\n * if (result.decompressParams) {\n * instructions.push(await program.methods\n * .decompressAccountsIdempotent(\n * result.decompressParams.proofOption,\n * result.decompressParams.compressedAccounts,\n * result.decompressParams.systemAccountsOffset,\n * )\n * .remainingAccounts(result.decompressParams.remainingAccounts)\n * .instruction());\n * }\n * ```\n */\nexport async function createLoadAccountsParams(\n rpc: Rpc,\n payer: PublicKey,\n programId: PublicKey,\n programAccounts: CompressibleAccountInput[] = [],\n atas: AccountInterface[] = [],\n options?: InterfaceOptions,\n): Promise<LoadResult> {\n let decompressParams: CompressibleLoadParams | null = null;\n\n const compressedProgramAccounts = programAccounts.filter(\n acc => acc.info.loadContext !== undefined,\n );\n\n if (compressedProgramAccounts.length > 0) {\n // Build proof inputs\n const proofInputs = compressedProgramAccounts.map(acc => ({\n hash: acc.info.loadContext!.hash,\n tree: acc.info.loadContext!.treeInfo.tree,\n queue: acc.info.loadContext!.treeInfo.queue,\n }));\n\n const proofResult = await rpc.getValidityProofV0(proofInputs, []);\n\n // Build accounts data for packing\n const accountsData = compressedProgramAccounts.map(acc => {\n if (acc.accountType === 'cTokenData') {\n if (!acc.tokenVariant) {\n throw new Error(\n 'tokenVariant is required when accountType is \"cTokenData\"',\n );\n }\n return {\n key: 'cTokenData',\n data: {\n variant: { [acc.tokenVariant]: {} },\n tokenData: acc.info.parsed,\n },\n treeInfo: acc.info.loadContext!.treeInfo,\n };\n }\n return {\n key: acc.accountType,\n data: acc.info.parsed,\n treeInfo: acc.info.loadContext!.treeInfo,\n };\n });\n\n const addresses = compressedProgramAccounts.map(acc => acc.address);\n const treeInfos = compressedProgramAccounts.map(\n acc => acc.info.loadContext!.treeInfo,\n );\n\n const packed = await packDecompressAccountsIdempotent(\n programId,\n {\n compressedProof: proofResult.compressedProof,\n treeInfos,\n },\n accountsData,\n addresses,\n );\n\n decompressParams = {\n proofOption: packed.proofOption,\n compressedAccounts:\n packed.compressedAccounts as PackedCompressedAccount[],\n systemAccountsOffset: packed.systemAccountsOffset,\n remainingAccounts: packed.remainingAccounts,\n };\n }\n\n const ataInstructions: TransactionInstruction[] = [];\n\n for (const ata of atas) {\n const ixs = await createLoadAtaInstructionsFromInterface(\n rpc,\n payer,\n ata,\n options,\n );\n ataInstructions.push(...ixs);\n }\n\n return {\n decompressParams,\n ataInstructions,\n };\n}\n\n/**\n * Calculate compute units for compressible load operation\n */\nexport function calculateCompressibleLoadComputeUnits(\n compressedAccountCount: number,\n hasValidityProof: boolean,\n): number {\n let cu = 50_000; // Base\n\n if (hasValidityProof) {\n cu += 100_000; // Proof verification\n }\n\n // Per compressed account\n cu += compressedAccountCount * 30_000;\n\n return cu;\n}\n","import {\n ConfirmOptions,\n Keypair,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\nimport { CompressedTokenProgram } from '../program';\nimport {\n MINT_SIZE,\n TOKEN_2022_PROGRAM_ID,\n TOKEN_PROGRAM_ID,\n} from '@solana/spl-token';\nimport {\n Rpc,\n buildAndSignTx,\n dedupeSigner,\n sendAndConfirmTx,\n} from '@lightprotocol/stateless.js';\n\n/**\n * Create and initialize a new SPL token mint\n *\n * @deprecated Use {@link createMintInterface} instead, which supports both SPL and compressed mints.\n *\n * @param rpc RPC connection to use\n * @param payer Fee payer\n * @param mintAuthority Account that will control minting\n * @param decimals Location of the decimal place\n * @param keypair Optional: Mint keypair. Defaults to a random\n * keypair.\n * @param confirmOptions Options for confirming the transaction\n * @param tokenProgramId Optional: Program ID for the token. Defaults to\n * TOKEN_PROGRAM_ID.\n * @param freezeAuthority Optional: Account that will control freeze and thaw.\n *\n * @return Object with mint address and transaction signature\n */\nexport async function createMint(\n rpc: Rpc,\n payer: Signer,\n mintAuthority: PublicKey | Signer,\n decimals: number,\n keypair: Keypair = Keypair.generate(),\n confirmOptions?: ConfirmOptions,\n tokenProgramId?: PublicKey | boolean,\n freezeAuthority?: PublicKey | Signer | null,\n): Promise<{ mint: PublicKey; transactionSignature: TransactionSignature }> {\n const rentExemptBalance =\n await rpc.getMinimumBalanceForRentExemption(MINT_SIZE);\n\n // If true, uses TOKEN_2022_PROGRAM_ID.\n // If false or undefined, defaults to TOKEN_PROGRAM_ID.\n // Otherwise, uses the provided tokenProgramId.\n const resolvedTokenProgramId =\n tokenProgramId === true\n ? TOKEN_2022_PROGRAM_ID\n : tokenProgramId || TOKEN_PROGRAM_ID;\n\n const ixs = await CompressedTokenProgram.createMint({\n feePayer: payer.publicKey,\n mint: keypair.publicKey,\n decimals,\n authority:\n 'secretKey' in mintAuthority\n ? mintAuthority.publicKey\n : mintAuthority,\n freezeAuthority:\n freezeAuthority && 'secretKey' in freezeAuthority\n ? freezeAuthority.publicKey\n : (freezeAuthority ?? null),\n rentExemptBalance,\n tokenProgramId: resolvedTokenProgramId,\n });\n\n const { blockhash } = await rpc.getLatestBlockhash();\n\n const additionalSigners = dedupeSigner(\n payer,\n [mintAuthority, freezeAuthority ?? null].filter(\n (signer): signer is Signer =>\n signer != undefined && 'secretKey' in signer,\n ),\n );\n\n const tx = buildAndSignTx(ixs, payer, blockhash, [\n ...additionalSigners,\n keypair,\n ]);\n const txId = await sendAndConfirmTx(rpc, tx, confirmOptions);\n\n return { mint: keypair.publicKey, transactionSignature: txId };\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n Keypair,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\nimport {\n Rpc,\n buildAndSignTx,\n dedupeSigner,\n sendAndConfirmTx,\n TreeInfo,\n AddressTreeInfo,\n selectStateTreeInfo,\n getBatchAddressTreeInfo,\n DerivationMode,\n CTOKEN_PROGRAM_ID,\n} from '@lightprotocol/stateless.js';\nimport { TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from '@solana/spl-token';\nimport {\n createMintInstruction,\n TokenMetadataInstructionData,\n} from '../instructions/create-mint';\nimport { findMintAddress } from '../derivation';\nimport { createMint } from '../../actions/create-mint';\n\nexport { TokenMetadataInstructionData };\n\n/**\n * Create and initialize a new mint for SPL/T22/c-token.\n *\n * @param rpc RPC connection to use\n * @param payer Fee payer\n * @param mintAuthority Account that will control minting (signer for c-token mints)\n * @param freezeAuthority Account that will control freeze and thaw (optional)\n * @param decimals Location of the decimal place\n * @param keypair Mint keypair (defaults to a random keypair)\n * @param confirmOptions Confirm options\n * @param programId Token program ID (defaults to CTOKEN_PROGRAM_ID)\n * @param tokenMetadata Optional token metadata (c-token mints only)\n * @param outputStateTreeInfo Optional output state tree info (c-token mints only)\n * @param addressTreeInfo Optional address tree info (c-token mints only)\n *\n * @returns Object with mint address and transaction signature\n */\nexport async function createMintInterface(\n rpc: Rpc,\n payer: Signer,\n mintAuthority: PublicKey | Signer,\n freezeAuthority: PublicKey | Signer | null,\n decimals: number,\n keypair: Keypair = Keypair.generate(),\n confirmOptions?: ConfirmOptions,\n programId: PublicKey = CTOKEN_PROGRAM_ID,\n tokenMetadata?: TokenMetadataInstructionData,\n outputStateTreeInfo?: TreeInfo,\n addressTreeInfo?: AddressTreeInfo,\n): Promise<{ mint: PublicKey; transactionSignature: TransactionSignature }> {\n // Dispatch to SPL/Token-2022 mint creation\n if (\n programId.equals(TOKEN_PROGRAM_ID) ||\n programId.equals(TOKEN_2022_PROGRAM_ID)\n ) {\n return createMint(\n rpc,\n payer,\n mintAuthority,\n decimals,\n keypair,\n confirmOptions,\n programId,\n freezeAuthority,\n );\n }\n\n // Default: compressed token mint creation\n if (!('secretKey' in mintAuthority)) {\n throw new Error(\n 'mintAuthority must be a Signer for compressed token mints',\n );\n }\n\n const resolvedFreezeAuthority =\n freezeAuthority && 'secretKey' in freezeAuthority\n ? freezeAuthority.publicKey\n : (freezeAuthority as PublicKey | null);\n\n addressTreeInfo = addressTreeInfo ?? getBatchAddressTreeInfo();\n outputStateTreeInfo =\n outputStateTreeInfo ??\n selectStateTreeInfo(await rpc.getStateTreeInfos());\n\n const validityProof = await rpc.getValidityProofV2(\n [],\n [\n {\n address: findMintAddress(keypair.publicKey)[0].toBytes(),\n treeInfo: addressTreeInfo,\n },\n ],\n DerivationMode.compressible,\n );\n\n const ix = createMintInstruction(\n keypair.publicKey,\n decimals,\n mintAuthority.publicKey,\n resolvedFreezeAuthority,\n payer.publicKey,\n validityProof,\n addressTreeInfo,\n outputStateTreeInfo,\n tokenMetadata,\n );\n\n const additionalSigners = dedupeSigner(payer, [keypair, mintAuthority]);\n const { blockhash } = await rpc.getLatestBlockhash();\n const tx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 500_000 }), ix],\n payer,\n blockhash,\n additionalSigners,\n );\n const txId = await sendAndConfirmTx(rpc, tx, {\n ...confirmOptions,\n skipPreflight: true,\n });\n\n const mint = findMintAddress(keypair.publicKey);\n return { mint: mint[0], transactionSignature: txId };\n}\n","/* The MIT License (MIT)\n *\n * Copyright 2015-2018 Peter A. Bigot\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n/**\n * Support for translating between Uint8Array instances and JavaScript\n * native types.\n *\n * {@link module:Layout~Layout|Layout} is the basis of a class\n * hierarchy that associates property names with sequences of encoded\n * bytes.\n *\n * Layouts are supported for these scalar (numeric) types:\n * * {@link module:Layout~UInt|Unsigned integers in little-endian\n * format} with {@link module:Layout.u8|8-bit}, {@link\n * module:Layout.u16|16-bit}, {@link module:Layout.u24|24-bit},\n * {@link module:Layout.u32|32-bit}, {@link\n * module:Layout.u40|40-bit}, and {@link module:Layout.u48|48-bit}\n * representation ranges;\n * * {@link module:Layout~UIntBE|Unsigned integers in big-endian\n * format} with {@link module:Layout.u16be|16-bit}, {@link\n * module:Layout.u24be|24-bit}, {@link module:Layout.u32be|32-bit},\n * {@link module:Layout.u40be|40-bit}, and {@link\n * module:Layout.u48be|48-bit} representation ranges;\n * * {@link module:Layout~Int|Signed integers in little-endian\n * format} with {@link module:Layout.s8|8-bit}, {@link\n * module:Layout.s16|16-bit}, {@link module:Layout.s24|24-bit},\n * {@link module:Layout.s32|32-bit}, {@link\n * module:Layout.s40|40-bit}, and {@link module:Layout.s48|48-bit}\n * representation ranges;\n * * {@link module:Layout~IntBE|Signed integers in big-endian format}\n * with {@link module:Layout.s16be|16-bit}, {@link\n * module:Layout.s24be|24-bit}, {@link module:Layout.s32be|32-bit},\n * {@link module:Layout.s40be|40-bit}, and {@link\n * module:Layout.s48be|48-bit} representation ranges;\n * * 64-bit integral values that decode to an exact (if magnitude is\n * less than 2^53) or nearby integral Number in {@link\n * module:Layout.nu64|unsigned little-endian}, {@link\n * module:Layout.nu64be|unsigned big-endian}, {@link\n * module:Layout.ns64|signed little-endian}, and {@link\n * module:Layout.ns64be|unsigned big-endian} encodings;\n * * 32-bit floating point values with {@link\n * module:Layout.f32|little-endian} and {@link\n * module:Layout.f32be|big-endian} representations;\n * * 64-bit floating point values with {@link\n * module:Layout.f64|little-endian} and {@link\n * module:Layout.f64be|big-endian} representations;\n * * {@link module:Layout.const|Constants} that take no space in the\n * encoded expression.\n *\n * and for these aggregate types:\n * * {@link module:Layout.seq|Sequence}s of instances of a {@link\n * module:Layout~Layout|Layout}, with JavaScript representation as\n * an Array and constant or data-dependent {@link\n * module:Layout~Sequence#count|length};\n * * {@link module:Layout.struct|Structure}s that aggregate a\n * heterogeneous sequence of {@link module:Layout~Layout|Layout}\n * instances, with JavaScript representation as an Object;\n * * {@link module:Layout.union|Union}s that support multiple {@link\n * module:Layout~VariantLayout|variant layouts} over a fixed\n * (padded) or variable (not padded) span of bytes, using an\n * unsigned integer at the start of the data or a separate {@link\n * module:Layout.unionLayoutDiscriminator|layout element} to\n * determine which layout to use when interpreting the buffer\n * contents;\n * * {@link module:Layout.bits|BitStructure}s that contain a sequence\n * of individual {@link\n * module:Layout~BitStructure#addField|BitField}s packed into an 8,\n * 16, 24, or 32-bit unsigned integer starting at the least- or\n * most-significant bit;\n * * {@link module:Layout.cstr|C strings} of varying length;\n * * {@link module:Layout.blob|Blobs} of fixed- or variable-{@link\n * module:Layout~Blob#length|length} raw data.\n *\n * All {@link module:Layout~Layout|Layout} instances are immutable\n * after construction, to prevent internal state from becoming\n * inconsistent.\n *\n * @local Layout\n * @local ExternalLayout\n * @local GreedyCount\n * @local OffsetLayout\n * @local UInt\n * @local UIntBE\n * @local Int\n * @local IntBE\n * @local NearUInt64\n * @local NearUInt64BE\n * @local NearInt64\n * @local NearInt64BE\n * @local Float\n * @local FloatBE\n * @local Double\n * @local DoubleBE\n * @local Sequence\n * @local Structure\n * @local UnionDiscriminator\n * @local UnionLayoutDiscriminator\n * @local Union\n * @local VariantLayout\n * @local BitStructure\n * @local BitField\n * @local Boolean\n * @local Blob\n * @local CString\n * @local Constant\n * @local bindConstructorLayout\n * @module Layout\n * @license MIT\n * @author Peter A. Bigot\n * @see {@link https://github.com/pabigot/buffer-layout|buffer-layout on GitHub}\n */\n'use strict';\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.s16 = exports.s8 = exports.nu64be = exports.u48be = exports.u40be = exports.u32be = exports.u24be = exports.u16be = exports.nu64 = exports.u48 = exports.u40 = exports.u32 = exports.u24 = exports.u16 = exports.u8 = exports.offset = exports.greedy = exports.Constant = exports.UTF8 = exports.CString = exports.Blob = exports.Boolean = exports.BitField = exports.BitStructure = exports.VariantLayout = exports.Union = exports.UnionLayoutDiscriminator = exports.UnionDiscriminator = exports.Structure = exports.Sequence = exports.DoubleBE = exports.Double = exports.FloatBE = exports.Float = exports.NearInt64BE = exports.NearInt64 = exports.NearUInt64BE = exports.NearUInt64 = exports.IntBE = exports.Int = exports.UIntBE = exports.UInt = exports.OffsetLayout = exports.GreedyCount = exports.ExternalLayout = exports.bindConstructorLayout = exports.nameWithProperty = exports.Layout = exports.uint8ArrayToBuffer = exports.checkUint8Array = void 0;\nexports.constant = exports.utf8 = exports.cstr = exports.blob = exports.unionLayoutDiscriminator = exports.union = exports.seq = exports.bits = exports.struct = exports.f64be = exports.f64 = exports.f32be = exports.f32 = exports.ns64be = exports.s48be = exports.s40be = exports.s32be = exports.s24be = exports.s16be = exports.ns64 = exports.s48 = exports.s40 = exports.s32 = exports.s24 = void 0;\nconst buffer_1 = require(\"buffer\");\n/* Check if a value is a Uint8Array.\n *\n * @ignore */\nfunction checkUint8Array(b) {\n if (!(b instanceof Uint8Array)) {\n throw new TypeError('b must be a Uint8Array');\n }\n}\nexports.checkUint8Array = checkUint8Array;\n/* Create a Buffer instance from a Uint8Array.\n *\n * @ignore */\nfunction uint8ArrayToBuffer(b) {\n checkUint8Array(b);\n return buffer_1.Buffer.from(b.buffer, b.byteOffset, b.length);\n}\nexports.uint8ArrayToBuffer = uint8ArrayToBuffer;\n/**\n * Base class for layout objects.\n *\n * **NOTE** This is an abstract base class; you can create instances\n * if it amuses you, but they won't support the {@link\n * Layout#encode|encode} or {@link Layout#decode|decode} functions.\n *\n * @param {Number} span - Initializer for {@link Layout#span|span}. The\n * parameter must be an integer; a negative value signifies that the\n * span is {@link Layout#getSpan|value-specific}.\n *\n * @param {string} [property] - Initializer for {@link\n * Layout#property|property}.\n *\n * @abstract\n */\nclass Layout {\n constructor(span, property) {\n if (!Number.isInteger(span)) {\n throw new TypeError('span must be an integer');\n }\n /** The span of the layout in bytes.\n *\n * Positive values are generally expected.\n *\n * Zero will only appear in {@link Constant}s and in {@link\n * Sequence}s where the {@link Sequence#count|count} is zero.\n *\n * A negative value indicates that the span is value-specific, and\n * must be obtained using {@link Layout#getSpan|getSpan}. */\n this.span = span;\n /** The property name used when this layout is represented in an\n * Object.\n *\n * Used only for layouts that {@link Layout#decode|decode} to Object\n * instances. If left undefined the span of the unnamed layout will\n * be treated as padding: it will not be mutated by {@link\n * Layout#encode|encode} nor represented as a property in the\n * decoded Object. */\n this.property = property;\n }\n /** Function to create an Object into which decoded properties will\n * be written.\n *\n * Used only for layouts that {@link Layout#decode|decode} to Object\n * instances, which means:\n * * {@link Structure}\n * * {@link Union}\n * * {@link VariantLayout}\n * * {@link BitStructure}\n *\n * If left undefined the JavaScript representation of these layouts\n * will be Object instances.\n *\n * See {@link bindConstructorLayout}.\n */\n makeDestinationObject() {\n return {};\n }\n /**\n * Calculate the span of a specific instance of a layout.\n *\n * @param {Uint8Array} b - the buffer that contains an encoded instance.\n *\n * @param {Number} [offset] - the offset at which the encoded instance\n * starts. If absent a zero offset is inferred.\n *\n * @return {Number} - the number of bytes covered by the layout\n * instance. If this method is not overridden in a subclass the\n * definition-time constant {@link Layout#span|span} will be\n * returned.\n *\n * @throws {RangeError} - if the length of the value cannot be\n * determined.\n */\n getSpan(b, offset) {\n if (0 > this.span) {\n throw new RangeError('indeterminate span');\n }\n return this.span;\n }\n /**\n * Replicate the layout using a new property.\n *\n * This function must be used to get a structurally-equivalent layout\n * with a different name since all {@link Layout} instances are\n * immutable.\n *\n * **NOTE** This is a shallow copy. All fields except {@link\n * Layout#property|property} are strictly equal to the origin layout.\n *\n * @param {String} property - the value for {@link\n * Layout#property|property} in the replica.\n *\n * @returns {Layout} - the copy with {@link Layout#property|property}\n * set to `property`.\n */\n replicate(property) {\n const rv = Object.create(this.constructor.prototype);\n Object.assign(rv, this);\n rv.property = property;\n return rv;\n }\n /**\n * Create an object from layout properties and an array of values.\n *\n * **NOTE** This function returns `undefined` if invoked on a layout\n * that does not return its value as an Object. Objects are\n * returned for things that are a {@link Structure}, which includes\n * {@link VariantLayout|variant layouts} if they are structures, and\n * excludes {@link Union}s. If you want this feature for a union\n * you must use {@link Union.getVariant|getVariant} to select the\n * desired layout.\n *\n * @param {Array} values - an array of values that correspond to the\n * default order for properties. As with {@link Layout#decode|decode}\n * layout elements that have no property name are skipped when\n * iterating over the array values. Only the top-level properties are\n * assigned; arguments are not assigned to properties of contained\n * layouts. Any unused values are ignored.\n *\n * @return {(Object|undefined)}\n */\n fromArray(values) {\n return undefined;\n }\n}\nexports.Layout = Layout;\n/* Provide text that carries a name (such as for a function that will\n * be throwing an error) annotated with the property of a given layout\n * (such as one for which the value was unacceptable).\n *\n * @ignore */\nfunction nameWithProperty(name, lo) {\n if (lo.property) {\n return name + '[' + lo.property + ']';\n }\n return name;\n}\nexports.nameWithProperty = nameWithProperty;\n/**\n * Augment a class so that instances can be encoded/decoded using a\n * given layout.\n *\n * Calling this function couples `Class` with `layout` in several ways:\n *\n * * `Class.layout_` becomes a static member property equal to `layout`;\n * * `layout.boundConstructor_` becomes a static member property equal\n * to `Class`;\n * * The {@link Layout#makeDestinationObject|makeDestinationObject()}\n * property of `layout` is set to a function that returns a `new\n * Class()`;\n * * `Class.decode(b, offset)` becomes a static member function that\n * delegates to {@link Layout#decode|layout.decode}. The\n * synthesized function may be captured and extended.\n * * `Class.prototype.encode(b, offset)` provides an instance member\n * function that delegates to {@link Layout#encode|layout.encode}\n * with `src` set to `this`. The synthesized function may be\n * captured and extended, but when the extension is invoked `this`\n * must be explicitly bound to the instance.\n *\n * @param {class} Class - a JavaScript class with a nullary\n * constructor.\n *\n * @param {Layout} layout - the {@link Layout} instance used to encode\n * instances of `Class`.\n */\n// `Class` must be a constructor Function, but the assignment of a `layout_` property to it makes it difficult to type\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nfunction bindConstructorLayout(Class, layout) {\n if ('function' !== typeof Class) {\n throw new TypeError('Class must be constructor');\n }\n if (Object.prototype.hasOwnProperty.call(Class, 'layout_')) {\n throw new Error('Class is already bound to a layout');\n }\n if (!(layout && (layout instanceof Layout))) {\n throw new TypeError('layout must be a Layout');\n }\n if (Object.prototype.hasOwnProperty.call(layout, 'boundConstructor_')) {\n throw new Error('layout is already bound to a constructor');\n }\n Class.layout_ = layout;\n layout.boundConstructor_ = Class;\n layout.makeDestinationObject = (() => new Class());\n Object.defineProperty(Class.prototype, 'encode', {\n value(b, offset) {\n return layout.encode(this, b, offset);\n },\n writable: true,\n });\n Object.defineProperty(Class, 'decode', {\n value(b, offset) {\n return layout.decode(b, offset);\n },\n writable: true,\n });\n}\nexports.bindConstructorLayout = bindConstructorLayout;\n/**\n * An object that behaves like a layout but does not consume space\n * within its containing layout.\n *\n * This is primarily used to obtain metadata about a member, such as a\n * {@link OffsetLayout} that can provide data about a {@link\n * Layout#getSpan|value-specific span}.\n *\n * **NOTE** This is an abstract base class; you can create instances\n * if it amuses you, but they won't support {@link\n * ExternalLayout#isCount|isCount} or other {@link Layout} functions.\n *\n * @param {Number} span - initializer for {@link Layout#span|span}.\n * The parameter can range from 1 through 6.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @abstract\n * @augments {Layout}\n */\nclass ExternalLayout extends Layout {\n /**\n * Return `true` iff the external layout decodes to an unsigned\n * integer layout.\n *\n * In that case it can be used as the source of {@link\n * Sequence#count|Sequence counts}, {@link Blob#length|Blob lengths},\n * or as {@link UnionLayoutDiscriminator#layout|external union\n * discriminators}.\n *\n * @abstract\n */\n isCount() {\n throw new Error('ExternalLayout is abstract');\n }\n}\nexports.ExternalLayout = ExternalLayout;\n/**\n * An {@link ExternalLayout} that determines its {@link\n * Layout#decode|value} based on offset into and length of the buffer\n * on which it is invoked.\n *\n * *Factory*: {@link module:Layout.greedy|greedy}\n *\n * @param {Number} [elementSpan] - initializer for {@link\n * GreedyCount#elementSpan|elementSpan}.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {ExternalLayout}\n */\nclass GreedyCount extends ExternalLayout {\n constructor(elementSpan = 1, property) {\n if ((!Number.isInteger(elementSpan)) || (0 >= elementSpan)) {\n throw new TypeError('elementSpan must be a (positive) integer');\n }\n super(-1, property);\n /** The layout for individual elements of the sequence. The value\n * must be a positive integer. If not provided, the value will be\n * 1. */\n this.elementSpan = elementSpan;\n }\n /** @override */\n isCount() {\n return true;\n }\n /** @override */\n decode(b, offset = 0) {\n checkUint8Array(b);\n const rem = b.length - offset;\n return Math.floor(rem / this.elementSpan);\n }\n /** @override */\n encode(src, b, offset) {\n return 0;\n }\n}\nexports.GreedyCount = GreedyCount;\n/**\n * An {@link ExternalLayout} that supports accessing a {@link Layout}\n * at a fixed offset from the start of another Layout. The offset may\n * be before, within, or after the base layout.\n *\n * *Factory*: {@link module:Layout.offset|offset}\n *\n * @param {Layout} layout - initializer for {@link\n * OffsetLayout#layout|layout}, modulo `property`.\n *\n * @param {Number} [offset] - Initializes {@link\n * OffsetLayout#offset|offset}. Defaults to zero.\n *\n * @param {string} [property] - Optional new property name for a\n * {@link Layout#replicate| replica} of `layout` to be used as {@link\n * OffsetLayout#layout|layout}. If not provided the `layout` is used\n * unchanged.\n *\n * @augments {Layout}\n */\nclass OffsetLayout extends ExternalLayout {\n constructor(layout, offset = 0, property) {\n if (!(layout instanceof Layout)) {\n throw new TypeError('layout must be a Layout');\n }\n if (!Number.isInteger(offset)) {\n throw new TypeError('offset must be integer or undefined');\n }\n super(layout.span, property || layout.property);\n /** The subordinated layout. */\n this.layout = layout;\n /** The location of {@link OffsetLayout#layout} relative to the\n * start of another layout.\n *\n * The value may be positive or negative, but an error will thrown\n * if at the point of use it goes outside the span of the Uint8Array\n * being accessed. */\n this.offset = offset;\n }\n /** @override */\n isCount() {\n return ((this.layout instanceof UInt)\n || (this.layout instanceof UIntBE));\n }\n /** @override */\n decode(b, offset = 0) {\n return this.layout.decode(b, offset + this.offset);\n }\n /** @override */\n encode(src, b, offset = 0) {\n return this.layout.encode(src, b, offset + this.offset);\n }\n}\nexports.OffsetLayout = OffsetLayout;\n/**\n * Represent an unsigned integer in little-endian format.\n *\n * *Factory*: {@link module:Layout.u8|u8}, {@link\n * module:Layout.u16|u16}, {@link module:Layout.u24|u24}, {@link\n * module:Layout.u32|u32}, {@link module:Layout.u40|u40}, {@link\n * module:Layout.u48|u48}\n *\n * @param {Number} span - initializer for {@link Layout#span|span}.\n * The parameter can range from 1 through 6.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass UInt extends Layout {\n constructor(span, property) {\n super(span, property);\n if (6 < this.span) {\n throw new RangeError('span must not exceed 6 bytes');\n }\n }\n /** @override */\n decode(b, offset = 0) {\n return uint8ArrayToBuffer(b).readUIntLE(offset, this.span);\n }\n /** @override */\n encode(src, b, offset = 0) {\n uint8ArrayToBuffer(b).writeUIntLE(src, offset, this.span);\n return this.span;\n }\n}\nexports.UInt = UInt;\n/**\n * Represent an unsigned integer in big-endian format.\n *\n * *Factory*: {@link module:Layout.u8be|u8be}, {@link\n * module:Layout.u16be|u16be}, {@link module:Layout.u24be|u24be},\n * {@link module:Layout.u32be|u32be}, {@link\n * module:Layout.u40be|u40be}, {@link module:Layout.u48be|u48be}\n *\n * @param {Number} span - initializer for {@link Layout#span|span}.\n * The parameter can range from 1 through 6.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass UIntBE extends Layout {\n constructor(span, property) {\n super(span, property);\n if (6 < this.span) {\n throw new RangeError('span must not exceed 6 bytes');\n }\n }\n /** @override */\n decode(b, offset = 0) {\n return uint8ArrayToBuffer(b).readUIntBE(offset, this.span);\n }\n /** @override */\n encode(src, b, offset = 0) {\n uint8ArrayToBuffer(b).writeUIntBE(src, offset, this.span);\n return this.span;\n }\n}\nexports.UIntBE = UIntBE;\n/**\n * Represent a signed integer in little-endian format.\n *\n * *Factory*: {@link module:Layout.s8|s8}, {@link\n * module:Layout.s16|s16}, {@link module:Layout.s24|s24}, {@link\n * module:Layout.s32|s32}, {@link module:Layout.s40|s40}, {@link\n * module:Layout.s48|s48}\n *\n * @param {Number} span - initializer for {@link Layout#span|span}.\n * The parameter can range from 1 through 6.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Int extends Layout {\n constructor(span, property) {\n super(span, property);\n if (6 < this.span) {\n throw new RangeError('span must not exceed 6 bytes');\n }\n }\n /** @override */\n decode(b, offset = 0) {\n return uint8ArrayToBuffer(b).readIntLE(offset, this.span);\n }\n /** @override */\n encode(src, b, offset = 0) {\n uint8ArrayToBuffer(b).writeIntLE(src, offset, this.span);\n return this.span;\n }\n}\nexports.Int = Int;\n/**\n * Represent a signed integer in big-endian format.\n *\n * *Factory*: {@link module:Layout.s8be|s8be}, {@link\n * module:Layout.s16be|s16be}, {@link module:Layout.s24be|s24be},\n * {@link module:Layout.s32be|s32be}, {@link\n * module:Layout.s40be|s40be}, {@link module:Layout.s48be|s48be}\n *\n * @param {Number} span - initializer for {@link Layout#span|span}.\n * The parameter can range from 1 through 6.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass IntBE extends Layout {\n constructor(span, property) {\n super(span, property);\n if (6 < this.span) {\n throw new RangeError('span must not exceed 6 bytes');\n }\n }\n /** @override */\n decode(b, offset = 0) {\n return uint8ArrayToBuffer(b).readIntBE(offset, this.span);\n }\n /** @override */\n encode(src, b, offset = 0) {\n uint8ArrayToBuffer(b).writeIntBE(src, offset, this.span);\n return this.span;\n }\n}\nexports.IntBE = IntBE;\nconst V2E32 = Math.pow(2, 32);\n/* True modulus high and low 32-bit words, where low word is always\n * non-negative. */\nfunction divmodInt64(src) {\n const hi32 = Math.floor(src / V2E32);\n const lo32 = src - (hi32 * V2E32);\n return { hi32, lo32 };\n}\n/* Reconstruct Number from quotient and non-negative remainder */\nfunction roundedInt64(hi32, lo32) {\n return hi32 * V2E32 + lo32;\n}\n/**\n * Represent an unsigned 64-bit integer in little-endian format when\n * encoded and as a near integral JavaScript Number when decoded.\n *\n * *Factory*: {@link module:Layout.nu64|nu64}\n *\n * **NOTE** Values with magnitude greater than 2^52 may not decode to\n * the exact value of the encoded representation.\n *\n * @augments {Layout}\n */\nclass NearUInt64 extends Layout {\n constructor(property) {\n super(8, property);\n }\n /** @override */\n decode(b, offset = 0) {\n const buffer = uint8ArrayToBuffer(b);\n const lo32 = buffer.readUInt32LE(offset);\n const hi32 = buffer.readUInt32LE(offset + 4);\n return roundedInt64(hi32, lo32);\n }\n /** @override */\n encode(src, b, offset = 0) {\n const split = divmodInt64(src);\n const buffer = uint8ArrayToBuffer(b);\n buffer.writeUInt32LE(split.lo32, offset);\n buffer.writeUInt32LE(split.hi32, offset + 4);\n return 8;\n }\n}\nexports.NearUInt64 = NearUInt64;\n/**\n * Represent an unsigned 64-bit integer in big-endian format when\n * encoded and as a near integral JavaScript Number when decoded.\n *\n * *Factory*: {@link module:Layout.nu64be|nu64be}\n *\n * **NOTE** Values with magnitude greater than 2^52 may not decode to\n * the exact value of the encoded representation.\n *\n * @augments {Layout}\n */\nclass NearUInt64BE extends Layout {\n constructor(property) {\n super(8, property);\n }\n /** @override */\n decode(b, offset = 0) {\n const buffer = uint8ArrayToBuffer(b);\n const hi32 = buffer.readUInt32BE(offset);\n const lo32 = buffer.readUInt32BE(offset + 4);\n return roundedInt64(hi32, lo32);\n }\n /** @override */\n encode(src, b, offset = 0) {\n const split = divmodInt64(src);\n const buffer = uint8ArrayToBuffer(b);\n buffer.writeUInt32BE(split.hi32, offset);\n buffer.writeUInt32BE(split.lo32, offset + 4);\n return 8;\n }\n}\nexports.NearUInt64BE = NearUInt64BE;\n/**\n * Represent a signed 64-bit integer in little-endian format when\n * encoded and as a near integral JavaScript Number when decoded.\n *\n * *Factory*: {@link module:Layout.ns64|ns64}\n *\n * **NOTE** Values with magnitude greater than 2^52 may not decode to\n * the exact value of the encoded representation.\n *\n * @augments {Layout}\n */\nclass NearInt64 extends Layout {\n constructor(property) {\n super(8, property);\n }\n /** @override */\n decode(b, offset = 0) {\n const buffer = uint8ArrayToBuffer(b);\n const lo32 = buffer.readUInt32LE(offset);\n const hi32 = buffer.readInt32LE(offset + 4);\n return roundedInt64(hi32, lo32);\n }\n /** @override */\n encode(src, b, offset = 0) {\n const split = divmodInt64(src);\n const buffer = uint8ArrayToBuffer(b);\n buffer.writeUInt32LE(split.lo32, offset);\n buffer.writeInt32LE(split.hi32, offset + 4);\n return 8;\n }\n}\nexports.NearInt64 = NearInt64;\n/**\n * Represent a signed 64-bit integer in big-endian format when\n * encoded and as a near integral JavaScript Number when decoded.\n *\n * *Factory*: {@link module:Layout.ns64be|ns64be}\n *\n * **NOTE** Values with magnitude greater than 2^52 may not decode to\n * the exact value of the encoded representation.\n *\n * @augments {Layout}\n */\nclass NearInt64BE extends Layout {\n constructor(property) {\n super(8, property);\n }\n /** @override */\n decode(b, offset = 0) {\n const buffer = uint8ArrayToBuffer(b);\n const hi32 = buffer.readInt32BE(offset);\n const lo32 = buffer.readUInt32BE(offset + 4);\n return roundedInt64(hi32, lo32);\n }\n /** @override */\n encode(src, b, offset = 0) {\n const split = divmodInt64(src);\n const buffer = uint8ArrayToBuffer(b);\n buffer.writeInt32BE(split.hi32, offset);\n buffer.writeUInt32BE(split.lo32, offset + 4);\n return 8;\n }\n}\nexports.NearInt64BE = NearInt64BE;\n/**\n * Represent a 32-bit floating point number in little-endian format.\n *\n * *Factory*: {@link module:Layout.f32|f32}\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Float extends Layout {\n constructor(property) {\n super(4, property);\n }\n /** @override */\n decode(b, offset = 0) {\n return uint8ArrayToBuffer(b).readFloatLE(offset);\n }\n /** @override */\n encode(src, b, offset = 0) {\n uint8ArrayToBuffer(b).writeFloatLE(src, offset);\n return 4;\n }\n}\nexports.Float = Float;\n/**\n * Represent a 32-bit floating point number in big-endian format.\n *\n * *Factory*: {@link module:Layout.f32be|f32be}\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass FloatBE extends Layout {\n constructor(property) {\n super(4, property);\n }\n /** @override */\n decode(b, offset = 0) {\n return uint8ArrayToBuffer(b).readFloatBE(offset);\n }\n /** @override */\n encode(src, b, offset = 0) {\n uint8ArrayToBuffer(b).writeFloatBE(src, offset);\n return 4;\n }\n}\nexports.FloatBE = FloatBE;\n/**\n * Represent a 64-bit floating point number in little-endian format.\n *\n * *Factory*: {@link module:Layout.f64|f64}\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Double extends Layout {\n constructor(property) {\n super(8, property);\n }\n /** @override */\n decode(b, offset = 0) {\n return uint8ArrayToBuffer(b).readDoubleLE(offset);\n }\n /** @override */\n encode(src, b, offset = 0) {\n uint8ArrayToBuffer(b).writeDoubleLE(src, offset);\n return 8;\n }\n}\nexports.Double = Double;\n/**\n * Represent a 64-bit floating point number in big-endian format.\n *\n * *Factory*: {@link module:Layout.f64be|f64be}\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass DoubleBE extends Layout {\n constructor(property) {\n super(8, property);\n }\n /** @override */\n decode(b, offset = 0) {\n return uint8ArrayToBuffer(b).readDoubleBE(offset);\n }\n /** @override */\n encode(src, b, offset = 0) {\n uint8ArrayToBuffer(b).writeDoubleBE(src, offset);\n return 8;\n }\n}\nexports.DoubleBE = DoubleBE;\n/**\n * Represent a contiguous sequence of a specific layout as an Array.\n *\n * *Factory*: {@link module:Layout.seq|seq}\n *\n * @param {Layout} elementLayout - initializer for {@link\n * Sequence#elementLayout|elementLayout}.\n *\n * @param {(Number|ExternalLayout)} count - initializer for {@link\n * Sequence#count|count}. The parameter must be either a positive\n * integer or an instance of {@link ExternalLayout}.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Sequence extends Layout {\n constructor(elementLayout, count, property) {\n if (!(elementLayout instanceof Layout)) {\n throw new TypeError('elementLayout must be a Layout');\n }\n if (!(((count instanceof ExternalLayout) && count.isCount())\n || (Number.isInteger(count) && (0 <= count)))) {\n throw new TypeError('count must be non-negative integer '\n + 'or an unsigned integer ExternalLayout');\n }\n let span = -1;\n if ((!(count instanceof ExternalLayout))\n && (0 < elementLayout.span)) {\n span = count * elementLayout.span;\n }\n super(span, property);\n /** The layout for individual elements of the sequence. */\n this.elementLayout = elementLayout;\n /** The number of elements in the sequence.\n *\n * This will be either a non-negative integer or an instance of\n * {@link ExternalLayout} for which {@link\n * ExternalLayout#isCount|isCount()} is `true`. */\n this.count = count;\n }\n /** @override */\n getSpan(b, offset = 0) {\n if (0 <= this.span) {\n return this.span;\n }\n let span = 0;\n let count = this.count;\n if (count instanceof ExternalLayout) {\n count = count.decode(b, offset);\n }\n if (0 < this.elementLayout.span) {\n span = count * this.elementLayout.span;\n }\n else {\n let idx = 0;\n while (idx < count) {\n span += this.elementLayout.getSpan(b, offset + span);\n ++idx;\n }\n }\n return span;\n }\n /** @override */\n decode(b, offset = 0) {\n const rv = [];\n let i = 0;\n let count = this.count;\n if (count instanceof ExternalLayout) {\n count = count.decode(b, offset);\n }\n while (i < count) {\n rv.push(this.elementLayout.decode(b, offset));\n offset += this.elementLayout.getSpan(b, offset);\n i += 1;\n }\n return rv;\n }\n /** Implement {@link Layout#encode|encode} for {@link Sequence}.\n *\n * **NOTE** If `src` is shorter than {@link Sequence#count|count} then\n * the unused space in the buffer is left unchanged. If `src` is\n * longer than {@link Sequence#count|count} the unneeded elements are\n * ignored.\n *\n * **NOTE** If {@link Layout#count|count} is an instance of {@link\n * ExternalLayout} then the length of `src` will be encoded as the\n * count after `src` is encoded. */\n encode(src, b, offset = 0) {\n const elo = this.elementLayout;\n const span = src.reduce((span, v) => {\n return span + elo.encode(v, b, offset + span);\n }, 0);\n if (this.count instanceof ExternalLayout) {\n this.count.encode(src.length, b, offset);\n }\n return span;\n }\n}\nexports.Sequence = Sequence;\n/**\n * Represent a contiguous sequence of arbitrary layout elements as an\n * Object.\n *\n * *Factory*: {@link module:Layout.struct|struct}\n *\n * **NOTE** The {@link Layout#span|span} of the structure is variable\n * if any layout in {@link Structure#fields|fields} has a variable\n * span. When {@link Layout#encode|encoding} we must have a value for\n * all variable-length fields, or we wouldn't be able to figure out\n * how much space to use for storage. We can only identify the value\n * for a field when it has a {@link Layout#property|property}. As\n * such, although a structure may contain both unnamed fields and\n * variable-length fields, it cannot contain an unnamed\n * variable-length field.\n *\n * @param {Layout[]} fields - initializer for {@link\n * Structure#fields|fields}. An error is raised if this contains a\n * variable-length field for which a {@link Layout#property|property}\n * is not defined.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @param {Boolean} [decodePrefixes] - initializer for {@link\n * Structure#decodePrefixes|property}.\n *\n * @throws {Error} - if `fields` contains an unnamed variable-length\n * layout.\n *\n * @augments {Layout}\n */\nclass Structure extends Layout {\n constructor(fields, property, decodePrefixes) {\n if (!(Array.isArray(fields)\n && fields.reduce((acc, v) => acc && (v instanceof Layout), true))) {\n throw new TypeError('fields must be array of Layout instances');\n }\n if (('boolean' === typeof property)\n && (undefined === decodePrefixes)) {\n decodePrefixes = property;\n property = undefined;\n }\n /* Verify absence of unnamed variable-length fields. */\n for (const fd of fields) {\n if ((0 > fd.span)\n && (undefined === fd.property)) {\n throw new Error('fields cannot contain unnamed variable-length layout');\n }\n }\n let span = -1;\n try {\n span = fields.reduce((span, fd) => span + fd.getSpan(), 0);\n }\n catch (e) {\n // ignore error\n }\n super(span, property);\n /** The sequence of {@link Layout} values that comprise the\n * structure.\n *\n * The individual elements need not be the same type, and may be\n * either scalar or aggregate layouts. If a member layout leaves\n * its {@link Layout#property|property} undefined the\n * corresponding region of the buffer associated with the element\n * will not be mutated.\n *\n * @type {Layout[]} */\n this.fields = fields;\n /** Control behavior of {@link Layout#decode|decode()} given short\n * buffers.\n *\n * In some situations a structure many be extended with additional\n * fields over time, with older installations providing only a\n * prefix of the full structure. If this property is `true`\n * decoding will accept those buffers and leave subsequent fields\n * undefined, as long as the buffer ends at a field boundary.\n * Defaults to `false`. */\n this.decodePrefixes = !!decodePrefixes;\n }\n /** @override */\n getSpan(b, offset = 0) {\n if (0 <= this.span) {\n return this.span;\n }\n let span = 0;\n try {\n span = this.fields.reduce((span, fd) => {\n const fsp = fd.getSpan(b, offset);\n offset += fsp;\n return span + fsp;\n }, 0);\n }\n catch (e) {\n throw new RangeError('indeterminate span');\n }\n return span;\n }\n /** @override */\n decode(b, offset = 0) {\n checkUint8Array(b);\n const dest = this.makeDestinationObject();\n for (const fd of this.fields) {\n if (undefined !== fd.property) {\n dest[fd.property] = fd.decode(b, offset);\n }\n offset += fd.getSpan(b, offset);\n if (this.decodePrefixes\n && (b.length === offset)) {\n break;\n }\n }\n return dest;\n }\n /** Implement {@link Layout#encode|encode} for {@link Structure}.\n *\n * If `src` is missing a property for a member with a defined {@link\n * Layout#property|property} the corresponding region of the buffer is\n * left unmodified. */\n encode(src, b, offset = 0) {\n const firstOffset = offset;\n let lastOffset = 0;\n let lastWrote = 0;\n for (const fd of this.fields) {\n let span = fd.span;\n lastWrote = (0 < span) ? span : 0;\n if (undefined !== fd.property) {\n const fv = src[fd.property];\n if (undefined !== fv) {\n lastWrote = fd.encode(fv, b, offset);\n if (0 > span) {\n /* Read the as-encoded span, which is not necessarily the\n * same as what we wrote. */\n span = fd.getSpan(b, offset);\n }\n }\n }\n lastOffset = offset;\n offset += span;\n }\n /* Use (lastOffset + lastWrote) instead of offset because the last\n * item may have had a dynamic length and we don't want to include\n * the padding between it and the end of the space reserved for\n * it. */\n return (lastOffset + lastWrote) - firstOffset;\n }\n /** @override */\n fromArray(values) {\n const dest = this.makeDestinationObject();\n for (const fd of this.fields) {\n if ((undefined !== fd.property)\n && (0 < values.length)) {\n dest[fd.property] = values.shift();\n }\n }\n return dest;\n }\n /**\n * Get access to the layout of a given property.\n *\n * @param {String} property - the structure member of interest.\n *\n * @return {Layout} - the layout associated with `property`, or\n * undefined if there is no such property.\n */\n layoutFor(property) {\n if ('string' !== typeof property) {\n throw new TypeError('property must be string');\n }\n for (const fd of this.fields) {\n if (fd.property === property) {\n return fd;\n }\n }\n return undefined;\n }\n /**\n * Get the offset of a structure member.\n *\n * @param {String} property - the structure member of interest.\n *\n * @return {Number} - the offset in bytes to the start of `property`\n * within the structure, or undefined if `property` is not a field\n * within the structure. If the property is a member but follows a\n * variable-length structure member a negative number will be\n * returned.\n */\n offsetOf(property) {\n if ('string' !== typeof property) {\n throw new TypeError('property must be string');\n }\n let offset = 0;\n for (const fd of this.fields) {\n if (fd.property === property) {\n return offset;\n }\n if (0 > fd.span) {\n offset = -1;\n }\n else if (0 <= offset) {\n offset += fd.span;\n }\n }\n return undefined;\n }\n}\nexports.Structure = Structure;\n/**\n * An object that can provide a {@link\n * Union#discriminator|discriminator} API for {@link Union}.\n *\n * **NOTE** This is an abstract base class; you can create instances\n * if it amuses you, but they won't support the {@link\n * UnionDiscriminator#encode|encode} or {@link\n * UnionDiscriminator#decode|decode} functions.\n *\n * @param {string} [property] - Default for {@link\n * UnionDiscriminator#property|property}.\n *\n * @abstract\n */\nclass UnionDiscriminator {\n constructor(property) {\n /** The {@link Layout#property|property} to be used when the\n * discriminator is referenced in isolation (generally when {@link\n * Union#decode|Union decode} cannot delegate to a specific\n * variant). */\n this.property = property;\n }\n /** Analog to {@link Layout#decode|Layout decode} for union discriminators.\n *\n * The implementation of this method need not reference the buffer if\n * variant information is available through other means. */\n decode(b, offset) {\n throw new Error('UnionDiscriminator is abstract');\n }\n /** Analog to {@link Layout#decode|Layout encode} for union discriminators.\n *\n * The implementation of this method need not store the value if\n * variant information is maintained through other means. */\n encode(src, b, offset) {\n throw new Error('UnionDiscriminator is abstract');\n }\n}\nexports.UnionDiscriminator = UnionDiscriminator;\n/**\n * An object that can provide a {@link\n * UnionDiscriminator|discriminator API} for {@link Union} using an\n * unsigned integral {@link Layout} instance located either inside or\n * outside the union.\n *\n * @param {ExternalLayout} layout - initializes {@link\n * UnionLayoutDiscriminator#layout|layout}. Must satisfy {@link\n * ExternalLayout#isCount|isCount()}.\n *\n * @param {string} [property] - Default for {@link\n * UnionDiscriminator#property|property}, superseding the property\n * from `layout`, but defaulting to `variant` if neither `property`\n * nor layout provide a property name.\n *\n * @augments {UnionDiscriminator}\n */\nclass UnionLayoutDiscriminator extends UnionDiscriminator {\n constructor(layout, property) {\n if (!((layout instanceof ExternalLayout)\n && layout.isCount())) {\n throw new TypeError('layout must be an unsigned integer ExternalLayout');\n }\n super(property || layout.property || 'variant');\n /** The {@link ExternalLayout} used to access the discriminator\n * value. */\n this.layout = layout;\n }\n /** Delegate decoding to {@link UnionLayoutDiscriminator#layout|layout}. */\n decode(b, offset) {\n return this.layout.decode(b, offset);\n }\n /** Delegate encoding to {@link UnionLayoutDiscriminator#layout|layout}. */\n encode(src, b, offset) {\n return this.layout.encode(src, b, offset);\n }\n}\nexports.UnionLayoutDiscriminator = UnionLayoutDiscriminator;\n/**\n * Represent any number of span-compatible layouts.\n *\n * *Factory*: {@link module:Layout.union|union}\n *\n * If the union has a {@link Union#defaultLayout|default layout} that\n * layout must have a non-negative {@link Layout#span|span}. The span\n * of a fixed-span union includes its {@link\n * Union#discriminator|discriminator} if the variant is a {@link\n * Union#usesPrefixDiscriminator|prefix of the union}, plus the span\n * of its {@link Union#defaultLayout|default layout}.\n *\n * If the union does not have a default layout then the encoded span\n * of the union depends on the encoded span of its variant (which may\n * be fixed or variable).\n *\n * {@link VariantLayout#layout|Variant layout}s are added through\n * {@link Union#addVariant|addVariant}. If the union has a default\n * layout, the span of the {@link VariantLayout#layout|layout\n * contained by the variant} must not exceed the span of the {@link\n * Union#defaultLayout|default layout} (minus the span of a {@link\n * Union#usesPrefixDiscriminator|prefix disriminator}, if used). The\n * span of the variant will equal the span of the union itself.\n *\n * The variant for a buffer can only be identified from the {@link\n * Union#discriminator|discriminator} {@link\n * UnionDiscriminator#property|property} (in the case of the {@link\n * Union#defaultLayout|default layout}), or by using {@link\n * Union#getVariant|getVariant} and examining the resulting {@link\n * VariantLayout} instance.\n *\n * A variant compatible with a JavaScript object can be identified\n * using {@link Union#getSourceVariant|getSourceVariant}.\n *\n * @param {(UnionDiscriminator|ExternalLayout|Layout)} discr - How to\n * identify the layout used to interpret the union contents. The\n * parameter must be an instance of {@link UnionDiscriminator}, an\n * {@link ExternalLayout} that satisfies {@link\n * ExternalLayout#isCount|isCount()}, or {@link UInt} (or {@link\n * UIntBE}). When a non-external layout element is passed the layout\n * appears at the start of the union. In all cases the (synthesized)\n * {@link UnionDiscriminator} instance is recorded as {@link\n * Union#discriminator|discriminator}.\n *\n * @param {(Layout|null)} defaultLayout - initializer for {@link\n * Union#defaultLayout|defaultLayout}. If absent defaults to `null`.\n * If `null` there is no default layout: the union has data-dependent\n * length and attempts to decode or encode unrecognized variants will\n * throw an exception. A {@link Layout} instance must have a\n * non-negative {@link Layout#span|span}, and if it lacks a {@link\n * Layout#property|property} the {@link\n * Union#defaultLayout|defaultLayout} will be a {@link\n * Layout#replicate|replica} with property `content`.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Union extends Layout {\n constructor(discr, defaultLayout, property) {\n let discriminator;\n if ((discr instanceof UInt)\n || (discr instanceof UIntBE)) {\n discriminator = new UnionLayoutDiscriminator(new OffsetLayout(discr));\n }\n else if ((discr instanceof ExternalLayout)\n && discr.isCount()) {\n discriminator = new UnionLayoutDiscriminator(discr);\n }\n else if (!(discr instanceof UnionDiscriminator)) {\n throw new TypeError('discr must be a UnionDiscriminator '\n + 'or an unsigned integer layout');\n }\n else {\n discriminator = discr;\n }\n if (undefined === defaultLayout) {\n defaultLayout = null;\n }\n if (!((null === defaultLayout)\n || (defaultLayout instanceof Layout))) {\n throw new TypeError('defaultLayout must be null or a Layout');\n }\n if (null !== defaultLayout) {\n if (0 > defaultLayout.span) {\n throw new Error('defaultLayout must have constant span');\n }\n if (undefined === defaultLayout.property) {\n defaultLayout = defaultLayout.replicate('content');\n }\n }\n /* The union span can be estimated only if there's a default\n * layout. The union spans its default layout, plus any prefix\n * variant layout. By construction both layouts, if present, have\n * non-negative span. */\n let span = -1;\n if (defaultLayout) {\n span = defaultLayout.span;\n if ((0 <= span) && ((discr instanceof UInt)\n || (discr instanceof UIntBE))) {\n span += discriminator.layout.span;\n }\n }\n super(span, property);\n /** The interface for the discriminator value in isolation.\n *\n * This a {@link UnionDiscriminator} either passed to the\n * constructor or synthesized from the `discr` constructor\n * argument. {@link\n * Union#usesPrefixDiscriminator|usesPrefixDiscriminator} will be\n * `true` iff the `discr` parameter was a non-offset {@link\n * Layout} instance. */\n this.discriminator = discriminator;\n /** `true` if the {@link Union#discriminator|discriminator} is the\n * first field in the union.\n *\n * If `false` the discriminator is obtained from somewhere\n * else. */\n this.usesPrefixDiscriminator = (discr instanceof UInt)\n || (discr instanceof UIntBE);\n /** The layout for non-discriminator content when the value of the\n * discriminator is not recognized.\n *\n * This is the value passed to the constructor. It is\n * structurally equivalent to the second component of {@link\n * Union#layout|layout} but may have a different property\n * name. */\n this.defaultLayout = defaultLayout;\n /** A registry of allowed variants.\n *\n * The keys are unsigned integers which should be compatible with\n * {@link Union.discriminator|discriminator}. The property value\n * is the corresponding {@link VariantLayout} instances assigned\n * to this union by {@link Union#addVariant|addVariant}.\n *\n * **NOTE** The registry remains mutable so that variants can be\n * {@link Union#addVariant|added} at any time. Users should not\n * manipulate the content of this property. */\n this.registry = {};\n /* Private variable used when invoking getSourceVariant */\n let boundGetSourceVariant = this.defaultGetSourceVariant.bind(this);\n /** Function to infer the variant selected by a source object.\n *\n * Defaults to {@link\n * Union#defaultGetSourceVariant|defaultGetSourceVariant} but may\n * be overridden using {@link\n * Union#configGetSourceVariant|configGetSourceVariant}.\n *\n * @param {Object} src - as with {@link\n * Union#defaultGetSourceVariant|defaultGetSourceVariant}.\n *\n * @returns {(undefined|VariantLayout)} The default variant\n * (`undefined`) or first registered variant that uses a property\n * available in `src`. */\n this.getSourceVariant = function (src) {\n return boundGetSourceVariant(src);\n };\n /** Function to override the implementation of {@link\n * Union#getSourceVariant|getSourceVariant}.\n *\n * Use this if the desired variant cannot be identified using the\n * algorithm of {@link\n * Union#defaultGetSourceVariant|defaultGetSourceVariant}.\n *\n * **NOTE** The provided function will be invoked bound to this\n * Union instance, providing local access to {@link\n * Union#registry|registry}.\n *\n * @param {Function} gsv - a function that follows the API of\n * {@link Union#defaultGetSourceVariant|defaultGetSourceVariant}. */\n this.configGetSourceVariant = function (gsv) {\n boundGetSourceVariant = gsv.bind(this);\n };\n }\n /** @override */\n getSpan(b, offset = 0) {\n if (0 <= this.span) {\n return this.span;\n }\n /* Default layouts always have non-negative span, so we don't have\n * one and we have to recognize the variant which will in turn\n * determine the span. */\n const vlo = this.getVariant(b, offset);\n if (!vlo) {\n throw new Error('unable to determine span for unrecognized variant');\n }\n return vlo.getSpan(b, offset);\n }\n /**\n * Method to infer a registered Union variant compatible with `src`.\n *\n * The first satisfied rule in the following sequence defines the\n * return value:\n * * If `src` has properties matching the Union discriminator and\n * the default layout, `undefined` is returned regardless of the\n * value of the discriminator property (this ensures the default\n * layout will be used);\n * * If `src` has a property matching the Union discriminator, the\n * value of the discriminator identifies a registered variant, and\n * either (a) the variant has no layout, or (b) `src` has the\n * variant's property, then the variant is returned (because the\n * source satisfies the constraints of the variant it identifies);\n * * If `src` does not have a property matching the Union\n * discriminator, but does have a property matching a registered\n * variant, then the variant is returned (because the source\n * matches a variant without an explicit conflict);\n * * An error is thrown (because we either can't identify a variant,\n * or we were explicitly told the variant but can't satisfy it).\n *\n * @param {Object} src - an object presumed to be compatible with\n * the content of the Union.\n *\n * @return {(undefined|VariantLayout)} - as described above.\n *\n * @throws {Error} - if `src` cannot be associated with a default or\n * registered variant.\n */\n defaultGetSourceVariant(src) {\n if (Object.prototype.hasOwnProperty.call(src, this.discriminator.property)) {\n if (this.defaultLayout && this.defaultLayout.property\n && Object.prototype.hasOwnProperty.call(src, this.defaultLayout.property)) {\n return undefined;\n }\n const vlo = this.registry[src[this.discriminator.property]];\n if (vlo\n && ((!vlo.layout)\n || (vlo.property && Object.prototype.hasOwnProperty.call(src, vlo.property)))) {\n return vlo;\n }\n }\n else {\n for (const tag in this.registry) {\n const vlo = this.registry[tag];\n if (vlo.property && Object.prototype.hasOwnProperty.call(src, vlo.property)) {\n return vlo;\n }\n }\n }\n throw new Error('unable to infer src variant');\n }\n /** Implement {@link Layout#decode|decode} for {@link Union}.\n *\n * If the variant is {@link Union#addVariant|registered} the return\n * value is an instance of that variant, with no explicit\n * discriminator. Otherwise the {@link Union#defaultLayout|default\n * layout} is used to decode the content. */\n decode(b, offset = 0) {\n let dest;\n const dlo = this.discriminator;\n const discr = dlo.decode(b, offset);\n const clo = this.registry[discr];\n if (undefined === clo) {\n const defaultLayout = this.defaultLayout;\n let contentOffset = 0;\n if (this.usesPrefixDiscriminator) {\n contentOffset = dlo.layout.span;\n }\n dest = this.makeDestinationObject();\n dest[dlo.property] = discr;\n // defaultLayout.property can be undefined, but this is allowed by buffer-layout\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n dest[defaultLayout.property] = defaultLayout.decode(b, offset + contentOffset);\n }\n else {\n dest = clo.decode(b, offset);\n }\n return dest;\n }\n /** Implement {@link Layout#encode|encode} for {@link Union}.\n *\n * This API assumes the `src` object is consistent with the union's\n * {@link Union#defaultLayout|default layout}. To encode variants\n * use the appropriate variant-specific {@link VariantLayout#encode}\n * method. */\n encode(src, b, offset = 0) {\n const vlo = this.getSourceVariant(src);\n if (undefined === vlo) {\n const dlo = this.discriminator;\n // this.defaultLayout is not undefined when vlo is undefined\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const clo = this.defaultLayout;\n let contentOffset = 0;\n if (this.usesPrefixDiscriminator) {\n contentOffset = dlo.layout.span;\n }\n dlo.encode(src[dlo.property], b, offset);\n // clo.property is not undefined when vlo is undefined\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return contentOffset + clo.encode(src[clo.property], b, offset + contentOffset);\n }\n return vlo.encode(src, b, offset);\n }\n /** Register a new variant structure within a union. The newly\n * created variant is returned.\n *\n * @param {Number} variant - initializer for {@link\n * VariantLayout#variant|variant}.\n *\n * @param {Layout} layout - initializer for {@link\n * VariantLayout#layout|layout}.\n *\n * @param {String} property - initializer for {@link\n * Layout#property|property}.\n *\n * @return {VariantLayout} */\n addVariant(variant, layout, property) {\n const rv = new VariantLayout(this, variant, layout, property);\n this.registry[variant] = rv;\n return rv;\n }\n /**\n * Get the layout associated with a registered variant.\n *\n * If `vb` does not produce a registered variant the function returns\n * `undefined`.\n *\n * @param {(Number|Uint8Array)} vb - either the variant number, or a\n * buffer from which the discriminator is to be read.\n *\n * @param {Number} offset - offset into `vb` for the start of the\n * union. Used only when `vb` is an instance of {Uint8Array}.\n *\n * @return {({VariantLayout}|undefined)}\n */\n getVariant(vb, offset = 0) {\n let variant;\n if (vb instanceof Uint8Array) {\n variant = this.discriminator.decode(vb, offset);\n }\n else {\n variant = vb;\n }\n return this.registry[variant];\n }\n}\nexports.Union = Union;\n/**\n * Represent a specific variant within a containing union.\n *\n * **NOTE** The {@link Layout#span|span} of the variant may include\n * the span of the {@link Union#discriminator|discriminator} used to\n * identify it, but values read and written using the variant strictly\n * conform to the content of {@link VariantLayout#layout|layout}.\n *\n * **NOTE** User code should not invoke this constructor directly. Use\n * the union {@link Union#addVariant|addVariant} helper method.\n *\n * @param {Union} union - initializer for {@link\n * VariantLayout#union|union}.\n *\n * @param {Number} variant - initializer for {@link\n * VariantLayout#variant|variant}.\n *\n * @param {Layout} [layout] - initializer for {@link\n * VariantLayout#layout|layout}. If absent the variant carries no\n * data.\n *\n * @param {String} [property] - initializer for {@link\n * Layout#property|property}. Unlike many other layouts, variant\n * layouts normally include a property name so they can be identified\n * within their containing {@link Union}. The property identifier may\n * be absent only if `layout` is is absent.\n *\n * @augments {Layout}\n */\nclass VariantLayout extends Layout {\n constructor(union, variant, layout, property) {\n if (!(union instanceof Union)) {\n throw new TypeError('union must be a Union');\n }\n if ((!Number.isInteger(variant)) || (0 > variant)) {\n throw new TypeError('variant must be a (non-negative) integer');\n }\n if (('string' === typeof layout)\n && (undefined === property)) {\n property = layout;\n layout = null;\n }\n if (layout) {\n if (!(layout instanceof Layout)) {\n throw new TypeError('layout must be a Layout');\n }\n if ((null !== union.defaultLayout)\n && (0 <= layout.span)\n && (layout.span > union.defaultLayout.span)) {\n throw new Error('variant span exceeds span of containing union');\n }\n if ('string' !== typeof property) {\n throw new TypeError('variant must have a String property');\n }\n }\n let span = union.span;\n if (0 > union.span) {\n span = layout ? layout.span : 0;\n if ((0 <= span) && union.usesPrefixDiscriminator) {\n span += union.discriminator.layout.span;\n }\n }\n super(span, property);\n /** The {@link Union} to which this variant belongs. */\n this.union = union;\n /** The unsigned integral value identifying this variant within\n * the {@link Union#discriminator|discriminator} of the containing\n * union. */\n this.variant = variant;\n /** The {@link Layout} to be used when reading/writing the\n * non-discriminator part of the {@link\n * VariantLayout#union|union}. If `null` the variant carries no\n * data. */\n this.layout = layout || null;\n }\n /** @override */\n getSpan(b, offset = 0) {\n if (0 <= this.span) {\n /* Will be equal to the containing union span if that is not\n * variable. */\n return this.span;\n }\n let contentOffset = 0;\n if (this.union.usesPrefixDiscriminator) {\n contentOffset = this.union.discriminator.layout.span;\n }\n /* Span is defined solely by the variant (and prefix discriminator) */\n let span = 0;\n if (this.layout) {\n span = this.layout.getSpan(b, offset + contentOffset);\n }\n return contentOffset + span;\n }\n /** @override */\n decode(b, offset = 0) {\n const dest = this.makeDestinationObject();\n if (this !== this.union.getVariant(b, offset)) {\n throw new Error('variant mismatch');\n }\n let contentOffset = 0;\n if (this.union.usesPrefixDiscriminator) {\n contentOffset = this.union.discriminator.layout.span;\n }\n if (this.layout) {\n dest[this.property] = this.layout.decode(b, offset + contentOffset);\n }\n else if (this.property) {\n dest[this.property] = true;\n }\n else if (this.union.usesPrefixDiscriminator) {\n dest[this.union.discriminator.property] = this.variant;\n }\n return dest;\n }\n /** @override */\n encode(src, b, offset = 0) {\n let contentOffset = 0;\n if (this.union.usesPrefixDiscriminator) {\n contentOffset = this.union.discriminator.layout.span;\n }\n if (this.layout\n && (!Object.prototype.hasOwnProperty.call(src, this.property))) {\n throw new TypeError('variant lacks property ' + this.property);\n }\n this.union.discriminator.encode(this.variant, b, offset);\n let span = contentOffset;\n if (this.layout) {\n this.layout.encode(src[this.property], b, offset + contentOffset);\n span += this.layout.getSpan(b, offset + contentOffset);\n if ((0 <= this.union.span)\n && (span > this.union.span)) {\n throw new Error('encoded variant overruns containing union');\n }\n }\n return span;\n }\n /** Delegate {@link Layout#fromArray|fromArray} to {@link\n * VariantLayout#layout|layout}. */\n fromArray(values) {\n if (this.layout) {\n return this.layout.fromArray(values);\n }\n return undefined;\n }\n}\nexports.VariantLayout = VariantLayout;\n/** JavaScript chose to define bitwise operations as operating on\n * signed 32-bit values in 2's complement form, meaning any integer\n * with bit 31 set is going to look negative. For right shifts that's\n * not a problem, because `>>>` is a logical shift, but for every\n * other bitwise operator we have to compensate for possible negative\n * results. */\nfunction fixBitwiseResult(v) {\n if (0 > v) {\n v += 0x100000000;\n }\n return v;\n}\n/**\n * Contain a sequence of bit fields as an unsigned integer.\n *\n * *Factory*: {@link module:Layout.bits|bits}\n *\n * This is a container element; within it there are {@link BitField}\n * instances that provide the extracted properties. The container\n * simply defines the aggregate representation and its bit ordering.\n * The representation is an object containing properties with numeric\n * or {@link Boolean} values.\n *\n * {@link BitField}s are added with the {@link\n * BitStructure#addField|addField} and {@link\n * BitStructure#addBoolean|addBoolean} methods.\n\n * @param {Layout} word - initializer for {@link\n * BitStructure#word|word}. The parameter must be an instance of\n * {@link UInt} (or {@link UIntBE}) that is no more than 4 bytes wide.\n *\n * @param {bool} [msb] - `true` if the bit numbering starts at the\n * most significant bit of the containing word; `false` (default) if\n * it starts at the least significant bit of the containing word. If\n * the parameter at this position is a string and `property` is\n * `undefined` the value of this argument will instead be used as the\n * value of `property`.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass BitStructure extends Layout {\n constructor(word, msb, property) {\n if (!((word instanceof UInt)\n || (word instanceof UIntBE))) {\n throw new TypeError('word must be a UInt or UIntBE layout');\n }\n if (('string' === typeof msb)\n && (undefined === property)) {\n property = msb;\n msb = false;\n }\n if (4 < word.span) {\n throw new RangeError('word cannot exceed 32 bits');\n }\n super(word.span, property);\n /** The layout used for the packed value. {@link BitField}\n * instances are packed sequentially depending on {@link\n * BitStructure#msb|msb}. */\n this.word = word;\n /** Whether the bit sequences are packed starting at the most\n * significant bit growing down (`true`), or the least significant\n * bit growing up (`false`).\n *\n * **NOTE** Regardless of this value, the least significant bit of\n * any {@link BitField} value is the least significant bit of the\n * corresponding section of the packed value. */\n this.msb = !!msb;\n /** The sequence of {@link BitField} layouts that comprise the\n * packed structure.\n *\n * **NOTE** The array remains mutable to allow fields to be {@link\n * BitStructure#addField|added} after construction. Users should\n * not manipulate the content of this property.*/\n this.fields = [];\n /* Storage for the value. Capture a variable instead of using an\n * instance property because we don't want anything to change the\n * value without going through the mutator. */\n let value = 0;\n this._packedSetValue = function (v) {\n value = fixBitwiseResult(v);\n return this;\n };\n this._packedGetValue = function () {\n return value;\n };\n }\n /** @override */\n decode(b, offset = 0) {\n const dest = this.makeDestinationObject();\n const value = this.word.decode(b, offset);\n this._packedSetValue(value);\n for (const fd of this.fields) {\n if (undefined !== fd.property) {\n dest[fd.property] = fd.decode(b);\n }\n }\n return dest;\n }\n /** Implement {@link Layout#encode|encode} for {@link BitStructure}.\n *\n * If `src` is missing a property for a member with a defined {@link\n * Layout#property|property} the corresponding region of the packed\n * value is left unmodified. Unused bits are also left unmodified. */\n encode(src, b, offset = 0) {\n const value = this.word.decode(b, offset);\n this._packedSetValue(value);\n for (const fd of this.fields) {\n if (undefined !== fd.property) {\n const fv = src[fd.property];\n if (undefined !== fv) {\n fd.encode(fv);\n }\n }\n }\n return this.word.encode(this._packedGetValue(), b, offset);\n }\n /** Register a new bitfield with a containing bit structure. The\n * resulting bitfield is returned.\n *\n * @param {Number} bits - initializer for {@link BitField#bits|bits}.\n *\n * @param {string} property - initializer for {@link\n * Layout#property|property}.\n *\n * @return {BitField} */\n addField(bits, property) {\n const bf = new BitField(this, bits, property);\n this.fields.push(bf);\n return bf;\n }\n /** As with {@link BitStructure#addField|addField} for single-bit\n * fields with `boolean` value representation.\n *\n * @param {string} property - initializer for {@link\n * Layout#property|property}.\n *\n * @return {Boolean} */\n // `Boolean` conflicts with the native primitive type\n // eslint-disable-next-line @typescript-eslint/ban-types\n addBoolean(property) {\n // This is my Boolean, not the Javascript one.\n const bf = new Boolean(this, property);\n this.fields.push(bf);\n return bf;\n }\n /**\n * Get access to the bit field for a given property.\n *\n * @param {String} property - the bit field of interest.\n *\n * @return {BitField} - the field associated with `property`, or\n * undefined if there is no such property.\n */\n fieldFor(property) {\n if ('string' !== typeof property) {\n throw new TypeError('property must be string');\n }\n for (const fd of this.fields) {\n if (fd.property === property) {\n return fd;\n }\n }\n return undefined;\n }\n}\nexports.BitStructure = BitStructure;\n/**\n * Represent a sequence of bits within a {@link BitStructure}.\n *\n * All bit field values are represented as unsigned integers.\n *\n * **NOTE** User code should not invoke this constructor directly.\n * Use the container {@link BitStructure#addField|addField} helper\n * method.\n *\n * **NOTE** BitField instances are not instances of {@link Layout}\n * since {@link Layout#span|span} measures 8-bit units.\n *\n * @param {BitStructure} container - initializer for {@link\n * BitField#container|container}.\n *\n * @param {Number} bits - initializer for {@link BitField#bits|bits}.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n */\nclass BitField {\n constructor(container, bits, property) {\n if (!(container instanceof BitStructure)) {\n throw new TypeError('container must be a BitStructure');\n }\n if ((!Number.isInteger(bits)) || (0 >= bits)) {\n throw new TypeError('bits must be positive integer');\n }\n const totalBits = 8 * container.span;\n const usedBits = container.fields.reduce((sum, fd) => sum + fd.bits, 0);\n if ((bits + usedBits) > totalBits) {\n throw new Error('bits too long for span remainder ('\n + (totalBits - usedBits) + ' of '\n + totalBits + ' remain)');\n }\n /** The {@link BitStructure} instance to which this bit field\n * belongs. */\n this.container = container;\n /** The span of this value in bits. */\n this.bits = bits;\n /** A mask of {@link BitField#bits|bits} bits isolating value bits\n * that fit within the field.\n *\n * That is, it masks a value that has not yet been shifted into\n * position within its containing packed integer. */\n this.valueMask = (1 << bits) - 1;\n if (32 === bits) { // shifted value out of range\n this.valueMask = 0xFFFFFFFF;\n }\n /** The offset of the value within the containing packed unsigned\n * integer. The least significant bit of the packed value is at\n * offset zero, regardless of bit ordering used. */\n this.start = usedBits;\n if (this.container.msb) {\n this.start = totalBits - usedBits - bits;\n }\n /** A mask of {@link BitField#bits|bits} isolating the field value\n * within the containing packed unsigned integer. */\n this.wordMask = fixBitwiseResult(this.valueMask << this.start);\n /** The property name used when this bitfield is represented in an\n * Object.\n *\n * Intended to be functionally equivalent to {@link\n * Layout#property}.\n *\n * If left undefined the corresponding span of bits will be\n * treated as padding: it will not be mutated by {@link\n * Layout#encode|encode} nor represented as a property in the\n * decoded Object. */\n this.property = property;\n }\n /** Store a value into the corresponding subsequence of the containing\n * bit field. */\n decode(b, offset) {\n const word = this.container._packedGetValue();\n const wordValue = fixBitwiseResult(word & this.wordMask);\n const value = wordValue >>> this.start;\n return value;\n }\n /** Store a value into the corresponding subsequence of the containing\n * bit field.\n *\n * **NOTE** This is not a specialization of {@link\n * Layout#encode|Layout.encode} and there is no return value. */\n encode(value) {\n if ('number' !== typeof value\n || !Number.isInteger(value)\n || (value !== fixBitwiseResult(value & this.valueMask))) {\n throw new TypeError(nameWithProperty('BitField.encode', this)\n + ' value must be integer not exceeding ' + this.valueMask);\n }\n const word = this.container._packedGetValue();\n const wordValue = fixBitwiseResult(value << this.start);\n this.container._packedSetValue(fixBitwiseResult(word & ~this.wordMask)\n | wordValue);\n }\n}\nexports.BitField = BitField;\n/**\n * Represent a single bit within a {@link BitStructure} as a\n * JavaScript boolean.\n *\n * **NOTE** User code should not invoke this constructor directly.\n * Use the container {@link BitStructure#addBoolean|addBoolean} helper\n * method.\n *\n * @param {BitStructure} container - initializer for {@link\n * BitField#container|container}.\n *\n * @param {string} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {BitField}\n */\n/* eslint-disable no-extend-native */\nclass Boolean extends BitField {\n constructor(container, property) {\n super(container, 1, property);\n }\n /** Override {@link BitField#decode|decode} for {@link Boolean|Boolean}.\n *\n * @returns {boolean} */\n decode(b, offset) {\n return !!super.decode(b, offset);\n }\n /** @override */\n encode(value) {\n if ('boolean' === typeof value) {\n // BitField requires integer values\n value = +value;\n }\n super.encode(value);\n }\n}\nexports.Boolean = Boolean;\n/* eslint-enable no-extend-native */\n/**\n * Contain a fixed-length block of arbitrary data, represented as a\n * Uint8Array.\n *\n * *Factory*: {@link module:Layout.blob|blob}\n *\n * @param {(Number|ExternalLayout)} length - initializes {@link\n * Blob#length|length}.\n *\n * @param {String} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Blob extends Layout {\n constructor(length, property) {\n if (!(((length instanceof ExternalLayout) && length.isCount())\n || (Number.isInteger(length) && (0 <= length)))) {\n throw new TypeError('length must be positive integer '\n + 'or an unsigned integer ExternalLayout');\n }\n let span = -1;\n if (!(length instanceof ExternalLayout)) {\n span = length;\n }\n super(span, property);\n /** The number of bytes in the blob.\n *\n * This may be a non-negative integer, or an instance of {@link\n * ExternalLayout} that satisfies {@link\n * ExternalLayout#isCount|isCount()}. */\n this.length = length;\n }\n /** @override */\n getSpan(b, offset) {\n let span = this.span;\n if (0 > span) {\n span = this.length.decode(b, offset);\n }\n return span;\n }\n /** @override */\n decode(b, offset = 0) {\n let span = this.span;\n if (0 > span) {\n span = this.length.decode(b, offset);\n }\n return uint8ArrayToBuffer(b).slice(offset, offset + span);\n }\n /** Implement {@link Layout#encode|encode} for {@link Blob}.\n *\n * **NOTE** If {@link Layout#count|count} is an instance of {@link\n * ExternalLayout} then the length of `src` will be encoded as the\n * count after `src` is encoded. */\n encode(src, b, offset) {\n let span = this.length;\n if (this.length instanceof ExternalLayout) {\n span = src.length;\n }\n if (!(src instanceof Uint8Array && span === src.length)) {\n throw new TypeError(nameWithProperty('Blob.encode', this)\n + ' requires (length ' + span + ') Uint8Array as src');\n }\n if ((offset + span) > b.length) {\n throw new RangeError('encoding overruns Uint8Array');\n }\n const srcBuffer = uint8ArrayToBuffer(src);\n uint8ArrayToBuffer(b).write(srcBuffer.toString('hex'), offset, span, 'hex');\n if (this.length instanceof ExternalLayout) {\n this.length.encode(span, b, offset);\n }\n return span;\n }\n}\nexports.Blob = Blob;\n/**\n * Contain a `NUL`-terminated UTF8 string.\n *\n * *Factory*: {@link module:Layout.cstr|cstr}\n *\n * **NOTE** Any UTF8 string that incorporates a zero-valued byte will\n * not be correctly decoded by this layout.\n *\n * @param {String} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass CString extends Layout {\n constructor(property) {\n super(-1, property);\n }\n /** @override */\n getSpan(b, offset = 0) {\n checkUint8Array(b);\n let idx = offset;\n while ((idx < b.length) && (0 !== b[idx])) {\n idx += 1;\n }\n return 1 + idx - offset;\n }\n /** @override */\n decode(b, offset = 0) {\n const span = this.getSpan(b, offset);\n return uint8ArrayToBuffer(b).slice(offset, offset + span - 1).toString('utf-8');\n }\n /** @override */\n encode(src, b, offset = 0) {\n /* Must force this to a string, lest it be a number and the\n * \"utf8-encoding\" below actually allocate a buffer of length\n * src */\n if ('string' !== typeof src) {\n src = String(src);\n }\n const srcb = buffer_1.Buffer.from(src, 'utf8');\n const span = srcb.length;\n if ((offset + span) > b.length) {\n throw new RangeError('encoding overruns Buffer');\n }\n const buffer = uint8ArrayToBuffer(b);\n srcb.copy(buffer, offset);\n buffer[offset + span] = 0;\n return span + 1;\n }\n}\nexports.CString = CString;\n/**\n * Contain a UTF8 string with implicit length.\n *\n * *Factory*: {@link module:Layout.utf8|utf8}\n *\n * **NOTE** Because the length is implicit in the size of the buffer\n * this layout should be used only in isolation, or in a situation\n * where the length can be expressed by operating on a slice of the\n * containing buffer.\n *\n * @param {Number} [maxSpan] - the maximum length allowed for encoded\n * string content. If not provided there is no bound on the allowed\n * content.\n *\n * @param {String} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass UTF8 extends Layout {\n constructor(maxSpan, property) {\n if (('string' === typeof maxSpan) && (undefined === property)) {\n property = maxSpan;\n maxSpan = undefined;\n }\n if (undefined === maxSpan) {\n maxSpan = -1;\n }\n else if (!Number.isInteger(maxSpan)) {\n throw new TypeError('maxSpan must be an integer');\n }\n super(-1, property);\n /** The maximum span of the layout in bytes.\n *\n * Positive values are generally expected. Zero is abnormal.\n * Attempts to encode or decode a value that exceeds this length\n * will throw a `RangeError`.\n *\n * A negative value indicates that there is no bound on the length\n * of the content. */\n this.maxSpan = maxSpan;\n }\n /** @override */\n getSpan(b, offset = 0) {\n checkUint8Array(b);\n return b.length - offset;\n }\n /** @override */\n decode(b, offset = 0) {\n const span = this.getSpan(b, offset);\n if ((0 <= this.maxSpan)\n && (this.maxSpan < span)) {\n throw new RangeError('text length exceeds maxSpan');\n }\n return uint8ArrayToBuffer(b).slice(offset, offset + span).toString('utf-8');\n }\n /** @override */\n encode(src, b, offset = 0) {\n /* Must force this to a string, lest it be a number and the\n * \"utf8-encoding\" below actually allocate a buffer of length\n * src */\n if ('string' !== typeof src) {\n src = String(src);\n }\n const srcb = buffer_1.Buffer.from(src, 'utf8');\n const span = srcb.length;\n if ((0 <= this.maxSpan)\n && (this.maxSpan < span)) {\n throw new RangeError('text length exceeds maxSpan');\n }\n if ((offset + span) > b.length) {\n throw new RangeError('encoding overruns Buffer');\n }\n srcb.copy(uint8ArrayToBuffer(b), offset);\n return span;\n }\n}\nexports.UTF8 = UTF8;\n/**\n * Contain a constant value.\n *\n * This layout may be used in cases where a JavaScript value can be\n * inferred without an expression in the binary encoding. An example\n * would be a {@link VariantLayout|variant layout} where the content\n * is implied by the union {@link Union#discriminator|discriminator}.\n *\n * @param {Object|Number|String} value - initializer for {@link\n * Constant#value|value}. If the value is an object (or array) and\n * the application intends the object to remain unchanged regardless\n * of what is done to values decoded by this layout, the value should\n * be frozen prior passing it to this constructor.\n *\n * @param {String} [property] - initializer for {@link\n * Layout#property|property}.\n *\n * @augments {Layout}\n */\nclass Constant extends Layout {\n constructor(value, property) {\n super(0, property);\n /** The value produced by this constant when the layout is {@link\n * Constant#decode|decoded}.\n *\n * Any JavaScript value including `null` and `undefined` is\n * permitted.\n *\n * **WARNING** If `value` passed in the constructor was not\n * frozen, it is possible for users of decoded values to change\n * the content of the value. */\n this.value = value;\n }\n /** @override */\n decode(b, offset) {\n return this.value;\n }\n /** @override */\n encode(src, b, offset) {\n /* Constants take no space */\n return 0;\n }\n}\nexports.Constant = Constant;\n/** Factory for {@link GreedyCount}. */\nexports.greedy = ((elementSpan, property) => new GreedyCount(elementSpan, property));\n/** Factory for {@link OffsetLayout}. */\nexports.offset = ((layout, offset, property) => new OffsetLayout(layout, offset, property));\n/** Factory for {@link UInt|unsigned int layouts} spanning one\n * byte. */\nexports.u8 = ((property) => new UInt(1, property));\n/** Factory for {@link UInt|little-endian unsigned int layouts}\n * spanning two bytes. */\nexports.u16 = ((property) => new UInt(2, property));\n/** Factory for {@link UInt|little-endian unsigned int layouts}\n * spanning three bytes. */\nexports.u24 = ((property) => new UInt(3, property));\n/** Factory for {@link UInt|little-endian unsigned int layouts}\n * spanning four bytes. */\nexports.u32 = ((property) => new UInt(4, property));\n/** Factory for {@link UInt|little-endian unsigned int layouts}\n * spanning five bytes. */\nexports.u40 = ((property) => new UInt(5, property));\n/** Factory for {@link UInt|little-endian unsigned int layouts}\n * spanning six bytes. */\nexports.u48 = ((property) => new UInt(6, property));\n/** Factory for {@link NearUInt64|little-endian unsigned int\n * layouts} interpreted as Numbers. */\nexports.nu64 = ((property) => new NearUInt64(property));\n/** Factory for {@link UInt|big-endian unsigned int layouts}\n * spanning two bytes. */\nexports.u16be = ((property) => new UIntBE(2, property));\n/** Factory for {@link UInt|big-endian unsigned int layouts}\n * spanning three bytes. */\nexports.u24be = ((property) => new UIntBE(3, property));\n/** Factory for {@link UInt|big-endian unsigned int layouts}\n * spanning four bytes. */\nexports.u32be = ((property) => new UIntBE(4, property));\n/** Factory for {@link UInt|big-endian unsigned int layouts}\n * spanning five bytes. */\nexports.u40be = ((property) => new UIntBE(5, property));\n/** Factory for {@link UInt|big-endian unsigned int layouts}\n * spanning six bytes. */\nexports.u48be = ((property) => new UIntBE(6, property));\n/** Factory for {@link NearUInt64BE|big-endian unsigned int\n * layouts} interpreted as Numbers. */\nexports.nu64be = ((property) => new NearUInt64BE(property));\n/** Factory for {@link Int|signed int layouts} spanning one\n * byte. */\nexports.s8 = ((property) => new Int(1, property));\n/** Factory for {@link Int|little-endian signed int layouts}\n * spanning two bytes. */\nexports.s16 = ((property) => new Int(2, property));\n/** Factory for {@link Int|little-endian signed int layouts}\n * spanning three bytes. */\nexports.s24 = ((property) => new Int(3, property));\n/** Factory for {@link Int|little-endian signed int layouts}\n * spanning four bytes. */\nexports.s32 = ((property) => new Int(4, property));\n/** Factory for {@link Int|little-endian signed int layouts}\n * spanning five bytes. */\nexports.s40 = ((property) => new Int(5, property));\n/** Factory for {@link Int|little-endian signed int layouts}\n * spanning six bytes. */\nexports.s48 = ((property) => new Int(6, property));\n/** Factory for {@link NearInt64|little-endian signed int layouts}\n * interpreted as Numbers. */\nexports.ns64 = ((property) => new NearInt64(property));\n/** Factory for {@link Int|big-endian signed int layouts}\n * spanning two bytes. */\nexports.s16be = ((property) => new IntBE(2, property));\n/** Factory for {@link Int|big-endian signed int layouts}\n * spanning three bytes. */\nexports.s24be = ((property) => new IntBE(3, property));\n/** Factory for {@link Int|big-endian signed int layouts}\n * spanning four bytes. */\nexports.s32be = ((property) => new IntBE(4, property));\n/** Factory for {@link Int|big-endian signed int layouts}\n * spanning five bytes. */\nexports.s40be = ((property) => new IntBE(5, property));\n/** Factory for {@link Int|big-endian signed int layouts}\n * spanning six bytes. */\nexports.s48be = ((property) => new IntBE(6, property));\n/** Factory for {@link NearInt64BE|big-endian signed int layouts}\n * interpreted as Numbers. */\nexports.ns64be = ((property) => new NearInt64BE(property));\n/** Factory for {@link Float|little-endian 32-bit floating point} values. */\nexports.f32 = ((property) => new Float(property));\n/** Factory for {@link FloatBE|big-endian 32-bit floating point} values. */\nexports.f32be = ((property) => new FloatBE(property));\n/** Factory for {@link Double|little-endian 64-bit floating point} values. */\nexports.f64 = ((property) => new Double(property));\n/** Factory for {@link DoubleBE|big-endian 64-bit floating point} values. */\nexports.f64be = ((property) => new DoubleBE(property));\n/** Factory for {@link Structure} values. */\nexports.struct = ((fields, property, decodePrefixes) => new Structure(fields, property, decodePrefixes));\n/** Factory for {@link BitStructure} values. */\nexports.bits = ((word, msb, property) => new BitStructure(word, msb, property));\n/** Factory for {@link Sequence} values. */\nexports.seq = ((elementLayout, count, property) => new Sequence(elementLayout, count, property));\n/** Factory for {@link Union} values. */\nexports.union = ((discr, defaultLayout, property) => new Union(discr, defaultLayout, property));\n/** Factory for {@link UnionLayoutDiscriminator} values. */\nexports.unionLayoutDiscriminator = ((layout, property) => new UnionLayoutDiscriminator(layout, property));\n/** Factory for {@link Blob} values. */\nexports.blob = ((length, property) => new Blob(length, property));\n/** Factory for {@link CString} values. */\nexports.cstr = ((property) => new CString(property));\n/** Factory for {@link UTF8} values. */\nexports.utf8 = ((maxSpan, property) => new UTF8(maxSpan, property));\n/** Factory for {@link Constant} values. */\nexports.constant = ((value, property) => new Constant(value, property));\n//# sourceMappingURL=Layout.js.map","export const encodeDecode = (layout) => {\n const decode = layout.decode.bind(layout);\n const encode = layout.encode.bind(layout);\n return { decode, encode };\n};\n//# sourceMappingURL=base.js.map","import { MINT_SIZE, MintLayout } from '@solana/spl-token';\nimport { PublicKey } from '@solana/web3.js';\nimport { Buffer } from 'buffer';\nimport { struct, u8, u32 } from '@solana/buffer-layout';\nimport { publicKey } from '@solana/buffer-layout-utils';\nimport {\n struct as borshStruct,\n option,\n vec,\n vecU8,\n publicKey as borshPublicKey,\n} from '@coral-xyz/borsh';\n\n/**\n * SPL-compatible base mint structure\n */\nexport interface BaseMint {\n /** Optional authority used to mint new tokens */\n mintAuthority: PublicKey | null;\n /** Total supply of tokens */\n supply: bigint;\n /** Number of base 10 digits to the right of the decimal place */\n decimals: number;\n /** Is initialized - for SPL compatibility */\n isInitialized: boolean;\n /** Optional authority to freeze token accounts */\n freezeAuthority: PublicKey | null;\n}\n\n/**\n * Compressed mint context (protocol version, SPL mint reference)\n */\nexport interface MintContext {\n /** Protocol version for upgradability */\n version: number;\n /** Whether the associated SPL mint is initialized */\n splMintInitialized: boolean;\n /** PDA of the associated SPL mint */\n splMint: PublicKey;\n}\n\n/**\n * Raw extension data as stored on-chain\n */\nexport interface MintExtension {\n extensionType: number;\n data: Uint8Array;\n}\n\n/**\n * Parsed token metadata matching on-chain TokenMetadata extension.\n * Fields: updateAuthority, mint, name, symbol, uri, additionalMetadata\n */\nexport interface TokenMetadata {\n /** Authority that can update metadata (None if zero pubkey) */\n updateAuthority?: PublicKey | null;\n /** Associated mint pubkey */\n mint: PublicKey;\n /** Token name */\n name: string;\n /** Token symbol */\n symbol: string;\n /** URI pointing to off-chain metadata JSON */\n uri: string;\n /** Additional key-value metadata pairs */\n additionalMetadata?: { key: string; value: string }[];\n}\n\n/**\n * Borsh layout for TokenMetadata extension data\n * Format: updateAuthority (32) + mint (32) + name + symbol + uri + additional_metadata\n */\nexport const TokenMetadataLayout = borshStruct([\n borshPublicKey('updateAuthority'),\n borshPublicKey('mint'),\n vecU8('name'),\n vecU8('symbol'),\n vecU8('uri'),\n vec(borshStruct([vecU8('key'), vecU8('value')]), 'additionalMetadata'),\n]);\n\n/**\n * Complete compressed mint structure (raw format)\n */\nexport interface CompressedMint {\n base: BaseMint;\n mintContext: MintContext;\n extensions: MintExtension[] | null;\n}\n\n/** MintContext as stored by the program */\nexport interface RawMintContext {\n version: number;\n splMintInitialized: number; // bool as u8\n splMint: PublicKey;\n}\n\n/** Buffer layout for de/serializing MintContext */\nexport const MintContextLayout = struct<RawMintContext>([\n u8('version'),\n u8('splMintInitialized'),\n publicKey('splMint'),\n]);\n\n/** Byte length of MintContext */\nexport const MINT_CONTEXT_SIZE = MintContextLayout.span; // 34 bytes\n\n/**\n * Calculate the byte length of a TokenMetadata extension from buffer.\n * Format: updateAuthority (32) + mint (32) + name (4+len) + symbol (4+len) + uri (4+len) + additional (4 + items)\n */\nfunction getTokenMetadataByteLength(\n buffer: Buffer,\n startOffset: number,\n): number {\n let offset = startOffset;\n\n // updateAuthority: 32 bytes\n offset += 32;\n // mint: 32 bytes\n offset += 32;\n\n // name: Vec<u8>\n const nameLen = buffer.readUInt32LE(offset);\n offset += 4 + nameLen;\n\n // symbol: Vec<u8>\n const symbolLen = buffer.readUInt32LE(offset);\n offset += 4 + symbolLen;\n\n // uri: Vec<u8>\n const uriLen = buffer.readUInt32LE(offset);\n offset += 4 + uriLen;\n\n // additional_metadata: Vec<AdditionalMetadata>\n const additionalCount = buffer.readUInt32LE(offset);\n offset += 4;\n for (let i = 0; i < additionalCount; i++) {\n const keyLen = buffer.readUInt32LE(offset);\n offset += 4 + keyLen;\n const valueLen = buffer.readUInt32LE(offset);\n offset += 4 + valueLen;\n }\n\n return offset - startOffset;\n}\n\n/**\n * Get the byte length of an extension based on its type.\n * Returns the length of the extension data (excluding the 1-byte discriminant).\n */\nfunction getExtensionByteLength(\n extensionType: number,\n buffer: Buffer,\n dataStartOffset: number,\n): number {\n switch (extensionType) {\n case ExtensionType.TokenMetadata:\n return getTokenMetadataByteLength(buffer, dataStartOffset);\n default:\n // For unknown extensions, we can't determine the length\n // Return remaining buffer length as fallback\n return buffer.length - dataStartOffset;\n }\n}\n\n/**\n * Deserialize a compressed mint from buffer\n * Uses SPL's MintLayout for BaseMint and buffer-layout struct for context\n *\n * @param data - The raw account data buffer\n * @returns The deserialized CompressedMint\n */\nexport function deserializeMint(data: Buffer | Uint8Array): CompressedMint {\n const buffer = data instanceof Buffer ? data : Buffer.from(data);\n let offset = 0;\n\n // 1. Decode BaseMint using SPL's MintLayout (82 bytes)\n const rawMint = MintLayout.decode(buffer.slice(offset, offset + MINT_SIZE));\n offset += MINT_SIZE;\n\n // 2. Decode MintContext using our layout (34 bytes)\n const rawContext = MintContextLayout.decode(\n buffer.slice(offset, offset + MINT_CONTEXT_SIZE),\n );\n offset += MINT_CONTEXT_SIZE;\n\n // 3. Parse extensions: Option<Vec<ExtensionStruct>>\n // Borsh format: Option byte + Vec length + (discriminant + variant data) for each\n const hasExtensions = buffer.readUInt8(offset) === 1;\n offset += 1;\n\n let extensions: MintExtension[] | null = null;\n if (hasExtensions) {\n const vecLen = buffer.readUInt32LE(offset);\n offset += 4;\n\n extensions = [];\n for (let i = 0; i < vecLen; i++) {\n const extensionType = buffer.readUInt8(offset);\n offset += 1;\n\n // Calculate extension data length based on type\n const dataLength = getExtensionByteLength(\n extensionType,\n buffer,\n offset,\n );\n const extensionData = buffer.slice(offset, offset + dataLength);\n offset += dataLength;\n\n extensions.push({\n extensionType,\n data: extensionData,\n });\n }\n }\n\n // Convert raw types to our interface with proper null handling\n const baseMint: BaseMint = {\n mintAuthority:\n rawMint.mintAuthorityOption === 1 ? rawMint.mintAuthority : null,\n supply: rawMint.supply,\n decimals: rawMint.decimals,\n isInitialized: rawMint.isInitialized,\n freezeAuthority:\n rawMint.freezeAuthorityOption === 1\n ? rawMint.freezeAuthority\n : null,\n };\n\n const mintContext: MintContext = {\n version: rawContext.version,\n splMintInitialized: rawContext.splMintInitialized !== 0,\n splMint: rawContext.splMint,\n };\n\n const mint: CompressedMint = {\n base: baseMint,\n mintContext,\n extensions,\n };\n\n return mint;\n}\n\n/**\n * Serialize a CompressedMint to buffer\n * Uses SPL's MintLayout for BaseMint, helper functions for context/metadata\n *\n * @param mint - The CompressedMint to serialize\n * @returns The serialized buffer\n */\nexport function serializeMint(mint: CompressedMint): Buffer {\n const buffers: Buffer[] = [];\n\n // 1. Encode BaseMint using SPL's MintLayout (82 bytes)\n const baseMintBuffer = Buffer.alloc(MINT_SIZE);\n MintLayout.encode(\n {\n mintAuthorityOption: mint.base.mintAuthority ? 1 : 0,\n mintAuthority: mint.base.mintAuthority || new PublicKey(0),\n supply: mint.base.supply,\n decimals: mint.base.decimals,\n isInitialized: mint.base.isInitialized,\n freezeAuthorityOption: mint.base.freezeAuthority ? 1 : 0,\n freezeAuthority: mint.base.freezeAuthority || new PublicKey(0),\n },\n baseMintBuffer,\n );\n buffers.push(baseMintBuffer);\n\n // 2. Encode MintContext using our layout (34 bytes)\n const contextBuffer = Buffer.alloc(MINT_CONTEXT_SIZE);\n MintContextLayout.encode(\n {\n version: mint.mintContext.version,\n splMintInitialized: mint.mintContext.splMintInitialized ? 1 : 0,\n splMint: mint.mintContext.splMint,\n },\n contextBuffer,\n );\n buffers.push(contextBuffer);\n\n // 3. Encode extensions: Option<Vec<ExtensionStruct>>\n // Borsh format: Option byte + Vec length + (discriminant + variant data) for each\n // NOTE: No length prefix per extension - Borsh enums are discriminant + data directly\n if (mint.extensions && mint.extensions.length > 0) {\n buffers.push(Buffer.from([1])); // Some\n const vecLenBuf = Buffer.alloc(4);\n vecLenBuf.writeUInt32LE(mint.extensions.length);\n buffers.push(vecLenBuf);\n\n for (const ext of mint.extensions) {\n // Write discriminant (1 byte)\n buffers.push(Buffer.from([ext.extensionType]));\n // Write extension data directly (no length prefix - Borsh format)\n buffers.push(Buffer.from(ext.data));\n }\n } else {\n buffers.push(Buffer.from([0])); // None\n }\n\n return Buffer.concat(buffers);\n}\n\n/**\n * Extension type constants\n */\nexport enum ExtensionType {\n TokenMetadata = 19, // Name, symbol, uri\n // Add more extension types as needed\n}\n\n/**\n * Decode TokenMetadata from raw extension data using Borsh layout\n * Extension format: updateAuthority (32) + mint (32) + name (Vec) + symbol (Vec) + uri (Vec) + additional (Vec)\n */\nexport function decodeTokenMetadata(data: Uint8Array): TokenMetadata | null {\n try {\n const buffer = Buffer.from(data);\n // Minimum size: 32 (updateAuthority) + 32 (mint) + 4 (name len) + 4 (symbol len) + 4 (uri len) + 4 (additional len) = 80\n if (buffer.length < 80) {\n return null;\n }\n\n // Decode using Borsh layout\n const decoded = TokenMetadataLayout.decode(buffer) as {\n updateAuthority: PublicKey;\n mint: PublicKey;\n name: Buffer;\n symbol: Buffer;\n uri: Buffer;\n additionalMetadata: { key: Buffer; value: Buffer }[];\n };\n\n // Convert zero pubkey to undefined for updateAuthority\n const updateAuthorityBytes = decoded.updateAuthority.toBuffer();\n const isZero = updateAuthorityBytes.every((b: number) => b === 0);\n const updateAuthority = isZero ? undefined : decoded.updateAuthority;\n\n // Convert Buffer fields to strings\n const name = Buffer.from(decoded.name).toString('utf-8');\n const symbol = Buffer.from(decoded.symbol).toString('utf-8');\n const uri = Buffer.from(decoded.uri).toString('utf-8');\n\n // Convert additional metadata\n let additionalMetadata: { key: string; value: string }[] | undefined;\n if (\n decoded.additionalMetadata &&\n decoded.additionalMetadata.length > 0\n ) {\n additionalMetadata = decoded.additionalMetadata.map(item => ({\n key: Buffer.from(item.key).toString('utf-8'),\n value: Buffer.from(item.value).toString('utf-8'),\n }));\n }\n\n return {\n updateAuthority,\n mint: decoded.mint,\n name,\n symbol,\n uri,\n additionalMetadata,\n };\n } catch (e) {\n console.error('Failed to decode TokenMetadata:', e);\n return null;\n }\n}\n\n/**\n * Encode TokenMetadata to raw bytes using Borsh layout\n * @param metadata - TokenMetadata to encode\n * @returns Encoded buffer\n */\nexport function encodeTokenMetadata(metadata: TokenMetadata): Buffer {\n const buffer = Buffer.alloc(2000); // Allocate generous buffer\n\n // Use zero pubkey if updateAuthority is not provided\n const updateAuthority = metadata.updateAuthority || new PublicKey(0);\n\n const len = TokenMetadataLayout.encode(\n {\n updateAuthority,\n mint: metadata.mint,\n name: Buffer.from(metadata.name),\n symbol: Buffer.from(metadata.symbol),\n uri: Buffer.from(metadata.uri),\n additionalMetadata: metadata.additionalMetadata\n ? metadata.additionalMetadata.map(item => ({\n key: Buffer.from(item.key),\n value: Buffer.from(item.value),\n }))\n : [],\n },\n buffer,\n );\n return buffer.subarray(0, len);\n}\n\n/**\n * @deprecated Use decodeTokenMetadata instead\n */\nexport const parseTokenMetadata = decodeTokenMetadata;\n\n/**\n * Extract and parse TokenMetadata from extensions array\n * @param extensions - Array of raw extensions\n * @returns Parsed TokenMetadata or null if not found\n */\nexport function extractTokenMetadata(\n extensions: MintExtension[] | null,\n): TokenMetadata | null {\n if (!extensions) return null;\n const metadataExt = extensions.find(\n ext => ext.extensionType === ExtensionType.TokenMetadata,\n );\n return metadataExt ? parseTokenMetadata(metadataExt.data) : null;\n}\n\n/**\n * Metadata portion of MintInstructionData\n * Used for instruction encoding when metadata extension is present\n */\nexport interface MintMetadataField {\n updateAuthority: PublicKey | null;\n name: string;\n symbol: string;\n uri: string;\n}\n\n/**\n * Flattened mint data structure for instruction encoding\n * This is the format expected by mint action instructions\n */\nexport interface MintInstructionData {\n supply: bigint;\n decimals: number;\n mintAuthority: PublicKey | null;\n freezeAuthority: PublicKey | null;\n splMint: PublicKey;\n splMintInitialized: boolean;\n version: number;\n metadata?: MintMetadataField;\n}\n\n/**\n * MintInstructionData with required metadata field\n * Used for metadata update instructions where metadata must be present\n */\nexport interface MintInstructionDataWithMetadata extends MintInstructionData {\n metadata: MintMetadataField;\n}\n\n/**\n * Convert a deserialized CompressedMint to MintInstructionData format\n * This extracts and flattens the data structure for instruction encoding\n *\n * @param compressedMint - Deserialized CompressedMint from account data\n * @returns Flattened MintInstructionData for instruction encoding\n */\nexport function toMintInstructionData(\n compressedMint: CompressedMint,\n): MintInstructionData {\n const { base, mintContext, extensions } = compressedMint;\n\n // Extract metadata from extensions if present\n const tokenMetadata = extractTokenMetadata(extensions);\n const metadata: MintMetadataField | undefined = tokenMetadata\n ? {\n updateAuthority: tokenMetadata.updateAuthority ?? null,\n name: tokenMetadata.name,\n symbol: tokenMetadata.symbol,\n uri: tokenMetadata.uri,\n }\n : undefined;\n\n return {\n supply: base.supply,\n decimals: base.decimals,\n mintAuthority: base.mintAuthority,\n freezeAuthority: base.freezeAuthority,\n splMint: mintContext.splMint,\n splMintInitialized: mintContext.splMintInitialized,\n version: mintContext.version,\n metadata,\n };\n}\n\n/**\n * Convert a deserialized CompressedMint to MintInstructionDataWithMetadata\n * Throws if the mint doesn't have metadata extension\n *\n * @param compressedMint - Deserialized CompressedMint from account data\n * @returns MintInstructionDataWithMetadata for metadata update instructions\n * @throws Error if metadata extension is not present\n */\nexport function toMintInstructionDataWithMetadata(\n compressedMint: CompressedMint,\n): MintInstructionDataWithMetadata {\n const data = toMintInstructionData(compressedMint);\n\n if (!data.metadata) {\n throw new Error('CompressedMint does not have TokenMetadata extension');\n }\n\n return data as MintInstructionDataWithMetadata;\n}\n","import { blob } from '@solana/buffer-layout';\nimport { PublicKey } from '@solana/web3.js';\nimport { encodeDecode } from './base.mjs';\nexport const publicKey = (property) => {\n const layout = blob(32, property);\n const { encode, decode } = encodeDecode(layout);\n const publicKeyLayout = layout;\n publicKeyLayout.decode = (buffer, offset) => {\n const src = decode(buffer, offset);\n return new PublicKey(src);\n };\n publicKeyLayout.encode = (publicKey, buffer, offset) => {\n const src = publicKey.toBuffer();\n return encode(src, buffer, offset);\n };\n return publicKeyLayout;\n};\n//# sourceMappingURL=web3.js.map","import { PublicKey, AccountInfo, Commitment } from '@solana/web3.js';\nimport { Buffer } from 'buffer';\nimport {\n Rpc,\n bn,\n deriveAddressV2,\n CTOKEN_PROGRAM_ID,\n getDefaultAddressTreeInfo,\n MerkleContext,\n} from '@lightprotocol/stateless.js';\nimport {\n Mint,\n getMint as getSplMint,\n unpackMint as unpackSplMint,\n TOKEN_PROGRAM_ID,\n TOKEN_2022_PROGRAM_ID,\n} from '@solana/spl-token';\nimport {\n deserializeMint,\n MintContext,\n TokenMetadata,\n MintExtension,\n extractTokenMetadata,\n} from './layout/layout-mint';\n\nexport interface MintInterface {\n mint: Mint;\n programId: PublicKey;\n merkleContext?: MerkleContext;\n mintContext?: MintContext;\n tokenMetadata?: TokenMetadata;\n extensions?: MintExtension[];\n}\n\n/**\n * Get unified mint info for SPL/T22/c-token mints.\n *\n * @param rpc RPC connection\n * @param address The mint address\n * @param commitment Optional commitment level\n * @param programId Token program ID. If not provided, tries all programs to\n * auto-detect.\n * @returns Object with mint, optional merkleContext, mintContext, and\n * tokenMetadata\n */\nexport async function getMintInterface(\n rpc: Rpc,\n address: PublicKey,\n commitment?: Commitment,\n programId?: PublicKey,\n): Promise<MintInterface> {\n // try all three programs in parallel\n if (!programId) {\n const [tokenResult, token2022Result, compressedResult] =\n await Promise.allSettled([\n getMintInterface(rpc, address, commitment, TOKEN_PROGRAM_ID),\n getMintInterface(\n rpc,\n address,\n commitment,\n TOKEN_2022_PROGRAM_ID,\n ),\n getMintInterface(rpc, address, commitment, CTOKEN_PROGRAM_ID),\n ]);\n\n if (tokenResult.status === 'fulfilled') {\n return tokenResult.value;\n }\n if (token2022Result.status === 'fulfilled') {\n return token2022Result.value;\n }\n if (compressedResult.status === 'fulfilled') {\n return compressedResult.value;\n }\n\n throw new Error(\n `Mint not found: ${address.toString()}. ` +\n `Tried TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, and CTOKEN_PROGRAM_ID.`,\n );\n }\n\n if (programId.equals(CTOKEN_PROGRAM_ID)) {\n const addressTree = getDefaultAddressTreeInfo().tree;\n const compressedAddress = deriveAddressV2(\n address.toBytes(),\n addressTree,\n CTOKEN_PROGRAM_ID,\n );\n const compressedAccount = await rpc.getCompressedAccount(\n bn(compressedAddress.toBytes()),\n );\n\n if (!compressedAccount?.data?.data) {\n throw new Error(\n `Compressed mint not found for ${address.toString()}`,\n );\n }\n\n const compressedMintData = deserializeMint(\n Buffer.from(compressedAccount.data.data),\n );\n\n const mint: Mint = {\n address,\n mintAuthority: compressedMintData.base.mintAuthority,\n supply: compressedMintData.base.supply,\n decimals: compressedMintData.base.decimals,\n isInitialized: compressedMintData.base.isInitialized,\n freezeAuthority: compressedMintData.base.freezeAuthority,\n tlvData: Buffer.alloc(0),\n };\n\n const merkleContext: MerkleContext = {\n treeInfo: compressedAccount.treeInfo,\n hash: compressedAccount.hash,\n leafIndex: compressedAccount.leafIndex,\n proveByIndex: compressedAccount.proveByIndex,\n };\n\n const tokenMetadata = extractTokenMetadata(\n compressedMintData.extensions,\n );\n\n const result: MintInterface = {\n mint,\n programId,\n merkleContext,\n mintContext: compressedMintData.mintContext,\n tokenMetadata: tokenMetadata || undefined,\n extensions: compressedMintData.extensions || undefined,\n };\n\n if (programId.equals(CTOKEN_PROGRAM_ID)) {\n if (!result.merkleContext) {\n throw new Error(\n `Invalid compressed mint: merkleContext is required for CTOKEN_PROGRAM_ID`,\n );\n }\n if (!result.mintContext) {\n throw new Error(\n `Invalid compressed mint: mintContext is required for CTOKEN_PROGRAM_ID`,\n );\n }\n }\n\n return result;\n }\n\n // Otherwise, fetch SPL/T22 mint\n const mint = await getSplMint(rpc, address, commitment, programId);\n return { mint, programId };\n}\n\n/**\n * Unpack mint info from raw account data for SPL/T22/c-token.\n *\n * @param address The mint pubkey\n * @param data The raw account data or AccountInfo\n * @param programId Token program ID. Default c-token.\n * @returns Object with mint, optional mintContext and tokenMetadata.\n */\nexport function unpackMintInterface(\n address: PublicKey,\n data: Buffer | Uint8Array | AccountInfo<Buffer>,\n programId: PublicKey = TOKEN_PROGRAM_ID,\n): Omit<MintInterface, 'merkleContext'> {\n const buffer =\n data instanceof Buffer\n ? data\n : data instanceof Uint8Array\n ? Buffer.from(data)\n : data.data;\n\n // If compressed token program, deserialize as compressed mint\n if (programId.equals(CTOKEN_PROGRAM_ID)) {\n const compressedMintData = deserializeMint(buffer);\n\n const mint: Mint = {\n address,\n mintAuthority: compressedMintData.base.mintAuthority,\n supply: compressedMintData.base.supply,\n decimals: compressedMintData.base.decimals,\n isInitialized: compressedMintData.base.isInitialized,\n freezeAuthority: compressedMintData.base.freezeAuthority,\n tlvData: Buffer.alloc(0),\n };\n\n // Extract and parse TokenMetadata\n const tokenMetadata = extractTokenMetadata(\n compressedMintData.extensions,\n );\n\n const result = {\n mint,\n programId,\n mintContext: compressedMintData.mintContext,\n tokenMetadata: tokenMetadata || undefined,\n extensions: compressedMintData.extensions || undefined,\n };\n\n // Validate: CTOKEN_PROGRAM_ID requires mintContext\n if (programId.equals(CTOKEN_PROGRAM_ID)) {\n if (!result.mintContext) {\n throw new Error(\n `Invalid compressed mint: mintContext is required for CTOKEN_PROGRAM_ID`,\n );\n }\n }\n\n return result;\n }\n\n // Otherwise, unpack as SPL mint\n const info = data as AccountInfo<Buffer>;\n const mint = unpackSplMint(address, info, programId);\n return { mint, programId };\n}\n\n/**\n * Unpack c-token mint context and metadata from raw account data\n *\n * @param data The raw account data\n * @returns Object with mintContext, tokenMetadata, and extensions\n */\nexport function unpackMintData(data: Buffer | Uint8Array): {\n mintContext: MintContext;\n tokenMetadata?: TokenMetadata;\n extensions?: MintExtension[];\n} {\n const buffer = data instanceof Buffer ? data : Buffer.from(data);\n const compressedMint = deserializeMint(buffer);\n const tokenMetadata = extractTokenMetadata(compressedMint.extensions);\n\n return {\n mintContext: compressedMint.mintContext,\n tokenMetadata: tokenMetadata || undefined,\n extensions: compressedMint.extensions || undefined,\n };\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\nimport {\n Rpc,\n buildAndSignTx,\n sendAndConfirmTx,\n DerivationMode,\n bn,\n CTOKEN_PROGRAM_ID,\n} from '@lightprotocol/stateless.js';\nimport {\n createUpdateMintAuthorityInstruction,\n createUpdateFreezeAuthorityInstruction,\n} from '../instructions/update-mint';\nimport { getMintInterface } from '../get-mint-interface';\n\n/**\n * Update the mint authority of a compressed token mint.\n *\n * @param rpc RPC connection\n * @param payer Fee payer (signer)\n * @param mint Mint address\n * @param currentMintAuthority Current mint authority (signer)\n * @param newMintAuthority New mint authority (or null to revoke)\n * @param confirmOptions Optional confirm options\n */\nexport async function updateMintAuthority(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n currentMintAuthority: Signer,\n newMintAuthority: PublicKey | null,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n const mintInterface = await getMintInterface(\n rpc,\n mint,\n confirmOptions?.commitment,\n CTOKEN_PROGRAM_ID,\n );\n\n if (!mintInterface.merkleContext) {\n throw new Error('Mint does not have MerkleContext');\n }\n\n const validityProof = await rpc.getValidityProofV2(\n [\n {\n hash: bn(mintInterface.merkleContext.hash),\n leafIndex: mintInterface.merkleContext.leafIndex,\n treeInfo: mintInterface.merkleContext.treeInfo,\n proveByIndex: mintInterface.merkleContext.proveByIndex,\n },\n ],\n [],\n DerivationMode.compressible,\n );\n\n const ix = createUpdateMintAuthorityInstruction(\n mintInterface,\n currentMintAuthority.publicKey,\n newMintAuthority,\n payer.publicKey,\n validityProof,\n );\n\n const additionalSigners = currentMintAuthority.publicKey.equals(\n payer.publicKey,\n )\n ? []\n : [currentMintAuthority];\n\n const { blockhash } = await rpc.getLatestBlockhash();\n const tx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 500_000 }), ix],\n payer,\n blockhash,\n additionalSigners,\n );\n\n return await sendAndConfirmTx(rpc, tx, confirmOptions);\n}\n\n/**\n * Update the freeze authority of a compressed token mint.\n *\n * @param rpc RPC connection\n * @param payer Fee payer (signer)\n * @param mint Mint address\n * @param currentFreezeAuthority Current freeze authority (signer)\n * @param newFreezeAuthority New freeze authority (or null to revoke)\n * @param confirmOptions Optional confirm options\n */\nexport async function updateFreezeAuthority(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n currentFreezeAuthority: Signer,\n newFreezeAuthority: PublicKey | null,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n const mintInterface = await getMintInterface(\n rpc,\n mint,\n confirmOptions?.commitment,\n CTOKEN_PROGRAM_ID,\n );\n\n if (!mintInterface.merkleContext) {\n throw new Error('Mint does not have MerkleContext');\n }\n\n const validityProof = await rpc.getValidityProofV2(\n [\n {\n hash: bn(mintInterface.merkleContext.hash),\n leafIndex: mintInterface.merkleContext.leafIndex,\n treeInfo: mintInterface.merkleContext.treeInfo,\n proveByIndex: mintInterface.merkleContext.proveByIndex,\n },\n ],\n [],\n DerivationMode.compressible,\n );\n\n const ix = createUpdateFreezeAuthorityInstruction(\n mintInterface,\n currentFreezeAuthority.publicKey,\n newFreezeAuthority,\n payer.publicKey,\n validityProof,\n );\n\n const additionalSigners = currentFreezeAuthority.publicKey.equals(\n payer.publicKey,\n )\n ? []\n : [currentFreezeAuthority];\n\n const { blockhash } = await rpc.getLatestBlockhash();\n const tx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 500_000 }), ix],\n payer,\n blockhash,\n additionalSigners,\n );\n\n return await sendAndConfirmTx(rpc, tx, confirmOptions);\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\nimport {\n Rpc,\n buildAndSignTx,\n sendAndConfirmTx,\n DerivationMode,\n bn,\n CTOKEN_PROGRAM_ID,\n} from '@lightprotocol/stateless.js';\nimport {\n createUpdateMetadataFieldInstruction,\n createUpdateMetadataAuthorityInstruction,\n createRemoveMetadataKeyInstruction,\n} from '../instructions/update-metadata';\nimport { getMintInterface } from '../get-mint-interface';\n\n/**\n * Update a metadata field on a compressed token mint.\n *\n * @param rpc RPC connection\n * @param payer Fee payer (signer)\n * @param mint Mint address\n * @param authority Metadata update authority (signer)\n * @param fieldType Field to update: 'name', 'symbol', 'uri', or 'custom'\n * @param value New value for the field\n * @param customKey Custom key name (required if fieldType is 'custom')\n * @param extensionIndex Extension index (default: 0)\n * @param confirmOptions Optional confirm options\n */\nexport async function updateMetadataField(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n authority: Signer,\n fieldType: 'name' | 'symbol' | 'uri' | 'custom',\n value: string,\n customKey?: string,\n extensionIndex: number = 0,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n const mintInterface = await getMintInterface(\n rpc,\n mint,\n confirmOptions?.commitment,\n CTOKEN_PROGRAM_ID,\n );\n\n if (!mintInterface.tokenMetadata || !mintInterface.merkleContext) {\n throw new Error('Mint does not have TokenMetadata extension');\n }\n\n const validityProof = await rpc.getValidityProofV2(\n [\n {\n hash: bn(mintInterface.merkleContext.hash),\n leafIndex: mintInterface.merkleContext.leafIndex,\n treeInfo: mintInterface.merkleContext.treeInfo,\n proveByIndex: mintInterface.merkleContext.proveByIndex,\n },\n ],\n [],\n DerivationMode.compressible,\n );\n\n const ix = createUpdateMetadataFieldInstruction(\n mintInterface,\n authority.publicKey,\n payer.publicKey,\n validityProof,\n fieldType,\n value,\n customKey,\n extensionIndex,\n );\n\n const additionalSigners = authority.publicKey.equals(payer.publicKey)\n ? []\n : [authority];\n\n const { blockhash } = await rpc.getLatestBlockhash();\n const tx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 500_000 }), ix],\n payer,\n blockhash,\n additionalSigners,\n );\n\n return await sendAndConfirmTx(rpc, tx, confirmOptions);\n}\n\n/**\n * Update the metadata authority of a compressed token mint.\n *\n * @param rpc RPC connection\n * @param payer Fee payer (signer)\n * @param mint Mint address\n * @param currentAuthority Current metadata update authority (signer)\n * @param newAuthority New metadata update authority\n * @param extensionIndex Extension index (default: 0)\n * @param confirmOptions Optional confirm options\n */\nexport async function updateMetadataAuthority(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n currentAuthority: Signer,\n newAuthority: PublicKey,\n extensionIndex: number = 0,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n const mintInterface = await getMintInterface(\n rpc,\n mint,\n confirmOptions?.commitment,\n CTOKEN_PROGRAM_ID,\n );\n\n if (!mintInterface.tokenMetadata || !mintInterface.merkleContext) {\n throw new Error('Mint does not have TokenMetadata extension');\n }\n\n const validityProof = await rpc.getValidityProofV2(\n [\n {\n hash: bn(mintInterface.merkleContext.hash),\n leafIndex: mintInterface.merkleContext.leafIndex,\n treeInfo: mintInterface.merkleContext.treeInfo,\n proveByIndex: mintInterface.merkleContext.proveByIndex,\n },\n ],\n [],\n DerivationMode.compressible,\n );\n\n const ix = createUpdateMetadataAuthorityInstruction(\n mintInterface,\n currentAuthority.publicKey,\n newAuthority,\n payer.publicKey,\n validityProof,\n extensionIndex,\n );\n\n const additionalSigners = currentAuthority.publicKey.equals(payer.publicKey)\n ? []\n : [currentAuthority];\n\n const { blockhash } = await rpc.getLatestBlockhash();\n const tx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 500_000 }), ix],\n payer,\n blockhash,\n additionalSigners,\n );\n\n return await sendAndConfirmTx(rpc, tx, confirmOptions);\n}\n\n/**\n * Remove a metadata key from a compressed token mint.\n *\n * @param rpc RPC connection\n * @param payer Fee payer (signer)\n * @param mint Mint address\n * @param authority Metadata update authority (signer)\n * @param key Metadata key to remove\n * @param idempotent If true, don't error if key doesn't exist (default: false)\n * @param extensionIndex Extension index (default: 0)\n * @param confirmOptions Optional confirm options\n */\nexport async function removeMetadataKey(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n authority: Signer,\n key: string,\n idempotent: boolean = false,\n extensionIndex: number = 0,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n const mintInterface = await getMintInterface(\n rpc,\n mint,\n confirmOptions?.commitment,\n CTOKEN_PROGRAM_ID,\n );\n\n if (!mintInterface.tokenMetadata || !mintInterface.merkleContext) {\n throw new Error('Mint does not have TokenMetadata extension');\n }\n\n const validityProof = await rpc.getValidityProofV2(\n [\n {\n hash: bn(mintInterface.merkleContext.hash),\n leafIndex: mintInterface.merkleContext.leafIndex,\n treeInfo: mintInterface.merkleContext.treeInfo,\n proveByIndex: mintInterface.merkleContext.proveByIndex,\n },\n ],\n [],\n DerivationMode.compressible,\n );\n\n const ix = createRemoveMetadataKeyInstruction(\n mintInterface,\n authority.publicKey,\n payer.publicKey,\n validityProof,\n key,\n idempotent,\n extensionIndex,\n );\n\n const additionalSigners = authority.publicKey.equals(payer.publicKey)\n ? []\n : [authority];\n\n const { blockhash } = await rpc.getLatestBlockhash();\n const tx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 500_000 }), ix],\n payer,\n blockhash,\n additionalSigners,\n );\n\n return await sendAndConfirmTx(rpc, tx, confirmOptions);\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n PublicKey,\n Signer,\n Transaction,\n sendAndConfirmTransaction,\n} from '@solana/web3.js';\nimport {\n Rpc,\n CTOKEN_PROGRAM_ID,\n buildAndSignTx,\n sendAndConfirmTx,\n} from '@lightprotocol/stateless.js';\nimport {\n createAssociatedTokenAccountInterfaceInstruction,\n createAssociatedTokenAccountInterfaceIdempotentInstruction,\n CTokenConfig,\n} from '../instructions/create-ata-interface';\nimport { getAtaProgramId } from '../ata-utils';\nimport { getAssociatedTokenAddressInterface } from '../get-associated-token-address-interface';\n\n// Re-export types for backwards compatibility\nexport type { CTokenConfig };\n\n/**\n * Create an associated token account for SPL/T22/c-token. Defaults to c-token\n * program.\n *\n * @param rpc RPC connection\n * @param payer Fee payer and transaction signer\n * @param mint Mint address\n * @param owner Owner of the associated token account\n * @param allowOwnerOffCurve Allow owner to be a PDA (default: false)\n * @param confirmOptions Options for confirming the transaction\n * @param programId Token program ID (default:\n * CTOKEN_PROGRAM_ID)\n * @param associatedTokenProgramId ATA program ID (auto-derived if not\n * provided)\n * @param ctokenConfig Optional rent config\n * @returns Address of the new associated token account\n */\nexport async function createAtaInterface(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n owner: PublicKey,\n allowOwnerOffCurve = false,\n confirmOptions?: ConfirmOptions,\n programId: PublicKey = CTOKEN_PROGRAM_ID,\n associatedTokenProgramId?: PublicKey,\n ctokenConfig?: CTokenConfig,\n): Promise<PublicKey> {\n const effectiveAtaProgramId =\n associatedTokenProgramId ?? getAtaProgramId(programId);\n\n const associatedToken = getAssociatedTokenAddressInterface(\n mint,\n owner,\n allowOwnerOffCurve,\n programId,\n effectiveAtaProgramId,\n );\n\n const ix = createAssociatedTokenAccountInterfaceInstruction(\n payer.publicKey,\n associatedToken,\n owner,\n mint,\n programId,\n effectiveAtaProgramId,\n ctokenConfig,\n );\n\n if (programId.equals(CTOKEN_PROGRAM_ID)) {\n const { blockhash } = await rpc.getLatestBlockhash();\n const tx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 30_000 }), ix],\n payer,\n blockhash,\n [],\n );\n await sendAndConfirmTx(rpc, tx, confirmOptions);\n } else {\n const transaction = new Transaction().add(ix);\n await sendAndConfirmTransaction(\n rpc,\n transaction,\n [payer],\n confirmOptions,\n );\n }\n\n return associatedToken;\n}\n\n/**\n * Create an associated token account idempotently for SPL/T22/c-token. Defaults\n * to c-token program.\n *\n * If the account already exists, the instruction succeeds without error.\n *\n * @param rpc RPC connection\n * @param payer Fee payer and transaction signer\n * @param mint Mint address\n * @param owner Owner of the associated token account\n * @param allowOwnerOffCurve Allow owner to be a PDA (default: false)\n * @param confirmOptions Options for confirming the transaction\n * @param programId Token program ID (default:\n * CTOKEN_PROGRAM_ID)\n * @param associatedTokenProgramId ATA program ID (auto-derived if not\n * provided)\n * @param ctokenConfig Optional c-token-specific configuration\n *\n * @returns Address of the associated token account\n */\nexport async function createAtaInterfaceIdempotent(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n owner: PublicKey,\n allowOwnerOffCurve = false,\n confirmOptions?: ConfirmOptions,\n programId: PublicKey = CTOKEN_PROGRAM_ID,\n associatedTokenProgramId?: PublicKey,\n ctokenConfig?: CTokenConfig,\n): Promise<PublicKey> {\n const effectiveAtaProgramId =\n associatedTokenProgramId ?? getAtaProgramId(programId);\n\n const associatedToken = getAssociatedTokenAddressInterface(\n mint,\n owner,\n allowOwnerOffCurve,\n programId,\n effectiveAtaProgramId,\n );\n\n const ix = createAssociatedTokenAccountInterfaceIdempotentInstruction(\n payer.publicKey,\n associatedToken,\n owner,\n mint,\n programId,\n effectiveAtaProgramId,\n ctokenConfig,\n );\n\n if (programId.equals(CTOKEN_PROGRAM_ID)) {\n const { blockhash } = await rpc.getLatestBlockhash();\n const tx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 30_000 }), ix],\n payer,\n blockhash,\n [],\n );\n await sendAndConfirmTx(rpc, tx, confirmOptions);\n } else {\n const transaction = new Transaction().add(ix);\n await sendAndConfirmTransaction(\n rpc,\n transaction,\n [payer],\n confirmOptions,\n );\n }\n\n return associatedToken;\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\nimport {\n Rpc,\n buildAndSignTx,\n sendAndConfirmTx,\n DerivationMode,\n bn,\n CTOKEN_PROGRAM_ID,\n selectStateTreeInfo,\n TreeInfo,\n} from '@lightprotocol/stateless.js';\nimport { createMintToInstruction } from '../instructions/mint-to';\nimport { getMintInterface } from '../get-mint-interface';\n\nexport async function mintTo(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n recipientAccount: PublicKey,\n authority: Signer,\n amount: number | bigint,\n outputQueue?: PublicKey,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n const mintInfo = await getMintInterface(\n rpc,\n mint,\n confirmOptions?.commitment,\n CTOKEN_PROGRAM_ID,\n );\n\n if (!mintInfo.merkleContext) {\n throw new Error('Mint does not have MerkleContext');\n }\n\n let outputStateTreeInfo: TreeInfo;\n if (!outputQueue) {\n const trees = await rpc.getStateTreeInfos();\n outputStateTreeInfo = selectStateTreeInfo(trees);\n } else {\n const trees = await rpc.getStateTreeInfos();\n outputStateTreeInfo = trees.find(\n t => t.queue.equals(outputQueue!) || t.tree.equals(outputQueue!),\n )!;\n if (!outputStateTreeInfo) {\n throw new Error('Could not find TreeInfo for provided outputQueue');\n }\n }\n\n const validityProof = await rpc.getValidityProofV2(\n [\n {\n hash: bn(mintInfo.merkleContext.hash),\n leafIndex: mintInfo.merkleContext.leafIndex,\n treeInfo: mintInfo.merkleContext.treeInfo,\n proveByIndex: mintInfo.merkleContext.proveByIndex,\n },\n ],\n [],\n DerivationMode.compressible,\n );\n\n const ix = createMintToInstruction(\n authority.publicKey,\n payer.publicKey,\n validityProof,\n mintInfo.merkleContext,\n {\n supply: mintInfo.mint.supply,\n decimals: mintInfo.mint.decimals,\n mintAuthority: mintInfo.mint.mintAuthority,\n freezeAuthority: mintInfo.mint.freezeAuthority,\n splMint: mintInfo.mintContext!.splMint,\n splMintInitialized: mintInfo.mintContext!.splMintInitialized,\n version: mintInfo.mintContext!.version,\n metadata: mintInfo.tokenMetadata\n ? {\n updateAuthority:\n mintInfo.tokenMetadata.updateAuthority || null,\n name: mintInfo.tokenMetadata.name,\n symbol: mintInfo.tokenMetadata.symbol,\n uri: mintInfo.tokenMetadata.uri,\n }\n : undefined,\n },\n outputStateTreeInfo,\n recipientAccount,\n amount,\n );\n\n const additionalSigners = authority.publicKey.equals(payer.publicKey)\n ? []\n : [authority];\n\n const { blockhash } = await rpc.getLatestBlockhash();\n const tx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 500_000 }), ix],\n payer,\n blockhash,\n additionalSigners,\n );\n\n return await sendAndConfirmTx(rpc, tx, confirmOptions);\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\nimport {\n Rpc,\n buildAndSignTx,\n sendAndConfirmTx,\n DerivationMode,\n bn,\n CTOKEN_PROGRAM_ID,\n selectStateTreeInfo,\n TreeInfo,\n} from '@lightprotocol/stateless.js';\nimport { createMintToCompressedInstruction } from '../instructions/mint-to-compressed';\nimport { getMintInterface } from '../get-mint-interface';\n\n/**\n * Mint compressed tokens directly to compressed accounts.\n *\n * @param rpc RPC connection\n * @param payer Fee payer\n * @param mint Mint address\n * @param authority Mint authority (must sign)\n * @param recipients Array of recipients with amounts\n * @param outputStateTreeInfo Optional output state tree info (auto-fetched if not provided)\n * @param tokenAccountVersion Token account version (default: 3)\n * @param confirmOptions Optional confirm options\n */\nexport async function mintToCompressed(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n authority: Signer,\n recipients: Array<{ recipient: PublicKey; amount: number | bigint }>,\n outputStateTreeInfo?: TreeInfo,\n tokenAccountVersion: number = 3,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n const mintInfo = await getMintInterface(\n rpc,\n mint,\n confirmOptions?.commitment,\n CTOKEN_PROGRAM_ID,\n );\n\n if (!mintInfo.merkleContext) {\n throw new Error('Mint does not have MerkleContext');\n }\n\n // Auto-fetch output state tree info if not provided\n if (!outputStateTreeInfo) {\n const trees = await rpc.getStateTreeInfos();\n outputStateTreeInfo = selectStateTreeInfo(trees);\n }\n\n const validityProof = await rpc.getValidityProofV2(\n [\n {\n hash: bn(mintInfo.merkleContext.hash),\n leafIndex: mintInfo.merkleContext.leafIndex,\n treeInfo: mintInfo.merkleContext.treeInfo,\n proveByIndex: mintInfo.merkleContext.proveByIndex,\n },\n ],\n [],\n DerivationMode.compressible,\n );\n\n const ix = createMintToCompressedInstruction(\n authority.publicKey,\n payer.publicKey,\n validityProof,\n mintInfo.merkleContext,\n {\n supply: mintInfo.mint.supply,\n decimals: mintInfo.mint.decimals,\n mintAuthority: mintInfo.mint.mintAuthority,\n freezeAuthority: mintInfo.mint.freezeAuthority,\n splMint: mintInfo.mintContext!.splMint,\n splMintInitialized: mintInfo.mintContext!.splMintInitialized,\n version: mintInfo.mintContext!.version,\n metadata: mintInfo.tokenMetadata\n ? {\n updateAuthority:\n mintInfo.tokenMetadata.updateAuthority || null,\n name: mintInfo.tokenMetadata.name,\n symbol: mintInfo.tokenMetadata.symbol,\n uri: mintInfo.tokenMetadata.uri,\n }\n : undefined,\n },\n recipients,\n outputStateTreeInfo,\n tokenAccountVersion,\n );\n\n const additionalSigners = authority.publicKey.equals(payer.publicKey)\n ? []\n : [authority];\n\n const { blockhash } = await rpc.getLatestBlockhash();\n const tx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 500_000 }), ix],\n payer,\n blockhash,\n additionalSigners,\n );\n\n return await sendAndConfirmTx(rpc, tx, confirmOptions);\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\nimport {\n Rpc,\n buildAndSignTx,\n sendAndConfirmTx,\n DerivationMode,\n bn,\n} from '@lightprotocol/stateless.js';\nimport { createMintToInterfaceInstruction } from '../instructions/mint-to-interface';\nimport { getMintInterface } from '../get-mint-interface';\n\n/**\n * Mint tokens to a decompressed/onchain token account.\n * Works with SPL, Token-2022, and compressed token (c-token) mints.\n *\n * This function ONLY mints to decompressed onchain token accounts, never to compressed accounts.\n * The signature matches the standard SPL mintTo for simplicity and consistency.\n *\n * @param rpc - RPC connection to use\n * @param payer - Transaction fee payer\n * @param mint - Mint address (SPL, Token-2022, or compressed mint)\n * @param destination - Destination token account address (must be an existing onchain token account)\n * @param authority - Mint authority (can be Signer or PublicKey if multiSigners provided)\n * @param amount - Amount to mint\n * @param multiSigners - Optional: Multi-signature signers (default: [])\n * @param confirmOptions - Optional: Transaction confirmation options\n * @param programId - Optional: Token program ID (TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, or CTOKEN_PROGRAM_ID). If undefined, auto-detects.\n *\n * @returns Transaction signature\n */\nexport async function mintToInterface(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n destination: PublicKey,\n authority: Signer | PublicKey,\n amount: number | bigint,\n multiSigners: Signer[] = [],\n confirmOptions?: ConfirmOptions,\n programId?: PublicKey,\n): Promise<TransactionSignature> {\n // Fetch mint interface (auto-detects program type if not provided)\n const mintInterface = await getMintInterface(\n rpc,\n mint,\n confirmOptions?.commitment,\n programId,\n );\n\n // Fetch validity proof if this is a compressed mint (has merkleContext)\n let validityProof;\n if (mintInterface.merkleContext) {\n validityProof = await rpc.getValidityProofV2(\n [\n {\n hash: bn(mintInterface.merkleContext.hash),\n leafIndex: mintInterface.merkleContext.leafIndex,\n treeInfo: mintInterface.merkleContext.treeInfo,\n proveByIndex: mintInterface.merkleContext.proveByIndex,\n },\n ],\n [],\n DerivationMode.compressible,\n );\n }\n\n // Create instruction\n const authorityPubkey =\n authority instanceof PublicKey ? authority : authority.publicKey;\n const multiSignerPubkeys = multiSigners.map(s => s.publicKey);\n\n const ix = createMintToInterfaceInstruction(\n mintInterface,\n destination,\n authorityPubkey,\n payer.publicKey,\n amount,\n validityProof,\n multiSignerPubkeys,\n );\n\n // Build signers list\n const signers: Signer[] = [];\n if (authority instanceof PublicKey) {\n // Authority is a pubkey, so multiSigners must be provided\n signers.push(...multiSigners);\n } else {\n // Authority is a signer\n if (!authority.publicKey.equals(payer.publicKey)) {\n signers.push(authority);\n }\n signers.push(...multiSigners);\n }\n\n const { blockhash } = await rpc.getLatestBlockhash();\n const tx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 500_000 }), ix],\n payer,\n blockhash,\n signers,\n );\n\n return await sendAndConfirmTx(rpc, tx, confirmOptions);\n}\n","import {\n Rpc,\n CTOKEN_PROGRAM_ID,\n buildAndSignTx,\n sendAndConfirmTx,\n} from '@lightprotocol/stateless.js';\nimport {\n getAssociatedTokenAddressSync,\n TOKEN_PROGRAM_ID,\n TokenAccountNotFoundError,\n TokenInvalidAccountOwnerError,\n TokenInvalidMintError,\n TokenInvalidOwnerError,\n} from '@solana/spl-token';\nimport type {\n Commitment,\n ConfirmOptions,\n PublicKey,\n Signer,\n} from '@solana/web3.js';\nimport {\n sendAndConfirmTransaction,\n Transaction,\n ComputeBudgetProgram,\n} from '@solana/web3.js';\nimport {\n createAssociatedTokenAccountInterfaceInstruction,\n createAssociatedTokenAccountInterfaceIdempotentInstruction,\n} from '../instructions/create-ata-interface';\nimport {\n getAccountInterface,\n getAtaInterface,\n AccountInterface,\n TokenAccountSourceType,\n} from '../get-account-interface';\nimport { getAtaProgramId } from '../ata-utils';\nimport { loadAta } from './load-ata';\n\n/**\n * Retrieve the associated token account, or create it if it doesn't exist.\n *\n * @param rpc Connection to use\n * @param payer Payer of the transaction and initialization\n * fees.\n * @param mint Mint associated with the account to set or\n * verify.\n * @param owner Owner of the account. Pass Signer to\n * auto-load cold (compressed) tokens, or\n * PublicKey for read-only.\n * @param allowOwnerOffCurve Allow the owner account to be a PDA (Program\n * Derived Address).\n * @param commitment Desired level of commitment for querying the\n * state.\n * @param confirmOptions Options for confirming the transaction\n * @param programId Token program ID (defaults to\n * CTOKEN_PROGRAM_ID)\n * @param associatedTokenProgramId Associated token program ID (auto-derived if\n * not provided)\n *\n * @returns AccountInterface with aggregated balance and source breakdown\n */\nexport async function getOrCreateAtaInterface(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n owner: PublicKey | Signer,\n allowOwnerOffCurve = false,\n commitment?: Commitment,\n confirmOptions?: ConfirmOptions,\n programId = TOKEN_PROGRAM_ID,\n associatedTokenProgramId = getAtaProgramId(programId),\n): Promise<AccountInterface> {\n return _getOrCreateAtaInterface(\n rpc,\n payer,\n mint,\n owner,\n allowOwnerOffCurve,\n commitment,\n confirmOptions,\n programId,\n associatedTokenProgramId,\n false, // wrap=false for standard path\n );\n}\n\n/** Helper to check if owner is a Signer (has both publicKey and secretKey) */\nfunction isSigner(owner: PublicKey | Signer): owner is Signer {\n // Check for both publicKey and secretKey properties\n // A proper Signer (like Keypair) has secretKey as Uint8Array\n if (!('publicKey' in owner) || !('secretKey' in owner)) {\n return false;\n }\n // Verify secretKey is actually present and is a Uint8Array\n const signer = owner as Signer;\n return (\n signer.secretKey instanceof Uint8Array && signer.secretKey.length > 0\n );\n}\n\n/** Helper to get PublicKey from owner (which may be Signer or PublicKey) */\nfunction getOwnerPublicKey(owner: PublicKey | Signer): PublicKey {\n return isSigner(owner) ? owner.publicKey : owner;\n}\n\n/**\n * @internal\n * Internal implementation with wrap parameter.\n */\nexport async function _getOrCreateAtaInterface(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n owner: PublicKey | Signer,\n allowOwnerOffCurve: boolean,\n commitment: Commitment | undefined,\n confirmOptions: ConfirmOptions | undefined,\n programId: PublicKey,\n associatedTokenProgramId: PublicKey,\n wrap: boolean,\n): Promise<AccountInterface> {\n const ownerPubkey = getOwnerPublicKey(owner);\n const associatedToken = getAssociatedTokenAddressSync(\n mint,\n ownerPubkey,\n allowOwnerOffCurve,\n programId,\n associatedTokenProgramId,\n );\n\n // For c-token, use getAtaInterface which properly aggregates hot+cold balances\n // When wrap=true (unified path), also includes SPL/T22 balances\n if (programId.equals(CTOKEN_PROGRAM_ID)) {\n return getOrCreateCTokenAta(\n rpc,\n payer,\n mint,\n owner,\n associatedToken,\n commitment,\n confirmOptions,\n wrap,\n );\n }\n\n // For SPL/T22, use standard address-based lookup\n return getOrCreateSplAta(\n rpc,\n payer,\n mint,\n ownerPubkey,\n associatedToken,\n programId,\n associatedTokenProgramId,\n commitment,\n confirmOptions,\n );\n}\n\n/**\n * Get or create c-token ATA with proper cold balance handling.\n *\n * Like SPL's getOrCreateAssociatedTokenAccount, this is a write operation:\n * 1. Creates hot ATA if it doesn't exist\n * 2. If owner is Signer: loads cold (compressed) tokens into hot ATA\n * 3. When wrap=true and owner is Signer: also wraps SPL/T22 tokens\n *\n * After this call (with Signer owner), all tokens are in the hot ATA and ready\n * to use.\n *\n * @internal\n */\nasync function getOrCreateCTokenAta(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n owner: PublicKey | Signer,\n associatedToken: PublicKey,\n commitment?: Commitment,\n confirmOptions?: ConfirmOptions,\n wrap = false,\n): Promise<AccountInterface> {\n const ownerPubkey = getOwnerPublicKey(owner);\n const ownerIsSigner = isSigner(owner);\n\n let accountInterface: AccountInterface;\n let hasHotAccount = false;\n\n try {\n // Use getAtaInterface which properly fetches by owner+mint and aggregates\n // hot+cold balances. When wrap=true, also includes SPL/T22 balances.\n accountInterface = await getAtaInterface(\n rpc,\n associatedToken,\n ownerPubkey,\n mint,\n commitment,\n CTOKEN_PROGRAM_ID,\n wrap,\n );\n\n // Check if we have a hot account\n hasHotAccount =\n accountInterface._sources?.some(\n s => s.type === TokenAccountSourceType.CTokenHot,\n ) ?? false;\n } catch (error: unknown) {\n if (\n error instanceof TokenAccountNotFoundError ||\n error instanceof TokenInvalidAccountOwnerError\n ) {\n // No account found (neither hot nor cold), create hot ATA\n await createCTokenAtaIdempotent(\n rpc,\n payer,\n mint,\n ownerPubkey,\n associatedToken,\n confirmOptions,\n );\n\n // Fetch the newly created account\n accountInterface = await getAtaInterface(\n rpc,\n associatedToken,\n ownerPubkey,\n mint,\n commitment,\n CTOKEN_PROGRAM_ID,\n wrap,\n );\n hasHotAccount = true;\n } else {\n throw error;\n }\n }\n\n // If we only have cold balance (no hot ATA), create the hot ATA first\n if (!hasHotAccount) {\n await createCTokenAtaIdempotent(\n rpc,\n payer,\n mint,\n ownerPubkey,\n associatedToken,\n confirmOptions,\n );\n }\n\n // Only auto-load if owner is a Signer (we can sign the load transaction)\n // Use direct type guard in the if condition for proper type narrowing\n if (isSigner(owner)) {\n // Check if we need to load tokens into the hot ATA\n // Load if: cold balance exists, or (wrap=true and SPL/T22 balance exists)\n const sources = accountInterface._sources ?? [];\n const hasCold = sources.some(\n s =>\n s.type === TokenAccountSourceType.CTokenCold &&\n s.amount > BigInt(0),\n );\n const hasSplToWrap =\n wrap &&\n sources.some(\n s =>\n (s.type === TokenAccountSourceType.Spl ||\n s.type === TokenAccountSourceType.Token2022) &&\n s.amount > BigInt(0),\n );\n\n if (hasCold || hasSplToWrap) {\n // Verify owner is a valid Signer before loading\n if (\n !(owner.secretKey instanceof Uint8Array) ||\n owner.secretKey.length === 0\n ) {\n throw new Error(\n 'Owner must be a valid Signer with secretKey to auto-load',\n );\n }\n\n // Load all tokens into hot ATA (decompress cold, wrap SPL/T22 if\n // wrap=true)\n await loadAta(\n rpc,\n associatedToken,\n owner, // TypeScript now knows owner is Signer\n mint,\n payer,\n confirmOptions,\n undefined,\n wrap,\n );\n\n // Re-fetch the updated account state\n accountInterface = await getAtaInterface(\n rpc,\n associatedToken,\n ownerPubkey,\n mint,\n commitment,\n CTOKEN_PROGRAM_ID,\n wrap,\n );\n }\n }\n\n const account = accountInterface.parsed;\n\n if (!account.mint.equals(mint)) throw new TokenInvalidMintError();\n if (!account.owner.equals(ownerPubkey)) throw new TokenInvalidOwnerError();\n\n return accountInterface;\n}\n\n/**\n * Create c-token ATA idempotently.\n * @internal\n */\nasync function createCTokenAtaIdempotent(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n owner: PublicKey,\n associatedToken: PublicKey,\n confirmOptions?: ConfirmOptions,\n): Promise<void> {\n try {\n const ix = createAssociatedTokenAccountInterfaceIdempotentInstruction(\n payer.publicKey,\n associatedToken,\n owner,\n mint,\n CTOKEN_PROGRAM_ID,\n );\n\n const { blockhash } = await rpc.getLatestBlockhash();\n const tx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 200_000 }), ix],\n payer,\n blockhash,\n [],\n );\n\n await sendAndConfirmTx(rpc, tx, confirmOptions);\n } catch {\n // Ignore errors - ATA may already exist\n }\n}\n\n/**\n * Get or create SPL/T22 ATA.\n * @internal\n */\nasync function getOrCreateSplAta(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n owner: PublicKey,\n associatedToken: PublicKey,\n programId: PublicKey,\n associatedTokenProgramId: PublicKey,\n commitment?: Commitment,\n confirmOptions?: ConfirmOptions,\n): Promise<AccountInterface> {\n let accountInterface: AccountInterface;\n\n try {\n accountInterface = await getAccountInterface(\n rpc,\n associatedToken,\n commitment,\n programId,\n );\n } catch (error: unknown) {\n // TokenAccountNotFoundError can be possible if the associated address\n // has already received some lamports, becoming a system account.\n if (\n error instanceof TokenAccountNotFoundError ||\n error instanceof TokenInvalidAccountOwnerError\n ) {\n // As this isn't atomic, it's possible others can create associated\n // accounts meanwhile.\n try {\n const transaction = new Transaction().add(\n createAssociatedTokenAccountInterfaceInstruction(\n payer.publicKey,\n associatedToken,\n owner,\n mint,\n programId,\n associatedTokenProgramId,\n ),\n );\n\n await sendAndConfirmTransaction(\n rpc,\n transaction,\n [payer],\n confirmOptions,\n );\n } catch {\n // Ignore all errors; for now there is no API-compatible way to\n // selectively ignore the expected instruction error if the\n // associated account exists already.\n }\n\n // Now this should always succeed\n accountInterface = await getAccountInterface(\n rpc,\n associatedToken,\n commitment,\n programId,\n );\n } else {\n throw error;\n }\n }\n\n const account = accountInterface.parsed;\n\n if (!account.mint.equals(mint)) throw new TokenInvalidMintError();\n if (!account.owner.equals(owner)) throw new TokenInvalidOwnerError();\n\n return accountInterface;\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionInstruction,\n TransactionSignature,\n} from '@solana/web3.js';\nimport {\n Rpc,\n buildAndSignTx,\n sendAndConfirmTx,\n CTOKEN_PROGRAM_ID,\n dedupeSigner,\n ParsedTokenAccount,\n} from '@lightprotocol/stateless.js';\nimport {\n TOKEN_PROGRAM_ID,\n TOKEN_2022_PROGRAM_ID,\n getAssociatedTokenAddressSync,\n} from '@solana/spl-token';\nimport BN from 'bn.js';\nimport { getAtaProgramId } from '../ata-utils';\nimport {\n createTransferInterfaceInstruction,\n createCTokenTransferInstruction,\n} from '../instructions/transfer-interface';\nimport { createAssociatedTokenAccountInterfaceIdempotentInstruction } from '../instructions/create-ata-interface';\nimport { getAssociatedTokenAddressInterface } from '../get-associated-token-address-interface';\nimport {\n getSplInterfaceInfos,\n SplInterfaceInfo,\n} from '../../utils/get-token-pool-infos';\nimport { createWrapInstruction } from '../instructions/wrap';\nimport { createDecompressInterfaceInstruction } from '../instructions/create-decompress-interface-instruction';\n\n/**\n * Options for interface operations (load, transfer)\n */\nexport interface InterfaceOptions {\n /** SPL interface infos (fetched if not provided) */\n splInterfaceInfos?: SplInterfaceInfo[];\n}\n\n/**\n * Calculate compute units needed for the operation\n */\nfunction calculateComputeUnits(\n compressedAccounts: ParsedTokenAccount[],\n hasValidityProof: boolean,\n splWrapCount: number,\n): number {\n // Base CU for hot c-token transfer\n let cu = 5_000;\n\n // Compressed token decompression\n if (compressedAccounts.length > 0) {\n if (hasValidityProof) {\n cu += 100_000; // Validity proof verification\n }\n // Per compressed account\n for (const acc of compressedAccounts) {\n const proveByIndex = acc.compressedAccount.proveByIndex ?? false;\n cu += proveByIndex ? 10_000 : 30_000;\n }\n }\n\n // SPL/T22 wrap operations\n cu += splWrapCount * 5_000;\n\n return cu;\n}\n\n/**\n * Transfer tokens using the c-token interface.\n *\n * Matches SPL Token's transferChecked signature order. Destination must exist.\n *\n * @param rpc RPC connection\n * @param payer Fee payer (signer)\n * @param source Source c-token ATA address\n * @param mint Mint address\n * @param destination Destination c-token ATA address (must exist)\n * @param owner Source owner (signer)\n * @param amount Amount to transfer\n * @param programId Token program ID (default: CTOKEN_PROGRAM_ID)\n * @param confirmOptions Optional confirm options\n * @param options Optional interface options\n * @param wrap Include SPL/T22 wrapping (default: false)\n * @returns Transaction signature\n */\nexport async function transferInterface(\n rpc: Rpc,\n payer: Signer,\n source: PublicKey,\n mint: PublicKey,\n destination: PublicKey,\n owner: Signer,\n amount: number | bigint | BN,\n programId: PublicKey = CTOKEN_PROGRAM_ID,\n confirmOptions?: ConfirmOptions,\n options?: InterfaceOptions,\n wrap = false,\n): Promise<TransactionSignature> {\n const amountBigInt = BigInt(amount.toString());\n const { splInterfaceInfos: providedSplInterfaceInfos } = options ?? {};\n\n const instructions: TransactionInstruction[] = [];\n\n // For non-c-token programs, use simple SPL transfer (no load)\n if (!programId.equals(CTOKEN_PROGRAM_ID)) {\n const expectedSource = getAssociatedTokenAddressSync(\n mint,\n owner.publicKey,\n false,\n programId,\n getAtaProgramId(programId),\n );\n if (!source.equals(expectedSource)) {\n throw new Error(\n `Source mismatch. Expected ${expectedSource.toBase58()}, got ${source.toBase58()}`,\n );\n }\n\n instructions.push(\n createTransferInterfaceInstruction(\n source,\n destination,\n owner.publicKey,\n amountBigInt,\n [],\n programId,\n ),\n );\n\n const { blockhash } = await rpc.getLatestBlockhash();\n const tx = buildAndSignTx(\n [\n ComputeBudgetProgram.setComputeUnitLimit({ units: 10_000 }),\n ...instructions,\n ],\n payer,\n blockhash,\n [owner],\n );\n return sendAndConfirmTx(rpc, tx, confirmOptions);\n }\n\n // c-token transfer\n const expectedSource = getAssociatedTokenAddressInterface(\n mint,\n owner.publicKey,\n );\n if (!source.equals(expectedSource)) {\n throw new Error(\n `Source mismatch. Expected ${expectedSource.toBase58()}, got ${source.toBase58()}`,\n );\n }\n\n const ctokenAtaAddress = getAssociatedTokenAddressInterface(\n mint,\n owner.publicKey,\n );\n\n // Derive SPL/T22 ATAs only if wrap is true\n let splAta: PublicKey | undefined;\n let t22Ata: PublicKey | undefined;\n\n if (wrap) {\n splAta = getAssociatedTokenAddressSync(\n mint,\n owner.publicKey,\n false,\n TOKEN_PROGRAM_ID,\n getAtaProgramId(TOKEN_PROGRAM_ID),\n );\n t22Ata = getAssociatedTokenAddressSync(\n mint,\n owner.publicKey,\n false,\n TOKEN_2022_PROGRAM_ID,\n getAtaProgramId(TOKEN_2022_PROGRAM_ID),\n );\n }\n\n // Fetch sender's accounts in parallel (conditionally include SPL/T22)\n const fetchPromises: Promise<unknown>[] = [\n rpc.getAccountInfo(ctokenAtaAddress),\n rpc.getCompressedTokenAccountsByOwner(owner.publicKey, { mint }),\n ];\n if (wrap && splAta && t22Ata) {\n fetchPromises.push(rpc.getAccountInfo(splAta));\n fetchPromises.push(rpc.getAccountInfo(t22Ata));\n }\n\n const results = await Promise.all(fetchPromises);\n const ctokenAtaInfo = results[0] as Awaited<\n ReturnType<typeof rpc.getAccountInfo>\n >;\n const compressedResult = results[1] as Awaited<\n ReturnType<typeof rpc.getCompressedTokenAccountsByOwner>\n >;\n const splAtaInfo = wrap\n ? (results[2] as Awaited<ReturnType<typeof rpc.getAccountInfo>>)\n : null;\n const t22AtaInfo = wrap\n ? (results[3] as Awaited<ReturnType<typeof rpc.getAccountInfo>>)\n : null;\n\n const compressedAccounts = compressedResult.items;\n\n // Parse balances\n const hotBalance =\n ctokenAtaInfo && ctokenAtaInfo.data.length >= 72\n ? ctokenAtaInfo.data.readBigUInt64LE(64)\n : BigInt(0);\n const splBalance =\n wrap && splAtaInfo && splAtaInfo.data.length >= 72\n ? splAtaInfo.data.readBigUInt64LE(64)\n : BigInt(0);\n const t22Balance =\n wrap && t22AtaInfo && t22AtaInfo.data.length >= 72\n ? t22AtaInfo.data.readBigUInt64LE(64)\n : BigInt(0);\n const compressedBalance = compressedAccounts.reduce(\n (sum, acc) => sum + BigInt(acc.parsed.amount.toString()),\n BigInt(0),\n );\n\n const totalBalance =\n hotBalance + splBalance + t22Balance + compressedBalance;\n\n if (totalBalance < amountBigInt) {\n throw new Error(\n `Insufficient balance. Required: ${amountBigInt}, Available: ${totalBalance}`,\n );\n }\n\n // Track what we're doing for CU calculation\n let splWrapCount = 0;\n let hasValidityProof = false;\n let compressedToLoad: ParsedTokenAccount[] = [];\n\n // Create sender's c-token ATA if needed (idempotent)\n if (!ctokenAtaInfo) {\n instructions.push(\n createAssociatedTokenAccountInterfaceIdempotentInstruction(\n payer.publicKey,\n ctokenAtaAddress,\n owner.publicKey,\n mint,\n CTOKEN_PROGRAM_ID,\n ),\n );\n }\n\n // Get SPL interface infos if we need to load\n const needsLoad =\n splBalance > BigInt(0) ||\n t22Balance > BigInt(0) ||\n compressedBalance > BigInt(0);\n const splInterfaceInfos = needsLoad\n ? (providedSplInterfaceInfos ?? (await getSplInterfaceInfos(rpc, mint)))\n : [];\n const splInterfaceInfo = splInterfaceInfos.find(info => info.isInitialized);\n\n // Wrap SPL tokens if balance exists (only when wrap=true)\n if (wrap && splAta && splBalance > BigInt(0) && splInterfaceInfo) {\n instructions.push(\n createWrapInstruction(\n splAta,\n ctokenAtaAddress,\n owner.publicKey,\n mint,\n splBalance,\n splInterfaceInfo,\n payer.publicKey,\n ),\n );\n splWrapCount++;\n }\n\n // Wrap T22 tokens if balance exists (only when wrap=true)\n if (wrap && t22Ata && t22Balance > BigInt(0) && splInterfaceInfo) {\n instructions.push(\n createWrapInstruction(\n t22Ata,\n ctokenAtaAddress,\n owner.publicKey,\n mint,\n t22Balance,\n splInterfaceInfo,\n payer.publicKey,\n ),\n );\n splWrapCount++;\n }\n\n // Decompress compressed tokens if they exist\n if (compressedBalance > BigInt(0) && compressedAccounts.length > 0) {\n const proof = await rpc.getValidityProofV0(\n compressedAccounts.map(acc => ({\n hash: acc.compressedAccount.hash,\n tree: acc.compressedAccount.treeInfo.tree,\n queue: acc.compressedAccount.treeInfo.queue,\n })),\n );\n\n hasValidityProof = proof.compressedProof !== null;\n compressedToLoad = compressedAccounts;\n\n instructions.push(\n createDecompressInterfaceInstruction(\n payer.publicKey,\n compressedAccounts,\n ctokenAtaAddress,\n compressedBalance,\n proof,\n ),\n );\n }\n\n // Transfer (destination must already exist - like SPL Token)\n instructions.push(\n createCTokenTransferInstruction(\n source,\n destination,\n owner.publicKey,\n amountBigInt,\n payer.publicKey,\n ),\n );\n\n // Calculate compute units\n const computeUnits = calculateComputeUnits(\n compressedToLoad,\n hasValidityProof,\n splWrapCount,\n );\n\n // Build and send\n const { blockhash } = await rpc.getLatestBlockhash();\n const additionalSigners = dedupeSigner(payer, [owner]);\n\n const tx = buildAndSignTx(\n [\n ComputeBudgetProgram.setComputeUnitLimit({ units: computeUnits }),\n ...instructions,\n ],\n payer,\n blockhash,\n additionalSigners,\n );\n\n return sendAndConfirmTx(rpc, tx, confirmOptions);\n}\n","import {\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n ComputeBudgetProgram,\n} from '@solana/web3.js';\nimport {\n Rpc,\n buildAndSignTx,\n sendAndConfirmTx,\n dedupeSigner,\n ParsedTokenAccount,\n} from '@lightprotocol/stateless.js';\nimport {\n createAssociatedTokenAccountIdempotentInstruction,\n getAssociatedTokenAddress,\n} from '@solana/spl-token';\nimport BN from 'bn.js';\nimport { createDecompressInterfaceInstruction } from '../instructions/create-decompress-interface-instruction';\nimport { createAssociatedTokenAccountInterfaceIdempotentInstruction } from '../instructions/create-ata-interface';\nimport { getAssociatedTokenAddressInterface } from '../get-associated-token-address-interface';\nimport { CTOKEN_PROGRAM_ID } from '@lightprotocol/stateless.js';\nimport { SplInterfaceInfo } from '../../utils/get-token-pool-infos';\n\n/**\n * Decompress compressed (cold) tokens to an on-chain token account.\n *\n * For unified loading, use {@link loadAta} instead.\n *\n * @param rpc RPC connection\n * @param payer Fee payer (signer)\n * @param owner Owner of the compressed tokens (signer)\n * @param mint Mint address\n * @param amount Amount to decompress (defaults to all)\n * @param destinationAta Destination token account address\n * @param destinationOwner Owner of the destination ATA\n * @param splInterfaceInfo SPL interface info for SPL/T22 destinations\n * @param confirmOptions Confirm options\n * @returns Transaction signature, null if nothing to load.\n */\nexport async function decompressInterface(\n rpc: Rpc,\n payer: Signer,\n owner: Signer,\n mint: PublicKey,\n amount?: number | bigint | BN,\n destinationAta?: PublicKey,\n destinationOwner?: PublicKey,\n splInterfaceInfo?: SplInterfaceInfo,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature | null> {\n // Determine if this is SPL or c-token destination\n const isSplDestination = splInterfaceInfo !== undefined;\n\n // Get compressed token accounts\n const compressedResult = await rpc.getCompressedTokenAccountsByOwner(\n owner.publicKey,\n { mint },\n );\n const compressedAccounts = compressedResult.items;\n\n if (compressedAccounts.length === 0) {\n return null; // Nothing to decompress\n }\n\n // Calculate total and determine amount\n const totalBalance = compressedAccounts.reduce(\n (sum, acc) => sum + BigInt(acc.parsed.amount.toString()),\n BigInt(0),\n );\n\n const decompressAmount = amount ? BigInt(amount.toString()) : totalBalance;\n\n if (decompressAmount > totalBalance) {\n throw new Error(\n `Insufficient compressed balance. Requested: ${decompressAmount}, Available: ${totalBalance}`,\n );\n }\n\n // Select accounts to use (for now, use all - could optimize later)\n const accountsToUse: ParsedTokenAccount[] = [];\n let accumulatedAmount = BigInt(0);\n for (const acc of compressedAccounts) {\n if (accumulatedAmount >= decompressAmount) break;\n accountsToUse.push(acc);\n accumulatedAmount += BigInt(acc.parsed.amount.toString());\n }\n\n // Get validity proof\n const validityProof = await rpc.getValidityProofV0(\n accountsToUse.map(acc => ({\n hash: acc.compressedAccount.hash,\n tree: acc.compressedAccount.treeInfo.tree,\n queue: acc.compressedAccount.treeInfo.queue,\n })),\n );\n\n // Determine destination ATA based on token program\n const ataOwner = destinationOwner ?? owner.publicKey;\n let destinationAtaAddress: PublicKey;\n\n if (isSplDestination) {\n // SPL destination - use SPL ATA\n destinationAtaAddress =\n destinationAta ??\n (await getAssociatedTokenAddress(\n mint,\n ataOwner,\n false,\n splInterfaceInfo.tokenProgram,\n ));\n } else {\n // c-token destination - use c-token ATA\n destinationAtaAddress =\n destinationAta ??\n getAssociatedTokenAddressInterface(mint, ataOwner);\n }\n\n // Build instructions\n const instructions = [];\n\n // Create ATA if needed (idempotent)\n const ataInfo = await rpc.getAccountInfo(destinationAtaAddress);\n if (!ataInfo) {\n if (isSplDestination) {\n // Create SPL ATA\n instructions.push(\n createAssociatedTokenAccountIdempotentInstruction(\n payer.publicKey,\n destinationAtaAddress,\n ataOwner,\n mint,\n splInterfaceInfo.tokenProgram,\n ),\n );\n } else {\n // Create c-token ATA\n instructions.push(\n createAssociatedTokenAccountInterfaceIdempotentInstruction(\n payer.publicKey,\n destinationAtaAddress,\n ataOwner,\n mint,\n CTOKEN_PROGRAM_ID,\n ),\n );\n }\n }\n\n // Calculate compute units\n const hasValidityProof = validityProof.compressedProof !== null;\n let computeUnits = 50_000; // Base\n if (hasValidityProof) {\n computeUnits += 100_000;\n }\n for (const acc of accountsToUse) {\n const proveByIndex = acc.compressedAccount.proveByIndex ?? false;\n computeUnits += proveByIndex ? 10_000 : 30_000;\n }\n // SPL decompression needs extra compute for pool operations\n if (isSplDestination) {\n computeUnits += 50_000;\n }\n\n // Add decompressInterface instruction\n instructions.push(\n createDecompressInterfaceInstruction(\n payer.publicKey,\n accountsToUse,\n destinationAtaAddress,\n decompressAmount,\n validityProof,\n splInterfaceInfo,\n ),\n );\n\n // Build and send\n const { blockhash } = await rpc.getLatestBlockhash();\n const additionalSigners = dedupeSigner(payer, [owner]);\n\n const tx = buildAndSignTx(\n [\n ComputeBudgetProgram.setComputeUnitLimit({ units: computeUnits }),\n ...instructions,\n ],\n payer,\n blockhash,\n additionalSigners,\n );\n\n return sendAndConfirmTx(rpc, tx, confirmOptions);\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\nimport {\n Rpc,\n buildAndSignTx,\n sendAndConfirmTx,\n dedupeSigner,\n} from '@lightprotocol/stateless.js';\nimport { createWrapInstruction } from '../instructions/wrap';\nimport {\n getSplInterfaceInfos,\n SplInterfaceInfo,\n} from '../../utils/get-token-pool-infos';\n\n/**\n * Wrap tokens from an SPL/T22 account to a c-token account.\n *\n * This is an agnostic action that takes explicit account addresses (spl-token style).\n * Use getAssociatedTokenAddressSync() to derive ATA addresses if needed.\n *\n * @param rpc RPC connection\n * @param payer Fee payer\n * @param source Source SPL/T22 token account (any token account, not just ATA)\n * @param destination Destination c-token account\n * @param owner Owner/authority of the source account (must sign)\n * @param mint Mint address\n * @param amount Amount to wrap\n * @param splInterfaceInfo Optional: SPL interface info (will be fetched if not provided)\n * @param confirmOptions Optional: Confirm options\n *\n * @example\n * const splAta = getAssociatedTokenAddressSync(mint, owner.publicKey, false, TOKEN_PROGRAM_ID);\n * const ctokenAta = getAssociatedTokenAddressInterface(mint, owner.publicKey); // defaults to c-token\n *\n * await wrap(\n * rpc,\n * payer,\n * splAta,\n * ctokenAta,\n * owner,\n * mint,\n * 1000n,\n * );\n *\n * @returns Transaction signature\n */\nexport async function wrap(\n rpc: Rpc,\n payer: Signer,\n source: PublicKey,\n destination: PublicKey,\n owner: Signer,\n mint: PublicKey,\n amount: bigint,\n splInterfaceInfo?: SplInterfaceInfo,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n // Get SPL interface info if not provided\n let resolvedSplInterfaceInfo = splInterfaceInfo;\n if (!resolvedSplInterfaceInfo) {\n const splInterfaceInfos = await getSplInterfaceInfos(rpc, mint);\n resolvedSplInterfaceInfo = splInterfaceInfos.find(\n info => info.isInitialized,\n );\n\n if (!resolvedSplInterfaceInfo) {\n throw new Error(\n `No initialized SPL interface found for mint: ${mint.toBase58()}. ` +\n `Please create an SPL interface via createSplInterface().`,\n );\n }\n }\n\n // Build wrap instruction\n const ix = createWrapInstruction(\n source,\n destination,\n owner.publicKey,\n mint,\n amount,\n resolvedSplInterfaceInfo,\n payer.publicKey,\n );\n\n // Build and send transaction\n const { blockhash } = await rpc.getLatestBlockhash();\n\n const additionalSigners = dedupeSigner(payer, [owner]);\n\n const tx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 200_000 }), ix],\n payer,\n blockhash,\n additionalSigners,\n );\n\n const txId = await sendAndConfirmTx(rpc, tx, confirmOptions);\n\n return txId;\n}\n","/**\n * Input for creating off-chain metadata JSON.\n * Compatible with Token-2022 and Metaplex standards.\n */\nexport interface OffChainTokenMetadata {\n /** Token name */\n name: string;\n /** Token symbol */\n symbol: string;\n /** Optional description */\n description?: string;\n /** Optional image URI */\n image?: string;\n /** Optional additional metadata key-value pairs */\n additionalMetadata?: Array<{ key: string; value: string }>;\n}\n\n/**\n * Off-chain JSON format for token metadata.\n * Standard format compatible with Token-2022 and Metaplex tooling.\n */\nexport interface OffChainTokenMetadataJson {\n name: string;\n symbol: string;\n description?: string;\n image?: string;\n additionalMetadata?: Array<{ key: string; value: string }>;\n}\n\n/**\n * Format metadata for off-chain storage.\n *\n * Returns a plain object ready to be uploaded using any storage provider\n * (umi uploader, custom IPFS/Arweave/S3 solution, etc.).\n *\n * @example\n * // With umi uploader\n * import { toOffChainMetadataJson } from '@lightprotocol/compressed-token';\n * import { irysUploader } from '@metaplex-foundation/umi-uploader-irys';\n *\n * const umi = createUmi(connection).use(irysUploader());\n * const metadataJson = toOffChainMetadataJson({\n * name: 'My Token',\n * symbol: 'MTK',\n * description: 'A compressed token',\n * image: 'https://example.com/image.png',\n * });\n * const uri = await umi.uploader.uploadJson(metadataJson);\n *\n * // Then use uri with createMint\n * await createMint(rpc, payer, { ...params, uri });\n */\nexport function toOffChainMetadataJson(\n meta: OffChainTokenMetadata,\n): OffChainTokenMetadataJson {\n const json: OffChainTokenMetadataJson = {\n name: meta.name,\n symbol: meta.symbol,\n };\n\n if (meta.description !== undefined) {\n json.description = meta.description;\n }\n if (meta.image !== undefined) {\n json.image = meta.image;\n }\n if (\n meta.additionalMetadata !== undefined &&\n meta.additionalMetadata.length > 0\n ) {\n json.additionalMetadata = meta.additionalMetadata;\n }\n\n return json;\n}\n","import {\n struct,\n option,\n vec,\n bool,\n u64,\n u8,\n u16,\n u32,\n array,\n vecU8,\n} from '@coral-xyz/borsh';\nimport { Buffer } from 'buffer';\nimport { ValidityProof } from '@lightprotocol/stateless.js';\nimport { DECOMPRESS_ACCOUNTS_IDEMPOTENT_DISCRIMINATOR } from '../../constants';\n\nconst ValidityProofLayout = struct([\n array(u8(), 32, 'a'),\n array(u8(), 64, 'b'),\n array(u8(), 32, 'c'),\n]);\n\nconst PackedStateTreeInfoLayout = struct([\n u16('rootIndex'),\n bool('proveByIndex'),\n u8('merkleTreePubkeyIndex'),\n u8('queuePubkeyIndex'),\n u32('leafIndex'),\n]);\n\nconst CompressedAccountMetaLayout = struct([\n PackedStateTreeInfoLayout.replicate('treeInfo'),\n option(array(u8(), 32), 'address'),\n option(u64(), 'lamports'),\n u8('outputStateTreeIndex'),\n]);\n\nexport interface PackedStateTreeInfo {\n rootIndex: number;\n proveByIndex: boolean;\n merkleTreePubkeyIndex: number;\n queuePubkeyIndex: number;\n leafIndex: number;\n}\n\nexport interface CompressedAccountMeta {\n treeInfo: PackedStateTreeInfo;\n address: number[] | null;\n lamports: bigint | null;\n outputStateTreeIndex: number;\n}\n\nexport interface CompressedAccountData<T = any> {\n meta: CompressedAccountMeta;\n data: T;\n seeds: Uint8Array[];\n}\n\nexport interface DecompressAccountsIdempotentInstructionData<T = any> {\n proof: ValidityProof;\n compressedAccounts: CompressedAccountData<T>[];\n systemAccountsOffset: number;\n}\n\nexport function createCompressedAccountDataLayout<T>(dataLayout: any): any {\n return struct([\n CompressedAccountMetaLayout.replicate('meta'),\n dataLayout.replicate('data'),\n vec(vecU8(), 'seeds'),\n ]);\n}\n\nexport function createDecompressAccountsIdempotentLayout<T>(\n dataLayout: any,\n): any {\n return struct([\n ValidityProofLayout.replicate('proof'),\n vec(\n createCompressedAccountDataLayout(dataLayout),\n 'compressedAccounts',\n ),\n u8('systemAccountsOffset'),\n ]);\n}\n\n/**\n * Serialize decompress idempotent instruction data\n * @param data The decompress idempotent instruction data\n * @param dataLayout The data layout\n * @returns The serialized decompress idempotent instruction data\n */\nexport function serializeDecompressIdempotentInstructionData<T = any>(\n data: DecompressAccountsIdempotentInstructionData<T>,\n dataLayout: any,\n): Buffer {\n const layout = createDecompressAccountsIdempotentLayout(dataLayout);\n const buffer = Buffer.alloc(1000);\n\n const len = layout.encode(data, buffer);\n\n return Buffer.concat([\n DECOMPRESS_ACCOUNTS_IDEMPOTENT_DISCRIMINATOR,\n buffer.subarray(0, len),\n ]);\n}\n\n/**\n * Deserialize decompress idempotent instruction data\n * @param buffer The serialized decompress idempotent instruction data\n * @param dataLayout The data layout\n * @returns The decompress idempotent instruction data\n */\nexport function deserializeDecompressIdempotentInstructionData<T = any>(\n buffer: Buffer,\n dataLayout: any,\n): DecompressAccountsIdempotentInstructionData<T> {\n const layout = createDecompressAccountsIdempotentLayout(dataLayout);\n return layout.decode(\n buffer.subarray(DECOMPRESS_ACCOUNTS_IDEMPOTENT_DISCRIMINATOR.length),\n ) as DecompressAccountsIdempotentInstructionData<T>;\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\nimport {\n bn,\n sendAndConfirmTx,\n buildAndSignTx,\n Rpc,\n dedupeSigner,\n} from '@lightprotocol/stateless.js';\nimport BN from 'bn.js';\nimport { CompressedTokenProgram } from '../program';\nimport {\n selectMinCompressedTokenAccountsForTransfer,\n selectTokenAccountsForApprove,\n} from '../utils';\n\n/**\n * Approve a delegate to spend tokens\n *\n * @param rpc Rpc to use\n * @param payer Fee payer\n * @param mint SPL Mint address\n * @param amount Number of tokens to delegate\n * @param owner Owner of the SPL token account.\n * @param delegate Address of the delegate\n * @param confirmOptions Options for confirming the transaction\n *\n * @return Signature of the confirmed transaction\n */\nexport async function approve(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n amount: number | BN,\n owner: Signer,\n delegate: PublicKey,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n amount = bn(amount);\n const compressedTokenAccounts = await rpc.getCompressedTokenAccountsByOwner(\n owner.publicKey,\n {\n mint,\n },\n );\n\n const [inputAccounts] = selectTokenAccountsForApprove(\n compressedTokenAccounts.items,\n amount,\n );\n\n const proof = await rpc.getValidityProofV0(\n inputAccounts.map(account => ({\n hash: account.compressedAccount.hash,\n tree: account.compressedAccount.treeInfo.tree,\n queue: account.compressedAccount.treeInfo.queue,\n })),\n );\n\n const ix = await CompressedTokenProgram.approve({\n payer: payer.publicKey,\n inputCompressedTokenAccounts: inputAccounts,\n toAddress: delegate,\n amount,\n recentInputStateRootIndices: proof.rootIndices,\n recentValidityProof: proof.compressedProof,\n });\n\n const { blockhash } = await rpc.getLatestBlockhash();\n const additionalSigners = dedupeSigner(payer, [owner]);\n const signedTx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 350_000 }), ix],\n payer,\n blockhash,\n additionalSigners,\n );\n\n return sendAndConfirmTx(rpc, signedTx, confirmOptions);\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\nimport BN from 'bn.js';\nimport {\n sendAndConfirmTx,\n buildAndSignTx,\n Rpc,\n dedupeSigner,\n selectStateTreeInfo,\n toArray,\n TreeInfo,\n} from '@lightprotocol/stateless.js';\nimport { CompressedTokenProgram } from '../program';\nimport { getOrCreateAssociatedTokenAccount } from '@solana/spl-token';\n\nimport {\n getSplInterfaceInfos,\n selectSplInterfaceInfo,\n SplInterfaceInfo,\n} from '../utils/get-token-pool-infos';\n\n/**\n * Mint compressed tokens to a solana address from an external mint authority\n *\n * @param rpc Rpc to use\n * @param payer Fee payer\n * @param mint SPL Mint address\n * @param toPubkey Address of the account to mint to\n * @param authority Minting authority\n * @param amount Amount to mint\n * @param outputStateTreeInfo Optional: State tree account that the compressed\n * tokens should be inserted into. Defaults to a\n * shared state tree account.\n * @param splInterfaceInfo Optional: SPL interface info.\n * @param confirmOptions Options for confirming the transaction\n *\n * @return Signature of the confirmed transaction\n */\nexport async function approveAndMintTo(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n toPubkey: PublicKey,\n authority: Signer,\n amount: number | BN,\n outputStateTreeInfo?: TreeInfo,\n splInterfaceInfo?: SplInterfaceInfo,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n outputStateTreeInfo =\n outputStateTreeInfo ??\n selectStateTreeInfo(await rpc.getStateTreeInfos());\n splInterfaceInfo =\n splInterfaceInfo ??\n selectSplInterfaceInfo(await getSplInterfaceInfos(rpc, mint));\n\n const authorityTokenAccount = await getOrCreateAssociatedTokenAccount(\n rpc,\n payer,\n mint,\n authority.publicKey,\n undefined,\n undefined,\n confirmOptions,\n splInterfaceInfo.tokenProgram,\n );\n\n const ixs = await CompressedTokenProgram.approveAndMintTo({\n feePayer: payer.publicKey,\n mint,\n authority: authority.publicKey,\n authorityTokenAccount: authorityTokenAccount.address,\n amount,\n toPubkey,\n outputStateTreeInfo,\n tokenPoolInfo: splInterfaceInfo,\n });\n\n const { blockhash } = await rpc.getLatestBlockhash();\n const additionalSigners = dedupeSigner(payer, [authority]);\n\n const tx = buildAndSignTx(\n [\n ComputeBudgetProgram.setComputeUnitLimit({\n units: 150_000 + toArray(amount).length * 20_000,\n }),\n ...ixs,\n ],\n payer,\n blockhash,\n additionalSigners,\n );\n\n return await sendAndConfirmTx(rpc, tx, confirmOptions);\n}\n","import {\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n ComputeBudgetProgram,\n} from '@solana/web3.js';\nimport {\n sendAndConfirmTx,\n buildAndSignTx,\n Rpc,\n dedupeSigner,\n selectStateTreeInfo,\n toArray,\n TreeInfo,\n} from '@lightprotocol/stateless.js';\nimport BN from 'bn.js';\nimport { CompressedTokenProgram } from '../program';\nimport {\n getSplInterfaceInfos,\n selectSplInterfaceInfo,\n SplInterfaceInfo,\n} from '../utils/get-token-pool-infos';\n\n/**\n * Compress SPL tokens\n *\n * @param rpc Rpc connection to use\n * @param payer Fee payer\n * @param mint SPL Mint address\n * @param amount Number of tokens to compress.\n * @param owner Owner of the SPL token account.\n * @param sourceTokenAccount Source SPL token account. (ATA)\n * @param toAddress Recipient owner address.\n * @param outputStateTreeInfo Optional: State tree account that the compressed\n * tokens should be inserted into. Defaults to a\n * shared state tree account.\n * @param splInterfaceInfo Optional: SPL interface info.\n * @param confirmOptions Options for confirming the transaction\n *\n * @return Signature of the confirmed transaction\n */\nexport async function compress(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n amount: number | BN | number[] | BN[],\n owner: Signer,\n sourceTokenAccount: PublicKey,\n toAddress: PublicKey | Array<PublicKey>,\n outputStateTreeInfo?: TreeInfo,\n splInterfaceInfo?: SplInterfaceInfo,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n outputStateTreeInfo =\n outputStateTreeInfo ??\n selectStateTreeInfo(await rpc.getStateTreeInfos());\n splInterfaceInfo =\n splInterfaceInfo ??\n selectSplInterfaceInfo(await getSplInterfaceInfos(rpc, mint));\n\n const compressIx = await CompressedTokenProgram.compress({\n payer: payer.publicKey,\n owner: owner.publicKey,\n source: sourceTokenAccount,\n toAddress,\n amount,\n mint,\n outputStateTreeInfo,\n tokenPoolInfo: splInterfaceInfo,\n });\n\n const blockhashCtx = await rpc.getLatestBlockhash();\n const additionalSigners = dedupeSigner(payer, [owner]);\n const signedTx = buildAndSignTx(\n [\n ComputeBudgetProgram.setComputeUnitLimit({\n units: 130_000 + toArray(amount).length * 20_000,\n }),\n compressIx,\n ],\n payer,\n blockhashCtx.blockhash,\n additionalSigners,\n );\n\n return await sendAndConfirmTx(rpc, signedTx, confirmOptions, blockhashCtx);\n}\n","import {\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n ComputeBudgetProgram,\n} from '@solana/web3.js';\nimport {\n sendAndConfirmTx,\n buildAndSignTx,\n Rpc,\n dedupeSigner,\n selectStateTreeInfo,\n TreeInfo,\n} from '@lightprotocol/stateless.js';\nimport BN from 'bn.js';\nimport {\n getSplInterfaceInfos,\n selectSplInterfaceInfo,\n SplInterfaceInfo,\n} from '../utils/get-token-pool-infos';\nimport { CompressedTokenProgram } from '../program';\n\n/**\n * Compress SPL tokens into compressed token format\n *\n * @param rpc Rpc connection to use\n * @param payer Fee payer\n * @param mint SPL Mint address\n * @param owner Owner of the token account\n * @param tokenAccount Token account to compress\n * @param remainingAmount Optional: amount to leave in token account.\n * Default: 0\n * @param outputStateTreeInfo Optional: State tree account that the compressed\n * account into\n * @param splInterfaceInfo Optional: SPL interface info.\n * @param confirmOptions Options for confirming the transaction\n\n *\n * @return Signature of the confirmed transaction\n */\nexport async function compressSplTokenAccount(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n owner: Signer,\n tokenAccount: PublicKey,\n remainingAmount?: BN,\n outputStateTreeInfo?: TreeInfo,\n splInterfaceInfo?: SplInterfaceInfo,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n outputStateTreeInfo =\n outputStateTreeInfo ??\n selectStateTreeInfo(await rpc.getStateTreeInfos());\n splInterfaceInfo =\n splInterfaceInfo ??\n selectSplInterfaceInfo(await getSplInterfaceInfos(rpc, mint));\n\n const compressIx = await CompressedTokenProgram.compressSplTokenAccount({\n feePayer: payer.publicKey,\n authority: owner.publicKey,\n tokenAccount,\n mint,\n remainingAmount,\n outputStateTreeInfo,\n tokenPoolInfo: splInterfaceInfo,\n });\n\n const blockhashCtx = await rpc.getLatestBlockhash();\n const additionalSigners = dedupeSigner(payer, [owner]);\n\n const signedTx = buildAndSignTx(\n [\n ComputeBudgetProgram.setComputeUnitLimit({\n units: 150_000,\n }),\n compressIx,\n ],\n payer,\n blockhashCtx.blockhash,\n additionalSigners,\n );\n\n return await sendAndConfirmTx(rpc, signedTx, confirmOptions, blockhashCtx);\n}\n","import {\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionInstruction,\n TransactionSignature,\n} from '@solana/web3.js';\nimport { CompressedTokenProgram } from '../program';\nimport {\n Rpc,\n buildAndSignTx,\n sendAndConfirmTx,\n} from '@lightprotocol/stateless.js';\nimport { getSplInterfaceInfos } from '../utils/get-token-pool-infos';\n\n/**\n * Register an existing mint with the CompressedToken program\n *\n * @param rpc RPC connection to use\n * @param payer Fee payer\n * @param mint SPL Mint address\n * @param confirmOptions Options for confirming the transaction\n * @param tokenProgramId Optional: Address of the token program. Default:\n * TOKEN_PROGRAM_ID\n *\n * @return transaction signature\n */\nexport async function createSplInterface(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n confirmOptions?: ConfirmOptions,\n tokenProgramId?: PublicKey,\n): Promise<TransactionSignature> {\n tokenProgramId = tokenProgramId\n ? tokenProgramId\n : await CompressedTokenProgram.getMintProgramId(mint, rpc);\n\n const ix = await CompressedTokenProgram.createTokenPool({\n feePayer: payer.publicKey,\n mint,\n tokenProgramId,\n });\n\n const { blockhash } = await rpc.getLatestBlockhash();\n\n const tx = buildAndSignTx([ix], payer, blockhash);\n\n const txId = await sendAndConfirmTx(rpc, tx, confirmOptions);\n\n return txId;\n}\n\n/**\n * @deprecated Use {@link createSplInterface} instead.\n */\nexport const createTokenPool = createSplInterface;\n\n/**\n * Create additional SPL interfaces for an existing mint\n *\n * @param rpc RPC connection to use\n * @param payer Fee payer\n * @param mint SPL Mint address\n * @param numMaxAdditionalPools Number of additional SPL interfaces to create. Max\n * 3.\n * @param confirmOptions Optional: Options for confirming the transaction\n * @param tokenProgramId Optional: Address of the token program. Default:\n * TOKEN_PROGRAM_ID\n *\n * @return transaction signature\n */\nexport async function addSplInterfaces(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n numMaxAdditionalPools: number,\n confirmOptions?: ConfirmOptions,\n tokenProgramId?: PublicKey,\n) {\n tokenProgramId = tokenProgramId\n ? tokenProgramId\n : await CompressedTokenProgram.getMintProgramId(mint, rpc);\n const instructions: TransactionInstruction[] = [];\n\n const infos = (await getSplInterfaceInfos(rpc, mint)).slice(0, 4);\n\n // Get indices of uninitialized interfaces\n const uninitializedIndices = [];\n for (let i = 0; i < infos.length; i++) {\n if (!infos[i].isInitialized) {\n uninitializedIndices.push(i);\n }\n }\n\n // Create instructions for requested number of interfaces\n for (let i = 0; i < numMaxAdditionalPools; i++) {\n if (i >= uninitializedIndices.length) {\n break;\n }\n\n instructions.push(\n await CompressedTokenProgram.addTokenPool({\n mint,\n feePayer: payer.publicKey,\n tokenProgramId,\n poolIndex: uninitializedIndices[i],\n }),\n );\n }\n const { blockhash } = await rpc.getLatestBlockhash();\n\n const tx = buildAndSignTx(instructions, payer, blockhash);\n\n const txId = await sendAndConfirmTx(rpc, tx, confirmOptions);\n\n return txId;\n}\n\n/**\n * @deprecated Use {@link addSplInterfaces} instead.\n */\nexport const addTokenPools = addSplInterfaces;\n","import { PublicKey, Signer, TransactionSignature } from '@solana/web3.js';\nimport {\n sendAndConfirmTx,\n buildAndSignTx,\n Rpc,\n dedupeSigner,\n} from '@lightprotocol/stateless.js';\n\nimport { CompressedTokenProgram } from '../program';\n\n/**\n * Create a lookup table for the token program's default accounts\n *\n * @param rpc Rpc connection to use\n * @param payer Fee payer\n * @param authority Authority of the lookup table\n * @param mints Optional array of mint public keys to include in\n * the lookup table\n * @param additionalAccounts Optional array of additional account public keys\n * to include in the lookup table\n *\n * @return Object with transaction signatures and the address of the created\n * lookup table\n */\nexport async function createTokenProgramLookupTable(\n rpc: Rpc,\n payer: Signer,\n authority: Signer,\n mints?: PublicKey[],\n additionalAccounts?: PublicKey[],\n): Promise<{ txIds: TransactionSignature[]; address: PublicKey }> {\n const recentSlot = await rpc.getSlot('finalized');\n const { instructions, address } =\n await CompressedTokenProgram.createTokenProgramLookupTable({\n payer: payer.publicKey,\n authority: authority.publicKey,\n mints,\n remainingAccounts: additionalAccounts,\n recentSlot,\n });\n\n const additionalSigners = dedupeSigner(payer, [authority]);\n const txIds = [];\n\n for (const instruction of instructions) {\n const blockhashCtx = await rpc.getLatestBlockhash();\n const signedTx = buildAndSignTx(\n [instruction],\n payer,\n blockhashCtx.blockhash,\n additionalSigners,\n );\n const txId = await sendAndConfirmTx(\n rpc,\n signedTx,\n { commitment: 'finalized' },\n blockhashCtx,\n );\n txIds.push(txId);\n }\n\n return { txIds, address };\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\nimport {\n bn,\n sendAndConfirmTx,\n buildAndSignTx,\n Rpc,\n dedupeSigner,\n} from '@lightprotocol/stateless.js';\nimport BN from 'bn.js';\nimport { CompressedTokenProgram } from '../program';\nimport { selectMinCompressedTokenAccountsForTransfer } from '../utils';\nimport {\n selectSplInterfaceInfosForDecompression,\n SplInterfaceInfo,\n getSplInterfaceInfos,\n} from '../utils/get-token-pool-infos';\n\n/**\n * Decompress compressed tokens\n *\n * @param rpc Rpc connection to use\n * @param payer Fee payer\n * @param mint SPL Mint address\n * @param amount Number of tokens to transfer\n * @param owner Owner of the compressed tokens\n * @param toAddress Destination **uncompressed** token account\n * address. (ATA)\n * @param splInterfaceInfos Optional: SPL interface infos.\n * @param confirmOptions Options for confirming the transaction\n *\n * @return confirmed transaction signature\n */\nexport async function decompress(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n amount: number | BN,\n owner: Signer,\n toAddress: PublicKey,\n splInterfaceInfos?: SplInterfaceInfo[],\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n amount = bn(amount);\n\n const compressedTokenAccounts = await rpc.getCompressedTokenAccountsByOwner(\n owner.publicKey,\n {\n mint,\n },\n );\n\n const [inputAccounts] = selectMinCompressedTokenAccountsForTransfer(\n compressedTokenAccounts.items,\n amount,\n );\n\n const proof = await rpc.getValidityProofV0(\n inputAccounts.map(account => ({\n hash: account.compressedAccount.hash,\n tree: account.compressedAccount.treeInfo.tree,\n queue: account.compressedAccount.treeInfo.queue,\n })),\n );\n\n splInterfaceInfos =\n splInterfaceInfos ?? (await getSplInterfaceInfos(rpc, mint));\n\n const selectedSplInterfaceInfos = selectSplInterfaceInfosForDecompression(\n splInterfaceInfos,\n amount,\n );\n\n const ix = await CompressedTokenProgram.decompress({\n payer: payer.publicKey,\n inputCompressedTokenAccounts: inputAccounts,\n toAddress,\n amount,\n tokenPoolInfos: selectedSplInterfaceInfos,\n recentInputStateRootIndices: proof.rootIndices,\n recentValidityProof: proof.compressedProof,\n });\n\n const { blockhash } = await rpc.getLatestBlockhash();\n const additionalSigners = dedupeSigner(payer, [owner]);\n const signedTx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 350_000 }), ix],\n payer,\n blockhash,\n additionalSigners,\n );\n return await sendAndConfirmTx(rpc, signedTx, confirmOptions);\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\nimport {\n Rpc,\n dedupeSigner,\n buildAndSignTx,\n sendAndConfirmTx,\n bn,\n} from '@lightprotocol/stateless.js';\nimport { CompressedTokenProgram } from '../program';\n\n/**\n * Merge multiple compressed token accounts for a given mint into a single\n * account\n *\n * @param rpc RPC connection to use\n * @param payer Fee payer\n * @param mint SPL Mint address\n * @param owner Owner of the token accounts to be merged\n * @param confirmOptions Options for confirming the transaction\n *\n * @return confirmed transaction signature\n */\nexport async function mergeTokenAccounts(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n owner: Signer,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n const compressedTokenAccounts = await rpc.getCompressedTokenAccountsByOwner(\n owner.publicKey,\n { mint },\n );\n\n if (compressedTokenAccounts.items.length === 0) {\n throw new Error(\n `No compressed token accounts found for mint ${mint.toBase58()}`,\n );\n }\n\n const instructions = [\n ComputeBudgetProgram.setComputeUnitLimit({ units: 1_000_000 }),\n ];\n\n for (\n let i = 0;\n i < compressedTokenAccounts.items.slice(0, 8).length;\n i += 4\n ) {\n const batch = compressedTokenAccounts.items.slice(i, i + 4);\n\n const proof = await rpc.getValidityProof(\n batch.map(account => bn(account.compressedAccount.hash)),\n );\n\n const batchInstructions =\n await CompressedTokenProgram.mergeTokenAccounts({\n payer: payer.publicKey,\n owner: owner.publicKey,\n inputCompressedTokenAccounts: batch,\n mint,\n recentValidityProof: proof.compressedProof,\n recentInputStateRootIndices: proof.rootIndices,\n });\n\n instructions.push(...batchInstructions);\n }\n\n const { blockhash } = await rpc.getLatestBlockhash();\n const additionalSigners = dedupeSigner(payer, [owner]);\n\n const signedTx = buildAndSignTx(\n instructions,\n payer,\n blockhash,\n additionalSigners,\n );\n\n return sendAndConfirmTx(rpc, signedTx, confirmOptions);\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\nimport BN from 'bn.js';\nimport {\n sendAndConfirmTx,\n buildAndSignTx,\n Rpc,\n dedupeSigner,\n selectStateTreeInfo,\n TreeInfo,\n} from '@lightprotocol/stateless.js';\nimport { CompressedTokenProgram } from '../program';\nimport {\n getSplInterfaceInfos,\n selectSplInterfaceInfo,\n SplInterfaceInfo,\n} from '../utils/get-token-pool-infos';\n\n/**\n * Mint compressed tokens to a solana address\n *\n * @param rpc Rpc connection to use\n * @param payer Fee payer\n * @param mint SPL Mint address\n * @param toPubkey Address of the account to mint to. Can be an\n * array of addresses if the amount is an array of\n * amounts.\n * @param authority Mint authority\n * @param amount Amount to mint. Pass an array of amounts if the\n * toPubkey is an array of addresses.\n * @param outputStateTreeInfo Optional: State tree account that the compressed\n * tokens should be part of. Defaults to the\n * default state tree account.\n * @param splInterfaceInfo Optional: SPL interface information\n * @param confirmOptions Options for confirming the transaction\n *\n * @return Signature of the confirmed transaction\n */\nexport async function mintTo(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n toPubkey: PublicKey | PublicKey[],\n authority: Signer,\n amount: number | BN | number[] | BN[],\n outputStateTreeInfo?: TreeInfo,\n splInterfaceInfo?: SplInterfaceInfo,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n outputStateTreeInfo =\n outputStateTreeInfo ??\n selectStateTreeInfo(await rpc.getStateTreeInfos());\n splInterfaceInfo =\n splInterfaceInfo ??\n selectSplInterfaceInfo(await getSplInterfaceInfos(rpc, mint));\n\n const ix = await CompressedTokenProgram.mintTo({\n feePayer: payer.publicKey,\n mint,\n authority: authority.publicKey,\n amount,\n toPubkey,\n outputStateTreeInfo,\n tokenPoolInfo: splInterfaceInfo,\n });\n\n const { blockhash } = await rpc.getLatestBlockhash();\n const additionalSigners = dedupeSigner(payer, [authority]);\n\n const tx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 1_000_000 }), ix],\n payer,\n blockhash,\n additionalSigners,\n );\n\n return sendAndConfirmTx(rpc, tx, confirmOptions);\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\nimport {\n sendAndConfirmTx,\n buildAndSignTx,\n Rpc,\n dedupeSigner,\n ParsedTokenAccount,\n} from '@lightprotocol/stateless.js';\nimport { CompressedTokenProgram } from '../program';\n\n/**\n * Revoke one or more delegated token accounts\n *\n * @param rpc Rpc connection to use\n * @param payer Fee payer\n * @param accounts Delegated compressed token accounts to revoke\n * @param owner Owner of the compressed tokens\n * @param confirmOptions Options for confirming the transaction\n *\n * @return Signature of the confirmed transaction\n */\nexport async function revoke(\n rpc: Rpc,\n payer: Signer,\n accounts: ParsedTokenAccount[],\n owner: Signer,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n const proof = await rpc.getValidityProofV0(\n accounts.map(account => ({\n hash: account.compressedAccount.hash,\n tree: account.compressedAccount.treeInfo.tree,\n queue: account.compressedAccount.treeInfo.queue,\n })),\n );\n checkOwner(owner, accounts);\n checkIsDelegated(accounts);\n\n const ix = await CompressedTokenProgram.revoke({\n payer: payer.publicKey,\n inputCompressedTokenAccounts: accounts,\n recentInputStateRootIndices: proof.rootIndices,\n recentValidityProof: proof.compressedProof,\n });\n\n const { blockhash } = await rpc.getLatestBlockhash();\n const additionalSigners = dedupeSigner(payer, [owner]);\n const signedTx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 500_000 }), ix],\n payer,\n blockhash,\n additionalSigners,\n );\n\n return sendAndConfirmTx(rpc, signedTx, confirmOptions);\n}\n\nfunction checkOwner(owner: Signer, accounts: ParsedTokenAccount[]) {\n if (!owner.publicKey.equals(accounts[0].parsed.owner)) {\n throw new Error(\n `Owner ${owner.publicKey.toBase58()} does not match account ${accounts[0].parsed.owner.toBase58()}`,\n );\n }\n}\n\nfunction checkIsDelegated(accounts: ParsedTokenAccount[]) {\n if (accounts.some(account => account.parsed.delegate === null)) {\n throw new Error('Account is not delegated');\n }\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\nimport {\n bn,\n sendAndConfirmTx,\n buildAndSignTx,\n Rpc,\n dedupeSigner,\n StateTreeInfo,\n selectStateTreeInfo,\n} from '@lightprotocol/stateless.js';\nimport BN from 'bn.js';\nimport { CompressedTokenProgram } from '../program';\nimport { selectMinCompressedTokenAccountsForTransfer } from '../utils';\n\n/**\n * Transfer compressed tokens from one owner to another\n *\n * @param rpc Rpc connection to use\n * @param payer Fee payer\n * @param mint SPL Mint address\n * @param amount Number of tokens to transfer\n * @param owner Owner of the compressed tokens\n * @param toAddress Destination address of the recipient\n * @param confirmOptions Options for confirming the transaction\n *\n * @return confirmed transaction signature\n */\nexport async function transfer(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n amount: number | BN,\n owner: Signer,\n toAddress: PublicKey,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n amount = bn(amount);\n const compressedTokenAccounts = await rpc.getCompressedTokenAccountsByOwner(\n owner.publicKey,\n {\n mint,\n },\n );\n\n const [inputAccounts] = selectMinCompressedTokenAccountsForTransfer(\n compressedTokenAccounts.items,\n amount,\n );\n\n const proof = await rpc.getValidityProofV0(\n inputAccounts.map(account => ({\n hash: account.compressedAccount.hash,\n tree: account.compressedAccount.treeInfo.tree,\n queue: account.compressedAccount.treeInfo.queue,\n })),\n );\n\n const ix = await CompressedTokenProgram.transfer({\n payer: payer.publicKey,\n inputCompressedTokenAccounts: inputAccounts,\n toAddress,\n amount,\n recentInputStateRootIndices: proof.rootIndices,\n recentValidityProof: proof.compressedProof,\n });\n\n const { blockhash } = await rpc.getLatestBlockhash();\n const additionalSigners = dedupeSigner(payer, [owner]);\n const signedTx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 500_000 }), ix],\n payer,\n blockhash,\n additionalSigners,\n );\n\n return sendAndConfirmTx(rpc, signedTx, confirmOptions);\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\nimport {\n bn,\n sendAndConfirmTx,\n buildAndSignTx,\n Rpc,\n dedupeSigner,\n} from '@lightprotocol/stateless.js';\nimport BN from 'bn.js';\nimport { CompressedTokenProgram } from '../program';\nimport { selectMinCompressedTokenAccountsForTransfer } from '../utils';\n\n/**\n * Transfer delegated compressed tokens to another owner\n *\n * @param rpc Rpc connection to use\n * @param payer Fee payer\n * @param mint SPL Mint address\n * @param amount Number of tokens to transfer\n * @param owner Owner of the compressed tokens\n * @param toAddress Destination address of the recipient\n * @param confirmOptions Options for confirming the transaction\n *\n * @return confirmed transaction signature\n */\nexport async function transferDelegated(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n amount: number | BN,\n owner: Signer,\n toAddress: PublicKey,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n amount = bn(amount);\n const compressedTokenAccounts =\n await rpc.getCompressedTokenAccountsByDelegate(owner.publicKey, {\n mint,\n });\n\n const [inputAccounts] = selectMinCompressedTokenAccountsForTransfer(\n compressedTokenAccounts.items,\n amount,\n );\n\n const proof = await rpc.getValidityProofV0(\n inputAccounts.map(account => ({\n hash: account.compressedAccount.hash,\n tree: account.compressedAccount.treeInfo.tree,\n queue: account.compressedAccount.treeInfo.queue,\n })),\n );\n\n const ix = await CompressedTokenProgram.transfer({\n payer: payer.publicKey,\n inputCompressedTokenAccounts: inputAccounts,\n toAddress,\n amount,\n recentInputStateRootIndices: proof.rootIndices,\n recentValidityProof: proof.compressedProof,\n });\n\n const { blockhash } = await rpc.getLatestBlockhash();\n const additionalSigners = dedupeSigner(payer, [owner]);\n const signedTx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 500_000 }), ix],\n payer,\n blockhash,\n additionalSigners,\n );\n\n return sendAndConfirmTx(rpc, signedTx, confirmOptions);\n}\n","import {\n ComputeBudgetProgram,\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\nimport {\n bn,\n sendAndConfirmTx,\n buildAndSignTx,\n Rpc,\n dedupeSigner,\n} from '@lightprotocol/stateless.js';\n\nimport BN from 'bn.js';\n\nimport { CompressedTokenProgram } from '../program';\nimport { selectMinCompressedTokenAccountsForTransfer } from '../utils';\nimport {\n selectSplInterfaceInfosForDecompression,\n SplInterfaceInfo,\n getSplInterfaceInfos,\n} from '../utils/get-token-pool-infos';\n\n/**\n * Decompress delegated compressed tokens. Remaining compressed tokens are\n * returned to the owner without delegation.\n *\n * @param rpc Rpc connection to use\n * @param payer Fee payer\n * @param mint SPL Mint address\n * @param amount Number of tokens to decompress\n * @param owner Owner of the compressed tokens\n * @param toAddress Destination **uncompressed** token account\n * address. (ATA)\n * @param splInterfaceInfos Optional: SPL interface infos.\n * @param confirmOptions Options for confirming the transaction\n *\n * @return Signature of the confirmed transaction\n */\nexport async function decompressDelegated(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n amount: number | BN,\n owner: Signer,\n toAddress: PublicKey,\n splInterfaceInfos?: SplInterfaceInfo[],\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n amount = bn(amount);\n\n const compressedTokenAccounts =\n await rpc.getCompressedTokenAccountsByDelegate(owner.publicKey, {\n mint,\n });\n\n const [inputAccounts] = selectMinCompressedTokenAccountsForTransfer(\n compressedTokenAccounts.items,\n amount,\n );\n\n const proof = await rpc.getValidityProofV0(\n inputAccounts.map(account => ({\n hash: account.compressedAccount.hash,\n tree: account.compressedAccount.treeInfo.tree,\n queue: account.compressedAccount.treeInfo.queue,\n })),\n );\n\n const splInterfaceInfosToUse =\n splInterfaceInfos ??\n selectSplInterfaceInfosForDecompression(\n await getSplInterfaceInfos(rpc, mint),\n amount,\n );\n\n const ix = await CompressedTokenProgram.decompress({\n payer: payer.publicKey,\n inputCompressedTokenAccounts: inputAccounts,\n toAddress,\n amount,\n recentInputStateRootIndices: proof.rootIndices,\n recentValidityProof: proof.compressedProof,\n tokenPoolInfos: splInterfaceInfosToUse,\n });\n\n const { blockhash } = await rpc.getLatestBlockhash();\n const additionalSigners = dedupeSigner(payer, [owner]);\n const signedTx = buildAndSignTx(\n [ComputeBudgetProgram.setComputeUnitLimit({ units: 350_000 }), ix],\n payer,\n blockhash,\n additionalSigners,\n );\n\n return sendAndConfirmTx(rpc, signedTx, confirmOptions);\n}\n","export type LightCompressedToken = {\n version: '1.2.0';\n name: 'light_compressed_token';\n instructions: [\n {\n name: 'createTokenPool';\n docs: [\n 'This instruction creates a token pool for a given mint. Every spl mint',\n 'can have one token pool. When a token is compressed the tokens are',\n 'transferrred to the token pool, and their compressed equivalent is',\n 'minted into a Merkle tree.',\n ];\n accounts: [\n {\n name: 'feePayer';\n isMut: true;\n isSigner: true;\n docs: ['UNCHECKED: only pays fees.'];\n },\n {\n name: 'tokenPoolPda';\n isMut: true;\n isSigner: false;\n },\n {\n name: 'systemProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'mint';\n isMut: true;\n isSigner: false;\n },\n {\n name: 'tokenProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'cpiAuthorityPda';\n isMut: false;\n isSigner: false;\n },\n ];\n args: [];\n },\n {\n name: 'addTokenPool';\n docs: [\n 'This instruction creates an additional token pool for a given mint.',\n 'The maximum number of token pools per mint is 5.',\n ];\n accounts: [\n {\n name: 'feePayer';\n isMut: true;\n isSigner: true;\n docs: ['UNCHECKED: only pays fees.'];\n },\n {\n name: 'tokenPoolPda';\n isMut: true;\n isSigner: false;\n },\n {\n name: 'existingTokenPoolPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'systemProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'mint';\n isMut: true;\n isSigner: false;\n },\n {\n name: 'tokenProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'cpiAuthorityPda';\n isMut: false;\n isSigner: false;\n },\n ];\n args: [\n {\n name: 'tokenPoolIndex';\n type: 'u8';\n },\n ];\n },\n {\n name: 'mintTo';\n docs: [\n 'Mints tokens from an spl token mint to a list of compressed accounts.',\n 'Minted tokens are transferred to a pool account owned by the compressed',\n 'token program. The instruction creates one compressed output account for',\n 'every amount and pubkey input pair. A constant amount of lamports can be',\n 'transferred to each output account to enable. A use case to add lamports',\n 'to a compressed token account is to prevent spam. This is the only way',\n 'to add lamports to a compressed token account.',\n ];\n accounts: [\n {\n name: 'feePayer';\n isMut: true;\n isSigner: true;\n docs: ['UNCHECKED: only pays fees.'];\n },\n {\n name: 'authority';\n isMut: false;\n isSigner: true;\n },\n {\n name: 'cpiAuthorityPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'mint';\n isMut: true;\n isSigner: false;\n },\n {\n name: 'tokenPoolPda';\n isMut: true;\n isSigner: false;\n },\n {\n name: 'tokenProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'lightSystemProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'registeredProgramPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'noopProgram';\n isMut: false;\n isSigner: false;\n docs: ['programs'];\n },\n {\n name: 'accountCompressionAuthority';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'merkleTree';\n isMut: true;\n isSigner: false;\n },\n {\n name: 'selfProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'systemProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'solPoolPda';\n isMut: true;\n isSigner: false;\n isOptional: true;\n },\n ];\n args: [\n {\n name: 'publicKeys';\n type: {\n vec: 'publicKey';\n };\n },\n {\n name: 'amounts';\n type: {\n vec: 'u64';\n };\n },\n {\n name: 'lamports';\n type: {\n option: 'u64';\n };\n },\n ];\n },\n {\n name: 'compressSplTokenAccount';\n docs: [\n 'Compresses the balance of an spl token account sub an optional remaining',\n 'amount. This instruction does not close the spl token account. To close',\n 'the account bundle a close spl account instruction in your transaction.',\n ];\n accounts: [\n {\n name: 'feePayer';\n isMut: true;\n isSigner: true;\n docs: ['UNCHECKED: only pays fees.'];\n },\n {\n name: 'authority';\n isMut: false;\n isSigner: true;\n docs: [\n 'Authority is verified through proof since both owner and delegate',\n 'are included in the token data hash, which is a public input to the',\n 'validity proof.',\n ];\n },\n {\n name: 'cpiAuthorityPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'lightSystemProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'registeredProgramPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'noopProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionAuthority';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'selfProgram';\n isMut: false;\n isSigner: false;\n docs: ['this program is the signer of the cpi.'];\n },\n {\n name: 'tokenPoolPda';\n isMut: true;\n isSigner: false;\n isOptional: true;\n },\n {\n name: 'compressOrDecompressTokenAccount';\n isMut: true;\n isSigner: false;\n isOptional: true;\n },\n {\n name: 'tokenProgram';\n isMut: false;\n isSigner: false;\n isOptional: true;\n },\n {\n name: 'systemProgram';\n isMut: false;\n isSigner: false;\n },\n ];\n args: [\n {\n name: 'owner';\n type: 'publicKey';\n },\n {\n name: 'remainingAmount';\n type: {\n option: 'u64';\n };\n },\n {\n name: 'cpiContext';\n type: {\n option: {\n defined: 'CompressedCpiContext';\n };\n };\n },\n ];\n },\n {\n name: 'transfer';\n docs: [\n 'Transfers compressed tokens from one account to another. All accounts',\n 'must be of the same mint. Additional spl tokens can be compressed or',\n 'decompressed. In one transaction only compression or decompression is',\n 'possible. Lamports can be transferred alongside tokens. If output token',\n 'accounts specify less lamports than inputs the remaining lamports are',\n 'transferred to an output compressed account. Signer must be owner or',\n 'delegate. If a delegated token account is transferred the delegate is',\n 'not preserved.',\n ];\n accounts: [\n {\n name: 'feePayer';\n isMut: true;\n isSigner: true;\n docs: ['UNCHECKED: only pays fees.'];\n },\n {\n name: 'authority';\n isMut: false;\n isSigner: true;\n docs: [\n 'Authority is verified through proof since both owner and delegate',\n 'are included in the token data hash, which is a public input to the',\n 'validity proof.',\n ];\n },\n {\n name: 'cpiAuthorityPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'lightSystemProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'registeredProgramPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'noopProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionAuthority';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'selfProgram';\n isMut: false;\n isSigner: false;\n docs: ['this program is the signer of the cpi.'];\n },\n {\n name: 'tokenPoolPda';\n isMut: true;\n isSigner: false;\n isOptional: true;\n },\n {\n name: 'compressOrDecompressTokenAccount';\n isMut: true;\n isSigner: false;\n isOptional: true;\n },\n {\n name: 'tokenProgram';\n isMut: false;\n isSigner: false;\n isOptional: true;\n },\n {\n name: 'systemProgram';\n isMut: false;\n isSigner: false;\n },\n ];\n args: [\n {\n name: 'inputs';\n type: 'bytes';\n },\n ];\n },\n {\n name: 'approve';\n docs: [\n 'Delegates an amount to a delegate. A compressed token account is either',\n 'completely delegated or not. Prior delegates are not preserved. Cannot',\n 'be called by a delegate.',\n 'The instruction creates two output accounts:',\n '1. one account with delegated amount',\n '2. one account with remaining(change) amount',\n ];\n accounts: [\n {\n name: 'feePayer';\n isMut: true;\n isSigner: true;\n docs: ['UNCHECKED: only pays fees.'];\n },\n {\n name: 'authority';\n isMut: false;\n isSigner: true;\n docs: [\n 'Authority is verified through proof since both owner and delegate',\n 'are included in the token data hash, which is a public input to the',\n 'validity proof.',\n ];\n },\n {\n name: 'cpiAuthorityPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'lightSystemProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'registeredProgramPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'noopProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionAuthority';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'selfProgram';\n isMut: false;\n isSigner: false;\n docs: ['this program is the signer of the cpi.'];\n },\n {\n name: 'systemProgram';\n isMut: false;\n isSigner: false;\n },\n ];\n args: [\n {\n name: 'inputs';\n type: 'bytes';\n },\n ];\n },\n {\n name: 'revoke';\n docs: [\n 'Revokes a delegation. The instruction merges all inputs into one output',\n 'account. Cannot be called by a delegate. Delegates are not preserved.',\n ];\n accounts: [\n {\n name: 'feePayer';\n isMut: true;\n isSigner: true;\n docs: ['UNCHECKED: only pays fees.'];\n },\n {\n name: 'authority';\n isMut: false;\n isSigner: true;\n docs: [\n 'Authority is verified through proof since both owner and delegate',\n 'are included in the token data hash, which is a public input to the',\n 'validity proof.',\n ];\n },\n {\n name: 'cpiAuthorityPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'lightSystemProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'registeredProgramPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'noopProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionAuthority';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'selfProgram';\n isMut: false;\n isSigner: false;\n docs: ['this program is the signer of the cpi.'];\n },\n {\n name: 'systemProgram';\n isMut: false;\n isSigner: false;\n },\n ];\n args: [\n {\n name: 'inputs';\n type: 'bytes';\n },\n ];\n },\n {\n name: 'freeze';\n docs: [\n 'Freezes compressed token accounts. Inputs must not be frozen. Creates as',\n 'many outputs as inputs. Balances and delegates are preserved.',\n ];\n accounts: [\n {\n name: 'feePayer';\n isMut: true;\n isSigner: true;\n docs: ['UNCHECKED: only pays fees.'];\n },\n {\n name: 'authority';\n isMut: false;\n isSigner: true;\n },\n {\n name: 'cpiAuthorityPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'lightSystemProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'registeredProgramPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'noopProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionAuthority';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'selfProgram';\n isMut: false;\n isSigner: false;\n docs: ['that this program is the signer of the cpi.'];\n },\n {\n name: 'systemProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'mint';\n isMut: false;\n isSigner: false;\n },\n ];\n args: [\n {\n name: 'inputs';\n type: 'bytes';\n },\n ];\n },\n {\n name: 'thaw';\n docs: [\n 'Thaws frozen compressed token accounts. Inputs must be frozen. Creates',\n 'as many outputs as inputs. Balances and delegates are preserved.',\n ];\n accounts: [\n {\n name: 'feePayer';\n isMut: true;\n isSigner: true;\n docs: ['UNCHECKED: only pays fees.'];\n },\n {\n name: 'authority';\n isMut: false;\n isSigner: true;\n },\n {\n name: 'cpiAuthorityPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'lightSystemProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'registeredProgramPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'noopProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionAuthority';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'selfProgram';\n isMut: false;\n isSigner: false;\n docs: ['that this program is the signer of the cpi.'];\n },\n {\n name: 'systemProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'mint';\n isMut: false;\n isSigner: false;\n },\n ];\n args: [\n {\n name: 'inputs';\n type: 'bytes';\n },\n ];\n },\n {\n name: 'burn';\n docs: [\n 'Burns compressed tokens and spl tokens from the pool account. Delegates',\n 'can burn tokens. The output compressed token account remains delegated.',\n 'Creates one output compressed token account.',\n ];\n accounts: [\n {\n name: 'feePayer';\n isMut: true;\n isSigner: true;\n docs: ['UNCHECKED: only pays fees.'];\n },\n {\n name: 'authority';\n isMut: false;\n isSigner: true;\n docs: [\n 'Authority is verified through proof since both owner and delegate',\n 'are included in the token data hash, which is a public input to the',\n 'validity proof.',\n ];\n },\n {\n name: 'cpiAuthorityPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'mint';\n isMut: true;\n isSigner: false;\n },\n {\n name: 'tokenPoolPda';\n isMut: true;\n isSigner: false;\n },\n {\n name: 'tokenProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'lightSystemProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'registeredProgramPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'noopProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionAuthority';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'selfProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'systemProgram';\n isMut: false;\n isSigner: false;\n },\n ];\n args: [\n {\n name: 'inputs';\n type: 'bytes';\n },\n ];\n },\n {\n name: 'stubIdlBuild';\n docs: [\n 'This function is a stub to allow Anchor to include the input types in',\n 'the IDL. It should not be included in production builds nor be called in',\n 'practice.',\n ];\n accounts: [\n {\n name: 'feePayer';\n isMut: true;\n isSigner: true;\n docs: ['UNCHECKED: only pays fees.'];\n },\n {\n name: 'authority';\n isMut: false;\n isSigner: true;\n docs: [\n 'Authority is verified through proof since both owner and delegate',\n 'are included in the token data hash, which is a public input to the',\n 'validity proof.',\n ];\n },\n {\n name: 'cpiAuthorityPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'lightSystemProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'registeredProgramPda';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'noopProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionAuthority';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'accountCompressionProgram';\n isMut: false;\n isSigner: false;\n },\n {\n name: 'selfProgram';\n isMut: false;\n isSigner: false;\n docs: ['this program is the signer of the cpi.'];\n },\n {\n name: 'tokenPoolPda';\n isMut: true;\n isSigner: false;\n isOptional: true;\n },\n {\n name: 'compressOrDecompressTokenAccount';\n isMut: true;\n isSigner: false;\n isOptional: true;\n },\n {\n name: 'tokenProgram';\n isMut: false;\n isSigner: false;\n isOptional: true;\n },\n {\n name: 'systemProgram';\n isMut: false;\n isSigner: false;\n },\n ];\n args: [\n {\n name: 'inputs1';\n type: {\n defined: 'CompressedTokenInstructionDataTransfer';\n };\n },\n {\n name: 'inputs2';\n type: {\n defined: 'TokenData';\n };\n },\n ];\n },\n ];\n types: [\n {\n name: 'AccountState';\n type: {\n kind: 'enum';\n variants: [\n {\n name: 'Initialized';\n },\n {\n name: 'Frozen';\n },\n ];\n };\n },\n {\n name: 'CompressedAccount';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'owner';\n type: 'publicKey';\n },\n {\n name: 'lamports';\n type: 'u64';\n },\n {\n name: 'address';\n type: {\n option: {\n array: ['u8', 32];\n };\n };\n },\n {\n name: 'data';\n type: {\n option: {\n defined: 'CompressedAccountData';\n };\n };\n },\n ];\n };\n },\n {\n name: 'CompressedAccountData';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'discriminator';\n type: {\n array: ['u8', 8];\n };\n },\n {\n name: 'data';\n type: 'bytes';\n },\n {\n name: 'dataHash';\n type: {\n array: ['u8', 32];\n };\n },\n ];\n };\n },\n {\n name: 'CompressedCpiContext';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'setContext';\n docs: [\n 'Is set by the program that is invoking the CPI to signal that is should',\n 'set the cpi context.',\n ];\n type: 'bool';\n },\n {\n name: 'firstSetContext';\n docs: [\n 'Is set to wipe the cpi context since someone could have set it before',\n 'with unrelated data.',\n ];\n type: 'bool';\n },\n {\n name: 'cpiContextAccountIndex';\n docs: [\n 'Index of cpi context account in remaining accounts.',\n ];\n type: 'u8';\n },\n ];\n };\n },\n {\n name: 'CompressedProof';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'a';\n type: {\n array: ['u8', 32];\n };\n },\n {\n name: 'b';\n type: {\n array: ['u8', 64];\n };\n },\n {\n name: 'c';\n type: {\n array: ['u8', 32];\n };\n },\n ];\n };\n },\n {\n name: 'CompressedTokenInstructionDataTransfer';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'proof';\n type: {\n option: {\n defined: 'CompressedProof';\n };\n };\n },\n {\n name: 'mint';\n type: 'publicKey';\n },\n {\n name: 'delegatedTransfer';\n docs: [\n 'Is required if the signer is delegate,',\n '-> delegate is authority account,',\n 'owner = Some(owner) is the owner of the token account.',\n ];\n type: {\n option: {\n defined: 'DelegatedTransfer';\n };\n };\n },\n {\n name: 'inputTokenDataWithContext';\n type: {\n vec: {\n defined: 'InputTokenDataWithContext';\n };\n };\n },\n {\n name: 'outputCompressedAccounts';\n type: {\n vec: {\n defined: 'PackedTokenTransferOutputData';\n };\n };\n },\n {\n name: 'isCompress';\n type: 'bool';\n },\n {\n name: 'compressOrDecompressAmount';\n type: {\n option: 'u64';\n };\n },\n {\n name: 'cpiContext';\n type: {\n option: {\n defined: 'CompressedCpiContext';\n };\n };\n },\n {\n name: 'lamportsChangeAccountMerkleTreeIndex';\n type: {\n option: 'u8';\n };\n },\n ];\n };\n },\n {\n name: 'CompressedTokenInstructionDataRevoke';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'proof';\n type: {\n option: {\n defined: 'CompressedProof';\n };\n };\n },\n {\n name: 'mint';\n type: 'publicKey';\n },\n {\n name: 'inputTokenDataWithContext';\n type: {\n vec: {\n defined: 'InputTokenDataWithContext';\n };\n };\n },\n {\n name: 'cpiContext';\n type: {\n option: {\n defined: 'CompressedCpiContext';\n };\n };\n },\n {\n name: 'outputAccountMerkleTreeIndex';\n type: 'u8';\n },\n ];\n };\n },\n {\n name: 'CompressedTokenInstructionDataApprove';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'proof';\n type: {\n option: {\n defined: 'CompressedProof';\n };\n };\n },\n {\n name: 'mint';\n type: 'publicKey';\n },\n {\n name: 'inputTokenDataWithContext';\n type: {\n vec: {\n defined: 'InputTokenDataWithContext';\n };\n };\n },\n {\n name: 'cpiContext';\n type: {\n option: {\n defined: 'CompressedCpiContext';\n };\n };\n },\n {\n name: 'delegate';\n type: 'publicKey';\n },\n {\n name: 'delegatedAmount';\n type: 'u64';\n },\n {\n name: 'delegateMerkleTreeIndex';\n type: 'u8';\n },\n {\n name: 'changeAccountMerkleTreeIndex';\n type: 'u8';\n },\n {\n name: 'delegateLamports';\n type: {\n option: 'u64';\n };\n },\n ];\n };\n },\n {\n name: 'DelegatedTransfer';\n docs: [\n 'Struct to provide the owner when the delegate is signer of the transaction.',\n ];\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'owner';\n type: 'publicKey';\n },\n {\n name: 'delegateChangeAccountIndex';\n docs: [\n 'Index of change compressed account in output compressed accounts. In',\n \"case that the delegate didn't spend the complete delegated compressed\",\n 'account balance the change compressed account will be delegated to her',\n 'as well.',\n ];\n type: {\n option: 'u8';\n };\n },\n ];\n };\n },\n {\n name: 'InputTokenDataWithContext';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'amount';\n type: 'u64';\n },\n {\n name: 'delegateIndex';\n type: {\n option: 'u8';\n };\n },\n {\n name: 'merkleContext';\n type: {\n defined: 'PackedMerkleContext';\n };\n },\n {\n name: 'rootIndex';\n type: 'u16';\n },\n {\n name: 'lamports';\n type: {\n option: 'u64';\n };\n },\n {\n name: 'tlv';\n docs: [\n 'Placeholder for TokenExtension tlv data (unimplemented)',\n ];\n type: {\n option: 'bytes';\n };\n },\n ];\n };\n },\n {\n name: 'InstructionDataInvoke';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'proof';\n type: {\n option: {\n defined: 'CompressedProof';\n };\n };\n },\n {\n name: 'inputCompressedAccountsWithMerkleContext';\n type: {\n vec: {\n defined: 'PackedCompressedAccountWithMerkleContext';\n };\n };\n },\n {\n name: 'outputCompressedAccounts';\n type: {\n vec: {\n defined: 'OutputCompressedAccountWithPackedContext';\n };\n };\n },\n {\n name: 'relayFee';\n type: {\n option: 'u64';\n };\n },\n {\n name: 'newAddressParams';\n type: {\n vec: {\n defined: 'NewAddressParamsPacked';\n };\n };\n },\n {\n name: 'compressOrDecompressLamports';\n type: {\n option: 'u64';\n };\n },\n {\n name: 'isCompress';\n type: 'bool';\n },\n ];\n };\n },\n {\n name: 'InstructionDataInvokeCpi';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'proof';\n type: {\n option: {\n defined: 'CompressedProof';\n };\n };\n },\n {\n name: 'newAddressParams';\n type: {\n vec: {\n defined: 'NewAddressParamsPacked';\n };\n };\n },\n {\n name: 'inputCompressedAccountsWithMerkleContext';\n type: {\n vec: {\n defined: 'PackedCompressedAccountWithMerkleContext';\n };\n };\n },\n {\n name: 'outputCompressedAccounts';\n type: {\n vec: {\n defined: 'OutputCompressedAccountWithPackedContext';\n };\n };\n },\n {\n name: 'relayFee';\n type: {\n option: 'u64';\n };\n },\n {\n name: 'compressOrDecompressLamports';\n type: {\n option: 'u64';\n };\n },\n {\n name: 'isCompress';\n type: 'bool';\n },\n {\n name: 'cpiContext';\n type: {\n option: {\n defined: 'CompressedCpiContext';\n };\n };\n },\n ];\n };\n },\n {\n name: 'MerkleTreeSequenceNumber';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'pubkey';\n type: 'publicKey';\n },\n {\n name: 'seq';\n type: 'u64';\n },\n ];\n };\n },\n {\n name: 'NewAddressParamsPacked';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'seed';\n type: {\n array: ['u8', 32];\n };\n },\n {\n name: 'addressQueueAccountIndex';\n type: 'u8';\n },\n {\n name: 'addressMerkleTreeAccountIndex';\n type: 'u8';\n },\n {\n name: 'addressMerkleTreeRootIndex';\n type: 'u16';\n },\n ];\n };\n },\n {\n name: 'OutputCompressedAccountWithPackedContext';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'compressedAccount';\n type: {\n defined: 'CompressedAccount';\n };\n },\n {\n name: 'merkleTreeIndex';\n type: 'u8';\n },\n ];\n };\n },\n {\n name: 'PackedCompressedAccountWithMerkleContext';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'compressedAccount';\n type: {\n defined: 'CompressedAccount';\n };\n },\n {\n name: 'merkleContext';\n type: {\n defined: 'PackedMerkleContext';\n };\n },\n {\n name: 'rootIndex';\n docs: [\n 'Index of root used in inclusion validity proof.',\n ];\n type: 'u16';\n },\n {\n name: 'readOnly';\n docs: [\n 'Placeholder to mark accounts read-only unimplemented set to false.',\n ];\n type: 'bool';\n },\n ];\n };\n },\n {\n name: 'PackedMerkleContext';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'merkleTreePubkeyIndex';\n type: 'u8';\n },\n {\n name: 'queuePubkeyIndex';\n type: 'u8';\n },\n {\n name: 'leafIndex';\n type: 'u32';\n },\n {\n name: 'proveByIndex';\n type: 'bool';\n },\n ];\n };\n },\n {\n name: 'PackedTokenTransferOutputData';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'owner';\n type: 'publicKey';\n },\n {\n name: 'amount';\n type: 'u64';\n },\n {\n name: 'lamports';\n type: {\n option: 'u64';\n };\n },\n {\n name: 'merkleTreeIndex';\n type: 'u8';\n },\n {\n name: 'tlv';\n docs: [\n 'Placeholder for TokenExtension tlv data (unimplemented)',\n ];\n type: {\n option: 'bytes';\n };\n },\n ];\n };\n },\n {\n name: 'PublicTransactionEvent';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'inputCompressedAccountHashes';\n type: {\n vec: {\n array: ['u8', 32];\n };\n };\n },\n {\n name: 'outputCompressedAccountHashes';\n type: {\n vec: {\n array: ['u8', 32];\n };\n };\n },\n {\n name: 'outputCompressedAccounts';\n type: {\n vec: {\n defined: 'OutputCompressedAccountWithPackedContext';\n };\n };\n },\n {\n name: 'outputLeafIndices';\n type: {\n vec: 'u32';\n };\n },\n {\n name: 'sequenceNumbers';\n type: {\n vec: {\n defined: 'MerkleTreeSequenceNumber';\n };\n };\n },\n {\n name: 'relayFee';\n type: {\n option: 'u64';\n };\n },\n {\n name: 'isCompress';\n type: 'bool';\n },\n {\n name: 'compressOrDecompressLamports';\n type: {\n option: 'u64';\n };\n },\n {\n name: 'pubkeyArray';\n type: {\n vec: 'publicKey';\n };\n },\n {\n name: 'message';\n type: {\n option: 'bytes';\n };\n },\n ];\n };\n },\n {\n name: 'QueueIndex';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'queueId';\n docs: ['Id of queue in queue account.'];\n type: 'u8';\n },\n {\n name: 'index';\n docs: ['Index of compressed account hash in queue.'];\n type: 'u16';\n },\n ];\n };\n },\n {\n name: 'TokenData';\n type: {\n kind: 'struct';\n fields: [\n {\n name: 'mint';\n docs: ['The mint associated with this account'];\n type: 'publicKey';\n },\n {\n name: 'owner';\n docs: ['The owner of this account.'];\n type: 'publicKey';\n },\n {\n name: 'amount';\n docs: ['The amount of tokens this account holds.'];\n type: 'u64';\n },\n {\n name: 'delegate';\n docs: [\n 'If `delegate` is `Some` then `delegated_amount` represents',\n 'the amount authorized by the delegate',\n ];\n type: {\n option: 'publicKey';\n };\n },\n {\n name: 'state';\n docs: [\"The account's state\"];\n type: {\n defined: 'AccountState';\n };\n },\n {\n name: 'tlv';\n docs: [\n 'Placeholder for TokenExtension tlv data (unimplemented)',\n ];\n type: {\n option: 'bytes';\n };\n },\n ];\n };\n },\n ];\n errors: [\n {\n code: 6000;\n name: 'PublicKeyAmountMissmatch';\n msg: 'public keys and amounts must be of same length';\n },\n {\n code: 6001;\n name: 'ComputeInputSumFailed';\n msg: 'ComputeInputSumFailed';\n },\n {\n code: 6002;\n name: 'ComputeOutputSumFailed';\n msg: 'ComputeOutputSumFailed';\n },\n {\n code: 6003;\n name: 'ComputeCompressSumFailed';\n msg: 'ComputeCompressSumFailed';\n },\n {\n code: 6004;\n name: 'ComputeDecompressSumFailed';\n msg: 'ComputeDecompressSumFailed';\n },\n {\n code: 6005;\n name: 'SumCheckFailed';\n msg: 'SumCheckFailed';\n },\n {\n code: 6006;\n name: 'DecompressRecipientUndefinedForDecompress';\n msg: 'DecompressRecipientUndefinedForDecompress';\n },\n {\n code: 6007;\n name: 'CompressedPdaUndefinedForDecompress';\n msg: 'CompressedPdaUndefinedForDecompress';\n },\n {\n code: 6008;\n name: 'DeCompressAmountUndefinedForDecompress';\n msg: 'DeCompressAmountUndefinedForDecompress';\n },\n {\n code: 6009;\n name: 'CompressedPdaUndefinedForCompress';\n msg: 'CompressedPdaUndefinedForCompress';\n },\n {\n code: 6010;\n name: 'DeCompressAmountUndefinedForCompress';\n msg: 'DeCompressAmountUndefinedForCompress';\n },\n {\n code: 6011;\n name: 'DelegateSignerCheckFailed';\n msg: 'DelegateSignerCheckFailed';\n },\n {\n code: 6012;\n name: 'MintTooLarge';\n msg: 'Minted amount greater than u64::MAX';\n },\n {\n code: 6013;\n name: 'SplTokenSupplyMismatch';\n msg: 'SplTokenSupplyMismatch';\n },\n {\n code: 6014;\n name: 'HeapMemoryCheckFailed';\n msg: 'HeapMemoryCheckFailed';\n },\n {\n code: 6015;\n name: 'InstructionNotCallable';\n msg: 'The instruction is not callable';\n },\n {\n code: 6016;\n name: 'ArithmeticUnderflow';\n msg: 'ArithmeticUnderflow';\n },\n {\n code: 6017;\n name: 'HashToFieldError';\n msg: 'HashToFieldError';\n },\n {\n code: 6018;\n name: 'InvalidAuthorityMint';\n msg: 'Expected the authority to be also a mint authority';\n },\n {\n code: 6019;\n name: 'InvalidFreezeAuthority';\n msg: 'Provided authority is not the freeze authority';\n },\n {\n code: 6020;\n name: 'InvalidDelegateIndex';\n },\n {\n code: 6021;\n name: 'TokenPoolPdaUndefined';\n },\n {\n code: 6022;\n name: 'IsTokenPoolPda';\n msg: 'Compress or decompress recipient is the same account as the token pool pda.';\n },\n {\n code: 6023;\n name: 'InvalidTokenPoolPda';\n },\n {\n code: 6024;\n name: 'NoInputTokenAccountsProvided';\n },\n {\n code: 6025;\n name: 'NoInputsProvided';\n },\n {\n code: 6026;\n name: 'MintHasNoFreezeAuthority';\n },\n {\n code: 6027;\n name: 'MintWithInvalidExtension';\n },\n {\n code: 6028;\n name: 'InsufficientTokenAccountBalance';\n msg: 'The token account balance is less than the remaining amount.';\n },\n {\n code: 6029;\n name: 'InvalidTokenPoolBump';\n msg: 'Max number of token pools reached.';\n },\n {\n code: 6030;\n name: 'FailedToDecompress';\n },\n {\n code: 6031;\n name: 'FailedToBurnSplTokensFromTokenPool';\n },\n {\n code: 6032;\n name: 'NoMatchingBumpFound';\n },\n ];\n};\nexport const IDL: LightCompressedToken = {\n version: '1.2.0',\n name: 'light_compressed_token',\n instructions: [\n {\n name: 'createTokenPool',\n docs: [\n 'This instruction creates a token pool for a given mint. Every spl mint',\n 'can have one token pool. When a token is compressed the tokens are',\n 'transferrred to the token pool, and their compressed equivalent is',\n 'minted into a Merkle tree.',\n ],\n accounts: [\n {\n name: 'feePayer',\n isMut: true,\n isSigner: true,\n docs: ['UNCHECKED: only pays fees.'],\n },\n {\n name: 'tokenPoolPda',\n isMut: true,\n isSigner: false,\n },\n {\n name: 'systemProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'mint',\n isMut: true,\n isSigner: false,\n },\n {\n name: 'tokenProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'cpiAuthorityPda',\n isMut: false,\n isSigner: false,\n },\n ],\n args: [],\n },\n {\n name: 'addTokenPool',\n docs: [\n 'This instruction creates an additional token pool for a given mint.',\n 'The maximum number of token pools per mint is 5.',\n ],\n accounts: [\n {\n name: 'feePayer',\n isMut: true,\n isSigner: true,\n docs: ['UNCHECKED: only pays fees.'],\n },\n {\n name: 'tokenPoolPda',\n isMut: true,\n isSigner: false,\n },\n {\n name: 'existingTokenPoolPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'systemProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'mint',\n isMut: true,\n isSigner: false,\n },\n {\n name: 'tokenProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'cpiAuthorityPda',\n isMut: false,\n isSigner: false,\n },\n ],\n args: [\n {\n name: 'tokenPoolIndex',\n type: 'u8',\n },\n ],\n },\n {\n name: 'mintTo',\n docs: [\n 'Mints tokens from an spl token mint to a list of compressed accounts.',\n 'Minted tokens are transferred to a pool account owned by the compressed',\n 'token program. The instruction creates one compressed output account for',\n 'every amount and pubkey input pair. A constant amount of lamports can be',\n 'transferred to each output account to enable. A use case to add lamports',\n 'to a compressed token account is to prevent spam. This is the only way',\n 'to add lamports to a compressed token account.',\n ],\n accounts: [\n {\n name: 'feePayer',\n isMut: true,\n isSigner: true,\n docs: ['UNCHECKED: only pays fees.'],\n },\n {\n name: 'authority',\n isMut: false,\n isSigner: true,\n },\n {\n name: 'cpiAuthorityPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'mint',\n isMut: true,\n isSigner: false,\n },\n {\n name: 'tokenPoolPda',\n isMut: true,\n isSigner: false,\n },\n {\n name: 'tokenProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'lightSystemProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'registeredProgramPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'noopProgram',\n isMut: false,\n isSigner: false,\n docs: ['programs'],\n },\n {\n name: 'accountCompressionAuthority',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'merkleTree',\n isMut: true,\n isSigner: false,\n },\n {\n name: 'selfProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'systemProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'solPoolPda',\n isMut: true,\n isSigner: false,\n isOptional: true,\n },\n ],\n args: [\n {\n name: 'publicKeys',\n type: {\n vec: 'publicKey',\n },\n },\n {\n name: 'amounts',\n type: {\n vec: 'u64',\n },\n },\n {\n name: 'lamports',\n type: {\n option: 'u64',\n },\n },\n ],\n },\n {\n name: 'compressSplTokenAccount',\n docs: [\n 'Compresses the balance of an spl token account sub an optional remaining',\n 'amount. This instruction does not close the spl token account. To close',\n 'the account bundle a close spl account instruction in your transaction.',\n ],\n accounts: [\n {\n name: 'feePayer',\n isMut: true,\n isSigner: true,\n docs: ['UNCHECKED: only pays fees.'],\n },\n {\n name: 'authority',\n isMut: false,\n isSigner: true,\n docs: [\n 'Authority is verified through proof since both owner and delegate',\n 'are included in the token data hash, which is a public input to the',\n 'validity proof.',\n ],\n },\n {\n name: 'cpiAuthorityPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'lightSystemProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'registeredProgramPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'noopProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionAuthority',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'selfProgram',\n isMut: false,\n isSigner: false,\n docs: ['this program is the signer of the cpi.'],\n },\n {\n name: 'tokenPoolPda',\n isMut: true,\n isSigner: false,\n isOptional: true,\n },\n {\n name: 'compressOrDecompressTokenAccount',\n isMut: true,\n isSigner: false,\n isOptional: true,\n },\n {\n name: 'tokenProgram',\n isMut: false,\n isSigner: false,\n isOptional: true,\n },\n {\n name: 'systemProgram',\n isMut: false,\n isSigner: false,\n },\n ],\n args: [\n {\n name: 'owner',\n type: 'publicKey',\n },\n {\n name: 'remainingAmount',\n type: {\n option: 'u64',\n },\n },\n {\n name: 'cpiContext',\n type: {\n option: {\n defined: 'CompressedCpiContext',\n },\n },\n },\n ],\n },\n {\n name: 'transfer',\n docs: [\n 'Transfers compressed tokens from one account to another. All accounts',\n 'must be of the same mint. Additional spl tokens can be compressed or',\n 'decompressed. In one transaction only compression or decompression is',\n 'possible. Lamports can be transferred alongside tokens. If output token',\n 'accounts specify less lamports than inputs the remaining lamports are',\n 'transferred to an output compressed account. Signer must be owner or',\n 'delegate. If a delegated token account is transferred the delegate is',\n 'not preserved.',\n ],\n accounts: [\n {\n name: 'feePayer',\n isMut: true,\n isSigner: true,\n docs: ['UNCHECKED: only pays fees.'],\n },\n {\n name: 'authority',\n isMut: false,\n isSigner: true,\n docs: [\n 'Authority is verified through proof since both owner and delegate',\n 'are included in the token data hash, which is a public input to the',\n 'validity proof.',\n ],\n },\n {\n name: 'cpiAuthorityPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'lightSystemProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'registeredProgramPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'noopProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionAuthority',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'selfProgram',\n isMut: false,\n isSigner: false,\n docs: ['this program is the signer of the cpi.'],\n },\n {\n name: 'tokenPoolPda',\n isMut: true,\n isSigner: false,\n isOptional: true,\n },\n {\n name: 'compressOrDecompressTokenAccount',\n isMut: true,\n isSigner: false,\n isOptional: true,\n },\n {\n name: 'tokenProgram',\n isMut: false,\n isSigner: false,\n isOptional: true,\n },\n {\n name: 'systemProgram',\n isMut: false,\n isSigner: false,\n },\n ],\n args: [\n {\n name: 'inputs',\n type: 'bytes',\n },\n ],\n },\n {\n name: 'approve',\n docs: [\n 'Delegates an amount to a delegate. A compressed token account is either',\n 'completely delegated or not. Prior delegates are not preserved. Cannot',\n 'be called by a delegate.',\n 'The instruction creates two output accounts:',\n '1. one account with delegated amount',\n '2. one account with remaining(change) amount',\n ],\n accounts: [\n {\n name: 'feePayer',\n isMut: true,\n isSigner: true,\n docs: ['UNCHECKED: only pays fees.'],\n },\n {\n name: 'authority',\n isMut: false,\n isSigner: true,\n docs: [\n 'Authority is verified through proof since both owner and delegate',\n 'are included in the token data hash, which is a public input to the',\n 'validity proof.',\n ],\n },\n {\n name: 'cpiAuthorityPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'lightSystemProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'registeredProgramPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'noopProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionAuthority',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'selfProgram',\n isMut: false,\n isSigner: false,\n docs: ['this program is the signer of the cpi.'],\n },\n {\n name: 'systemProgram',\n isMut: false,\n isSigner: false,\n },\n ],\n args: [\n {\n name: 'inputs',\n type: 'bytes',\n },\n ],\n },\n {\n name: 'revoke',\n docs: [\n 'Revokes a delegation. The instruction merges all inputs into one output',\n 'account. Cannot be called by a delegate. Delegates are not preserved.',\n ],\n accounts: [\n {\n name: 'feePayer',\n isMut: true,\n isSigner: true,\n docs: ['UNCHECKED: only pays fees.'],\n },\n {\n name: 'authority',\n isMut: false,\n isSigner: true,\n docs: [\n 'Authority is verified through proof since both owner and delegate',\n 'are included in the token data hash, which is a public input to the',\n 'validity proof.',\n ],\n },\n {\n name: 'cpiAuthorityPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'lightSystemProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'registeredProgramPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'noopProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionAuthority',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'selfProgram',\n isMut: false,\n isSigner: false,\n docs: ['this program is the signer of the cpi.'],\n },\n {\n name: 'systemProgram',\n isMut: false,\n isSigner: false,\n },\n ],\n args: [\n {\n name: 'inputs',\n type: 'bytes',\n },\n ],\n },\n {\n name: 'freeze',\n docs: [\n 'Freezes compressed token accounts. Inputs must not be frozen. Creates as',\n 'many outputs as inputs. Balances and delegates are preserved.',\n ],\n accounts: [\n {\n name: 'feePayer',\n isMut: true,\n isSigner: true,\n docs: ['UNCHECKED: only pays fees.'],\n },\n {\n name: 'authority',\n isMut: false,\n isSigner: true,\n },\n {\n name: 'cpiAuthorityPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'lightSystemProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'registeredProgramPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'noopProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionAuthority',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'selfProgram',\n isMut: false,\n isSigner: false,\n docs: ['that this program is the signer of the cpi.'],\n },\n {\n name: 'systemProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'mint',\n isMut: false,\n isSigner: false,\n },\n ],\n args: [\n {\n name: 'inputs',\n type: 'bytes',\n },\n ],\n },\n {\n name: 'thaw',\n docs: [\n 'Thaws frozen compressed token accounts. Inputs must be frozen. Creates',\n 'as many outputs as inputs. Balances and delegates are preserved.',\n ],\n accounts: [\n {\n name: 'feePayer',\n isMut: true,\n isSigner: true,\n docs: ['UNCHECKED: only pays fees.'],\n },\n {\n name: 'authority',\n isMut: false,\n isSigner: true,\n },\n {\n name: 'cpiAuthorityPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'lightSystemProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'registeredProgramPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'noopProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionAuthority',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'selfProgram',\n isMut: false,\n isSigner: false,\n docs: ['that this program is the signer of the cpi.'],\n },\n {\n name: 'systemProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'mint',\n isMut: false,\n isSigner: false,\n },\n ],\n args: [\n {\n name: 'inputs',\n type: 'bytes',\n },\n ],\n },\n {\n name: 'burn',\n docs: [\n 'Burns compressed tokens and spl tokens from the pool account. Delegates',\n 'can burn tokens. The output compressed token account remains delegated.',\n 'Creates one output compressed token account.',\n ],\n accounts: [\n {\n name: 'feePayer',\n isMut: true,\n isSigner: true,\n docs: ['UNCHECKED: only pays fees.'],\n },\n {\n name: 'authority',\n isMut: false,\n isSigner: true,\n docs: [\n 'Authority is verified through proof since both owner and delegate',\n 'are included in the token data hash, which is a public input to the',\n 'validity proof.',\n ],\n },\n {\n name: 'cpiAuthorityPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'mint',\n isMut: true,\n isSigner: false,\n },\n {\n name: 'tokenPoolPda',\n isMut: true,\n isSigner: false,\n },\n {\n name: 'tokenProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'lightSystemProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'registeredProgramPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'noopProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionAuthority',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'selfProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'systemProgram',\n isMut: false,\n isSigner: false,\n },\n ],\n args: [\n {\n name: 'inputs',\n type: 'bytes',\n },\n ],\n },\n {\n name: 'stubIdlBuild',\n docs: [\n 'This function is a stub to allow Anchor to include the input types in',\n 'the IDL. It should not be included in production builds nor be called in',\n 'practice.',\n ],\n accounts: [\n {\n name: 'feePayer',\n isMut: true,\n isSigner: true,\n docs: ['UNCHECKED: only pays fees.'],\n },\n {\n name: 'authority',\n isMut: false,\n isSigner: true,\n docs: [\n 'Authority is verified through proof since both owner and delegate',\n 'are included in the token data hash, which is a public input to the',\n 'validity proof.',\n ],\n },\n {\n name: 'cpiAuthorityPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'lightSystemProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'registeredProgramPda',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'noopProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionAuthority',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'accountCompressionProgram',\n isMut: false,\n isSigner: false,\n },\n {\n name: 'selfProgram',\n isMut: false,\n isSigner: false,\n docs: ['this program is the signer of the cpi.'],\n },\n {\n name: 'tokenPoolPda',\n isMut: true,\n isSigner: false,\n isOptional: true,\n },\n {\n name: 'compressOrDecompressTokenAccount',\n isMut: true,\n isSigner: false,\n isOptional: true,\n },\n {\n name: 'tokenProgram',\n isMut: false,\n isSigner: false,\n isOptional: true,\n },\n {\n name: 'systemProgram',\n isMut: false,\n isSigner: false,\n },\n ],\n args: [\n {\n name: 'inputs1',\n type: {\n defined: 'CompressedTokenInstructionDataTransfer',\n },\n },\n {\n name: 'inputs2',\n type: {\n defined: 'TokenData',\n },\n },\n ],\n },\n ],\n types: [\n {\n name: 'AccountState',\n type: {\n kind: 'enum',\n variants: [\n {\n name: 'Initialized',\n },\n {\n name: 'Frozen',\n },\n ],\n },\n },\n {\n name: 'CompressedAccount',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'owner',\n type: 'publicKey',\n },\n {\n name: 'lamports',\n type: 'u64',\n },\n {\n name: 'address',\n type: {\n option: {\n array: ['u8', 32],\n },\n },\n },\n {\n name: 'data',\n type: {\n option: {\n defined: 'CompressedAccountData',\n },\n },\n },\n ],\n },\n },\n {\n name: 'CompressedAccountData',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'discriminator',\n type: {\n array: ['u8', 8],\n },\n },\n {\n name: 'data',\n type: 'bytes',\n },\n {\n name: 'dataHash',\n type: {\n array: ['u8', 32],\n },\n },\n ],\n },\n },\n {\n name: 'CompressedCpiContext',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'setContext',\n docs: [\n 'Is set by the program that is invoking the CPI to signal that is should',\n 'set the cpi context.',\n ],\n type: 'bool',\n },\n {\n name: 'firstSetContext',\n docs: [\n 'Is set to wipe the cpi context since someone could have set it before',\n 'with unrelated data.',\n ],\n type: 'bool',\n },\n {\n name: 'cpiContextAccountIndex',\n docs: [\n 'Index of cpi context account in remaining accounts.',\n ],\n type: 'u8',\n },\n ],\n },\n },\n {\n name: 'CompressedProof',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'a',\n type: {\n array: ['u8', 32],\n },\n },\n {\n name: 'b',\n type: {\n array: ['u8', 64],\n },\n },\n {\n name: 'c',\n type: {\n array: ['u8', 32],\n },\n },\n ],\n },\n },\n {\n name: 'CompressedTokenInstructionDataTransfer',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'proof',\n type: {\n option: {\n defined: 'CompressedProof',\n },\n },\n },\n {\n name: 'mint',\n type: 'publicKey',\n },\n {\n name: 'delegatedTransfer',\n docs: [\n 'Is required if the signer is delegate,',\n '-> delegate is authority account,',\n 'owner = Some(owner) is the owner of the token account.',\n ],\n type: {\n option: {\n defined: 'DelegatedTransfer',\n },\n },\n },\n {\n name: 'inputTokenDataWithContext',\n type: {\n vec: {\n defined: 'InputTokenDataWithContext',\n },\n },\n },\n {\n name: 'outputCompressedAccounts',\n type: {\n vec: {\n defined: 'PackedTokenTransferOutputData',\n },\n },\n },\n {\n name: 'isCompress',\n type: 'bool',\n },\n {\n name: 'compressOrDecompressAmount',\n type: {\n option: 'u64',\n },\n },\n {\n name: 'cpiContext',\n type: {\n option: {\n defined: 'CompressedCpiContext',\n },\n },\n },\n {\n name: 'lamportsChangeAccountMerkleTreeIndex',\n type: {\n option: 'u8',\n },\n },\n ],\n },\n },\n {\n name: 'CompressedTokenInstructionDataRevoke',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'proof',\n type: {\n option: {\n defined: 'CompressedProof',\n },\n },\n },\n {\n name: 'mint',\n type: 'publicKey',\n },\n {\n name: 'inputTokenDataWithContext',\n type: {\n vec: {\n defined: 'InputTokenDataWithContext',\n },\n },\n },\n {\n name: 'cpiContext',\n type: {\n option: {\n defined: 'CompressedCpiContext',\n },\n },\n },\n {\n name: 'outputAccountMerkleTreeIndex',\n type: 'u8',\n },\n ],\n },\n },\n {\n name: 'CompressedTokenInstructionDataApprove',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'proof',\n type: {\n option: {\n defined: 'CompressedProof',\n },\n },\n },\n {\n name: 'mint',\n type: 'publicKey',\n },\n {\n name: 'inputTokenDataWithContext',\n type: {\n vec: {\n defined: 'InputTokenDataWithContext',\n },\n },\n },\n {\n name: 'cpiContext',\n type: {\n option: {\n defined: 'CompressedCpiContext',\n },\n },\n },\n {\n name: 'delegate',\n type: 'publicKey',\n },\n {\n name: 'delegatedAmount',\n type: 'u64',\n },\n {\n name: 'delegateMerkleTreeIndex',\n type: 'u8',\n },\n {\n name: 'changeAccountMerkleTreeIndex',\n type: 'u8',\n },\n {\n name: 'delegateLamports',\n type: {\n option: 'u64',\n },\n },\n ],\n },\n },\n {\n name: 'DelegatedTransfer',\n docs: [\n 'Struct to provide the owner when the delegate is signer of the transaction.',\n ],\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'owner',\n type: 'publicKey',\n },\n {\n name: 'delegateChangeAccountIndex',\n docs: [\n 'Index of change compressed account in output compressed accounts. In',\n \"case that the delegate didn't spend the complete delegated compressed\",\n 'account balance the change compressed account will be delegated to her',\n 'as well.',\n ],\n type: {\n option: 'u8',\n },\n },\n ],\n },\n },\n {\n name: 'InputTokenDataWithContext',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'amount',\n type: 'u64',\n },\n {\n name: 'delegateIndex',\n type: {\n option: 'u8',\n },\n },\n {\n name: 'merkleContext',\n type: {\n defined: 'PackedMerkleContext',\n },\n },\n {\n name: 'rootIndex',\n type: 'u16',\n },\n {\n name: 'lamports',\n type: {\n option: 'u64',\n },\n },\n {\n name: 'tlv',\n docs: [\n 'Placeholder for TokenExtension tlv data (unimplemented)',\n ],\n type: {\n option: 'bytes',\n },\n },\n ],\n },\n },\n {\n name: 'InstructionDataInvoke',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'proof',\n type: {\n option: {\n defined: 'CompressedProof',\n },\n },\n },\n {\n name: 'inputCompressedAccountsWithMerkleContext',\n type: {\n vec: {\n defined:\n 'PackedCompressedAccountWithMerkleContext',\n },\n },\n },\n {\n name: 'outputCompressedAccounts',\n type: {\n vec: {\n defined:\n 'OutputCompressedAccountWithPackedContext',\n },\n },\n },\n {\n name: 'relayFee',\n type: {\n option: 'u64',\n },\n },\n {\n name: 'newAddressParams',\n type: {\n vec: {\n defined: 'NewAddressParamsPacked',\n },\n },\n },\n {\n name: 'compressOrDecompressLamports',\n type: {\n option: 'u64',\n },\n },\n {\n name: 'isCompress',\n type: 'bool',\n },\n ],\n },\n },\n {\n name: 'InstructionDataInvokeCpi',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'proof',\n type: {\n option: {\n defined: 'CompressedProof',\n },\n },\n },\n {\n name: 'newAddressParams',\n type: {\n vec: {\n defined: 'NewAddressParamsPacked',\n },\n },\n },\n {\n name: 'inputCompressedAccountsWithMerkleContext',\n type: {\n vec: {\n defined:\n 'PackedCompressedAccountWithMerkleContext',\n },\n },\n },\n {\n name: 'outputCompressedAccounts',\n type: {\n vec: {\n defined:\n 'OutputCompressedAccountWithPackedContext',\n },\n },\n },\n {\n name: 'relayFee',\n type: {\n option: 'u64',\n },\n },\n {\n name: 'compressOrDecompressLamports',\n type: {\n option: 'u64',\n },\n },\n {\n name: 'isCompress',\n type: 'bool',\n },\n {\n name: 'cpiContext',\n type: {\n option: {\n defined: 'CompressedCpiContext',\n },\n },\n },\n ],\n },\n },\n {\n name: 'MerkleTreeSequenceNumber',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'pubkey',\n type: 'publicKey',\n },\n {\n name: 'seq',\n type: 'u64',\n },\n ],\n },\n },\n {\n name: 'NewAddressParamsPacked',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'seed',\n type: {\n array: ['u8', 32],\n },\n },\n {\n name: 'addressQueueAccountIndex',\n type: 'u8',\n },\n {\n name: 'addressMerkleTreeAccountIndex',\n type: 'u8',\n },\n {\n name: 'addressMerkleTreeRootIndex',\n type: 'u16',\n },\n ],\n },\n },\n {\n name: 'OutputCompressedAccountWithPackedContext',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'compressedAccount',\n type: {\n defined: 'CompressedAccount',\n },\n },\n {\n name: 'merkleTreeIndex',\n type: 'u8',\n },\n ],\n },\n },\n {\n name: 'PackedCompressedAccountWithMerkleContext',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'compressedAccount',\n type: {\n defined: 'CompressedAccount',\n },\n },\n {\n name: 'merkleContext',\n type: {\n defined: 'PackedMerkleContext',\n },\n },\n {\n name: 'rootIndex',\n docs: [\n 'Index of root used in inclusion validity proof.',\n ],\n type: 'u16',\n },\n {\n name: 'readOnly',\n docs: [\n 'Placeholder to mark accounts read-only unimplemented set to false.',\n ],\n type: 'bool',\n },\n ],\n },\n },\n {\n name: 'PackedMerkleContext',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'merkleTreePubkeyIndex',\n type: 'u8',\n },\n {\n name: 'queuePubkeyIndex',\n type: 'u8',\n },\n {\n name: 'leafIndex',\n type: 'u32',\n },\n {\n name: 'proveByIndex',\n type: 'bool',\n },\n ],\n },\n },\n {\n name: 'PackedTokenTransferOutputData',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'owner',\n type: 'publicKey',\n },\n {\n name: 'amount',\n type: 'u64',\n },\n {\n name: 'lamports',\n type: {\n option: 'u64',\n },\n },\n {\n name: 'merkleTreeIndex',\n type: 'u8',\n },\n {\n name: 'tlv',\n docs: [\n 'Placeholder for TokenExtension tlv data (unimplemented)',\n ],\n type: {\n option: 'bytes',\n },\n },\n ],\n },\n },\n {\n name: 'PublicTransactionEvent',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'inputCompressedAccountHashes',\n type: {\n vec: {\n array: ['u8', 32],\n },\n },\n },\n {\n name: 'outputCompressedAccountHashes',\n type: {\n vec: {\n array: ['u8', 32],\n },\n },\n },\n {\n name: 'outputCompressedAccounts',\n type: {\n vec: {\n defined:\n 'OutputCompressedAccountWithPackedContext',\n },\n },\n },\n {\n name: 'outputLeafIndices',\n type: {\n vec: 'u32',\n },\n },\n {\n name: 'sequenceNumbers',\n type: {\n vec: {\n defined: 'MerkleTreeSequenceNumber',\n },\n },\n },\n {\n name: 'relayFee',\n type: {\n option: 'u64',\n },\n },\n {\n name: 'isCompress',\n type: 'bool',\n },\n {\n name: 'compressOrDecompressLamports',\n type: {\n option: 'u64',\n },\n },\n {\n name: 'pubkeyArray',\n type: {\n vec: 'publicKey',\n },\n },\n {\n name: 'message',\n type: {\n option: 'bytes',\n },\n },\n ],\n },\n },\n {\n name: 'QueueIndex',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'queueId',\n docs: ['Id of queue in queue account.'],\n type: 'u8',\n },\n {\n name: 'index',\n docs: ['Index of compressed account hash in queue.'],\n type: 'u16',\n },\n ],\n },\n },\n {\n name: 'TokenData',\n type: {\n kind: 'struct',\n fields: [\n {\n name: 'mint',\n docs: ['The mint associated with this account'],\n type: 'publicKey',\n },\n {\n name: 'owner',\n docs: ['The owner of this account.'],\n type: 'publicKey',\n },\n {\n name: 'amount',\n docs: ['The amount of tokens this account holds.'],\n type: 'u64',\n },\n {\n name: 'delegate',\n docs: [\n 'If `delegate` is `Some` then `delegated_amount` represents',\n 'the amount authorized by the delegate',\n ],\n type: {\n option: 'publicKey',\n },\n },\n {\n name: 'state',\n docs: [\"The account's state\"],\n type: {\n defined: 'AccountState',\n },\n },\n {\n name: 'tlv',\n docs: [\n 'Placeholder for TokenExtension tlv data (unimplemented)',\n ],\n type: {\n option: 'bytes',\n },\n },\n ],\n },\n },\n ],\n errors: [\n {\n code: 6000,\n name: 'PublicKeyAmountMissmatch',\n msg: 'public keys and amounts must be of same length',\n },\n {\n code: 6001,\n name: 'ComputeInputSumFailed',\n msg: 'ComputeInputSumFailed',\n },\n {\n code: 6002,\n name: 'ComputeOutputSumFailed',\n msg: 'ComputeOutputSumFailed',\n },\n {\n code: 6003,\n name: 'ComputeCompressSumFailed',\n msg: 'ComputeCompressSumFailed',\n },\n {\n code: 6004,\n name: 'ComputeDecompressSumFailed',\n msg: 'ComputeDecompressSumFailed',\n },\n {\n code: 6005,\n name: 'SumCheckFailed',\n msg: 'SumCheckFailed',\n },\n {\n code: 6006,\n name: 'DecompressRecipientUndefinedForDecompress',\n msg: 'DecompressRecipientUndefinedForDecompress',\n },\n {\n code: 6007,\n name: 'CompressedPdaUndefinedForDecompress',\n msg: 'CompressedPdaUndefinedForDecompress',\n },\n {\n code: 6008,\n name: 'DeCompressAmountUndefinedForDecompress',\n msg: 'DeCompressAmountUndefinedForDecompress',\n },\n {\n code: 6009,\n name: 'CompressedPdaUndefinedForCompress',\n msg: 'CompressedPdaUndefinedForCompress',\n },\n {\n code: 6010,\n name: 'DeCompressAmountUndefinedForCompress',\n msg: 'DeCompressAmountUndefinedForCompress',\n },\n {\n code: 6011,\n name: 'DelegateSignerCheckFailed',\n msg: 'DelegateSignerCheckFailed',\n },\n {\n code: 6012,\n name: 'MintTooLarge',\n msg: 'Minted amount greater than u64::MAX',\n },\n {\n code: 6013,\n name: 'SplTokenSupplyMismatch',\n msg: 'SplTokenSupplyMismatch',\n },\n {\n code: 6014,\n name: 'HeapMemoryCheckFailed',\n msg: 'HeapMemoryCheckFailed',\n },\n {\n code: 6015,\n name: 'InstructionNotCallable',\n msg: 'The instruction is not callable',\n },\n {\n code: 6016,\n name: 'ArithmeticUnderflow',\n msg: 'ArithmeticUnderflow',\n },\n {\n code: 6017,\n name: 'HashToFieldError',\n msg: 'HashToFieldError',\n },\n {\n code: 6018,\n name: 'InvalidAuthorityMint',\n msg: 'Expected the authority to be also a mint authority',\n },\n {\n code: 6019,\n name: 'InvalidFreezeAuthority',\n msg: 'Provided authority is not the freeze authority',\n },\n {\n code: 6020,\n name: 'InvalidDelegateIndex',\n },\n {\n code: 6021,\n name: 'TokenPoolPdaUndefined',\n },\n {\n code: 6022,\n name: 'IsTokenPoolPda',\n msg: 'Compress or decompress recipient is the same account as the token pool pda.',\n },\n {\n code: 6023,\n name: 'InvalidTokenPoolPda',\n },\n {\n code: 6024,\n name: 'NoInputTokenAccountsProvided',\n },\n {\n code: 6025,\n name: 'NoInputsProvided',\n },\n {\n code: 6026,\n name: 'MintHasNoFreezeAuthority',\n },\n {\n code: 6027,\n name: 'MintWithInvalidExtension',\n },\n {\n code: 6028,\n name: 'InsufficientTokenAccountBalance',\n msg: 'The token account balance is less than the remaining amount.',\n },\n {\n code: 6029,\n name: 'InvalidTokenPoolBump',\n msg: 'Max number of token pools reached.',\n },\n {\n code: 6030,\n name: 'FailedToDecompress',\n },\n {\n code: 6031,\n name: 'FailedToBurnSplTokensFromTokenPool',\n },\n {\n code: 6032,\n name: 'NoMatchingBumpFound',\n },\n ],\n};\n","import { PublicKey } from '@solana/web3.js';\nimport BN from 'bn.js';\nimport { Buffer } from 'buffer';\nimport {\n ValidityProof,\n PackedMerkleContextLegacy,\n CompressedCpiContext,\n} from '@lightprotocol/stateless.js';\nimport { SplInterfaceInfo, TokenPoolInfo } from './utils/get-token-pool-infos';\n\nexport type TokenTransferOutputData = {\n /**\n * The owner of the output token account\n */\n owner: PublicKey;\n /**\n * The amount of tokens of the output token account\n */\n amount: BN;\n /**\n * lamports associated with the output token account\n */\n lamports: BN | null;\n /**\n * TokenExtension tlv\n */\n tlv: Buffer | null;\n};\n\nexport type PackedTokenTransferOutputData = {\n /**\n * The owner of the output token account\n */\n owner: PublicKey;\n /**\n * The amount of tokens of the output token account\n */\n amount: BN;\n /**\n * lamports associated with the output token account\n */\n lamports: BN | null;\n /**\n * Merkle tree pubkey index in remaining accounts\n */\n merkleTreeIndex: number;\n /**\n * TokenExtension tlv\n */\n tlv: Buffer | null;\n};\n\nexport type InputTokenDataWithContext = {\n amount: BN;\n delegateIndex: number | null;\n merkleContext: PackedMerkleContextLegacy;\n rootIndex: number;\n lamports: BN | null;\n tlv: Buffer | null;\n};\n\nexport type DelegatedTransfer = {\n owner: PublicKey;\n delegateChangeAccountIndex: number | null;\n};\n\nexport type BatchCompressInstructionData = {\n pubkeys: PublicKey[];\n amounts: BN[] | null;\n lamports: BN | null;\n amount: BN | null;\n index: number;\n bump: number;\n};\n\nexport type MintToInstructionData = {\n recipients: PublicKey[];\n amounts: BN[];\n lamports: BN | null;\n};\nexport type CompressSplTokenAccountInstructionData = {\n owner: PublicKey;\n remainingAmount: BN | null;\n cpiContext: CompressedCpiContext | null;\n};\n\nexport function isSingleSplInterfaceInfo(\n splInterfaceInfos: SplInterfaceInfo | SplInterfaceInfo[],\n): splInterfaceInfos is SplInterfaceInfo {\n return !Array.isArray(splInterfaceInfos);\n}\n\n/**\n * @deprecated Use {@link isSingleSplInterfaceInfo} instead.\n */\nexport const isSingleTokenPoolInfo = isSingleSplInterfaceInfo;\n\nexport type CompressedTokenInstructionDataTransfer = {\n /**\n * Validity proof\n */\n proof: ValidityProof | null;\n /**\n * The mint of the transfer\n */\n mint: PublicKey;\n /**\n * Whether the signer is a delegate\n */\n delegatedTransfer: DelegatedTransfer | null;\n /**\n * Input token data with packed merkle context\n */\n inputTokenDataWithContext: InputTokenDataWithContext[];\n /**\n * Data of the output token accounts\n */\n outputCompressedAccounts: PackedTokenTransferOutputData[];\n /**\n * Whether it's a compress or decompress action if compressOrDecompressAmount is non-null\n */\n isCompress: boolean;\n /**\n * If null, it's a transfer.\n * If some, the amount that is being deposited into (compress) or withdrawn from (decompress) the token escrow\n */\n compressOrDecompressAmount: BN | null;\n /**\n * CPI context if\n */\n cpiContext: CompressedCpiContext | null;\n /**\n * The index of the Merkle tree for a lamport change account.\n */\n lamportsChangeAccountMerkleTreeIndex: number | null;\n};\n\nexport type TokenData = {\n /**\n * The mint associated with this account\n */\n mint: PublicKey;\n /**\n * The owner of this account\n */\n owner: PublicKey;\n /**\n * The amount of tokens this account holds\n */\n amount: BN;\n /**\n * If `delegate` is `Some` then `delegated_amount` represents the amount\n * authorized by the delegate\n */\n delegate: PublicKey | null;\n /**\n * The account's state\n */\n state: number;\n /**\n * TokenExtension tlv\n */\n tlv: Buffer | null;\n};\n\nexport type CompressedTokenInstructionDataApprove = {\n proof: ValidityProof | null;\n mint: PublicKey;\n inputTokenDataWithContext: InputTokenDataWithContext[];\n cpiContext: CompressedCpiContext | null;\n delegate: PublicKey;\n delegatedAmount: BN;\n delegateMerkleTreeIndex: number;\n changeAccountMerkleTreeIndex: number;\n delegateLamports: BN | null;\n};\n\nexport type CompressedTokenInstructionDataRevoke = {\n proof: ValidityProof | null;\n mint: PublicKey;\n inputTokenDataWithContext: InputTokenDataWithContext[];\n cpiContext: CompressedCpiContext | null;\n outputAccountMerkleTreeIndex: number;\n};\n"],"names":["TokenDataVersion","POOL_SEED","Buffer","from","CPI_AUTHORITY_SEED","SPL_TOKEN_MINT_RENT_EXEMPT_BALANCE","CREATE_TOKEN_POOL_DISCRIMINATOR","MINT_TO_DISCRIMINATOR","BATCH_COMPRESS_DISCRIMINATOR","TRANSFER_DISCRIMINATOR","COMPRESS_SPL_TOKEN_ACCOUNT_DISCRIMINATOR","APPROVE_DISCRIMINATOR","REVOKE_DISCRIMINATOR","ADD_TOKEN_POOL_DISCRIMINATOR","DECOMPRESS_ACCOUNTS_IDEMPOTENT_DISCRIMINATOR","toTokenPoolInfo","info","mint","tokenPoolPda","splInterfacePda","tokenProgram","activity","isInitialized","balance","poolIndex","bump","toSplInterfaceInfo","deriveSplInterfaceInfo","tokenProgramId","CompressedTokenProgram","deriveSplInterfacePdaWithIndex","undefined","bn","checkSplInterfaceInfo","splInterfaceInfo","equals","Error","toBase58","async","getSplInterfaceInfos","rpc","commitment","addressesAndBumps","Array","length","_","i","accountInfos","getMultipleAccountsInfo","map","addressAndBump","parsedInfos","unpackAccount","owner","parsedInfo","address","amount","toString","Action","shuffleArray","array","j","Math","floor","random","selectSplInterfaceInfo","infos","filteredInfos","filter","selectSplInterfaceInfosForDecompression","decompressAmount","sufficientBalanceInfo","find","gte","mul","sort","a","b","every","isZero","deriveTokenPoolInfo","checkTokenPoolInfo","tokenPoolInfo","getTokenPoolInfos","selectTokenPoolInfo","selectTokenPoolInfosForDecompression","ERROR_NO_ACCOUNTS_FOUND","selectTokenAccountsForApprove","accounts","approveAmount","maxInputs","exactMatch","account","parsed","eq","compressedAccount","lamports","selectMinCompressedTokenAccountsForTransfer","selectMinCompressedTokenAccountsForDecompression","selectedAccounts","total","totalLamports","maxPossibleAmount","transferAmount","accumulatedAmount","accumulatedLamports","selectMinCompressedTokenAccountsForTransferOrPartial","lt","totalBalance","reduce","acc","add","cmp","push","slice","console","log","selectSmartCompressedTokenAccountsForTransfer","selectSmartCompressedTokenAccountsForTransferOrPartial","nonZeroAccounts","remainingAccounts","smallestAccount","min","max","packCompressedTokenAccounts","params","inputCompressedTokenAccounts","outputStateTreeInfo","rootIndices","tokenTransferOutputs","_remainingAccounts","delegateIndex","delegate","getIndexOrAdd","packedInputTokenData","forEach","index","merkleTreePubkeyIndex","treeInfo","tree","queuePubkeyIndex","queue","merkleContext","leafIndex","proveByIndex","rootIndex","tlv","activeTreeInfo","nextTreeInfo","activeTreeOrQueue","treeType","TreeType","StateV2","featureFlags","isV2","paddedOutputStateMerkleTrees","padOutputStateMerkleTrees","packedOutputTokenData","merkleTreeIndex","remainingAccountMetas","pubkey","isWritable","isSigner","inputTokenDataWithContext","checkMint","compressedTokenAccounts","CompressedProofLayout","struct","u8","PackedTokenTransferOutputDataLayout","publicKey","u64","option","vecU8","InputTokenDataWithContextLayout","u32","bool","u16","DelegatedTransferLayout","CpiContextLayout","CompressedTokenInstructionDataTransferLayout","vec","mintToLayout","batchCompressLayout","compressSplTokenAccountInstructionDataLayout","encodeMintToInstructionData","data","buffer","alloc","len","encode","recipients","amounts","concat","Uint8Array","subarray","decodeMintToInstructionData","decode","encodeBatchCompressInstructionData","lengthBuffer","writeUInt32LE","dataBuffer","decodeBatchCompressInstructionData","encodeCompressSplTokenAccountInstructionData","remainingAmount","cpiContext","decodeCompressSplTokenAccountInstructionData","encodeTransferInstructionData","decodeTransferInstructionData","createTokenPoolAccountsLayout","feePayer","systemProgram","cpiAuthorityPda","addTokenPoolAccountsLayout","existingTokenPoolPda","mintToAccountsLayout","defaultPubkey","programId","authority","lightSystemProgram","registeredProgramPda","noopProgram","accountCompressionAuthority","accountCompressionProgram","merkleTree","selfProgram","solPoolPda","transferAccountsLayout","compressOrDecompressTokenAccount","approveAccountsLayout","revokeAccountsLayout","freezeAccountsLayout","thawAccountsLayout","CompressedTokenInstructionDataApproveLayout","CompressedTokenInstructionDataRevokeLayout","emptyProof","fill","c","isEmptyProof","proof","encodeApproveInstructionData","proofOption","decodeApproveInstructionData","encodeRevokeInstructionData","decodeRevokeInstructionData","getTokenPoolPda","sumUpTokenAmount","validateSameTokenOwner","parseTokenData","currentOwner","parseMaybeDelegatedTransfer","inputs","outputs","delegatedAccountsIndex","findIndex","delegatedTransfer","delegateChangeAccountIndex","createTransferOutputState","toAddress","inputAmount","inputLamports","sumUpLamports","changeAmount","sub","validateSufficientBalance","validateSameOwner","createDecompressOutputState","constructor","static","PublicKey","setProgramId","this","deriveSplInterfacePda","seeds","toBuffer","findProgramAddressSync","deriveTokenPoolPda","findSplInterfaceIndexAndBump","poolPda","derivedPda","findTokenPoolIndexAndBump","deriveTokenPoolPdaWithIndex","deriveCpiAuthorityPda","createMint","freezeAuthority","decimals","rentExemptBalance","mintSize","TOKEN_PROGRAM_ID","SystemProgram","createAccount","fromPubkey","newAccountPubkey","space","MINT_SIZE","createInitializeMint2Instruction","createTokenPool","keys","TransactionInstruction","addTokenPool","existingSplInterfacePda","mintTo","toPubkey","systemKeys","defaultStaticAccountsStruct","toArray","toPubkeys","LightSystemProgram","approveAndMintTo","authorityTokenAccount","amountBigInt","BigInt","createMintToInstruction","compress","payer","source","transfer","recentValidityProof","recentInputStateRootIndices","outputCompressedAccounts","compressOrDecompressAmount","isCompress","lamportsChangeAccountMerkleTreeIndex","createTokenProgramLookupTable","mints","recentSlot","createInstruction","lookupTableAddress","AddressLookupTableProgram","createLookupTable","optionalMintKeys","instructions","extendLookupTable","lookupTable","addresses","ComputeBudgetProgram","defaultTestStateTreeAccounts","nullifierQueue","addressTree","addressQueue","TOKEN_2022_PROGRAM_ID","chunk","extendIx","amountArray","toAddressArray","pubkeys","amt","amountBN","isArray","sum","decompress","tokenPoolInfos","tokenPoolInfosArray","mergeTokenAccounts","compressSplTokenAccount","tokenAccount","getMintProgramId","connection","getAccountInfo","approve","CHANGE_INDEX","delegatedAmount","delegateMerkleTreeIndex","changeAccountMerkleTreeIndex","delegateLamports","revoke","outputAccountMerkleTreeIndex","deriveCMintAddress","mintSeed","addressTreeInfo","deriveAddressV2","findMintAddress","toBytes","CTOKEN_PROGRAM_ID","COMPRESSED_MINT_SEED","mintSigner","getAssociatedCTokenAddressAndBump","getAssociatedCTokenAddress","MINT_ACTION_DISCRIMINATOR","RecipientLayout","MintToCompressedActionLayout","UpdateAuthorityLayout","CreateSplMintActionLayout","MintToCTokenActionLayout","UpdateMetadataFieldActionLayout","UpdateMetadataAuthorityActionLayout","RemoveMetadataKeyActionLayout","ActionLayout","rustEnum","replicate","CreateMintLayout","AdditionalMetadataLayout","TokenMetadataInstructionDataLayout","PlaceholderLayout","ExtensionInstructionDataLayout","CompressedMintMetadataLayout","CompressedMintInstructionDataLayout","MintActionCompressedInstructionDataLayout","encodeMintActionInstructionData","encodableData","supply","actions","action","mintToCompressed","r","mintToCToken","createTokenMetadata","name","symbol","uri","updateAuthority","additionalMetadata","createMintInstruction","mintAuthority","validityProof","metadata","splMintPda","compressedAddress","extensions","tokenMetadata","validatedProof","validateProofArrays","tokenPoolBump","tokenPoolIndex","maxTopUp","readOnlyAddressTrees","readOnlyAddressTreeRootIndices","version","ShaFlat","splMintInitialized","encodeCreateMintInstructionData","outputQueue","compressedProof","sys","encodeUpdateMintInstructionData","splMint","actionType","updateMintAuthority","newAuthority","updateFreezeAuthority","mintInterface","mintContext","createUpdateMintAuthorityInstruction","currentMintAuthority","newMintAuthority","getOutputQueue","getDefaultAddressTreeInfo","createUpdateFreezeAuthorityInstruction","currentFreezeAuthority","newFreezeAuthority","createUpdateMetadataInstruction","type","updateMetadataField","extensionIndex","fieldType","key","value","updateMetadataAuthority","removeMetadataKey","idempotent","encodeUpdateMetadataInstructionData","createUpdateMetadataFieldInstruction","customKey","createUpdateMetadataAuthorityInstruction","currentAuthority","createRemoveMetadataKeyInstruction","CREATE_ASSOCIATED_TOKEN_ACCOUNT_DISCRIMINATOR","CREATE_ASSOCIATED_TOKEN_ACCOUNT_IDEMPOTENT_DISCRIMINATOR","CompressToPubkeyLayout","CompressibleExtensionInstructionDataLayout","CreateAssociatedTokenAccountInstructionDataLayout","encodeCreateAssociatedCTokenAccountData","compressibleConfig","discriminator","createAssociatedCTokenAccountInstruction","configAccount","rentPayerPda","associatedTokenAccount","createAssociatedCTokenAccountIdempotentInstruction","getAtaProgramId","ASSOCIATED_TOKEN_PROGRAM_ID","checkAtaAddress","ata","expected","getAssociatedTokenAddressSync","valid","programIdToAtaType","ctokenExpected","splExpected","t22Expected","createAssociatedTokenAccountInterfaceInstruction","associatedToken","associatedTokenProgramId","ctokenConfig","effectiveAssociatedTokenProgramId","createSplAssociatedTokenAccountInstruction","createAssociatedTokenAccountInterfaceIdempotentInstruction","createSplAssociatedTokenAccountIdempotentInstruction","createAtaInterfaceIdempotentInstruction","mintData","recipientAccount","accountIndex","recipientAccountIndex","encodeMintToCTokenInstructionData","createMintToCompressedInstruction","tokenAccountVersion","recipient","encodeCompressedMintToInstructionData","createMintToInterfaceInstruction","destination","multiSigners","createSplMintToInstruction","createCtokenMintToInstruction","getOutputTreeInfo","CTOKEN_TRANSFER_DISCRIMINATOR","createCTokenTransferInstruction","writeUInt8","writeBigUInt64LE","createTransferInterfaceInstruction","createSplTransferInstruction","pk","TRANSFER2_DISCRIMINATOR","COMPRESSION_MODE_COMPRESS","COMPRESSION_MODE_DECOMPRESS","CompressionLayout","PackedMerkleContextLayout","MultiInputTokenDataWithContextLayout","MultiTokenTransferOutputDataLayout","CompressedCpiContextLayout","Transfer2InstructionDataLayout","encodeTransfer2InstructionData","compressions","inTokenData","t","outTokenData","inLamports","v","outLamports","createCompressSpl","mintIndex","sourceIndex","authorityIndex","poolAccountIndex","mode","sourceOrRecipient","createDecompressCtoken","recipientIndex","tokenProgramIndex","createCompressCtoken","createDecompressSpl","getVersionFromDiscriminator","V1","V2","createDecompressInterfaceInstruction","packedAccountIndices","Map","packedAccounts","treeSet","Set","queueSet","set","firstQueueIndex","isFirstQueue","ownerIndex","destinationIndex","poolBump","ownerKey","mintKey","get","hasDelegate","buildInputTokenData","withTransactionHash","withLamportsChangeAccountMerkleTreeIndex","lamportsChangeAccountOwnerIndex","inTlv","outTlv","isTreeOrQueue","size","isDestination","isPool","module","exports","assert","val","msg","inherits","ctor","superCtor","super_","TempCtor","prototype","BN","number","base","endian","isBN","negative","words","red","_init","wordSize","window","require$$0","e","parseHex4Bits","string","charCodeAt","parseHexByte","lowerBound","parseBase","str","start","end","move","dest","src","num","left","right","_initNumber","_initArray","replace","_parseHex","_parseBase","ceil","w","off","_strip","limbLen","limbPow","mod","word","imuln","_iaddn","pow","copy","_move","clone","_expand","_normSign","Symbol","for","inspect","zeros","groupSizes","groupBases","smallMulTo","self","out","lo","carry","k","ncarry","rword","maxJ","padding","groupSize","groupBase","modrn","idivn","toNumber","ret","toJSON","toArrayLike","ArrayType","byteLength","reqLength","res","allocUnsafe","allocate","_toArrayLikeLE","position","shift","_toArrayLikeBE","clz32","_countBits","_zeroBits","bitLength","hi","zeroBits","toTwos","width","abs","inotn","iaddn","fromTwos","testn","notn","ineg","isNeg","neg","iuor","ior","or","uor","iuand","iand","and","uand","iuxor","ixor","xor","uxor","bytesNeeded","bitsLeft","setn","bit","wbit","iadd","isub","comb10MulTo","mid","o","a0","al0","ah0","a1","al1","ah1","a2","al2","ah2","a3","al3","ah3","a4","al4","ah4","a5","al5","ah5","a6","al6","ah6","a7","al7","ah7","a8","al8","ah8","a9","al9","ah9","b0","bl0","bh0","b1","bl1","bh1","b2","bl2","bh2","b3","bl3","bh3","b4","bl4","bh4","b5","bl5","bh5","b6","bl6","bh6","b7","bl7","bh7","b8","bl8","bh8","b9","bl9","bh9","w0","imul","w1","w2","w3","w4","w5","w6","w7","w8","w9","w10","w11","w12","w13","w14","w15","w16","w17","w18","bigMulTo","hncarry","jumboMulTo","mulTo","mulf","isNegNum","muln","sqr","isqr","toBitArray","q","iushln","bits","s","carryMask","newCarry","ishln","iushrn","hint","extended","h","mask","maskedWords","ishrn","shln","ushln","shrn","ushrn","imaskn","maskn","isubn","addn","subn","iabs","_ishlnsubmul","_wordDiv","bhi","m","diff","qj","div","divmod","positive","divn","umod","divRound","dm","half","r2","andln","p","modn","egcd","x","y","A","B","C","D","g","isEven","yp","xp","im","isOdd","jm","gcd","_invmp","x1","x2","delta","cmpn","invm","bincn","ucmp","gtn","gt","gten","ltn","lten","lte","eqn","Red","toRed","ctx","convertTo","_forceRed","fromRed","convertFrom","forceRed","redAdd","redIAdd","redSub","redISub","redShl","shl","redMul","_verify2","redIMul","redSqr","_verify1","redISqr","redSqrt","sqrt","redInvm","redNeg","redPow","primes","k256","p224","p192","p25519","MPrime","n","tmp","_tmp","K256","call","P224","P192","P25519","prime","_prime","Mont","imod","rinv","minv","ireduce","rlen","split","imulK","strip","input","output","outLen","prev","next","mod3","one","nOne","lpow","z","inv","wnd","current","currentLen","mont","u","TokenAccountSourceType","Spl","Token2022","SplCold","Token2022Cold","CTokenHot","CTokenCold","offset","delegateOption","state","tlvOption","error","convertTokenDataToAccount","tokenData","AccountState","Uninitialized","isFrozen","Frozen","isNative","rentExemptReserve","closeAuthority","tlvData","toAccountInfo","dataDiscriminatorBuffer","executable","rentEpoch","parseCTokenHot","accountInfo","loadContext","isCold","parseCTokenCold","hash","getAccountInterface","_getAccountInterface","getAtaInterface","wrap","validation","result","_isAta","_owner","_mint","fetchByOwner","cTokenAta","fetchPromises","fetchTypes","fetchAddresses","_tryFetchCTokenHot","ataAddress","getCompressedTokenAccountsByOwner","items","_tryFetchCTokenColdByOwner","getCompressedAccount","_tryFetchCTokenColdByAddress","splTokenAta","token2022Ata","unpackAccountSPL","_tryFetchSpl","_tryFetchToken2022","results","Promise","allSettled","sources","status","priority","indexOf","buildAccountInterfaceFromSources","getUnifiedAccountInterface","onchainResult","compressedResult","onchainAccount","compressedAccounts","item","TokenAccountNotFoundError","getCTokenAccountInterface","coldType","parsedCold","getSplOrToken2022AccountInterface","canonicalAddress","totalAmount","primarySource","some","anyFrozen","needsConsolidation","unifiedAccount","includes","_sources","_needsConsolidation","_hasDelegate","_anyFrozen","getAssociatedTokenAddressInterface","allowOwnerOffCurve","effectiveAssociatedProgramId","createWrapInstruction","createLoadAtaInstructions","options","createLoadAtaInstructionsFromInterface","_getAtaInterface","targetAta","ctokenAtaAddress","splAta","t22Ata","ataType","splSource","t22Source","ctokenHotSource","ctokenColdSource","splBalance","t22Balance","coldBalance","splInterfaceInfos","getValidityProofV0","createAssociatedTokenAccountIdempotentInstruction","loadAta","confirmOptions","interfaceOptions","ixs","blockhash","getLatestBlockhash","additionalSigners","dedupeSigner","tx","buildAndSignTx","setComputeUnitLimit","units","sendAndConfirmTx","createLoadAccountsParams","programAccounts","atas","decompressParams","compressedProgramAccounts","proofInputs","proofResult","accountsData","accountType","tokenVariant","variant","treeInfos","packed","packDecompressAccountsIdempotent","systemAccountsOffset","ataInstructions","calculateCompressibleLoadComputeUnits","compressedAccountCount","hasValidityProof","cu","keypair","Keypair","generate","getMinimumBalanceForRentExemption","resolvedTokenProgramId","signer","txId","transactionSignature","createMintInterface","resolvedFreezeAuthority","getBatchAddressTreeInfo","selectStateTreeInfo","getStateTreeInfos","getValidityProofV2","DerivationMode","compressible","ix","skipPreflight","Object","defineProperty","Layout_1","s16","nu64be","u48be","u40be","u32be","u16be","nu64","u40","u24","greedy","Constant","UTF8","Blob","Boolean","BitStructure","VariantLayout","Union","UnionLayoutDiscriminator","Structure","Sequence","DoubleBE","Double","Float","NearInt64BE","NearUInt64BE","NearUInt64","IntBE","Int","UInt","OffsetLayout","GreedyCount","ExternalLayout","nameWithProperty","Layout","uint8ArrayToBuffer","checkUint8Array","constant","cstr","blob","unionLayoutDiscriminator","union","f64","f32be","f32","ns64be","s40be","s32be","s24be","s16be","s48","s40","s32","s24","buffer_1","TypeError","byteOffset","span","property","Number","isInteger","makeDestinationObject","getSpan","RangeError","rv","create","assign","fromArray","values","bindConstructorLayout","Class","layout","hasOwnProperty","layout_","boundConstructor_","writable","isCount","elementSpan","super","rem","UIntBE","readUIntLE","writeUIntLE","readUIntBE","writeUIntBE","readIntLE","writeIntLE","readIntBE","writeIntBE","V2E32","divmodInt64","hi32","lo32","roundedInt64","readUInt32LE","readUInt32BE","writeUInt32BE","NearInt64","readInt32LE","writeInt32LE","readInt32BE","writeInt32BE","readFloatLE","writeFloatLE","FloatBE","readFloatBE","writeFloatBE","readDoubleLE","writeDoubleLE","readDoubleBE","writeDoubleBE","elementLayout","count","idx","elo","fields","decodePrefixes","fd","fsp","firstOffset","lastOffset","lastWrote","fv","layoutFor","offsetOf","UnionDiscriminator","discr","defaultLayout","usesPrefixDiscriminator","registry","boundGetSourceVariant","defaultGetSourceVariant","bind","getSourceVariant","configGetSourceVariant","gsv","vlo","getVariant","tag","dlo","clo","contentOffset","addVariant","vb","fixBitwiseResult","msb","_packedSetValue","_packedGetValue","addField","bf","BitField","addBoolean","fieldFor","container","totalBits","usedBits","valueMask","wordMask","wordValue","srcBuffer","write","CString","String","srcb","maxSpan","u48","u24be","s8","ns64","s48be","f64be","seq","utf8","TokenMetadataLayout","borshStruct","borshPublicKey","MintContextLayout","encodeDecode","publicKeyLayout","MINT_CONTEXT_SIZE","getExtensionByteLength","extensionType","dataStartOffset","ExtensionType","TokenMetadata","startOffset","additionalCount","getTokenMetadataByteLength","deserializeMint","rawMint","MintLayout","rawContext","hasExtensions","readUInt8","vecLen","dataLength","extensionData","mintAuthorityOption","freezeAuthorityOption","serializeMint","buffers","baseMintBuffer","contextBuffer","vecLenBuf","ext","decodeTokenMetadata","decoded","encodeTokenMetadata","parseTokenMetadata","extractTokenMetadata","metadataExt","getMintInterface","tokenResult","token2022Result","compressedMintData","getSplMint","unpackMintInterface","unpackSplMint","unpackMintData","compressedMint","createAtaInterface","effectiveAtaProgramId","transaction","Transaction","sendAndConfirmTransaction","createAtaInterfaceIdempotent","mintInfo","trees","mintToInterface","authorityPubkey","multiSignerPubkeys","signers","getOrCreateAtaInterface","_getOrCreateAtaInterface","secretKey","getOwnerPublicKey","ownerPubkey","accountInterface","hasHotAccount","TokenInvalidAccountOwnerError","createCTokenAtaIdempotent","hasCold","hasSplToWrap","TokenInvalidMintError","TokenInvalidOwnerError","getOrCreateCTokenAta","getOrCreateSplAta","transferInterface","providedSplInterfaceInfos","expectedSource","all","ctokenAtaInfo","splAtaInfo","t22AtaInfo","hotBalance","readBigUInt64LE","compressedBalance","splWrapCount","compressedToLoad","computeUnits","calculateComputeUnits","decompressInterface","destinationAta","destinationOwner","isSplDestination","accountsToUse","ataOwner","destinationAtaAddress","getAssociatedTokenAddress","resolvedSplInterfaceInfo","toOffChainMetadataJson","meta","json","description","image","PackedStateTreeInfoLayout","inputAccounts","signedTx","getOrCreateAssociatedTokenAccount","sourceTokenAccount","compressIx","blockhashCtx","createSplInterface","addSplInterfaces","numMaxAdditionalPools","uninitializedIndices","addTokenPools","additionalAccounts","getSlot","txIds","instruction","selectedSplInterfaceInfos","batch","getValidityProof","batchInstructions","checkOwner","checkIsDelegated","transferDelegated","getCompressedTokenAccountsByDelegate","decompressDelegated","splInterfaceInfosToUse","IDL","docs","isMut","args","isOptional","defined","types","kind","variants","errors","code","isSingleSplInterfaceInfo","isSingleTokenPoolInfo"],"mappings":"26tBAMYA,wJAAZ,SAAYA,GAERA,EAAAA,EAAA,GAAA,GAAA,KAEAA,EAAAA,EAAA,GAAA,GAAA,KAEAA,EAAAA,EAAA,QAAA,GAAA,SACH,CAPD,CAAYA,KAAAA,GAOX,CAAA,IAEY,MAAAC,GAAYC,GAAOC,KAAK,QAExBC,GAAqBF,GAAOC,KAAK,iBAEjCE,GAAqC,QAErCC,GAAkCJ,GAAOC,KAAK,CACvD,GAAI,IAAK,GAAI,IAAK,IAAK,IAAK,IAAK,MAExBI,GAAwBL,GAAOC,KAAK,CAC7C,IAAK,GAAI,GAAI,IAAK,GAAI,IAAK,IAAK,MAEvBK,GAA+BN,GAAOC,KAAK,CACpD,GAAI,IAAK,IAAK,GAAI,IAAK,GAAI,IAAK,MAEvBM,GAAyBP,GAAOC,KAAK,CAC9C,IAAK,GAAI,IAAK,IAAK,IAAK,EAAG,GAAI,MAEtBO,GAA2CR,G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