@lightprotocol/compressed-token 0.23.0-beta.1 → 0.23.0-beta.10
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.
- package/dist/cjs/browser/index.cjs +1 -1
- package/dist/cjs/browser/index.cjs.map +1 -1
- package/dist/cjs/browser/types-Csty9bc2.cjs +2 -0
- package/dist/cjs/browser/types-Csty9bc2.cjs.map +1 -0
- package/dist/cjs/browser/unified/index.cjs +1 -1
- package/dist/cjs/browser/unified/index.cjs.map +1 -1
- package/dist/cjs/node/index.cjs +1 -1
- package/dist/cjs/node/index.cjs.map +1 -1
- package/dist/cjs/node/types-DgmOPYyc.cjs +2 -0
- package/dist/cjs/node/types-DgmOPYyc.cjs.map +1 -0
- package/dist/cjs/node/unified/index.cjs +1 -1
- package/dist/cjs/node/unified/index.cjs.map +1 -1
- package/dist/es/browser/index.js +1 -1
- package/dist/es/browser/index.js.map +1 -1
- package/dist/es/browser/types-e_5LjLhR.js +2 -0
- package/dist/es/browser/types-e_5LjLhR.js.map +1 -0
- package/dist/es/browser/unified/index.js +1 -1
- package/dist/es/browser/unified/index.js.map +1 -1
- package/dist/types/index.d.ts +498 -461
- package/dist/types/unified/index.d.ts +718 -664
- package/package.json +17 -11
- package/dist/cjs/browser/types-BYVvBJS4.cjs +0 -2
- package/dist/cjs/browser/types-BYVvBJS4.cjs.map +0 -1
- package/dist/cjs/node/types-C6bFjLLI.cjs +0 -2
- package/dist/cjs/node/types-C6bFjLLI.cjs.map +0 -1
- package/dist/es/browser/types-Z2gqWJ9V.js +0 -2
- package/dist/es/browser/types-Z2gqWJ9V.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-e_5LjLhR.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-light-token.ts","../../../../../src/v3/ata-utils.ts","../../../../../src/v3/instructions/create-ata-interface.ts","../../../../../node_modules/.pnpm/bn.js@5.2.1/node_modules/bn.js/lib/bn.js","../../../../../src/v3/errors.ts","../../../../../src/v3/get-account-interface.ts","../../../../../src/v3/get-associated-token-address-interface.ts","../../../../../src/v3/layout/layout-transfer2.ts","../../../../../src/v3/instructions/wrap.ts","../../../../../src/v3/instructions/create-decompress-interface-instruction.ts","../../../../../src/v3/instructions/load-ata.ts","../../../../../src/v3/assert-v2-only.ts","../../../../../src/v3/instructions/mint-to.ts","../../../../../src/v3/instructions/mint-to-compressed.ts","../../../../../src/v3/instructions/mint-to-interface.ts","../../../../../src/v3/utils/estimate-tx-size.ts","../../../../../src/v3/instructions/calculate-combined-cu.ts","../../../../../src/v3/instructions/transfer-interface.ts","../../../../../src/v3/instructions/unwrap.ts","../../../../../src/v3/instructions/freeze-thaw.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/load-ata.ts","../../../../../src/v3/actions/get-or-create-ata-interface.ts","../../../../../src/v3/actions/slice-last.ts","../../../../../src/v3/actions/transfer-interface.ts","../../../../../src/v3/actions/wrap.ts","../../../../../src/v3/layout/layout-token-metadata.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';\nimport { PublicKey } from '@solana/web3.js';\n\n/** Default compressible config PDA (V1) */\nexport const LIGHT_TOKEN_CONFIG = new PublicKey(\n 'ACXg8a7VaqecBWrSbdu73W4Pg9gsqXJ3EXAqkHyhvVXg',\n);\n\n/** Default rent sponsor PDA (V1) */\nexport const LIGHT_TOKEN_RENT_SPONSOR = new PublicKey(\n 'r18WwUxfG8kQ69bQPAB2jV6zGNKy3GosFGctjQoV4ti',\n);\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\n/**\n * Maximum lamports for rent top-up in a single instruction.\n * u16::MAX = no limit; 0 = no top-ups allowed.\n * Matches Rust SDK (e.g. token-sdk create_mints uses u16::MAX for \"no limit\").\n */\nexport const MAX_TOP_UP = 65535;\n\n/**\n * Rent configuration constants for compressible light token accounts.\n * These match the Rust SDK defaults in program-libs/compressible/src/rent/config.rs\n */\n\n/** Base rent per epoch (lamports) */\nexport const BASE_RENT_PER_EPOCH = 128;\n\n/** Rent per byte per epoch (lamports) */\nexport const RENT_PER_BYTE_PER_EPOCH = 1;\n\n/** Slots per rent epoch (1.5 hours) */\nexport const SLOTS_PER_RENT_EPOCH = 13500;\n\n/** Compression cost (lamports) - paid at account creation */\nexport const COMPRESSION_COST = 10000;\n\n/** Compression incentive (lamports) - paid at account creation */\nexport const COMPRESSION_INCENTIVE = 1000;\n\n/** Total compression cost (COMPRESSION_COST + COMPRESSION_INCENTIVE) */\nexport const TOTAL_COMPRESSION_COST = COMPRESSION_COST + COMPRESSION_INCENTIVE;\n\n/**\n * Compressible light token account size in bytes.\n * = 165 (base SPL token) + 1 (account_type) + 1 (Option) + 4 (Vec len) + 1 (ext disc) + 4 (ext header) + 96 (CompressionInfo) = 272\n * Source: program-libs/token-interface/src/state/token/top_up.rs MIN_SIZE_WITH_COMPRESSIBLE\n */\nexport const COMPRESSIBLE_LIGHT_TOKEN_ACCOUNT_SIZE = 272;\n\n/**\n * Calculate rent per epoch for a given account size.\n * Formula: base_rent + (bytes * lamports_per_byte_per_epoch)\n */\nexport function rentPerEpoch(bytes: number): number {\n return BASE_RENT_PER_EPOCH + bytes * RENT_PER_BYTE_PER_EPOCH;\n}\n\n/**\n * Default rent per epoch for a compressible light token account (272 bytes).\n * = 128 + 272 = 400 lamports\n */\nexport const COMPRESSIBLE_LIGHT_TOKEN_RENT_PER_EPOCH = rentPerEpoch(\n COMPRESSIBLE_LIGHT_TOKEN_ACCOUNT_SIZE,\n);\n\n/** Default prepaid epochs (24 hours = 16 epochs * 1.5h) */\nexport const DEFAULT_PREPAY_EPOCHS = 16;\n\n/** Default write top-up (lamports) - ~2 epochs rent */\nexport const DEFAULT_WRITE_TOP_UP = 766;\n\n/**\n * Calculate fee payer cost at ATA creation.\n * = compression_cost (11K) + (prepay_epochs * rent_per_epoch)\n */\nexport function calculateFeePayerCostAtCreation(\n prepayEpochs: number = DEFAULT_PREPAY_EPOCHS,\n accountBytes: number = COMPRESSIBLE_LIGHT_TOKEN_ACCOUNT_SIZE,\n): number {\n return TOTAL_COMPRESSION_COST + prepayEpochs * rentPerEpoch(accountBytes);\n}\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 {\n bn,\n ParsedTokenAccount,\n TreeType,\n featureFlags,\n} 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\nexport const ERROR_MIXED_TREE_TYPES =\n 'Cannot select accounts from different tree types (V1/V2) in the same batch. Filter accounts by tree type first.';\n\n/**\n * Options for input account selection\n */\nexport interface SelectInputAccountsOptions {\n /**\n * Filter accounts by tree type. If provided, only accounts in trees of\n * this type will be selected. This prevents mixed V1/V2 batches which\n * fail at proof generation.\n */\n treeType?: TreeType;\n}\n\n/**\n * Filters accounts by tree type if specified\n */\nfunction filterByTreeType(\n accounts: ParsedTokenAccount[],\n treeType?: TreeType,\n): ParsedTokenAccount[] {\n if (!treeType) return accounts;\n return accounts.filter(\n acc => acc.compressedAccount.treeInfo.treeType === treeType,\n );\n}\n\n/**\n * Validates that all selected accounts are from the same tree type.\n * Throws if mixed tree types are detected.\n * Silently skips validation if accounts don't have treeInfo (e.g. mock accounts).\n */\nfunction validateSameTreeType(accounts: ParsedTokenAccount[]): void {\n if (accounts.length <= 1) return;\n\n // Skip validation if treeInfo is not available (mock accounts)\n const accountsWithTreeInfo = accounts.filter(\n acc => acc.compressedAccount?.treeInfo?.treeType !== undefined,\n );\n if (accountsWithTreeInfo.length <= 1) return;\n\n const firstTreeType =\n accountsWithTreeInfo[0].compressedAccount.treeInfo.treeType;\n const hasMixedTypes = accountsWithTreeInfo.some(\n acc => acc.compressedAccount.treeInfo.treeType !== firstTreeType,\n );\n\n if (hasMixedTypes) {\n throw new Error(ERROR_MIXED_TREE_TYPES);\n }\n}\n\n/**\n * Groups accounts by tree type for separate processing\n */\nexport function groupAccountsByTreeType(\n accounts: ParsedTokenAccount[],\n): Map<TreeType, ParsedTokenAccount[]> {\n const groups = new Map<TreeType, ParsedTokenAccount[]>();\n\n for (const account of accounts) {\n const treeType = account.compressedAccount.treeInfo.treeType;\n const existing = groups.get(treeType) || [];\n existing.push(account);\n groups.set(treeType, existing);\n }\n\n return groups;\n}\n\n/**\n * Result of selectAccountsByPreferredTreeType\n */\nexport interface SelectedAccountsResult {\n /** The selected accounts (all from the same tree type) */\n accounts: ParsedTokenAccount[];\n /** The tree type of the selected accounts */\n treeType: TreeType;\n /** Total balance of selected accounts */\n totalBalance: BN;\n}\n\n/**\n * Selects accounts by preferred tree type with automatic fallback.\n *\n * In V2 mode, prefers StateV2 accounts. Falls back to StateV1 if V2\n * has insufficient balance.\n *\n * This ensures all returned accounts are from the same tree type,\n * preventing mixed V1/V2 batch proof failures.\n *\n * @param accounts All available accounts (can be mixed V1/V2)\n * @param requiredAmount Minimum amount needed (optional - if not provided, returns all from preferred type)\n * @returns Selected accounts from a single tree type\n */\nexport function selectAccountsByPreferredTreeType(\n accounts: ParsedTokenAccount[],\n requiredAmount?: BN,\n): SelectedAccountsResult {\n const preferredTreeType = featureFlags.isV2()\n ? TreeType.StateV2\n : TreeType.StateV1;\n\n const accountsByTreeType = groupAccountsByTreeType(accounts);\n\n // Try preferred tree type first\n let selectedTreeType = preferredTreeType;\n let selectedAccounts = accountsByTreeType.get(preferredTreeType) || [];\n let totalBalance = selectedAccounts.reduce(\n (sum, acc) => sum.add(acc.parsed.amount),\n bn(0),\n );\n\n // If insufficient balance in preferred type and requiredAmount specified, try fallback\n if (requiredAmount && totalBalance.lt(requiredAmount)) {\n const fallbackType =\n preferredTreeType === TreeType.StateV2\n ? TreeType.StateV1\n : TreeType.StateV2;\n const fallbackAccounts = accountsByTreeType.get(fallbackType) || [];\n const fallbackBalance = fallbackAccounts.reduce(\n (sum, acc) => sum.add(acc.parsed.amount),\n bn(0),\n );\n\n if (fallbackBalance.gte(requiredAmount)) {\n selectedTreeType = fallbackType;\n selectedAccounts = fallbackAccounts;\n totalBalance = fallbackBalance;\n }\n // If neither type has enough, proceed with preferred type\n // and let downstream selection throw the insufficient balance error\n }\n\n return {\n accounts: selectedAccounts,\n treeType: selectedTreeType,\n totalBalance,\n };\n}\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 * @param {SelectInputAccountsOptions} [options] - Optional selection options.\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 options?: SelectInputAccountsOptions,\n): [\n selectedAccounts: ParsedTokenAccount[],\n total: BN,\n totalLamports: BN | null,\n maxPossibleAmount: BN,\n] {\n const filteredAccounts = filterByTreeType(accounts, options?.treeType);\n\n // First try to find an exact match\n const exactMatch = filteredAccounts.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 filteredAccounts,\n approveAmount,\n maxInputs,\n options,\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 * @param {SelectInputAccountsOptions} [options] - Optional selection options.\n *\n * @returns Returns selected accounts and their totals.\n */\nexport function selectMinCompressedTokenAccountsForDecompression(\n accounts: ParsedTokenAccount[],\n amount: BN,\n maxInputs: number = 4,\n options?: SelectInputAccountsOptions,\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 options,\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 * @param {SelectInputAccountsOptions} [options] - Optional selection options.\n * Use treeType to filter by V1/V2.\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 options?: SelectInputAccountsOptions,\n): [\n selectedAccounts: ParsedTokenAccount[],\n total: BN,\n totalLamports: BN | null,\n maxPossibleAmount: BN,\n] {\n const filteredAccounts = filterByTreeType(accounts, options?.treeType);\n\n const [\n selectedAccounts,\n accumulatedAmount,\n accumulatedLamports,\n maxPossibleAmount,\n ] = selectMinCompressedTokenAccountsForTransferOrPartial(\n filteredAccounts,\n transferAmount,\n maxInputs,\n );\n\n // Validate selected accounts are all same tree type\n validateSameTreeType(selectedAccounts);\n\n if (accumulatedAmount.lt(bn(transferAmount))) {\n const totalBalance = filteredAccounts.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()} (${filteredAccounts.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 * @param {SelectInputAccountsOptions} [options] - Optional selection options.\n * Use treeType to filter by V1/V2.\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 options?: SelectInputAccountsOptions,\n): [\n selectedAccounts: ParsedTokenAccount[],\n total: BN,\n totalLamports: BN | null,\n maxPossibleAmount: BN,\n] {\n const filteredAccounts = filterByTreeType(accounts, options?.treeType);\n\n const [\n selectedAccounts,\n accumulatedAmount,\n accumulatedLamports,\n maxPossibleAmount,\n ] = selectSmartCompressedTokenAccountsForTransferOrPartial(\n filteredAccounts,\n transferAmount,\n maxInputs,\n );\n\n // Validate selected accounts are all same tree type\n validateSameTreeType(selectedAccounts);\n\n if (accumulatedAmount.lt(bn(transferAmount))) {\n const totalBalance = filteredAccounts.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()} (${filteredAccounts.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 * Output state tree. Required for mint/compress (no inputs).\n * For transfer/merge with V1 inputs: pass a V2 tree for migration.\n * If not provided with inputs, uses input tree.\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 // Determine output tree:\n // 1. If outputStateTreeInfo provided, use it (enables V1→V2 migration)\n // 2. Otherwise use input tree (requires inputs)\n let outputTreeInfo: TreeInfo;\n\n if (outputStateTreeInfo) {\n outputTreeInfo = outputStateTreeInfo;\n } else if (inputCompressedTokenAccounts.length > 0) {\n outputTreeInfo =\n inputCompressedTokenAccounts[0].compressedAccount.treeInfo;\n } else {\n throw new Error(\n 'Either input accounts or outputStateTreeInfo must be provided',\n );\n }\n\n // Use next tree if available, otherwise fall back to current tree.\n // `nextTreeInfo` always takes precedence.\n const activeTreeInfo = outputTreeInfo.nextTreeInfo || outputTreeInfo;\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 batchMerkleTree1,\n batchQueue1,\n batchCpiContext1,\n} from '@lightprotocol/stateless.js';\n\n/**\n * Hardcoded V2 tree for V1→V2 migration in transfer/merge.\n */\nconst DEFAULT_V2_MIGRATION_TREE: TreeInfo = {\n tree: new PublicKey(batchMerkleTree1),\n queue: new PublicKey(batchQueue1),\n cpiContext: new PublicKey(batchCpiContext1),\n treeType: TreeType.StateV2,\n nextTreeInfo: null,\n};\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 * createSplInterfaceInstruction]\n *\n * Note that `createSplInterfaceInstruction` 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 createSplInterfaceInstruction = await this.createSplInterface({\n feePayer,\n mint,\n tokenProgramId: tokenProgram,\n });\n\n return [\n createMintAccountInstruction,\n initializeMintInstruction,\n createSplInterfaceInstruction,\n ];\n }\n\n /**\n * Create SPL interface (omnibus account) for an existing SPL mint.\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 createSplInterface instruction\n */\n static async createSplInterface({\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 * @deprecated Use {@link createSplInterface} instead.\n */\n static async createTokenPool(\n params: CreateSplInterfaceParams,\n ): Promise<TransactionInstruction> {\n return this.createSplInterface(params);\n }\n\n /**\n * Add a token pool to an existing SPL mint. For new mints, use\n * {@link createSplInterface}.\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 * V1 inputs automatically migrate to V2 outputs when in V2 mode.\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 // Determine output tree: V1 inputs in V2 mode -> hardcoded V2 tree\n const inputTreeType =\n inputCompressedTokenAccounts[0]?.compressedAccount.treeInfo\n .treeType;\n const outputStateTreeInfo =\n inputTreeType === TreeType.StateV1 && featureFlags.isV2()\n ? DEFAULT_V2_MIGRATION_TREE\n : undefined;\n\n const {\n inputTokenDataWithContext,\n packedOutputTokenData,\n remainingAccountMetas,\n } = packCompressedTokenAccounts({\n inputCompressedTokenAccounts,\n rootIndices: recentInputStateRootIndices,\n tokenTransferOutputs,\n outputStateTreeInfo,\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 * @returns instruction\n */\n static async mergeTokenAccounts({\n payer,\n owner,\n inputCompressedTokenAccounts,\n mint,\n recentValidityProof,\n recentInputStateRootIndices,\n }: MergeTokenAccountsParams): Promise<TransactionInstruction[]> {\n const maxAccounts = featureFlags.isV2() ? 8 : 4;\n if (inputCompressedTokenAccounts.length > maxAccounts) {\n throw new Error(\n `Cannot merge more than ${maxAccounts} token accounts at once`,\n );\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 LIGHT_TOKEN_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 light mint address as bytes.\n * @internal\n */\nexport function deriveCMintAddress(\n mintSeed: PublicKey,\n addressTreeInfo: TreeInfo,\n) {\n // find_mint_address returns [light mint, bump], we want light mint\n // In JS, just use the mintSeed directly as the light mint address\n const address = deriveAddressV2(\n findMintAddress(mintSeed)[0].toBytes(),\n addressTreeInfo.tree,\n LIGHT_TOKEN_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 light-token mint.\n * @param mintSeed The mint seed public key.\n * @returns [PDA, bump]\n * @internal\n */\nexport function findMintAddress(mintSigner: PublicKey): [PublicKey, number] {\n const [address, bump] = PublicKey.findProgramAddressSync(\n [COMPRESSED_MINT_SEED, mintSigner.toBuffer()],\n LIGHT_TOKEN_PROGRAM_ID,\n );\n return [address, bump];\n}\n\n/**\n * Same as \"getAssociatedTokenAddress\" but returns the bump as well.\n * Uses light-token program ID.\n * @internal\n */\nexport function getAssociatedLightTokenAddressAndBump(\n owner: PublicKey,\n mint: PublicKey,\n) {\n return PublicKey.findProgramAddressSync(\n [owner.toBuffer(), LIGHT_TOKEN_PROGRAM_ID.toBuffer(), mint.toBuffer()],\n LIGHT_TOKEN_PROGRAM_ID,\n );\n}\n\n/**\n * Same as \"getAssociatedTokenAddress\", returning just the associated token address.\n * Uses light-token program ID.\n * @internal\n */\nexport function getAssociatedLightTokenAddress(\n owner: PublicKey,\n mint: PublicKey,\n): PublicKey {\n return PublicKey.findProgramAddressSync(\n [owner.toBuffer(), LIGHT_TOKEN_PROGRAM_ID.toBuffer(), mint.toBuffer()],\n LIGHT_TOKEN_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/light-token-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 MintToLightTokenActionLayout = 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 DecompressMintActionLayout = struct([\n u8('rentPayment'),\n u32('writeTopUp'),\n]);\n\nexport const CompressAndCloseCMintActionLayout = struct([u8('idempotent')]);\n\nexport const ActionLayout = rustEnum([\n MintToCompressedActionLayout.replicate('mintToCompressed'),\n UpdateAuthorityLayout.replicate('updateMintAuthority'),\n UpdateAuthorityLayout.replicate('updateFreezeAuthority'),\n MintToLightTokenActionLayout.replicate('mintToLightToken'),\n UpdateMetadataFieldActionLayout.replicate('updateMetadataField'),\n UpdateMetadataAuthorityActionLayout.replicate('updateMetadataAuthority'),\n RemoveMetadataKeyActionLayout.replicate('removeMetadataKey'),\n DecompressMintActionLayout.replicate('decompressMint'),\n CompressAndCloseCMintActionLayout.replicate('compressAndCloseCMint'),\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('cmintDecompressed'),\n publicKey('mint'),\n array(u8(), 32, 'mintSigner'),\n u8('bump'),\n]);\n\nexport const MintInstructionDataLayout = 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 u16('maxTopUp'),\n option(CreateMintLayout, 'createMint'),\n vec(ActionLayout, 'actions'),\n option(CompressedProofLayout, 'proof'),\n option(CpiContextLayout, 'cpiContext'),\n option(MintInstructionDataLayout, '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 MintToLightTokenAction {\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 interface DecompressMintAction {\n rentPayment: number;\n writeTopUp: number;\n}\n\nexport interface CompressAndCloseCMintAction {\n idempotent: number;\n}\n\nexport type Action =\n | { mintToCompressed: MintToCompressedAction }\n | { updateMintAuthority: UpdateAuthority }\n | { updateFreezeAuthority: UpdateAuthority }\n | { mintToLightToken: MintToLightTokenAction }\n | { updateMetadataField: UpdateMetadataFieldAction }\n | { updateMetadataAuthority: UpdateMetadataAuthorityAction }\n | { removeMetadataKey: RemoveMetadataKeyAction }\n | { decompressMint: DecompressMintAction }\n | { compressAndCloseCMint: CompressAndCloseCMintAction };\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 cmintDecompressed: boolean;\n mint: PublicKey;\n mintSigner: number[];\n bump: number;\n}\n\nexport interface MintLayoutData {\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 maxTopUp: number;\n createMint: CreateMint | null;\n actions: Action[];\n proof: ValidityProof | null;\n cpiContext: CpiContext | null;\n mint: MintLayoutData | null;\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 * @internal\n */\nexport function encodeMintActionInstructionData(\n data: MintActionCompressedInstructionData,\n): Buffer {\n // Convert bigint fields to BN for Borsh encoding\n const convertedActions = data.actions.map(action => {\n if ('mintToCompressed' in action && action.mintToCompressed) {\n return {\n mintToCompressed: {\n ...action.mintToCompressed,\n recipients: action.mintToCompressed.recipients.map(r => ({\n ...r,\n amount: bn(r.amount.toString()),\n })),\n },\n };\n }\n if ('mintToLightToken' in action && action.mintToLightToken) {\n return {\n mintToLightToken: {\n ...action.mintToLightToken,\n amount: bn(action.mintToLightToken.amount.toString()),\n },\n };\n }\n return action;\n });\n\n const buffer = Buffer.alloc(10000);\n\n const encodableData = {\n ...data,\n actions: convertedActions,\n mint: data.mint\n ? {\n ...data.mint,\n supply: bn(data.mint.supply.toString()),\n }\n : null,\n };\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 * @internal\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 LIGHT_TOKEN_PROGRAM_ID,\n LightSystemProgram,\n defaultStaticAccountsStruct,\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 {\n MAX_TOP_UP,\n TokenDataVersion,\n LIGHT_TOKEN_CONFIG,\n LIGHT_TOKEN_RENT_SPONSOR,\n} from '../../constants';\n\n/**\n * Token metadata for creating a light-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 maxTopUp?: number;\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 * @internal\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\n/** @internal */\nexport function encodeCreateMintInstructionData(\n params: EncodeCreateMintInstructionParams,\n): Buffer {\n const [splMintPda, bump] = findMintAddress(params.mintSigner);\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 maxTopUp: params.maxTopUp ?? MAX_TOP_UP,\n createMint: {\n readOnlyAddressTrees: [0, 0, 0, 0],\n readOnlyAddressTreeRootIndices: [0, 0, 0, 0],\n },\n actions: [\n {\n decompressMint: {\n rentPayment: 16,\n writeTopUp: 766,\n },\n },\n ],\n proof: validatedProof,\n cpiContext: null,\n mint: {\n supply: BigInt(0),\n decimals: params.decimals,\n metadata: {\n version: TokenDataVersion.ShaFlat,\n cmintDecompressed: false,\n mint: splMintPda,\n mintSigner: Array.from(params.mintSigner.toBytes()),\n bump,\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 light-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 * @param maxTopUp Optional cap on rent top-up (units of 1k lamports; default no cap)\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 maxTopUp?: number,\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 maxTopUp,\n });\n\n return buildCreateMintIx(\n mintSigner,\n mintAuthority,\n payer,\n outputStateTreeInfo,\n addressTreeInfo,\n data,\n );\n}\n\n/** @internal */\nfunction buildCreateMintIx(\n mintSigner: PublicKey,\n mintAuthority: PublicKey,\n payer: PublicKey,\n outputStateTreeInfo: TreeInfo,\n addressTreeInfo: AddressTreeInfo,\n data: Buffer,\n): TransactionInstruction {\n const sys = defaultStaticAccountsStruct();\n const [splMintPda] = findMintAddress(mintSigner);\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 {\n pubkey: LIGHT_TOKEN_CONFIG,\n isSigner: false,\n isWritable: false,\n },\n { pubkey: splMintPda, isSigner: false, isWritable: true },\n {\n pubkey: LIGHT_TOKEN_RENT_SPONSOR,\n isSigner: false,\n isWritable: true,\n },\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: LIGHT_TOKEN_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 LIGHT_TOKEN_PROGRAM_ID,\n LightSystemProgram,\n defaultStaticAccountsStruct,\n getDefaultAddressTreeInfo,\n getOutputQueue,\n} from '@lightprotocol/stateless.js';\nimport { MAX_TOP_UP } from '../../constants';\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 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 maxTopUp?: number;\n}\n\n/** @internal */\nfunction encodeUpdateMintInstructionData(\n params: EncodeUpdateMintInstructionParams,\n): Buffer {\n // Build action\n const action: Action =\n params.actionType === 'mintAuthority'\n ? { updateMintAuthority: { newAuthority: params.newAuthority } }\n : { updateFreezeAuthority: { newAuthority: params.newAuthority } };\n\n // When mint is decompressed (cmintDecompressed=true), the program reads from light mint account\n // so we don't need to include mint data in the instruction\n const isDecompressed =\n params.mintInterface.mintContext?.cmintDecompressed ?? false;\n\n // Build extensions if metadata present (only needed when not decompressed)\n let extensions: ExtensionInstructionData[] | null = null;\n if (!isDecompressed && 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 maxTopUp: params.maxTopUp ?? MAX_TOP_UP,\n createMint: null,\n actions: [action],\n proof: params.proof,\n cpiContext: null,\n mint: isDecompressed\n ? null\n : {\n supply: params.mintInterface.mint.supply,\n decimals: params.mintInterface.mint.decimals,\n metadata: {\n version: params.mintInterface.mintContext!.version,\n cmintDecompressed:\n params.mintInterface.mintContext!.cmintDecompressed,\n mint: params.mintInterface.mintContext!.splMint,\n mintSigner: Array.from(\n params.mintInterface.mintContext!.mintSigner,\n ),\n bump: params.mintInterface.mintContext!.bump,\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 light mint's mint authority.\n * Works for both compressed and decompressed light mints.\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 light mint (null for decompressed light mints)\n * @param maxTopUp Optional cap on rent top-up (units of 1k lamports; default no cap)\n */\nexport function createUpdateMintAuthorityInstruction(\n mintInterface: MintInterface,\n currentMintAuthority: PublicKey,\n newMintAuthority: PublicKey | null,\n payer: PublicKey,\n validityProof: ValidityProofWithContext | null,\n maxTopUp?: number,\n): TransactionInstruction {\n if (!mintInterface.merkleContext) {\n throw new Error(\n 'MintInterface must have merkleContext for light mint operations',\n );\n }\n if (!mintInterface.mintContext) {\n throw new Error(\n 'MintInterface must have mintContext for light mint operations',\n );\n }\n\n const merkleContext = mintInterface.merkleContext;\n const outputQueue = getOutputQueue(merkleContext);\n const isDecompressed = mintInterface.mintContext.cmintDecompressed ?? false;\n\n const addressTreeInfo = getDefaultAddressTreeInfo();\n const data = encodeUpdateMintInstructionData({\n leafIndex: merkleContext.leafIndex,\n proveByIndex: true,\n rootIndex: validityProof?.rootIndices[0] ?? 0,\n proof: isDecompressed ? null : (validityProof?.compressedProof ?? null),\n mintInterface,\n newAuthority: newMintAuthority,\n actionType: 'mintAuthority',\n maxTopUp,\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 // light mint account when decompressed (must come before payer for correct account ordering)\n ...(isDecompressed\n ? [\n {\n pubkey: mintInterface.mint.address,\n isSigner: false,\n isWritable: true,\n },\n ]\n : []),\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: LIGHT_TOKEN_PROGRAM_ID,\n keys,\n data,\n });\n}\n\n/**\n * Create instruction for updating a light mint's freeze authority.\n * Works for both compressed and decompressed light mints.\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 light mint (null for decompressed light mints)\n * @param maxTopUp Optional cap on rent top-up (units of 1k lamports; default no cap)\n */\nexport function createUpdateFreezeAuthorityInstruction(\n mintInterface: MintInterface,\n currentFreezeAuthority: PublicKey,\n newFreezeAuthority: PublicKey | null,\n payer: PublicKey,\n validityProof: ValidityProofWithContext | null,\n maxTopUp?: number,\n): TransactionInstruction {\n if (!mintInterface.merkleContext) {\n throw new Error(\n 'MintInterface must have merkleContext for light mint operations',\n );\n }\n if (!mintInterface.mintContext) {\n throw new Error(\n 'MintInterface must have mintContext for light mint operations',\n );\n }\n\n const merkleContext = mintInterface.merkleContext;\n const outputQueue = getOutputQueue(merkleContext);\n const isDecompressed = mintInterface.mintContext.cmintDecompressed ?? false;\n\n const addressTreeInfo = getDefaultAddressTreeInfo();\n const data = encodeUpdateMintInstructionData({\n leafIndex: merkleContext.leafIndex,\n proveByIndex: true,\n rootIndex: validityProof?.rootIndices[0] ?? 0,\n proof: isDecompressed ? null : (validityProof?.compressedProof ?? null),\n mintInterface,\n newAuthority: newFreezeAuthority,\n actionType: 'freezeAuthority',\n maxTopUp,\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 // light mint account when decompressed (must come before payer for correct account ordering)\n ...(isDecompressed\n ? [\n {\n pubkey: mintInterface.mint.address,\n isSigner: false,\n isWritable: true,\n },\n ]\n : []),\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: LIGHT_TOKEN_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 LIGHT_TOKEN_PROGRAM_ID,\n LightSystemProgram,\n defaultStaticAccountsStruct,\n getDefaultAddressTreeInfo,\n getOutputQueue,\n} from '@lightprotocol/stateless.js';\nimport { MAX_TOP_UP } from '../../constants';\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 leafIndex: number;\n rootIndex: number;\n proof: { a: number[]; b: number[]; c: number[] } | null;\n mintInterface: MintInterface;\n action: UpdateMetadataAction;\n maxTopUp?: number;\n}\n\n/** @internal */\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\n/** @internal */\nfunction encodeUpdateMetadataInstructionData(\n params: EncodeUpdateMetadataInstructionParams,\n): Buffer {\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 // When mint is decompressed (cmintDecompressed=true), the program reads from light mint account\n // so we don't need to include mint data in the instruction\n const isDecompressed =\n mintInterface.mintContext?.cmintDecompressed ?? false;\n\n const instructionData: MintActionCompressedInstructionData = {\n leafIndex: params.leafIndex,\n proveByIndex: params.proof === null,\n rootIndex: params.rootIndex,\n maxTopUp: params.maxTopUp ?? MAX_TOP_UP,\n createMint: null,\n actions: [convertActionToBorsh(params.action)],\n proof: params.proof,\n cpiContext: null,\n mint: isDecompressed\n ? null\n : {\n supply: mintInterface.mint.supply,\n decimals: mintInterface.mint.decimals,\n metadata: {\n version: mintInterface.mintContext!.version,\n cmintDecompressed:\n mintInterface.mintContext!.cmintDecompressed,\n mint: mintInterface.mintContext!.splMint,\n mintSigner: Array.from(\n mintInterface.mintContext!.mintSigner,\n ),\n bump: mintInterface.mintContext!.bump,\n },\n mintAuthority: mintInterface.mint.mintAuthority,\n freezeAuthority: mintInterface.mint.freezeAuthority,\n extensions: [\n {\n tokenMetadata: {\n updateAuthority:\n mintInterface.tokenMetadata.updateAuthority ??\n null,\n name: Buffer.from(\n mintInterface.tokenMetadata.name,\n ),\n symbol: Buffer.from(\n mintInterface.tokenMetadata.symbol,\n ),\n uri: Buffer.from(mintInterface.tokenMetadata.uri),\n additionalMetadata: null,\n },\n },\n ],\n },\n };\n\n return encodeMintActionInstructionData(instructionData);\n}\n\n/** @internal */\nfunction createUpdateMetadataInstruction(\n mintInterface: MintInterface,\n authority: PublicKey,\n payer: PublicKey,\n validityProof: ValidityProofWithContext | null,\n action: UpdateMetadataAction,\n maxTopUp?: number,\n): TransactionInstruction {\n if (!mintInterface.merkleContext) {\n throw new Error(\n 'MintInterface must have merkleContext for light mint operations',\n );\n }\n if (!mintInterface.mintContext) {\n throw new Error(\n 'MintInterface must have mintContext for light 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 const isDecompressed = mintInterface.mintContext.cmintDecompressed ?? false;\n\n const addressTreeInfo = getDefaultAddressTreeInfo();\n const data = encodeUpdateMetadataInstructionData({\n leafIndex: merkleContext.leafIndex,\n rootIndex: validityProof?.rootIndices[0] ?? 0,\n proof: isDecompressed ? null : (validityProof?.compressedProof ?? null),\n mintInterface,\n action,\n maxTopUp,\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 // light mint account when decompressed (must come before payer for correct account ordering)\n ...(isDecompressed\n ? [\n {\n pubkey: mintInterface.mint.address,\n isSigner: false,\n isWritable: true,\n },\n ]\n : []),\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: LIGHT_TOKEN_PROGRAM_ID,\n keys,\n data,\n });\n}\n\n/**\n * Create instruction for updating a light 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 light mint (null for decompressed light mints)\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 maxTopUp Optional cap on rent top-up (units of 1k lamports; default no cap)\n */\nexport function createUpdateMetadataFieldInstruction(\n mintInterface: MintInterface,\n authority: PublicKey,\n payer: PublicKey,\n validityProof: ValidityProofWithContext | null,\n fieldType: 'name' | 'symbol' | 'uri' | 'custom',\n value: string,\n customKey?: string,\n extensionIndex: number = 0,\n maxTopUp?: number,\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 maxTopUp,\n );\n}\n\n/**\n * Create instruction for updating a light 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 light mint (null for decompressed light mints)\n * @param extensionIndex Extension index (default: 0)\n * @param maxTopUp Optional cap on rent top-up (units of 1k lamports; default no cap)\n */\nexport function createUpdateMetadataAuthorityInstruction(\n mintInterface: MintInterface,\n currentAuthority: PublicKey,\n newAuthority: PublicKey,\n payer: PublicKey,\n validityProof: ValidityProofWithContext | null,\n extensionIndex: number = 0,\n maxTopUp?: number,\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 maxTopUp,\n );\n}\n\n/**\n * Create instruction for removing a metadata key from a light 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 light mint (null for decompressed light mints)\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 maxTopUp Optional cap on rent top-up (units of 1k lamports; default no cap)\n */\nexport function createRemoveMetadataKeyInstruction(\n mintInterface: MintInterface,\n authority: PublicKey,\n payer: PublicKey,\n validityProof: ValidityProofWithContext | null,\n key: string,\n idempotent: boolean = false,\n extensionIndex: number = 0,\n maxTopUp?: number,\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 maxTopUp,\n );\n}\n","import {\n PublicKey,\n SystemProgram,\n TransactionInstruction,\n} from '@solana/web3.js';\nimport { Buffer } from 'buffer';\nimport { LIGHT_TOKEN_PROGRAM_ID } from '@lightprotocol/stateless.js';\nimport { struct, u8, u32, option, vec, array } from '@coral-xyz/borsh';\nimport { LIGHT_TOKEN_CONFIG, LIGHT_TOKEN_RENT_SPONSOR } from '../../constants';\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\n// From: program-libs/token-interface/src/instructions/extensions/compressible.rs\nconst CompressibleExtensionInstructionDataLayout = struct([\n u8('tokenAccountVersion'),\n u8('rentPayment'),\n u8('compressionOnly'),\n u32('writeTopUp'),\n option(CompressToPubkeyLayout, 'compressToAccountPubkey'),\n]);\n\nconst CreateAssociatedTokenAccountInstructionDataLayout = struct([\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 compressionOnly: number;\n writeTopUp: number;\n compressToAccountPubkey?: CompressToPubkey | null;\n}\n\nexport interface CreateAssociatedLightTokenAccountParams {\n compressibleConfig?: CompressibleConfig | null;\n}\n\n/**\n * Default compressible config for light-token ATAs - matches Rust SDK defaults.\n *\n * - tokenAccountVersion: 3 (ShaFlat) - latest hashing scheme\n * - rentPayment: 16 - prepay 16 epochs (~24 hours rent)\n * - compressionOnly: 1 - required for ATAs\n * - writeTopUp: 766 - per-write top-up (~2 epochs rent) when rent < 2 epochs\n * - compressToAccountPubkey: null - required for ATAs\n *\n * Cost breakdown at associated token account creation:\n * - Rent sponsor PDA (LIGHT_TOKEN_RENT_SPONSOR) pays: rent exemption (~890,880 lamports)\n * - Fee payer pays: compression_cost (11K) + 16 epochs rent (~6,400) = ~17,400 lamports + tx fees\n *\n * Per-write top-up (transfers):\n * - When account rent is below 2 epochs, fee payer pays 766 lamports top-up\n * - This keeps the account perpetually funded when actively used\n *\n * Rent calculation (272-byte compressible lightToken account):\n * - rent_per_epoch = base_rent (128) + bytes * rent_per_byte (272 * 1) = 400 lamports\n * - 16 epochs = 16 * 400 = 6,400 lamports (24 hours)\n * - 2 epochs = 2 * 400 = 800 lamports (~3 hours, writeTopUp = 766 is conservative)\n *\n * Account size breakdown (272 bytes):\n * - 165 bytes: SPL token base layout\n * - 1 byte: account_type discriminator\n * - 1 byte: Option discriminator for extensions\n * - 4 bytes: Vec length prefix\n * - 1 byte: extension type discriminant\n * - 4 bytes: CompressibleExtension header (decimals_option, decimals, compression_only, is_ata)\n * - 96 bytes: CompressionInfo struct\n */\nexport const DEFAULT_COMPRESSIBLE_CONFIG: CompressibleConfig = {\n tokenAccountVersion: 3, // ShaFlat (latest hashing scheme)\n rentPayment: 16, // 16 epochs (~24 hours) - matches Rust SDK\n compressionOnly: 1, // Required for ATAs\n writeTopUp: 766, // Per-write top-up (~2 epochs) - matches Rust SDK\n compressToAccountPubkey: null, // Required null for ATAs\n};\n\n/** @internal */\nfunction getAssociatedLightTokenAddress(\n owner: PublicKey,\n mint: PublicKey,\n): PublicKey {\n return PublicKey.findProgramAddressSync(\n [owner.toBuffer(), LIGHT_TOKEN_PROGRAM_ID.toBuffer(), mint.toBuffer()],\n LIGHT_TOKEN_PROGRAM_ID,\n )[0];\n}\n\n/** @internal */\nfunction encodeCreateAssociatedLightTokenAccountData(\n params: CreateAssociatedLightTokenAccountParams,\n idempotent: boolean,\n): Buffer {\n const buffer = Buffer.alloc(2000);\n const len = CreateAssociatedTokenAccountInstructionDataLayout.encode(\n {\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 CreateAssociatedLightTokenAccountInstructionParams {\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 light-token account.\n * Uses the default rent sponsor PDA by default.\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 Compressible configuration (defaults to rent sponsor config).\n * @param configAccount Config account (defaults to LIGHT_TOKEN_CONFIG).\n * @param rentPayerPda Rent payer PDA (defaults to LIGHT_TOKEN_RENT_SPONSOR).\n */\nexport function createAssociatedLightTokenAccountInstruction(\n feePayer: PublicKey,\n owner: PublicKey,\n mint: PublicKey,\n compressibleConfig: CompressibleConfig | null = DEFAULT_COMPRESSIBLE_CONFIG,\n configAccount: PublicKey = LIGHT_TOKEN_CONFIG,\n rentPayerPda: PublicKey = LIGHT_TOKEN_RENT_SPONSOR,\n): TransactionInstruction {\n const associatedTokenAccount = getAssociatedLightTokenAddress(owner, mint);\n\n const data = encodeCreateAssociatedLightTokenAccountData(\n {\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 // Optional (only when compressibleConfig is non-null):\n // 5. config account\n // 6. rent_payer PDA\n const keys: {\n pubkey: PublicKey;\n isSigner: boolean;\n isWritable: boolean;\n }[] = [\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 {\n pubkey: SystemProgram.programId,\n isSigner: false,\n isWritable: false,\n },\n ];\n\n if (compressibleConfig) {\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: LIGHT_TOKEN_PROGRAM_ID,\n keys,\n data,\n });\n}\n\n/**\n * Create idempotent instruction for creating an associated light-token account.\n * Uses the default rent sponsor PDA by default.\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 Compressible configuration (defaults to rent sponsor config).\n * @param configAccount Config account (defaults to LIGHT_TOKEN_CONFIG).\n * @param rentPayerPda Rent payer PDA (defaults to LIGHT_TOKEN_RENT_SPONSOR).\n */\nexport function createAssociatedLightTokenAccountIdempotentInstruction(\n feePayer: PublicKey,\n owner: PublicKey,\n mint: PublicKey,\n compressibleConfig: CompressibleConfig | null = DEFAULT_COMPRESSIBLE_CONFIG,\n configAccount: PublicKey = LIGHT_TOKEN_CONFIG,\n rentPayerPda: PublicKey = LIGHT_TOKEN_RENT_SPONSOR,\n): TransactionInstruction {\n const associatedTokenAccount = getAssociatedLightTokenAddress(owner, mint);\n\n const data = encodeCreateAssociatedLightTokenAccountData(\n {\n compressibleConfig,\n },\n true,\n );\n\n const keys: {\n pubkey: PublicKey;\n isSigner: boolean;\n isWritable: boolean;\n }[] = [\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 {\n pubkey: SystemProgram.programId,\n isSigner: false,\n isWritable: false,\n },\n ];\n\n if (compressibleConfig) {\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: LIGHT_TOKEN_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 { LIGHT_TOKEN_PROGRAM_ID } from '@lightprotocol/stateless.js';\nimport { PublicKey } from '@solana/web3.js';\n\n/**\n * Get associated token account program ID for a token program ID\n * @param tokenProgramId Token program ID\n * @returns associated token account program ID\n * @internal\n */\nexport function getAtaProgramId(tokenProgramId: PublicKey): PublicKey {\n if (tokenProgramId.equals(LIGHT_TOKEN_PROGRAM_ID)) {\n return LIGHT_TOKEN_PROGRAM_ID;\n }\n return ASSOCIATED_TOKEN_PROGRAM_ID;\n}\n\n/** associated token account type for validation result */\nexport type AtaType = 'spl' | 'token2022' | 'light-token';\n\n/** Result of associated token account validation */\nexport interface AtaValidationResult {\n valid: true;\n type: AtaType;\n programId: PublicKey;\n}\n\n/**\n * Check if an associated token account address matches the expected derivation from mint+owner.\n *\n * Pass programId for fast path.\n *\n * @param ata associated token account address to check\n * @param mint Mint address\n * @param owner Owner address\n * @param programId Optional: if known, only check this program's associated token account\n * @param allowOwnerOffCurve Allow the owner to be off-curve (PDA)\n * @returns Result with detected type, or throws on mismatch\n * @internal\n */\nexport function checkAtaAddress(\n ata: PublicKey,\n mint: PublicKey,\n owner: PublicKey,\n programId?: PublicKey,\n allowOwnerOffCurve = false,\n): AtaValidationResult {\n // fast path\n if (programId) {\n const expected = getAssociatedTokenAddressSync(\n mint,\n owner,\n allowOwnerOffCurve,\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 lightTokenExpected: PublicKey;\n let splExpected: PublicKey;\n let t22Expected: PublicKey;\n\n // light-token\n lightTokenExpected = getAssociatedTokenAddressSync(\n mint,\n owner,\n allowOwnerOffCurve,\n LIGHT_TOKEN_PROGRAM_ID,\n getAtaProgramId(LIGHT_TOKEN_PROGRAM_ID),\n );\n if (ata.equals(lightTokenExpected)) {\n return {\n valid: true,\n type: 'light-token',\n programId: LIGHT_TOKEN_PROGRAM_ID,\n };\n }\n\n // SPL\n splExpected = getAssociatedTokenAddressSync(\n mint,\n owner,\n allowOwnerOffCurve,\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 allowOwnerOffCurve,\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 `light-token=${lightTokenExpected.toBase58()}, ` +\n `SPL=${splExpected.toBase58()}, ` +\n `T22=${t22Expected.toBase58()}`,\n );\n}\n\n/**\n * Convert programId to AtaType\n * @internal\n */\nfunction programIdToAtaType(programId: PublicKey): AtaType {\n if (programId.equals(LIGHT_TOKEN_PROGRAM_ID)) return 'light-token';\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 { LIGHT_TOKEN_PROGRAM_ID } from '@lightprotocol/stateless.js';\nimport { getAtaProgramId } from '../ata-utils';\nimport {\n createAssociatedLightTokenAccountInstruction,\n createAssociatedLightTokenAccountIdempotentInstruction,\n CompressibleConfig,\n DEFAULT_COMPRESSIBLE_CONFIG,\n} from './create-associated-light-token';\n\n// Re-export for convenience\nexport { DEFAULT_COMPRESSIBLE_CONFIG };\n\n/**\n * light-token-specific config for createAssociatedTokenAccountInterfaceInstruction\n */\nexport interface LightTokenConfig {\n compressibleConfig?: CompressibleConfig | null;\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 light-token). Follows SPL Token API signature with optional light-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 lightTokenConfig Optional light-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 lightTokenConfig?: LightTokenConfig,\n): TransactionInstruction {\n const effectiveAssociatedTokenProgramId =\n associatedTokenProgramId ?? getAtaProgramId(programId);\n\n if (programId.equals(LIGHT_TOKEN_PROGRAM_ID)) {\n return createAssociatedLightTokenAccountInstruction(\n payer,\n owner,\n mint,\n lightTokenConfig?.compressibleConfig,\n lightTokenConfig?.configAccount,\n lightTokenConfig?.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 light-token). Follows SPL Token API signature with optional light-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 lightTokenConfig Optional light-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 lightTokenConfig?: LightTokenConfig,\n): TransactionInstruction {\n const effectiveAssociatedTokenProgramId =\n associatedTokenProgramId ?? getAtaProgramId(programId);\n\n if (programId.equals(LIGHT_TOKEN_PROGRAM_ID)) {\n return createAssociatedLightTokenAccountIdempotentInstruction(\n payer,\n owner,\n mint,\n lightTokenConfig?.compressibleConfig,\n lightTokenConfig?.configAccount,\n lightTokenConfig?.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","(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\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","export const ERR_FETCH_BY_OWNER_REQUIRED = 'fetchByOwner is required';\nexport const ERR_NO_LIGHT_TOKEN_BALANCE_UNWRAP =\n 'No light-token balance to unwrap';\nexport const ERR_MINT_MISSING_MERKLE_CONTEXT =\n 'Mint does not have MerkleContext';\nexport const ERR_MINT_MISSING_TOKEN_METADATA =\n 'Mint does not have TokenMetadata extension';\nexport const ERR_MINT_MISSING_MINT_CONTEXT = 'Mint does not have MintContext';\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 TokenInvalidAccountOwnerError,\n getAssociatedTokenAddressSync,\n AccountState,\n Account,\n} from '@solana/spl-token';\nimport {\n Rpc,\n LIGHT_TOKEN_PROGRAM_ID,\n MerkleContext,\n CompressedAccountWithMerkleContext,\n assertBetaEnabled,\n} from '@lightprotocol/stateless.js';\nimport { Buffer } from 'buffer';\nimport BN from 'bn.js';\nimport { getAtaProgramId, checkAtaAddress } from './ata-utils';\nimport { ERR_FETCH_BY_OWNER_REQUIRED } from './errors';\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 LightTokenHot: 'light-token-hot',\n LightTokenCold: 'light-token-cold',\n} as const;\n\nexport type TokenAccountSourceTypeValue =\n (typeof TokenAccountSourceType)[keyof typeof TokenAccountSourceType];\n\n/** Cold (compressed) source types. Used for load/decompress and isCold. */\nexport const COLD_SOURCE_TYPES: ReadonlySet<TokenAccountSourceTypeValue> =\n new Set([\n TokenAccountSourceType.LightTokenCold,\n TokenAccountSourceType.SplCold,\n TokenAccountSourceType.Token2022Cold,\n ]);\n\nfunction isColdSourceType(type: TokenAccountSourceTypeValue): boolean {\n return COLD_SOURCE_TYPES.has(type);\n}\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 /** Associated token account owner - set by getAtaInterface */\n _owner?: PublicKey;\n /** Associated token account mint - set by getAtaInterface */\n _mint?: PublicKey;\n}\n\nfunction toErrorMessage(error: unknown): string {\n if (error instanceof Error) return error.message;\n return String(error);\n}\n\nfunction throwRpcFetchFailure(context: string, error: unknown): never {\n throw new Error(`${context}: ${toErrorMessage(error)}`);\n}\n\nfunction throwIfUnexpectedRpcErrors(\n context: string,\n unexpectedErrors: unknown[],\n): void {\n if (unexpectedErrors.length > 0) {\n throwRpcFetchFailure(context, unexpectedErrors[0]);\n }\n}\n\nexport type FrozenOperation = 'load' | 'transfer' | 'unwrap';\n\nexport function checkNotFrozen(\n iface: AccountInterface,\n operation: FrozenOperation,\n): void {\n if (iface._anyFrozen) {\n throw new Error(\n `Account is frozen. One or more sources (hot or cold) are frozen; ${operation} is not allowed.`,\n );\n }\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/**\n * Known extension data sizes by Borsh enum discriminator.\n * undefined = variable-length (cannot skip without full parsing).\n * @internal\n */\nconst EXTENSION_DATA_SIZES: Record<number, number | undefined> = {\n 0: 0,\n 1: 0,\n 2: 0,\n 3: 0,\n 4: 0,\n 5: 0,\n 6: 0,\n 7: 0,\n 8: 0,\n 9: 0,\n 10: 0,\n 11: 0,\n 12: 0,\n 13: 0,\n 14: 0,\n 15: 0,\n 16: 0,\n 17: 0,\n 18: 0,\n 19: undefined, // TokenMetadata (variable)\n 20: 0,\n 21: 0,\n 22: 0,\n 23: 0,\n 24: 0,\n 25: 0,\n 26: 0,\n 27: 0, // PausableAccountExtension (unit struct)\n 28: 0, // PermanentDelegateAccountExtension (unit struct)\n 29: 8, // TransferFeeAccountExtension (u64)\n 30: 1, // TransferHookAccountExtension (u8)\n 31: 17, // CompressedOnlyExtension (u64 + u64 + u8)\n 32: undefined, // CompressibleExtension (variable)\n};\n\nconst COMPRESSED_ONLY_DISCRIMINATOR = 31;\n\n/**\n * Extract delegated_amount from CompressedOnly extension in Borsh-serialized\n * TLV data (Vec<ExtensionStruct>).\n * @internal\n */\nfunction extractDelegatedAmountFromTlv(tlv: Buffer | null): bigint | null {\n if (!tlv || tlv.length < 5) return null;\n\n try {\n let offset = 0;\n const vecLen = tlv.readUInt32LE(offset);\n offset += 4;\n\n for (let i = 0; i < vecLen; i++) {\n if (offset >= tlv.length) return null;\n\n const discriminator = tlv[offset];\n offset += 1;\n\n if (discriminator === COMPRESSED_ONLY_DISCRIMINATOR) {\n if (offset + 8 > tlv.length) return null;\n // delegated_amount is the first u64 field\n const lo = BigInt(tlv.readUInt32LE(offset));\n const hi = BigInt(tlv.readUInt32LE(offset + 4));\n return lo | (hi << BigInt(32));\n }\n\n const size = EXTENSION_DATA_SIZES[discriminator];\n if (size === undefined) return null;\n offset += size;\n }\n } catch {\n return null;\n }\n\n return null;\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 // Determine delegatedAmount for compressed TokenData:\n // 1. If CompressedOnly extension present in TLV, use its delegated_amount\n // 2. If delegate is set (regular compressed approve), the entire compressed\n // account's amount is the delegation (change goes to a separate account)\n // 3. Otherwise, 0\n let delegatedAmount = BigInt(0);\n const extensionDelegatedAmount = extractDelegatedAmountFromTlv(\n tokenData.tlv,\n );\n if (extensionDelegatedAmount !== null) {\n delegatedAmount = extensionDelegatedAmount;\n } else if (tokenData.delegate) {\n delegatedAmount = BigInt(tokenData.amount.toString());\n }\n\n return {\n address,\n mint: tokenData.mint,\n owner: tokenData.owner,\n amount: BigInt(tokenData.amount.toString()),\n delegate: tokenData.delegate,\n delegatedAmount,\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 parseLightTokenHot(\n address: PublicKey,\n accountInfo: AccountInfo<Buffer>,\n): {\n accountInfo: AccountInfo<Buffer>;\n loadContext: undefined;\n parsed: Account;\n isCold: false;\n} {\n // Hot light-token accounts use SPL-compatible layout with 4-byte COption tags.\n // unpackAccountSPL correctly parses all fields including delegatedAmount,\n // isNative, and closeAuthority.\n const parsed = unpackAccountSPL(\n address,\n accountInfo,\n LIGHT_TOKEN_PROGRAM_ID,\n );\n return {\n accountInfo,\n loadContext: undefined,\n parsed,\n isCold: false,\n };\n}\n\n/** @internal */\nexport function parseLightTokenCold(\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/light-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 assertBetaEnabled();\n\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 * @param allowOwnerOffCurve Allow owner to be off-curve (PDA)\n * @returns AccountInterface with associated token account 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 allowOwnerOffCurve = false,\n): Promise<AccountInterface> {\n assertBetaEnabled();\n\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 light-token associated token account.\n const validation = checkAtaAddress(\n ata,\n mint,\n owner,\n programId,\n allowOwnerOffCurve,\n );\n\n if (wrap && validation.type !== 'light-token') {\n throw new Error(\n `For wrap=true, ata must be the light-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 light-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} | null> {\n const info = await rpc.getAccountInfo(address, commitment);\n if (!info) {\n return null;\n }\n if (!info.owner.equals(TOKEN_PROGRAM_ID)) {\n throw new TokenInvalidAccountOwnerError();\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} | null> {\n const info = await rpc.getAccountInfo(address, commitment);\n if (!info) {\n return null;\n }\n if (!info.owner.equals(TOKEN_2022_PROGRAM_ID)) {\n throw new TokenInvalidAccountOwnerError();\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 _tryFetchLightTokenHot(\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} | null> {\n const info = await rpc.getAccountInfo(address, commitment);\n if (!info) {\n return null;\n }\n if (!info.owner.equals(LIGHT_TOKEN_PROGRAM_ID)) {\n throw new TokenInvalidAccountOwnerError();\n }\n return parseLightTokenHot(address, info);\n}\n\n/**\n * @internal\n */\nasync function _tryFetchLightTokenColdByOwner(\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 light-token account');\n }\n if (!compressedAccount.owner.equals(LIGHT_TOKEN_PROGRAM_ID)) {\n throw new Error('Invalid owner for light-token');\n }\n return parseLightTokenCold(ataAddress, compressedAccount);\n}\n\n/**\n * Retrieve information about a token account SPL/T22/light-token.\n * @internal\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 // light-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: light-token + optional SPL/T22)\n if (!programId) {\n return getUnifiedAccountInterface(\n rpc,\n address,\n commitment,\n fetchByOwner,\n wrap,\n );\n }\n\n // light-token-only mode\n if (programId.equals(LIGHT_TOKEN_PROGRAM_ID)) {\n return getLightTokenAccountInterface(\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\n/** @internal */\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 light-token associated token account\n const lightTokenAta =\n address ??\n getAssociatedTokenAddressSync(\n fetchByOwner!.mint,\n fetchByOwner!.owner,\n false,\n LIGHT_TOKEN_PROGRAM_ID,\n getAtaProgramId(LIGHT_TOKEN_PROGRAM_ID),\n );\n\n const fetchPromises: Promise<{\n accountInfo: AccountInfo<Buffer>;\n parsed: Account;\n isCold: boolean;\n loadContext?: MerkleContext;\n } | null>[] = [];\n const fetchTypes: TokenAccountSource['type'][] = [];\n const fetchAddresses: PublicKey[] = [];\n\n // light-token hot\n fetchPromises.push(_tryFetchLightTokenHot(rpc, lightTokenAta, commitment));\n fetchTypes.push(TokenAccountSourceType.LightTokenHot);\n fetchAddresses.push(lightTokenAta);\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 // light-token address. SPL and T22 associated token accounts are different from light-token associated token accounts.\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 // Fetch ALL cold light-token accounts (not just one) - important for V1/V2 detection\n const coldAccountsPromise = fetchByOwner\n ? rpc.getCompressedTokenAccountsByOwner(fetchByOwner.owner, {\n mint: fetchByOwner.mint,\n })\n : rpc.getCompressedTokenAccountsByOwner(address!);\n\n const hotResults = await Promise.allSettled(fetchPromises);\n const ownerMismatchErrors: TokenInvalidAccountOwnerError[] = [];\n const unexpectedErrors: unknown[] = [];\n\n let coldResult: Awaited<typeof coldAccountsPromise> | null = null;\n try {\n coldResult = await coldAccountsPromise;\n } catch (error) {\n unexpectedErrors.push(error);\n }\n\n // collect all successful hot results\n const sources: TokenAccountSource[] = [];\n\n for (let i = 0; i < hotResults.length; i++) {\n const result = hotResults[i];\n if (result.status === 'fulfilled') {\n const value = result.value;\n if (!value) {\n continue;\n }\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 } else if (result.reason instanceof TokenInvalidAccountOwnerError) {\n ownerMismatchErrors.push(result.reason);\n } else {\n unexpectedErrors.push(result.reason);\n }\n }\n\n // Add ALL cold light-token accounts (handles both V1 and V2)\n if (coldResult) {\n for (const item of coldResult.items) {\n const compressedAccount = item.compressedAccount;\n if (\n compressedAccount &&\n compressedAccount.data &&\n compressedAccount.data.data.length > 0 &&\n compressedAccount.owner.equals(LIGHT_TOKEN_PROGRAM_ID)\n ) {\n const parsed = parseLightTokenCold(\n lightTokenAta,\n compressedAccount,\n );\n sources.push({\n type: TokenAccountSourceType.LightTokenCold,\n address: lightTokenAta,\n amount: parsed.parsed.amount,\n accountInfo: parsed.accountInfo,\n loadContext: parsed.loadContext,\n parsed: parsed.parsed,\n });\n }\n }\n }\n\n throwIfUnexpectedRpcErrors(\n 'Failed to fetch token account data from RPC',\n unexpectedErrors,\n );\n\n // account not found\n if (sources.length === 0) {\n if (ownerMismatchErrors.length > 0) {\n throw ownerMismatchErrors[0];\n }\n throw new TokenAccountNotFoundError();\n }\n\n // priority order: light-token hot > light-token cold > SPL/T22\n const priority: TokenAccountSource['type'][] = [\n TokenAccountSourceType.LightTokenHot,\n TokenAccountSourceType.LightTokenCold,\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, lightTokenAta);\n}\n\n/** @internal */\nasync function getLightTokenAccountInterface(\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(ERR_FETCH_BY_OWNER_REQUIRED);\n }\n address = getAssociatedTokenAddressSync(\n fetchByOwner.mint,\n fetchByOwner.owner,\n false,\n LIGHT_TOKEN_PROGRAM_ID,\n getAtaProgramId(LIGHT_TOKEN_PROGRAM_ID),\n );\n }\n\n const [onchainResult, compressedResult] = await Promise.allSettled([\n rpc.getAccountInfo(address, commitment),\n // Fetch compressed: by owner+mint for associated token accounts, by address for non-ATAs\n fetchByOwner\n ? rpc.getCompressedTokenAccountsByOwner(fetchByOwner.owner, {\n mint: fetchByOwner.mint,\n })\n : rpc.getCompressedTokenAccountsByOwner(address),\n ]);\n const unexpectedErrors: unknown[] = [];\n const ownerMismatchErrors: TokenInvalidAccountOwnerError[] = [];\n\n const onchainAccount =\n onchainResult.status === 'fulfilled' ? onchainResult.value : null;\n if (onchainResult.status === 'rejected') {\n unexpectedErrors.push(onchainResult.reason);\n }\n const compressedAccounts =\n compressedResult.status === 'fulfilled'\n ? compressedResult.value.items.map(item => item.compressedAccount)\n : [];\n if (compressedResult.status === 'rejected') {\n unexpectedErrors.push(compressedResult.reason);\n }\n\n const sources: TokenAccountSource[] = [];\n\n // Collect light-token associated token account (hot balance)\n if (onchainAccount) {\n if (!onchainAccount.owner.equals(LIGHT_TOKEN_PROGRAM_ID)) {\n ownerMismatchErrors.push(new TokenInvalidAccountOwnerError());\n } else {\n const parsed = parseLightTokenHot(address, onchainAccount);\n sources.push({\n type: TokenAccountSourceType.LightTokenHot,\n address,\n amount: parsed.parsed.amount,\n accountInfo: onchainAccount,\n parsed: parsed.parsed,\n });\n }\n }\n\n // Collect compressed light-token accounts (cold balance)\n for (const compressedAccount of compressedAccounts) {\n if (\n compressedAccount &&\n compressedAccount.data &&\n compressedAccount.data.data.length > 0 &&\n compressedAccount.owner.equals(LIGHT_TOKEN_PROGRAM_ID)\n ) {\n const parsed = parseLightTokenCold(address, compressedAccount);\n sources.push({\n type: TokenAccountSourceType.LightTokenCold,\n address,\n amount: parsed.parsed.amount,\n accountInfo: parsed.accountInfo,\n loadContext: parsed.loadContext,\n parsed: parsed.parsed,\n });\n }\n }\n\n throwIfUnexpectedRpcErrors(\n 'Failed to fetch token account data from RPC',\n unexpectedErrors,\n );\n\n if (sources.length === 0) {\n if (ownerMismatchErrors.length > 0) {\n throw ownerMismatchErrors[0];\n }\n throw new TokenAccountNotFoundError();\n }\n\n // Priority: hot > cold\n sources.sort((a, b) => {\n if (a.type === 'light-token-hot' && b.type === 'light-token-cold')\n return -1;\n if (a.type === 'light-token-cold' && b.type === 'light-token-hot')\n return 1;\n return 0;\n });\n\n return buildAccountInterfaceFromSources(sources, address);\n}\n\n/** @internal */\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(ERR_FETCH_BY_OWNER_REQUIRED);\n }\n address = getAssociatedTokenAddressSync(\n fetchByOwner.mint,\n fetchByOwner.owner,\n false,\n programId,\n getAtaProgramId(programId),\n );\n }\n\n const hotType: TokenAccountSource['type'] = programId.equals(\n TOKEN_PROGRAM_ID,\n )\n ? TokenAccountSourceType.Spl\n : TokenAccountSourceType.Token2022;\n\n const coldType: TokenAccountSource['type'] = programId.equals(\n TOKEN_PROGRAM_ID,\n )\n ? TokenAccountSourceType.SplCold\n : TokenAccountSourceType.Token2022Cold;\n\n // Fetch hot and cold in parallel (neither is required individually)\n const [hotResult, coldResult] = await Promise.allSettled([\n rpc.getAccountInfo(address, commitment),\n fetchByOwner\n ? rpc.getCompressedTokenAccountsByOwner(fetchByOwner.owner, {\n mint: fetchByOwner.mint,\n })\n : Promise.resolve({ items: [] as any[] }),\n ]);\n\n const sources: TokenAccountSource[] = [];\n const unexpectedErrors: unknown[] = [];\n const ownerMismatchErrors: TokenInvalidAccountOwnerError[] = [];\n\n const hotInfo = hotResult.status === 'fulfilled' ? hotResult.value : null;\n if (hotResult.status === 'rejected')\n unexpectedErrors.push(hotResult.reason);\n const coldAccounts =\n coldResult.status === 'fulfilled'\n ? coldResult.value\n : ({ items: [] as any[] } as const);\n if (coldResult.status === 'rejected')\n unexpectedErrors.push(coldResult.reason);\n\n // Hot SPL/T22 account (may not exist)\n if (hotInfo) {\n if (!hotInfo.owner.equals(programId)) {\n ownerMismatchErrors.push(new TokenInvalidAccountOwnerError());\n } else {\n try {\n const account = unpackAccountSPL(address, hotInfo, programId);\n sources.push({\n type: hotType,\n address,\n amount: account.amount,\n accountInfo: hotInfo,\n parsed: account,\n });\n } catch (error) {\n unexpectedErrors.push(error);\n }\n }\n }\n\n // Cold (compressed) accounts\n for (const item of coldAccounts.items) {\n const compressedAccount = item.compressedAccount;\n if (\n compressedAccount &&\n compressedAccount.data &&\n compressedAccount.data.data.length > 0 &&\n compressedAccount.owner.equals(LIGHT_TOKEN_PROGRAM_ID)\n ) {\n const parsedCold = parseLightTokenCold(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 throwIfUnexpectedRpcErrors(\n 'Failed to fetch token account data from RPC',\n unexpectedErrors,\n );\n\n if (sources.length === 0) {\n if (ownerMismatchErrors.length > 0) {\n throw ownerMismatchErrors[0];\n }\n throw new TokenAccountNotFoundError();\n }\n\n return buildAccountInterfaceFromSources(sources, address);\n}\n\n/** @internal */\nexport function 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 hasColdSource = sources.some(src => isColdSourceType(src.type));\n const needsConsolidation = sources.length > 1;\n const delegatedContribution = (src: TokenAccountSource): bigint => {\n const delegated = src.parsed.delegatedAmount ?? src.amount;\n return src.amount < delegated ? src.amount : delegated;\n };\n\n const sumForDelegate = (\n candidate: PublicKey,\n scope: (src: TokenAccountSource) => boolean,\n ): bigint =>\n sources.reduce((sum, src) => {\n if (!scope(src)) return sum;\n const delegate = src.parsed.delegate;\n if (!delegate || !delegate.equals(candidate)) return sum;\n return sum + delegatedContribution(src);\n }, BigInt(0));\n\n const hotDelegatedSource = sources.find(\n src => !isColdSourceType(src.type) && src.parsed.delegate !== null,\n );\n const coldDelegatedSources = sources.filter(\n src => isColdSourceType(src.type) && src.parsed.delegate !== null,\n );\n\n let canonicalDelegate: PublicKey | null = null;\n let canonicalDelegatedAmount = BigInt(0);\n\n if (hotDelegatedSource?.parsed.delegate) {\n // If any hot source is delegated, it always determines canonical delegate.\n // Cold delegates only contribute when they match this hot delegate.\n canonicalDelegate = hotDelegatedSource.parsed.delegate;\n canonicalDelegatedAmount = sumForDelegate(\n canonicalDelegate,\n () => true,\n );\n } else if (coldDelegatedSources.length > 0) {\n // No hot delegate: canonical delegate is taken from the most recent\n // delegated cold source in source order (source[0] is most recent).\n canonicalDelegate = coldDelegatedSources[0].parsed.delegate!;\n canonicalDelegatedAmount = sumForDelegate(canonicalDelegate, src =>\n isColdSourceType(src.type),\n );\n }\n\n const unifiedAccount: Account = {\n ...primarySource.parsed,\n address: canonicalAddress,\n amount: totalAmount,\n // Synthetic ATA view models post-load state; any cold source implies initialized.\n isInitialized: primarySource.parsed.isInitialized || hasColdSource,\n delegate: canonicalDelegate,\n delegatedAmount: canonicalDelegatedAmount,\n ...(anyFrozen ? { state: AccountState.Frozen, isFrozen: true } : {}),\n };\n\n return {\n accountInfo: primarySource.accountInfo!,\n parsed: unifiedAccount,\n isCold: isColdSourceType(primarySource.type),\n loadContext: primarySource.loadContext,\n _sources: sources,\n _needsConsolidation: needsConsolidation,\n _hasDelegate: hasDelegate,\n _anyFrozen: anyFrozen,\n };\n}\n\n/**\n * Spendable amount for a given authority (owner or delegate).\n * - If authority equals the ATA owner: full parsed.amount.\n * - If authority is the canonical delegate: parsed.delegatedAmount (bounded by parsed.amount).\n * - Otherwise: 0.\n * @internal\n */\nexport function spendableAmountForAuthority(\n iface: AccountInterface,\n authority: PublicKey,\n): bigint {\n const owner = iface._owner;\n if (owner && authority.equals(owner)) {\n return iface.parsed.amount;\n }\n const delegate = iface.parsed.delegate;\n if (delegate && authority.equals(delegate)) {\n const delegated = iface.parsed.delegatedAmount ?? BigInt(0);\n return delegated < iface.parsed.amount\n ? delegated\n : iface.parsed.amount;\n }\n return BigInt(0);\n}\n\n/**\n * Whether the given authority can sign for this ATA (owner or canonical delegate).\n * @internal\n */\nexport function isAuthorityForInterface(\n iface: AccountInterface,\n authority: PublicKey,\n): boolean {\n const owner = iface._owner;\n if (owner && authority.equals(owner)) return true;\n const delegate = iface.parsed.delegate;\n return delegate !== null && authority.equals(delegate);\n}\n\n/**\n * @internal\n * Canonical authority projection for owner/delegate checks.\n */\nexport function filterInterfaceForAuthority(\n iface: AccountInterface,\n authority: PublicKey,\n): AccountInterface {\n const owner = iface._owner;\n if (owner && authority.equals(owner)) {\n return iface;\n }\n const spendable = spendableAmountForAuthority(iface, authority);\n const canonicalDelegate = iface.parsed.delegate;\n if (\n spendable === BigInt(0) ||\n canonicalDelegate === null ||\n !authority.equals(canonicalDelegate)\n ) {\n return {\n ...iface,\n _sources: [],\n _needsConsolidation: false,\n parsed: { ...iface.parsed, amount: BigInt(0) },\n };\n }\n const sources = iface._sources ?? [];\n const filtered = sources.filter(\n src =>\n src.parsed.delegate !== null &&\n src.parsed.delegate.equals(canonicalDelegate),\n );\n const primary = filtered[0];\n return {\n ...iface,\n ...(primary\n ? {\n accountInfo: primary.accountInfo!,\n isCold: isColdSourceType(primary.type),\n loadContext: primary.loadContext,\n }\n : {}),\n _sources: filtered,\n _needsConsolidation: filtered.length > 1,\n parsed: {\n ...iface.parsed,\n amount: spendable,\n },\n };\n}\n","import { PublicKey } from '@solana/web3.js';\nimport { getAssociatedTokenAddressSync } from '@solana/spl-token';\nimport { LIGHT_TOKEN_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/light-token.\n * Defaults to using light-token as the canonical associated token account.\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 light-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 = LIGHT_TOKEN_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 associated token account.\n return getAssociatedTokenAddressSync(\n mint,\n owner,\n allowOwnerOffCurve,\n programId,\n effectiveAssociatedProgramId,\n );\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';\nimport { PublicKey } from '@solana/web3.js';\nimport { CompressionInfo } from './layout-mint';\nimport {\n AdditionalMetadata,\n CompressedProofLayout,\n TokenMetadataInstructionDataLayout,\n} from './layout-mint-action';\n\n// Transfer2 discriminator = 101\nexport const TRANSFER2_DISCRIMINATOR = Buffer.from([101]);\n\n// Extension discriminant values (matching Rust enum)\nexport const EXTENSION_DISCRIMINANT_TOKEN_METADATA = 19;\nexport const EXTENSION_DISCRIMINANT_COMPRESSED_ONLY = 31;\nexport const EXTENSION_DISCRIMINANT_COMPRESSIBLE = 32;\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 * Token metadata extension instruction data for Transfer2 TLV\n */\nexport interface Transfer2TokenMetadata {\n updateAuthority: PublicKey | null;\n name: Uint8Array;\n symbol: Uint8Array;\n uri: Uint8Array;\n additionalMetadata: AdditionalMetadata[] | null;\n}\n\n/**\n * CompressedOnly extension instruction data for Transfer2 TLV\n */\nexport interface Transfer2CompressedOnly {\n delegatedAmount: bigint;\n withheldTransferFee: bigint;\n isFrozen: boolean;\n compressionIndex: number;\n isAta: boolean;\n bump: number;\n ownerIndex: number;\n}\n\n/**\n * Extension instruction data types for Transfer2 in_tlv/out_tlv\n */\nexport type Transfer2ExtensionData =\n | { type: 'TokenMetadata'; data: Transfer2TokenMetadata }\n | { type: 'CompressedOnly'; data: Transfer2CompressedOnly }\n | { type: 'Compressible'; data: CompressionInfo };\n\n/**\n * Full Transfer2 instruction data\n *\n * Note on `decimals` field in Compression:\n * - For SPL compress/decompress: actual token decimals\n * - For CompressAndClose mode: used as `rent_sponsor_is_signer` flag\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 /** Extensions for input light-token accounts (one array per input account) */\n inTlv: Transfer2ExtensionData[][] | null;\n /** Extensions for output light-token accounts (one array per output account) */\n outTlv: Transfer2ExtensionData[][] | null;\n}\n\n// Borsh layouts for extension data\n\nconst CompressedOnlyExtensionInstructionDataLayout = struct([\n u64('delegatedAmount'),\n u64('withheldTransferFee'),\n bool('isFrozen'),\n u8('compressionIndex'),\n bool('isAta'),\n u8('bump'),\n u8('ownerIndex'),\n]);\n\nconst RentConfigLayout = struct([\n u16('baseRent'),\n u16('compressionCost'),\n u8('lamportsPerBytePerEpoch'),\n u8('maxFundedEpochs'),\n u16('maxTopUp'),\n]);\n\nconst CompressionInfoLayout = struct([\n u16('configAccountVersion'),\n u8('compressToPubkey'),\n u8('accountVersion'),\n u32('lamportsPerWrite'),\n array(u8(), 32, 'compressionAuthority'),\n array(u8(), 32, 'rentSponsor'),\n u64('lastClaimedSlot'),\n u32('rentExemptionPaid'),\n u32('reserved'),\n RentConfigLayout.replicate('rentConfig'),\n]);\n\n/**\n * Serialize a single Transfer2ExtensionData to bytes\n * @internal\n */\nfunction serializeExtensionInstructionData(\n ext: Transfer2ExtensionData,\n): Uint8Array {\n const buffer = Buffer.alloc(1024);\n let offset = 0;\n\n // Write discriminant\n if (ext.type === 'TokenMetadata') {\n buffer.writeUInt8(EXTENSION_DISCRIMINANT_TOKEN_METADATA, offset);\n offset += 1;\n const data = {\n updateAuthority: ext.data.updateAuthority,\n name: ext.data.name,\n symbol: ext.data.symbol,\n uri: ext.data.uri,\n additionalMetadata: ext.data.additionalMetadata\n ? ext.data.additionalMetadata.map(m => ({\n key: Buffer.from(m.key),\n value: Buffer.from(m.value),\n }))\n : null,\n };\n offset += TokenMetadataInstructionDataLayout.encode(\n data,\n buffer,\n offset,\n );\n } else if (ext.type === 'CompressedOnly') {\n buffer.writeUInt8(EXTENSION_DISCRIMINANT_COMPRESSED_ONLY, offset);\n offset += 1;\n const data = {\n delegatedAmount: bn(ext.data.delegatedAmount.toString()),\n withheldTransferFee: bn(ext.data.withheldTransferFee.toString()),\n isFrozen: ext.data.isFrozen,\n compressionIndex: ext.data.compressionIndex,\n isAta: ext.data.isAta,\n bump: ext.data.bump,\n ownerIndex: ext.data.ownerIndex,\n };\n offset += CompressedOnlyExtensionInstructionDataLayout.encode(\n data,\n buffer,\n offset,\n );\n } else if (ext.type === 'Compressible') {\n buffer.writeUInt8(EXTENSION_DISCRIMINANT_COMPRESSIBLE, offset);\n offset += 1;\n const data = {\n configAccountVersion: ext.data.configAccountVersion,\n compressToPubkey: ext.data.compressToPubkey,\n accountVersion: ext.data.accountVersion,\n lamportsPerWrite: ext.data.lamportsPerWrite,\n compressionAuthority: Array.from(\n ext.data.compressionAuthority.toBytes(),\n ),\n rentSponsor: Array.from(ext.data.rentSponsor.toBytes()),\n lastClaimedSlot: bn(ext.data.lastClaimedSlot.toString()),\n rentExemptionPaid: ext.data.rentExemptionPaid,\n reserved: ext.data.reserved,\n rentConfig: ext.data.rentConfig,\n };\n offset += CompressionInfoLayout.encode(data, buffer, offset);\n }\n\n return buffer.subarray(0, offset);\n}\n\n/**\n * Serialize Vec<Vec<Transfer2ExtensionData>> to bytes for Borsh\n * @internal\n */\nfunction serializeExtensionTlv(\n tlv: Transfer2ExtensionData[][] | null,\n): Uint8Array | null {\n if (tlv === null) {\n return null;\n }\n\n const chunks: Uint8Array[] = [];\n\n // Write outer vec length (4 bytes, little-endian)\n const outerLenBuf = Buffer.alloc(4);\n outerLenBuf.writeUInt32LE(tlv.length, 0);\n chunks.push(outerLenBuf);\n\n for (const innerVec of tlv) {\n // Write inner vec length (4 bytes, little-endian)\n const innerLenBuf = Buffer.alloc(4);\n innerLenBuf.writeUInt32LE(innerVec.length, 0);\n chunks.push(innerLenBuf);\n\n for (const ext of innerVec) {\n chunks.push(serializeExtensionInstructionData(ext));\n }\n }\n\n return Buffer.concat(chunks);\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\n// Layout without TLV fields - we'll serialize those manually\nconst Transfer2InstructionDataBaseLayout = 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]);\n\n/**\n * Encode Transfer2 instruction data using Borsh\n * @internal\n */\nexport function encodeTransfer2InstructionData(\n data: Transfer2InstructionData,\n): Buffer {\n // Convert bigint values to BN for Borsh encoding\n const baseData = {\n withTransactionHash: data.withTransactionHash,\n withLamportsChangeAccountMerkleTreeIndex:\n data.withLamportsChangeAccountMerkleTreeIndex,\n lamportsChangeAccountMerkleTreeIndex:\n data.lamportsChangeAccountMerkleTreeIndex,\n lamportsChangeAccountOwnerIndex: data.lamportsChangeAccountOwnerIndex,\n outputQueue: data.outputQueue,\n maxTopUp: data.maxTopUp,\n cpiContext: data.cpiContext,\n compressions:\n data.compressions?.map(c => ({\n ...c,\n amount: bn(c.amount.toString()),\n })) ?? null,\n proof: data.proof,\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 // Encode base layout\n const baseBuffer = Buffer.alloc(4000);\n const baseLen = Transfer2InstructionDataBaseLayout.encode(\n baseData,\n baseBuffer,\n );\n\n // Manually serialize TLV fields\n const chunks: Buffer[] = [\n TRANSFER2_DISCRIMINATOR,\n baseBuffer.subarray(0, baseLen),\n ];\n\n // Serialize inTlv as Option<Vec<Vec<ExtensionInstructionData>>>\n if (data.inTlv === null) {\n // Option::None = 0\n chunks.push(Buffer.from([0]));\n } else {\n // Option::Some = 1\n chunks.push(Buffer.from([1]));\n const serialized = serializeExtensionTlv(data.inTlv);\n if (serialized) {\n chunks.push(Buffer.from(serialized));\n }\n }\n\n // Serialize outTlv as Option<Vec<Vec<ExtensionInstructionData>>>\n if (data.outTlv === null) {\n // Option::None = 0\n chunks.push(Buffer.from([0]));\n } else {\n // Option::Some = 1\n chunks.push(Buffer.from([1]));\n const serialized = serializeExtensionTlv(data.outTlv);\n if (serialized) {\n chunks.push(Buffer.from(serialized));\n }\n }\n\n return Buffer.concat(chunks);\n}\n\n/**\n * @internal\n * Create a compression struct for wrapping SPL tokens to light-token\n * (compress from SPL associated token account)\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 decimals: 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,\n };\n}\n\n/**\n * @internal\n * Create a compression struct for decompressing to light-token associated token account\n * @param amount - Amount to decompress\n * @param mintIndex - Index of mint in packed accounts\n * @param recipientIndex - Index of recipient light-token account in packed accounts\n * @param tokenProgramIndex - Index of light-token program in packed accounts (for CPI)\n */\nexport function createDecompressLightToken(\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 * @internal\n * Create a compression struct for compressing light-token (burn from light-token associated token account)\n * Used in unwrap flow: light-token associated token account -> pool -> SPL associated token account\n * @param amount - Amount to compress (burn from light-token)\n * @param mintIndex - Index of mint in packed accounts\n * @param sourceIndex - Index of source light-token account in packed accounts\n * @param authorityIndex - Index of authority/owner in packed accounts (must sign)\n * @param tokenProgramIndex - Index of light-token program in packed accounts (for CPI)\n */\nexport function createCompressLightToken(\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 * @internal\n */\nexport function createDecompressSpl(\n amount: bigint,\n mintIndex: number,\n recipientIndex: number,\n poolAccountIndex: number,\n poolIndex: number,\n bump: number,\n decimals: 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,\n };\n}\n","import {\n PublicKey,\n TransactionInstruction,\n SystemProgram,\n} from '@solana/web3.js';\nimport { LIGHT_TOKEN_PROGRAM_ID } from '@lightprotocol/stateless.js';\nimport { MAX_TOP_UP } from '../../constants';\nimport { CompressedTokenProgram } from '../../program';\nimport { SplInterfaceInfo } from '../../utils/get-token-pool-infos';\nimport {\n encodeTransfer2InstructionData,\n createCompressSpl,\n createDecompressLightToken,\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 * light-token account.\n *\n * @param source Source SPL/T22 token account\n * @param destination Destination light-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 decimals Mint decimals (required for transfer_checked)\n * @param payer Fee payer (defaults to owner)\n * @param maxTopUp Optional cap on rent top-up (units of 1k lamports; default no cap)\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 decimals: number,\n payer: PublicKey = owner,\n maxTopUp?: number,\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 LIGHT_TOKEN_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 decimals,\n ),\n createDecompressLightToken(\n amount,\n MINT_INDEX,\n DESTINATION_INDEX,\n LIGHT_TOKEN_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: maxTopUp ?? MAX_TOP_UP,\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: LIGHT_TOKEN_PROGRAM_ID,\n isSigner: false,\n isWritable: false,\n },\n // System program needed for top-up CPIs when destination has compressible extension\n {\n pubkey: SystemProgram.programId,\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 PublicKey,\n TransactionInstruction,\n SystemProgram,\n} from '@solana/web3.js';\nimport {\n LIGHT_TOKEN_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 Transfer2ExtensionData,\n} from '../layout/layout-transfer2';\nimport { MAX_TOP_UP, TokenDataVersion } from '../../constants';\nimport { SplInterfaceInfo } from '../../utils/get-token-pool-infos';\n\nconst COMPRESSED_ONLY_DISC = 31;\nconst COMPRESSED_ONLY_SIZE = 17; // u64 + u64 + u8\n\ninterface ParsedCompressedOnly {\n delegatedAmount: bigint;\n withheldTransferFee: bigint;\n isAta: boolean;\n}\n\n/**\n * Parse CompressedOnly extension from a Borsh-serialized TLV buffer\n * (Vec<ExtensionStruct>). Returns null if no CompressedOnly found.\n * @internal\n */\nfunction parseCompressedOnlyFromTlv(\n tlv: Buffer | null,\n): ParsedCompressedOnly | null {\n if (!tlv || tlv.length < 5) return null;\n try {\n let offset = 0;\n const vecLen = tlv.readUInt32LE(offset);\n offset += 4;\n for (let i = 0; i < vecLen; i++) {\n if (offset >= tlv.length) return null;\n const disc = tlv[offset];\n offset += 1;\n if (disc === COMPRESSED_ONLY_DISC) {\n if (offset + COMPRESSED_ONLY_SIZE > tlv.length) return null;\n const loDA = BigInt(tlv.readUInt32LE(offset));\n const hiDA = BigInt(tlv.readUInt32LE(offset + 4));\n const delegatedAmount = loDA | (hiDA << BigInt(32));\n const loFee = BigInt(tlv.readUInt32LE(offset + 8));\n const hiFee = BigInt(tlv.readUInt32LE(offset + 12));\n const withheldTransferFee = loFee | (hiFee << BigInt(32));\n const isAta = tlv[offset + 16] !== 0;\n return { delegatedAmount, withheldTransferFee, isAta };\n }\n const SIZES: Record<number, number | undefined> = {\n 29: 8,\n 30: 1,\n 31: 17,\n };\n const size = SIZES[disc];\n if (size === undefined) {\n throw new Error(\n `parseCompressedOnlyFromTlv: unknown TLV extension discriminant ${disc}`,\n );\n }\n offset += size;\n }\n } catch {\n // Ignoring unknown TLV extensions.\n return null;\n }\n return null;\n}\n\n/**\n * Build inTlv array for Transfer2 from input compressed accounts.\n * For each account, if CompressedOnly TLV is present, converts it to\n * the instruction format (enriched with is_frozen, compression_index,\n * bump, owner_index). Returns null if no accounts have TLV.\n * @internal\n */\nfunction buildInTlv(\n accounts: ParsedTokenAccount[],\n ownerIndex: number,\n owner: PublicKey,\n mint: PublicKey,\n): Transfer2ExtensionData[][] | null {\n let hasAny = false;\n const result: Transfer2ExtensionData[][] = [];\n\n for (const acc of accounts) {\n const co = parseCompressedOnlyFromTlv(acc.parsed.tlv);\n if (!co) {\n result.push([]);\n continue;\n }\n hasAny = true;\n let bump = 0;\n if (co.isAta) {\n const seeds = [\n owner.toBuffer(),\n LIGHT_TOKEN_PROGRAM_ID.toBuffer(),\n mint.toBuffer(),\n ];\n const [, b] = PublicKey.findProgramAddressSync(\n seeds,\n LIGHT_TOKEN_PROGRAM_ID,\n );\n bump = b;\n }\n const isFrozen = acc.parsed.state === 2;\n result.push([\n {\n type: 'CompressedOnly',\n data: {\n delegatedAmount: co.delegatedAmount,\n withheldTransferFee: co.withheldTransferFee,\n isFrozen,\n // This builder emits a single decompress compression per batch.\n // Keep index at 0 unless multi-compression output is added here.\n compressionIndex: 0,\n isAta: co.isAta,\n bump,\n ownerIndex,\n },\n },\n ]);\n }\n return hasAny ? result : null;\n}\n\n/**\n * Get token data version from compressed account discriminator.\n * @internal\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 * @internal\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 decompress instruction using Transfer2.\n *\n * @internal Use createLoadAtaInstructions instead.\n *\n * Supports decompressing to both light-token accounts and SPL token accounts:\n * - For light-token destinations: No splInterfaceInfo needed\n * - For SPL destinations: Provide splInterfaceInfo (token pool info) and decimals\n *\n * @param payer Fee payer public key\n * @param inputCompressedTokenAccounts Input light-token accounts\n * @param toAddress Destination token account address (light-token or SPL associated token account)\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 * @param decimals Mint decimals (required for SPL destinations)\n * @param maxTopUp Optional cap on rent top-up (units of 1k lamports; default no cap)\n * @param authority Optional signer (owner or delegate). When omitted, owner is the signer.\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 | undefined,\n decimals: number,\n maxTopUp?: number,\n authority?: PublicKey,\n): TransactionInstruction {\n if (inputCompressedTokenAccounts.length === 0) {\n throw new Error('No input light-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, light-token account, light-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 (light-token or SPL)\n const destinationIndex = packedAccounts.length;\n packedAccountIndices.set(toAddress.toBase58(), destinationIndex);\n packedAccounts.push(toAddress);\n\n // Add unique delegate pubkeys from input accounts\n for (const acc of inputCompressedTokenAccounts) {\n if (acc.parsed.delegate) {\n const delegateKey = acc.parsed.delegate.toBase58();\n if (!packedAccountIndices.has(delegateKey)) {\n packedAccountIndices.set(delegateKey, packedAccounts.length);\n packedAccounts.push(acc.parsed.delegate);\n }\n }\n }\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 light-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,\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: maxTopUp ?? MAX_TOP_UP,\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: buildInTlv(\n inputCompressedTokenAccounts,\n ownerIndex,\n owner,\n mint,\n ),\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 const signerIndex = (() => {\n if (!authority || authority.equals(owner)) {\n return ownerIndex;\n }\n const authorityIndex = packedAccountIndices.get(authority.toBase58());\n if (authorityIndex === undefined) {\n throw new Error(\n `Authority ${authority.toBase58()} is not present in packed accounts`,\n );\n }\n return authorityIndex;\n })();\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 const isTreeOrQueue = i < treeSet.size + queueSet.size;\n const isDestination = pubkey.equals(toAddress);\n const isPool =\n splInterfaceInfo !== undefined &&\n pubkey.equals(splInterfaceInfo.splInterfacePda);\n return {\n pubkey,\n isSigner: i === signerIndex,\n isWritable: isTreeOrQueue || isDestination || isPool,\n };\n }),\n ];\n\n return new TransactionInstruction({\n programId: CompressedTokenProgram.programId,\n keys,\n data,\n });\n}\n","import {\n Rpc,\n LIGHT_TOKEN_PROGRAM_ID,\n ParsedTokenAccount,\n bn,\n assertBetaEnabled,\n} from '@lightprotocol/stateless.js';\nimport { assertV2Only } from '../assert-v2-only';\nimport {\n ComputeBudgetProgram,\n PublicKey,\n TransactionInstruction,\n} from '@solana/web3.js';\nimport {\n TOKEN_PROGRAM_ID,\n TOKEN_2022_PROGRAM_ID,\n getAssociatedTokenAddressSync,\n createAssociatedTokenAccountIdempotentInstruction,\n TokenAccountNotFoundError,\n} from '@solana/spl-token';\nimport {\n AccountInterface,\n checkNotFrozen,\n COLD_SOURCE_TYPES,\n getAtaInterface as _getAtaInterface,\n TokenAccountSource,\n isAuthorityForInterface,\n filterInterfaceForAuthority,\n} from '../get-account-interface';\nimport { getAssociatedTokenAddressInterface } from '../get-associated-token-address-interface';\nimport { createAssociatedTokenAccountInterfaceIdempotentInstruction } from './create-ata-interface';\nimport { createWrapInstruction } from './wrap';\nimport { createDecompressInterfaceInstruction } from './create-decompress-interface-instruction';\nimport {\n getSplInterfaceInfos,\n SplInterfaceInfo,\n} from '../../utils/get-token-pool-infos';\nimport { getAtaProgramId, checkAtaAddress, AtaType } from '../ata-utils';\nimport type { InterfaceOptions } from '../actions/transfer-interface';\n\nexport const MAX_INPUT_ACCOUNTS = 8;\n\nfunction chunkArray<T>(array: T[], chunkSize: number): T[][] {\n const chunks: T[][] = [];\n for (let i = 0; i < array.length; i += chunkSize) {\n chunks.push(array.slice(i, i + chunkSize));\n }\n return chunks;\n}\n\nexport function selectInputsForAmount(\n accounts: ParsedTokenAccount[],\n neededAmount: bigint,\n): ParsedTokenAccount[] {\n if (accounts.length === 0 || neededAmount <= BigInt(0)) return [];\n\n const sorted = [...accounts].sort((a, b) => {\n const amtA = BigInt(a.parsed.amount.toString());\n const amtB = BigInt(b.parsed.amount.toString());\n if (amtB > amtA) return 1;\n if (amtB < amtA) return -1;\n return 0;\n });\n\n let accumulated = BigInt(0);\n let countNeeded = 0;\n for (const acc of sorted) {\n countNeeded++;\n accumulated += BigInt(acc.parsed.amount.toString());\n if (accumulated >= neededAmount) break;\n }\n\n const selectCount = Math.min(\n Math.max(countNeeded, MAX_INPUT_ACCOUNTS),\n sorted.length,\n );\n\n return sorted.slice(0, selectCount);\n}\n\nfunction assertUniqueInputHashes(chunks: ParsedTokenAccount[][]): void {\n const seen = new Set<string>();\n for (const chunk of chunks) {\n for (const acc of chunk) {\n const hashStr = acc.compressedAccount.hash.toString();\n if (seen.has(hashStr)) {\n throw new Error(\n `Duplicate compressed account hash across chunks: ${hashStr}. ` +\n `Each compressed account must appear in exactly one chunk.`,\n );\n }\n seen.add(hashStr);\n }\n }\n}\n\nexport function getCompressedTokenAccountsFromAtaSources(\n sources: TokenAccountSource[],\n): ParsedTokenAccount[] {\n return sources\n .filter(source => source.loadContext !== undefined)\n .filter(source => COLD_SOURCE_TYPES.has(source.type))\n .map(source => {\n const fullData = source.accountInfo.data;\n const discriminatorBytes = fullData.subarray(\n 0,\n Math.min(8, fullData.length),\n );\n const accountDataBytes =\n fullData.length > 8 ? fullData.subarray(8) : Buffer.alloc(0);\n\n const compressedAccount = {\n treeInfo: source.loadContext!.treeInfo,\n hash: source.loadContext!.hash,\n leafIndex: source.loadContext!.leafIndex,\n proveByIndex: source.loadContext!.proveByIndex,\n owner: source.accountInfo.owner,\n lamports: bn(source.accountInfo.lamports),\n address: null,\n data:\n fullData.length === 0\n ? null\n : {\n discriminator: Array.from(discriminatorBytes),\n data: Buffer.from(accountDataBytes),\n dataHash: new Array(32).fill(0),\n },\n readOnly: false,\n };\n\n const state = !source.parsed.isInitialized\n ? 0\n : source.parsed.isFrozen\n ? 2\n : 1;\n\n return {\n compressedAccount: compressedAccount as any,\n parsed: {\n mint: source.parsed.mint,\n owner: source.parsed.owner,\n amount: bn(source.parsed.amount.toString()),\n delegate: source.parsed.delegate,\n state,\n tlv:\n source.parsed.tlvData.length > 0\n ? source.parsed.tlvData\n : null,\n },\n } satisfies ParsedTokenAccount;\n });\n}\n\nexport { AtaType } from '../ata-utils';\n\nexport async function createLoadAtaInstructions(\n rpc: Rpc,\n ata: PublicKey,\n owner: PublicKey,\n mint: PublicKey,\n decimals: number,\n payer?: PublicKey,\n interfaceOptions?: InterfaceOptions,\n wrap = false,\n): Promise<TransactionInstruction[][]> {\n assertBetaEnabled();\n payer ??= owner;\n\n const effectiveOwner = interfaceOptions?.owner ?? owner;\n\n let accountInterface: AccountInterface;\n try {\n accountInterface = await _getAtaInterface(\n rpc,\n ata,\n effectiveOwner,\n mint,\n undefined,\n undefined,\n wrap,\n );\n } catch (e) {\n if (e instanceof TokenAccountNotFoundError) {\n return [];\n }\n throw e;\n }\n\n const isDelegate = !effectiveOwner.equals(owner);\n if (isDelegate) {\n if (!isAuthorityForInterface(accountInterface, owner)) {\n throw new Error(\n 'Signer is not the owner or a delegate of the account.',\n );\n }\n accountInterface = filterInterfaceForAuthority(accountInterface, owner);\n }\n\n const internalBatches = await _buildLoadBatches(\n rpc,\n payer,\n accountInterface,\n interfaceOptions,\n wrap,\n ata,\n undefined,\n owner,\n decimals,\n );\n\n return internalBatches.map(batch => [\n ComputeBudgetProgram.setComputeUnitLimit({\n units: calculateLoadBatchComputeUnits(batch),\n }),\n ...batch.instructions,\n ]);\n}\n\nexport interface InternalLoadBatch {\n instructions: TransactionInstruction[];\n compressedAccounts: ParsedTokenAccount[];\n wrapCount: number;\n hasAtaCreation: boolean;\n}\n\nconst CU_ATA_CREATION = 30_000;\nconst CU_WRAP = 50_000;\nconst CU_DECOMPRESS_BASE = 50_000;\nconst CU_FULL_PROOF = 100_000;\nconst CU_PER_ACCOUNT_PROVE_BY_INDEX = 10_000;\nconst CU_PER_ACCOUNT_FULL_PROOF = 30_000;\nconst CU_BUFFER_FACTOR = 1.3;\nconst CU_MIN = 50_000;\nconst CU_MAX = 1_400_000;\n\nexport function rawLoadBatchComputeUnits(batch: InternalLoadBatch): number {\n let cu = 0;\n if (batch.hasAtaCreation) cu += CU_ATA_CREATION;\n cu += batch.wrapCount * CU_WRAP;\n if (batch.compressedAccounts.length > 0) {\n cu += CU_DECOMPRESS_BASE;\n const needsFullProof = batch.compressedAccounts.some(\n acc => !(acc.compressedAccount.proveByIndex ?? false),\n );\n if (needsFullProof) cu += CU_FULL_PROOF;\n for (const acc of batch.compressedAccounts) {\n cu +=\n (acc.compressedAccount.proveByIndex ?? false)\n ? CU_PER_ACCOUNT_PROVE_BY_INDEX\n : CU_PER_ACCOUNT_FULL_PROOF;\n }\n }\n return cu;\n}\n\nexport function calculateLoadBatchComputeUnits(\n batch: InternalLoadBatch,\n): number {\n const cu = Math.ceil(rawLoadBatchComputeUnits(batch) * CU_BUFFER_FACTOR);\n return Math.max(CU_MIN, Math.min(CU_MAX, cu));\n}\n\nexport async function _buildLoadBatches(\n rpc: Rpc,\n payer: PublicKey,\n ata: AccountInterface,\n options: InterfaceOptions | undefined,\n wrap: boolean,\n targetAta: PublicKey,\n targetAmount: bigint | undefined,\n authority: PublicKey | undefined,\n decimals: number,\n): Promise<InternalLoadBatch[]> {\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 checkNotFrozen(ata, 'load');\n\n const owner = ata._owner;\n const mint = ata._mint;\n const sources = ata._sources ?? [];\n\n const allCompressedAccounts =\n getCompressedTokenAccountsFromAtaSources(sources);\n\n const lightTokenAtaAddress = getAssociatedTokenAddressInterface(\n mint,\n owner,\n );\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 let ataType: AtaType = 'light-token';\n const validation = checkAtaAddress(targetAta, mint, owner);\n ataType = validation.type;\n if (wrap && ataType !== 'light-token') {\n throw new Error(\n `For wrap=true, targetAta must be light-token associated token account. Got ${ataType} associated token account.`,\n );\n }\n\n const splSource = sources.find(s => s.type === 'spl');\n const t22Source = sources.find(s => s.type === 'token2022');\n const lightTokenHotSource = sources.find(s => s.type === 'light-token-hot');\n const coldSources = sources.filter(s => COLD_SOURCE_TYPES.has(s.type));\n\n const splBalance = splSource?.amount ?? BigInt(0);\n const t22Balance = t22Source?.amount ?? BigInt(0);\n const coldBalance = coldSources.reduce(\n (sum, s) => sum + s.amount,\n BigInt(0),\n );\n\n if (\n splBalance === BigInt(0) &&\n t22Balance === BigInt(0) &&\n coldBalance === BigInt(0)\n ) {\n return [];\n }\n\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 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 (e) {\n if (splBalance > BigInt(0) || t22Balance > BigInt(0)) {\n throw e;\n }\n }\n }\n\n const setupInstructions: TransactionInstruction[] = [];\n let wrapCount = 0;\n let needsAtaCreation = false;\n\n let decompressTarget: PublicKey = lightTokenAtaAddress;\n let decompressSplInfo: SplInterfaceInfo | undefined;\n let canDecompress = false;\n\n if (wrap) {\n decompressTarget = lightTokenAtaAddress;\n decompressSplInfo = undefined;\n canDecompress = true;\n\n if (!lightTokenHotSource) {\n needsAtaCreation = true;\n setupInstructions.push(\n createAssociatedTokenAccountInterfaceIdempotentInstruction(\n payer,\n lightTokenAtaAddress,\n owner,\n mint,\n LIGHT_TOKEN_PROGRAM_ID,\n ),\n );\n }\n\n if (splBalance > BigInt(0) && splInterfaceInfo) {\n setupInstructions.push(\n createWrapInstruction(\n splAta,\n lightTokenAtaAddress,\n owner,\n mint,\n splBalance,\n splInterfaceInfo,\n decimals,\n payer,\n ),\n );\n wrapCount++;\n }\n\n if (t22Balance > BigInt(0) && splInterfaceInfo) {\n setupInstructions.push(\n createWrapInstruction(\n t22Ata,\n lightTokenAtaAddress,\n owner,\n mint,\n t22Balance,\n splInterfaceInfo,\n decimals,\n payer,\n ),\n );\n wrapCount++;\n }\n } else {\n if (ataType === 'light-token') {\n decompressTarget = lightTokenAtaAddress;\n decompressSplInfo = undefined;\n canDecompress = true;\n if (!lightTokenHotSource) {\n needsAtaCreation = true;\n setupInstructions.push(\n createAssociatedTokenAccountInterfaceIdempotentInstruction(\n payer,\n lightTokenAtaAddress,\n owner,\n mint,\n LIGHT_TOKEN_PROGRAM_ID,\n ),\n );\n }\n } else if (ataType === 'spl' && splInterfaceInfo) {\n decompressTarget = splAta;\n decompressSplInfo = splInterfaceInfo;\n canDecompress = true;\n if (!splSource) {\n needsAtaCreation = true;\n setupInstructions.push(\n createAssociatedTokenAccountIdempotentInstruction(\n payer,\n splAta,\n owner,\n mint,\n TOKEN_PROGRAM_ID,\n ),\n );\n }\n } else if (ataType === 'token2022' && splInterfaceInfo) {\n decompressTarget = t22Ata;\n decompressSplInfo = splInterfaceInfo;\n canDecompress = true;\n if (!t22Source) {\n needsAtaCreation = true;\n setupInstructions.push(\n createAssociatedTokenAccountIdempotentInstruction(\n payer,\n t22Ata,\n owner,\n mint,\n TOKEN_2022_PROGRAM_ID,\n ),\n );\n }\n }\n }\n\n let accountsToLoad = allCompressedAccounts;\n\n if (\n targetAmount !== undefined &&\n canDecompress &&\n allCompressedAccounts.length > 0\n ) {\n const isDelegate = authority !== undefined && !authority.equals(owner);\n const hotBalance = (() => {\n if (!lightTokenHotSource) return BigInt(0);\n if (isDelegate) {\n const delegated =\n lightTokenHotSource.parsed.delegatedAmount ?? BigInt(0);\n return delegated < lightTokenHotSource.amount\n ? delegated\n : lightTokenHotSource.amount;\n }\n return lightTokenHotSource.amount;\n })();\n let effectiveHotAfterSetup: bigint;\n\n if (wrap) {\n effectiveHotAfterSetup = hotBalance + splBalance + t22Balance;\n } else if (ataType === 'light-token') {\n effectiveHotAfterSetup = hotBalance;\n } else if (ataType === 'spl') {\n effectiveHotAfterSetup = splBalance;\n } else {\n effectiveHotAfterSetup = t22Balance;\n }\n\n const neededFromCold =\n targetAmount > effectiveHotAfterSetup\n ? targetAmount - effectiveHotAfterSetup\n : BigInt(0);\n\n if (neededFromCold === BigInt(0)) {\n accountsToLoad = [];\n } else {\n accountsToLoad = selectInputsForAmount(\n allCompressedAccounts,\n neededFromCold,\n );\n }\n }\n\n if (!canDecompress || accountsToLoad.length === 0) {\n if (setupInstructions.length === 0) return [];\n return [\n {\n instructions: setupInstructions,\n compressedAccounts: [],\n wrapCount,\n hasAtaCreation: needsAtaCreation,\n },\n ];\n }\n\n assertV2Only(accountsToLoad);\n\n const chunks = chunkArray(accountsToLoad, MAX_INPUT_ACCOUNTS);\n assertUniqueInputHashes(chunks);\n\n const proofs = await Promise.all(\n chunks.map(async chunk => {\n const proofInputs = chunk.map(acc => ({\n hash: acc.compressedAccount.hash,\n tree: acc.compressedAccount.treeInfo.tree,\n queue: acc.compressedAccount.treeInfo.queue,\n }));\n return rpc.getValidityProofV0(proofInputs);\n }),\n );\n\n const idempotentAtaIx = (() => {\n if (wrap || ataType === 'light-token') {\n return createAssociatedTokenAccountInterfaceIdempotentInstruction(\n payer,\n lightTokenAtaAddress,\n owner,\n mint,\n LIGHT_TOKEN_PROGRAM_ID,\n );\n } else if (ataType === 'spl') {\n return createAssociatedTokenAccountIdempotentInstruction(\n payer,\n splAta,\n owner,\n mint,\n TOKEN_PROGRAM_ID,\n );\n } else {\n return createAssociatedTokenAccountIdempotentInstruction(\n payer,\n t22Ata,\n owner,\n mint,\n TOKEN_2022_PROGRAM_ID,\n );\n }\n })();\n\n const batches: InternalLoadBatch[] = [];\n\n for (let i = 0; i < chunks.length; i++) {\n const chunk = chunks[i];\n const proof = proofs[i];\n const chunkAmount = chunk.reduce(\n (sum, acc) => sum + BigInt(acc.parsed.amount.toString()),\n BigInt(0),\n );\n\n const batchIxs: TransactionInstruction[] = [];\n let batchWrapCount = 0;\n let batchHasAtaCreation = false;\n\n if (i === 0) {\n batchIxs.push(...setupInstructions);\n batchWrapCount = wrapCount;\n batchHasAtaCreation = needsAtaCreation;\n } else {\n batchIxs.push(idempotentAtaIx);\n batchHasAtaCreation = true;\n }\n\n const authorityForDecompress = authority ?? owner;\n batchIxs.push(\n createDecompressInterfaceInstruction(\n payer,\n chunk,\n decompressTarget,\n chunkAmount,\n proof,\n decompressSplInfo,\n decimals,\n undefined,\n authorityForDecompress,\n ),\n );\n\n batches.push({\n instructions: batchIxs,\n compressedAccounts: chunk,\n wrapCount: batchWrapCount,\n hasAtaCreation: batchHasAtaCreation,\n });\n }\n\n return batches;\n}\n","import { ParsedTokenAccount, TreeType } from '@lightprotocol/stateless.js';\n\n/**\n * Throws if any V1 compressed accounts are present.\n * v3 interface only supports V2 trees.\n * @internal\n */\nexport function assertV2Only(accounts: ParsedTokenAccount[]): void {\n const v1Count = accounts.filter(\n acc => acc.compressedAccount.treeInfo.treeType === TreeType.StateV1,\n ).length;\n\n if (v1Count > 0) {\n throw new Error(\n 'v3 interface does not support V1 compressed accounts. ' +\n `Found ${v1Count} V1 account(s). ` +\n 'Use the main SDK actions (transfer, decompress, merge) to migrate V1 accounts to V2.',\n );\n }\n}\n","import {\n PublicKey,\n SystemProgram,\n TransactionInstruction,\n} from '@solana/web3.js';\nimport { Buffer } from 'buffer';\nimport { LIGHT_TOKEN_PROGRAM_ID } from '@lightprotocol/stateless.js';\n\n/**\n * Parameters for creating a MintTo instruction.\n */\nexport interface CreateMintToInstructionParams {\n /** Light mint account (decompressed from compressed light mint) */\n mint: PublicKey;\n /** Destination light-token account to mint to */\n destination: PublicKey;\n /** Amount of tokens to mint */\n amount: number | bigint;\n /** Mint authority (must be signer) */\n authority: PublicKey;\n /** Maximum lamports for rent and top-up combined. Transaction fails if exceeded. (u16::MAX = no limit, 0 = no top-ups allowed) */\n maxTopUp?: number;\n /** Optional fee payer for rent top-ups. If not provided, authority pays. */\n feePayer?: PublicKey;\n}\n\n/**\n * Create instruction for minting tokens to a light-token account.\n *\n * This is a simple 3-4 account instruction for minting to light-token associated token accounts (hot).\n * Uses discriminator 7 (LightTokenMintTo).\n *\n * @param params - Mint instruction parameters\n * @returns TransactionInstruction for minting tokens\n */\nexport function createMintToInstruction(\n params: CreateMintToInstructionParams,\n): TransactionInstruction {\n const { mint, destination, amount, authority, maxTopUp, feePayer } = params;\n\n // Authority is writable only when maxTopUp is set AND no feePayer\n // (authority pays for top-ups only if no separate feePayer)\n const authorityWritable = maxTopUp !== undefined && !feePayer;\n\n const keys = [\n { pubkey: mint, isSigner: false, isWritable: true },\n { pubkey: destination, isSigner: false, isWritable: true },\n { pubkey: authority, isSigner: true, isWritable: authorityWritable },\n // System program required for rent top-up CPIs\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n ];\n\n // Add fee_payer if provided (must be signer and writable)\n if (feePayer) {\n keys.push({ pubkey: feePayer, isSigner: true, isWritable: true });\n }\n\n // Build instruction data: discriminator (7) + amount (u64) + optional max_top_up (u16)\n const amountBigInt = BigInt(amount.toString());\n const dataSize = maxTopUp !== undefined ? 11 : 9; // 1 + 8 + optional 2\n const data = Buffer.alloc(dataSize);\n\n data.writeUInt8(7, 0); // LightTokenMintTo discriminator\n data.writeBigUInt64LE(amountBigInt, 1);\n\n if (maxTopUp !== undefined) {\n data.writeUInt16LE(maxTopUp, 9);\n }\n\n return new TransactionInstruction({\n programId: LIGHT_TOKEN_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 LIGHT_TOKEN_PROGRAM_ID,\n LightSystemProgram,\n defaultStaticAccountsStruct,\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 { MAX_TOP_UP, TokenDataVersion } from '../../constants';\n\ninterface EncodeCompressedMintToInstructionParams {\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 maxTopUp?: number;\n}\n\n/** @internal */\nfunction encodeCompressedMintToInstructionData(\n params: EncodeCompressedMintToInstructionParams,\n): Buffer {\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 // When mint is decompressed, the program reads mint data from the light mint\n // Solana account. Setting mint to null signals this to the program.\n const isDecompressed = params.mintData.cmintDecompressed;\n\n const instructionData: MintActionCompressedInstructionData = {\n leafIndex: params.leafIndex,\n proveByIndex: true,\n rootIndex: params.rootIndex,\n maxTopUp: params.maxTopUp ?? MAX_TOP_UP,\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: isDecompressed ? null : params.proof,\n cpiContext: null,\n mint: isDecompressed\n ? null\n : {\n supply: params.mintData.supply,\n decimals: params.mintData.decimals,\n metadata: {\n version: params.mintData.version,\n cmintDecompressed: params.mintData.cmintDecompressed,\n mint: params.mintData.splMint,\n mintSigner: Array.from(params.mintData.mintSigner),\n bump: params.mintData.bump,\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 light mint to compressed accounts.\n * To mint to light-token associated token accounts across SPL/T22/light 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 light mint.\n * @param merkleContext Merkle context of the light 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 * @param maxTopUp Optional cap on rent top-up (units of 1k lamports; default no cap)\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 maxTopUp?: number,\n): TransactionInstruction {\n const isDecompressed = mintData.cmintDecompressed;\n const addressTreeInfo = getDefaultAddressTreeInfo();\n const data = encodeCompressedMintToInstructionData({\n leafIndex: merkleContext.leafIndex,\n rootIndex: validityProof.rootIndices[0],\n proof: validityProof.compressedProof,\n mintData,\n recipients,\n tokenAccountVersion,\n maxTopUp,\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 // light mint account when decompressed (must come before payer for correct account ordering)\n ...(isDecompressed\n ? [\n {\n pubkey: mintData.splMint,\n isSigner: false,\n isWritable: true,\n },\n ]\n : []),\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: LIGHT_TOKEN_PROGRAM_ID,\n keys,\n data,\n });\n}\n","import { PublicKey, TransactionInstruction } from '@solana/web3.js';\nimport { ValidityProofWithContext } from '@lightprotocol/stateless.js';\nimport { createMintToInstruction as createSplMintToInstruction } from '@solana/spl-token';\nimport { createMintToInstruction as createLightTokenMintToInstruction } 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 light-token mints.\n * This instruction ONLY mints to light-token associated token accounts (hot).\n *\n * For light-token mints, the light mint account must exist (mint must be decompressed first).\n *\n * @param mintInterface Mint interface (SPL, Token-2022, or light-token).\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 Not used (legacy parameter, kept for compatibility).\n * @param multiSigners Multi-signature signer public keys (SPL/T22 only).\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 - no merkleContext means it's a native SPL mint\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 // light-token (light-token) - use simple LightTokenMintTo instruction\n // The light mint account must exist for this to work (mint must be decompressed first)\n if (!mintInterface.mintContext) {\n throw new Error('mintContext required for light-token mint-to');\n }\n\n // Use payer as fee payer for top-ups if different from authority\n const feePayer = authority.equals(payer) ? undefined : payer;\n\n return createLightTokenMintToInstruction({\n mint,\n destination,\n amount,\n authority,\n feePayer,\n });\n}\n","import { TransactionInstruction } from '@solana/web3.js';\n\n/** Solana maximum transaction size in bytes. */\nexport const MAX_TRANSACTION_SIZE = 1232;\n\n/**\n * Conservative size budget for a combined batch (load + transfer + ATA).\n * Leaves headroom below MAX_TRANSACTION_SIZE for edge-case key counts.\n */\nexport const MAX_COMBINED_BATCH_BYTES = 900;\n\n/**\n * Conservative size budget for a load-only or setup-only batch.\n */\nexport const MAX_LOAD_ONLY_BATCH_BYTES = 1000;\n\n/**\n * Asserts that the serialized transaction size is within MAX_TRANSACTION_SIZE.\n * @internal\n */\nexport function assertTransactionSizeWithinLimit(\n instructions: TransactionInstruction[],\n numSigners: number,\n context = 'Batch',\n): void {\n const size = estimateTransactionSize(instructions, numSigners);\n if (size > MAX_TRANSACTION_SIZE) {\n throw new Error(\n `${context} exceeds max transaction size: ${size} > ${MAX_TRANSACTION_SIZE}. ` +\n 'This indicates a bug in batch assembly.',\n );\n }\n}\n\n/**\n * Encode length as compact-u16 (Solana's variable-length encoding).\n * Returns the number of bytes the encoded value occupies.\n * @internal\n */\nfunction compactU16Size(value: number): number {\n if (value < 0x80) return 1;\n if (value < 0x4000) return 2;\n return 3;\n}\n\n/**\n * Estimate the serialized byte size of a V0 VersionedTransaction built from\n * the given instructions and signer count.\n *\n * The estimate accounts for Solana's account-key deduplication: all unique\n * pubkeys across every instruction (keys + programIds) are collected into a\n * single set, matching the behaviour of\n * `TransactionMessage.compileToV0Message`.\n *\n * This intentionally does NOT use address lookup tables, so the result is an\n * upper bound. If lookup tables are used at send time the actual size will be\n * smaller.\n *\n * @param instructions The instructions that will be included in the tx.\n * @param numSigners Number of signers (determines signature count).\n * @returns Estimated byte size of the serialized transaction.\n */\nexport function estimateTransactionSize(\n instructions: TransactionInstruction[],\n numSigners: number,\n): number {\n // 1. Collect unique account keys (pubkeys + programIds)\n const uniqueKeys = new Set<string>();\n for (const ix of instructions) {\n uniqueKeys.add(ix.programId.toBase58());\n for (const key of ix.keys) {\n uniqueKeys.add(key.pubkey.toBase58());\n }\n }\n const numKeys = uniqueKeys.size;\n\n // 2. Signatures section\n const signaturesSize = compactU16Size(numSigners) + 64 * numSigners;\n\n // 3. Message\n const messagePrefix = 1; // V0 prefix byte (0x80)\n const header = 3; // numRequiredSignatures, numReadonlySignedAccounts, numReadonlyUnsignedAccounts\n const accountKeysSize = compactU16Size(numKeys) + 32 * numKeys;\n const blockhashSize = 32;\n\n // 4. Instructions\n let instructionsSize = compactU16Size(instructions.length);\n for (const ix of instructions) {\n instructionsSize += 1; // programIdIndex (u8)\n instructionsSize += compactU16Size(ix.keys.length); // accounts array length\n instructionsSize += ix.keys.length; // account indices (u8 each)\n instructionsSize += compactU16Size(ix.data.length); // data length\n instructionsSize += ix.data.length; // data bytes\n }\n\n // 5. Address table lookups (empty)\n const lookupTablesSize = compactU16Size(0); // empty array\n\n return (\n signaturesSize +\n messagePrefix +\n header +\n accountKeysSize +\n blockhashSize +\n instructionsSize +\n lookupTablesSize\n );\n}\n","import { rawLoadBatchComputeUnits, type InternalLoadBatch } from './load-ata';\n\nconst CU_BUFFER_FACTOR = 1.3;\nconst CU_MIN = 50_000;\nconst CU_MAX = 1_400_000;\n\nexport function calculateCombinedCU(\n baseCu: number,\n loadBatch: InternalLoadBatch | null,\n): number {\n const rawLoadCu = loadBatch ? rawLoadBatchComputeUnits(loadBatch) : 0;\n const cu = Math.ceil((baseCu + rawLoadCu) * CU_BUFFER_FACTOR);\n return Math.max(CU_MIN, Math.min(CU_MAX, cu));\n}\n","import {\n ComputeBudgetProgram,\n PublicKey,\n TransactionInstruction,\n SystemProgram,\n} from '@solana/web3.js';\nimport {\n Rpc,\n assertBetaEnabled,\n LIGHT_TOKEN_PROGRAM_ID,\n} from '@lightprotocol/stateless.js';\nimport {\n TOKEN_PROGRAM_ID,\n TOKEN_2022_PROGRAM_ID,\n createTransferCheckedInstruction,\n TokenAccountNotFoundError,\n} from '@solana/spl-token';\nimport BN from 'bn.js';\nimport { getAssociatedTokenAddressInterface } from '../get-associated-token-address-interface';\nimport {\n _buildLoadBatches,\n calculateLoadBatchComputeUnits,\n type InternalLoadBatch,\n} from './load-ata';\nimport {\n getAtaInterface as _getAtaInterface,\n checkNotFrozen,\n type AccountInterface,\n spendableAmountForAuthority,\n isAuthorityForInterface,\n filterInterfaceForAuthority,\n} from '../get-account-interface';\nimport { assertTransactionSizeWithinLimit } from '../utils/estimate-tx-size';\nimport type { TransferOptions } from '../actions/transfer-interface';\nimport { calculateCombinedCU } from './calculate-combined-cu';\n\nconst LIGHT_TOKEN_TRANSFER_DISCRIMINATOR = 3;\nconst LIGHT_TOKEN_TRANSFER_CHECKED_DISCRIMINATOR = 12;\n\nconst TRANSFER_BASE_CU = 10_000;\n\nexport function calculateTransferCU(\n loadBatch: InternalLoadBatch | null,\n): number {\n return calculateCombinedCU(TRANSFER_BASE_CU, loadBatch);\n}\n\n/**\n * Create a light-token transfer instruction.\n *\n * For light-token accounts with compressible extension, the program needs\n * system_program and fee_payer to handle rent top-ups.\n *\n * @param source Source light-token account\n * @param destination Destination light-token account\n * @param owner Owner of the source account (signer, also pays for compressible extension top-ups)\n * @param amount Amount to transfer\n * @param feePayer Optional fee payer for top-ups (defaults to owner)\n * @returns Transaction instruction for light-token transfer\n */\nexport function createLightTokenTransferInstruction(\n source: PublicKey,\n destination: PublicKey,\n owner: PublicKey,\n amount: number | bigint,\n feePayer?: PublicKey,\n): TransactionInstruction {\n // Instruction data format:\n // byte 0: discriminator (3)\n // bytes 1-8: amount (u64 LE)\n const data = Buffer.alloc(9);\n data.writeUInt8(LIGHT_TOKEN_TRANSFER_DISCRIMINATOR, 0);\n data.writeBigUInt64LE(BigInt(amount), 1);\n\n const effectiveFeePayer = feePayer ?? owner;\n\n // Account order per program:\n // 0: source (writable)\n // 1: destination (writable)\n // 2: authority/owner (signer, writable only when paying top-ups)\n // 3: system_program (for top-ups via CPI)\n // 4: fee_payer (signer, writable - pays for top-ups)\n const keys = [\n { pubkey: source, isSigner: false, isWritable: true },\n { pubkey: destination, isSigner: false, isWritable: true },\n {\n pubkey: owner,\n isSigner: true,\n isWritable: effectiveFeePayer.equals(owner),\n },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n {\n pubkey: effectiveFeePayer,\n isSigner: !effectiveFeePayer.equals(owner), // Only mark as signer if different from owner (owner already signed)\n isWritable: true,\n },\n ];\n\n return new TransactionInstruction({\n programId: LIGHT_TOKEN_PROGRAM_ID,\n keys,\n data,\n });\n}\n\n/**\n * Create a light-token transfer_checked instruction. Same semantics as SPL\n * TransferChecked.\n */\nexport function createLightTokenTransferCheckedInstruction(\n source: PublicKey,\n destination: PublicKey,\n mint: PublicKey,\n owner: PublicKey,\n amount: number | bigint,\n decimals: number,\n payer: PublicKey,\n): TransactionInstruction {\n const data = Buffer.alloc(10);\n data.writeUInt8(LIGHT_TOKEN_TRANSFER_CHECKED_DISCRIMINATOR, 0);\n data.writeBigUInt64LE(BigInt(amount), 1);\n data.writeUInt8(decimals, 9);\n\n const keys = [\n { pubkey: source, isSigner: false, isWritable: true },\n { pubkey: mint, isSigner: false, isWritable: false },\n { pubkey: destination, isSigner: false, isWritable: true },\n { pubkey: owner, isSigner: true, isWritable: payer.equals(owner) },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n {\n pubkey: payer,\n isSigner: !payer.equals(owner),\n isWritable: true,\n },\n ];\n\n return new TransactionInstruction({\n programId: LIGHT_TOKEN_PROGRAM_ID,\n keys,\n data,\n });\n}\n\nexport async function createTransferInterfaceInstructions(\n rpc: Rpc,\n payer: PublicKey,\n mint: PublicKey,\n amount: number | bigint | BN,\n sender: PublicKey,\n destination: PublicKey,\n decimals: number,\n options?: TransferOptions,\n): Promise<TransactionInstruction[][]> {\n assertBetaEnabled();\n\n const amountBigInt = BigInt(amount.toString());\n\n if (amountBigInt <= BigInt(0)) {\n throw new Error('Transfer amount must be greater than zero.');\n }\n\n const {\n wrap = false,\n programId = LIGHT_TOKEN_PROGRAM_ID,\n owner: optionsOwner,\n ...interfaceOptions\n } = options ?? {};\n\n const effectiveOwner = optionsOwner ?? sender;\n\n const isSplOrT22 =\n programId.equals(TOKEN_PROGRAM_ID) ||\n programId.equals(TOKEN_2022_PROGRAM_ID);\n\n const senderAta = getAssociatedTokenAddressInterface(\n mint,\n effectiveOwner,\n false,\n programId,\n );\n\n let senderInterface: AccountInterface;\n try {\n senderInterface = await _getAtaInterface(\n rpc,\n senderAta,\n effectiveOwner,\n mint,\n undefined,\n programId.equals(LIGHT_TOKEN_PROGRAM_ID) ? undefined : programId,\n wrap,\n );\n } catch (error) {\n if (error instanceof TokenAccountNotFoundError) {\n throw new Error('Sender has no token accounts for this mint.');\n }\n throw error;\n }\n\n checkNotFrozen(senderInterface, 'transfer');\n\n const isDelegate = !effectiveOwner.equals(sender);\n if (isDelegate) {\n if (!isAuthorityForInterface(senderInterface, sender)) {\n throw new Error(\n 'Signer is not the owner or a delegate of the sender account.',\n );\n }\n const spendable = spendableAmountForAuthority(senderInterface, sender);\n if (amountBigInt > spendable) {\n throw new Error(\n `Insufficient delegated balance. Required: ${amountBigInt}, Available (delegate): ${spendable}`,\n );\n }\n senderInterface = filterInterfaceForAuthority(senderInterface, sender);\n } else {\n if (senderInterface.parsed.amount < amountBigInt) {\n throw new Error(\n `Insufficient balance. Required: ${amountBigInt}, Available: ${senderInterface.parsed.amount}`,\n );\n }\n }\n\n const internalBatches = await _buildLoadBatches(\n rpc,\n payer,\n senderInterface,\n interfaceOptions,\n wrap,\n senderAta,\n amountBigInt,\n sender,\n decimals,\n );\n\n let transferIx: TransactionInstruction;\n if (isSplOrT22 && !wrap) {\n transferIx = createTransferCheckedInstruction(\n senderAta,\n mint,\n destination,\n sender,\n amountBigInt,\n decimals,\n [],\n programId,\n );\n } else {\n transferIx = createLightTokenTransferCheckedInstruction(\n senderAta,\n destination,\n mint,\n sender,\n amountBigInt,\n decimals,\n payer,\n );\n }\n\n const numSigners = payer.equals(sender) ? 1 : 2;\n\n if (internalBatches.length === 0) {\n const cu = calculateTransferCU(null);\n const txIxs = [\n ComputeBudgetProgram.setComputeUnitLimit({ units: cu }),\n transferIx,\n ];\n assertTransactionSizeWithinLimit(txIxs, numSigners, 'Batch');\n return [txIxs];\n }\n\n if (internalBatches.length === 1) {\n const batch = internalBatches[0];\n const cu = calculateTransferCU(batch);\n const txIxs = [\n ComputeBudgetProgram.setComputeUnitLimit({ units: cu }),\n ...batch.instructions,\n transferIx,\n ];\n assertTransactionSizeWithinLimit(txIxs, numSigners, 'Batch');\n return [txIxs];\n }\n\n const result: TransactionInstruction[][] = [];\n\n for (let i = 0; i < internalBatches.length - 1; i++) {\n const batch = internalBatches[i];\n const cu = calculateLoadBatchComputeUnits(batch);\n const txIxs = [\n ComputeBudgetProgram.setComputeUnitLimit({ units: cu }),\n ...batch.instructions,\n ];\n assertTransactionSizeWithinLimit(txIxs, numSigners, 'Batch');\n result.push(txIxs);\n }\n\n const lastBatch = internalBatches[internalBatches.length - 1];\n const lastCu = calculateTransferCU(lastBatch);\n const lastTxIxs = [\n ComputeBudgetProgram.setComputeUnitLimit({ units: lastCu }),\n ...lastBatch.instructions,\n transferIx,\n ];\n assertTransactionSizeWithinLimit(lastTxIxs, numSigners, 'Batch');\n result.push(lastTxIxs);\n\n return result;\n}\n","import {\n ComputeBudgetProgram,\n PublicKey,\n TransactionInstruction,\n SystemProgram,\n} from '@solana/web3.js';\nimport {\n Rpc,\n assertBetaEnabled,\n LIGHT_TOKEN_PROGRAM_ID,\n} from '@lightprotocol/stateless.js';\nimport { TokenAccountNotFoundError } from '@solana/spl-token';\nimport type BN from 'bn.js';\nimport { MAX_TOP_UP } from '../../constants';\nimport { CompressedTokenProgram } from '../../program';\nimport {\n getSplInterfaceInfos,\n SplInterfaceInfo,\n} from '../../utils/get-token-pool-infos';\nimport { getAssociatedTokenAddressInterface } from '../get-associated-token-address-interface';\nimport {\n getAtaInterface as _getAtaInterface,\n checkNotFrozen,\n type AccountInterface,\n} from '../get-account-interface';\nimport {\n _buildLoadBatches,\n calculateLoadBatchComputeUnits,\n type InternalLoadBatch,\n} from './load-ata';\nimport type { InterfaceOptions } from '../actions/transfer-interface';\nimport { assertTransactionSizeWithinLimit } from '../utils/estimate-tx-size';\nimport { ERR_NO_LIGHT_TOKEN_BALANCE_UNWRAP } from '../errors';\nimport {\n encodeTransfer2InstructionData,\n createCompressLightToken,\n createDecompressSpl,\n Transfer2InstructionData,\n Compression,\n} from '../layout/layout-transfer2';\nimport { calculateCombinedCU } from './calculate-combined-cu';\n\nconst UNWRAP_BASE_CU = 10_000;\n\nfunction calculateUnwrapCU(loadBatch: InternalLoadBatch | null): number {\n return calculateCombinedCU(UNWRAP_BASE_CU, loadBatch);\n}\n\n/**\n * Create an unwrap instruction that moves tokens from a light-token account to an\n * SPL/T22 account.\n *\n * @param source Source light-token account\n * @param destination Destination SPL/T22 token account\n * @param owner Owner of the source account (signer)\n * @param mint Mint address\n * @param amount Amount to unwrap,\n * @param splInterfaceInfo SPL interface info for the decompression\n * @param decimals Mint decimals (required for transfer_checked)\n * @param payer Fee payer (defaults to owner if not provided)\n * @param maxTopUp Optional cap on rent top-up (units of 1k lamports; default no cap)\n * @returns TransactionInstruction to unwrap tokens\n */\nexport function createUnwrapInstruction(\n source: PublicKey,\n destination: PublicKey,\n owner: PublicKey,\n mint: PublicKey,\n amount: bigint,\n splInterfaceInfo: SplInterfaceInfo,\n decimals: number,\n payer: PublicKey = owner,\n maxTopUp?: number,\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 LIGHT_TOKEN_PROGRAM_INDEX = 6;\n\n // Unwrap flow: compress from light-token, decompress to SPL\n const compressions: Compression[] = [\n createCompressLightToken(\n amount,\n MINT_INDEX,\n SOURCE_INDEX,\n OWNER_INDEX,\n LIGHT_TOKEN_PROGRAM_INDEX,\n ),\n createDecompressSpl(\n amount,\n MINT_INDEX,\n DESTINATION_INDEX,\n POOL_INDEX,\n splInterfaceInfo.poolIndex,\n splInterfaceInfo.bump,\n decimals,\n ),\n ];\n\n const instructionData: Transfer2InstructionData = {\n withTransactionHash: false,\n withLamportsChangeAccountMerkleTreeIndex: false,\n lamportsChangeAccountMerkleTreeIndex: 0,\n lamportsChangeAccountOwnerIndex: 0,\n outputQueue: 0,\n maxTopUp: maxTopUp ?? MAX_TOP_UP,\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 // Account order matches wrap instruction for consistency\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: LIGHT_TOKEN_PROGRAM_ID,\n isSigner: false,\n isWritable: false,\n },\n // System program needed for top-up CPIs when source has compressible extension\n {\n pubkey: SystemProgram.programId,\n isSigner: false,\n isWritable: false,\n },\n ];\n\n return new TransactionInstruction({\n programId: CompressedTokenProgram.programId,\n keys,\n data,\n });\n}\n\nexport async function createUnwrapInstructions(\n rpc: Rpc,\n destination: PublicKey,\n owner: PublicKey,\n mint: PublicKey,\n decimals: number,\n amount?: number | bigint | BN,\n payer?: PublicKey,\n splInterfaceInfo?: SplInterfaceInfo,\n maxTopUp?: number,\n interfaceOptions?: InterfaceOptions,\n wrap = false,\n): Promise<TransactionInstruction[][]> {\n assertBetaEnabled();\n\n payer ??= owner;\n\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 const destAtaInfo = await rpc.getAccountInfo(destination);\n if (!destAtaInfo) {\n throw new Error(\n `Destination account does not exist: ${destination.toBase58()}. ` +\n `Create it first using getOrCreateAssociatedTokenAccount or createAssociatedTokenAccountIdempotentInstruction.`,\n );\n }\n\n const lightTokenAta = getAssociatedTokenAddressInterface(mint, owner);\n\n let accountInterface: AccountInterface;\n try {\n accountInterface = await _getAtaInterface(\n rpc,\n lightTokenAta,\n owner,\n mint,\n undefined,\n undefined,\n wrap,\n );\n } catch (error) {\n if (error instanceof TokenAccountNotFoundError) {\n throw new Error(ERR_NO_LIGHT_TOKEN_BALANCE_UNWRAP);\n }\n throw error;\n }\n\n checkNotFrozen(accountInterface, 'unwrap');\n\n const totalBalance = accountInterface.parsed.amount;\n if (totalBalance === BigInt(0)) {\n throw new Error(ERR_NO_LIGHT_TOKEN_BALANCE_UNWRAP);\n }\n\n const unwrapAmount =\n amount != null ? BigInt(amount.toString()) : totalBalance;\n\n if (unwrapAmount === BigInt(0)) {\n throw new Error('Unwrap amount must be greater than zero.');\n }\n\n if (unwrapAmount > totalBalance) {\n throw new Error(\n `Insufficient light-token balance. Requested: ${unwrapAmount}, Available: ${totalBalance}`,\n );\n }\n\n const internalBatches = await _buildLoadBatches(\n rpc,\n payer,\n accountInterface,\n interfaceOptions,\n wrap,\n lightTokenAta,\n amount != null ? unwrapAmount : undefined,\n undefined,\n decimals,\n );\n\n const ix = createUnwrapInstruction(\n lightTokenAta,\n destination,\n owner,\n mint,\n unwrapAmount,\n resolvedSplInterfaceInfo,\n decimals,\n payer,\n maxTopUp,\n );\n\n const numSigners = payer.equals(owner) ? 1 : 2;\n if (internalBatches.length === 0) {\n const txIxs = [\n ComputeBudgetProgram.setComputeUnitLimit({\n units: calculateUnwrapCU(null),\n }),\n ix,\n ];\n assertTransactionSizeWithinLimit(txIxs, numSigners, 'Unwrap batch');\n return [txIxs];\n }\n\n if (internalBatches.length === 1) {\n const batch = internalBatches[0];\n const txIxs = [\n ComputeBudgetProgram.setComputeUnitLimit({\n units: calculateUnwrapCU(batch),\n }),\n ...batch.instructions,\n ix,\n ];\n assertTransactionSizeWithinLimit(txIxs, numSigners, 'Unwrap batch');\n return [txIxs];\n }\n\n const result: TransactionInstruction[][] = [];\n for (let i = 0; i < internalBatches.length - 1; i++) {\n const batch = internalBatches[i];\n const cu = calculateLoadBatchComputeUnits(batch);\n const txIxs = [\n ComputeBudgetProgram.setComputeUnitLimit({ units: cu }),\n ...batch.instructions,\n ];\n assertTransactionSizeWithinLimit(txIxs, numSigners, 'Unwrap batch');\n result.push(txIxs);\n }\n\n const lastBatch = internalBatches[internalBatches.length - 1];\n const lastTxIxs = [\n ComputeBudgetProgram.setComputeUnitLimit({\n units: calculateUnwrapCU(lastBatch),\n }),\n ...lastBatch.instructions,\n ix,\n ];\n assertTransactionSizeWithinLimit(lastTxIxs, numSigners, 'Unwrap batch');\n result.push(lastTxIxs);\n\n return result;\n}\n","import { PublicKey, TransactionInstruction } from '@solana/web3.js';\nimport { Buffer } from 'buffer';\nimport { LIGHT_TOKEN_PROGRAM_ID } from '@lightprotocol/stateless.js';\n\n/**\n * Discriminator for LightTokenFreezeAccount (native instruction 10).\n * Matches InstructionType::LightTokenFreezeAccount in the on-chain program.\n */\nconst LIGHT_TOKEN_FREEZE_ACCOUNT_DISCRIMINATOR = Buffer.from([10]);\n\n/**\n * Discriminator for LightTokenThawAccount (native instruction 11).\n * Matches InstructionType::LightTokenThawAccount in the on-chain program.\n */\nconst LIGHT_TOKEN_THAW_ACCOUNT_DISCRIMINATOR = Buffer.from([11]);\n\n/**\n * Create an instruction to freeze a decompressed light-token account.\n *\n * Freezing sets the account state to AccountState::Frozen, preventing\n * transfers and other token operations. Only the mint's freeze_authority\n * can freeze accounts.\n *\n * Account order per program:\n * 0. token_account (mutable) - the light-token account to freeze\n * 1. mint (readonly) - the mint associated with the token account\n * 2. freeze_authority - must match mint.freeze_authority (signer)\n *\n * @param tokenAccount The light-token account to freeze (must be Initialized)\n * @param mint The mint of the light-token account\n * @param freezeAuthority The freeze authority of the mint (signer)\n * @returns TransactionInstruction\n */\nexport function createLightTokenFreezeAccountInstruction(\n tokenAccount: PublicKey,\n mint: PublicKey,\n freezeAuthority: PublicKey,\n): TransactionInstruction {\n return new TransactionInstruction({\n programId: LIGHT_TOKEN_PROGRAM_ID,\n keys: [\n { pubkey: tokenAccount, isSigner: false, isWritable: true },\n { pubkey: mint, isSigner: false, isWritable: false },\n { pubkey: freezeAuthority, isSigner: true, isWritable: false },\n ],\n data: LIGHT_TOKEN_FREEZE_ACCOUNT_DISCRIMINATOR,\n });\n}\n\n/**\n * Create an instruction to thaw (unfreeze) a frozen light-token account.\n *\n * Thawing restores the account state from AccountState::Frozen to\n * AccountState::Initialized, re-enabling token operations. Only the\n * mint's freeze_authority can thaw accounts.\n *\n * Account order per program:\n * 0. token_account (mutable) - the frozen light-token account to thaw\n * 1. mint (readonly) - the mint associated with the token account\n * 2. freeze_authority - must match mint.freeze_authority (signer)\n *\n * @param tokenAccount The frozen light-token account to thaw\n * @param mint The mint of the light-token account\n * @param freezeAuthority The freeze authority of the mint (signer)\n * @returns TransactionInstruction\n */\nexport function createLightTokenThawAccountInstruction(\n tokenAccount: PublicKey,\n mint: PublicKey,\n freezeAuthority: PublicKey,\n): TransactionInstruction {\n return new TransactionInstruction({\n programId: LIGHT_TOKEN_PROGRAM_ID,\n keys: [\n { pubkey: tokenAccount, isSigner: false, isWritable: true },\n { pubkey: mint, isSigner: false, isWritable: false },\n { pubkey: freezeAuthority, isSigner: true, isWritable: false },\n ],\n data: LIGHT_TOKEN_THAW_ACCOUNT_DISCRIMINATOR,\n });\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 LIGHT_TOKEN_PROGRAM_ID,\n getDefaultAddressTreeInfo,\n assertBetaEnabled,\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 { deriveCMintAddress, findMintAddress } from '../derivation';\nimport { createMint } from '../../actions/create-mint';\n\nexport { TokenMetadataInstructionData };\n\n/**\n * Create and initialize a new mint for SPL/T22/light-token.\n *\n * @param rpc RPC connection to use\n * @param payer Fee payer\n * @param mintAuthority Account that will control minting (signer for light-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 LIGHT_TOKEN_PROGRAM_ID)\n * @param tokenMetadata Optional token metadata (light-token mints only)\n * @param outputStateTreeInfo Optional output state tree info (light-token mints only)\n * @param addressTreeInfo Optional address tree info (light-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 = LIGHT_TOKEN_PROGRAM_ID,\n tokenMetadata?: TokenMetadataInstructionData,\n outputStateTreeInfo?: TreeInfo,\n addressTreeInfo?: AddressTreeInfo,\n): Promise<{ mint: PublicKey; transactionSignature: TransactionSignature }> {\n assertBetaEnabled();\n\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: light-token mint creation\n if (!('secretKey' in mintAuthority)) {\n throw new Error('mintAuthority must be a Signer for light-token mints');\n }\n if (\n addressTreeInfo &&\n !addressTreeInfo.tree.equals(getDefaultAddressTreeInfo().tree)\n ) {\n throw new Error(\n `addressTreeInfo ${addressTreeInfo?.tree.toString()} must be the default address tree info: ${getDefaultAddressTreeInfo().tree.toString()}`,\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 compressedMintAddress = deriveCMintAddress(\n keypair.publicKey,\n addressTreeInfo,\n );\n\n const validityProof = await rpc.getValidityProofV2(\n [],\n [\n {\n address: Uint8Array.from(compressedMintAddress),\n treeInfo: addressTreeInfo,\n },\n ],\n DerivationMode.standard,\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\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 } from '@solana/buffer-layout';\nimport { publicKey } from '@solana/buffer-layout-utils';\nimport {\n struct as borshStruct,\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 * Light mint context (protocol version, SPL mint reference)\n */\nexport interface MintContext {\n /** Protocol version for upgradability */\n version: number;\n /** Whether the compressed light mint has been decompressed to a light mint account */\n cmintDecompressed: boolean;\n /** PDA of the associated SPL mint */\n splMint: PublicKey;\n /** Signer pubkey used to derive the mint PDA */\n mintSigner: Uint8Array;\n /** Bump seed for the mint PDA */\n bump: number;\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 light mint structure (raw format)\n */\nexport interface CompressedMint {\n base: BaseMint;\n mintContext: MintContext;\n /** Reserved bytes for T22 layout compatibility */\n reserved: Uint8Array;\n /** Account type discriminator (1 = Mint) */\n accountType: number;\n /** Compression info embedded in mint */\n compression: CompressionInfo;\n extensions: MintExtension[] | null;\n}\n\n/** MintContext as stored by the program */\n/**\n * Raw mint context for layout encoding (mintSigner and bump are encoded separately)\n */\nexport interface RawMintContext {\n version: number;\n cmintDecompressed: 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('cmintDecompressed'),\n publicKey('splMint'),\n]);\n\n/** Byte length of MintContext (excluding mintSigner and bump which are read separately) */\nexport const MINT_CONTEXT_SIZE = MintContextLayout.span; // 34 bytes\n\n/** Additional bytes for mintSigner (32) + bump (1) */\nexport const MINT_SIGNER_SIZE = 32;\nexport const BUMP_SIZE = 1;\n\n/** Reserved bytes for T22 layout compatibility (padding to reach byte 165) */\nexport const RESERVED_SIZE = 16;\n\n/** Account type discriminator size */\nexport const ACCOUNT_TYPE_SIZE = 1;\n\n/** Account type value for light mint */\nexport const ACCOUNT_TYPE_MINT = 1;\n\n/**\n * Rent configuration for compressible accounts\n */\nexport interface RentConfig {\n /** Base rent constant per epoch */\n baseRent: number;\n /** Compression cost in lamports */\n compressionCost: number;\n /** Lamports per byte per epoch */\n lamportsPerBytePerEpoch: number;\n /** Maximum epochs that can be pre-funded */\n maxFundedEpochs: number;\n /** Maximum lamports for top-up operation */\n maxTopUp: number;\n}\n\n/** Byte length of RentConfig */\nexport const RENT_CONFIG_SIZE = 8; // 2 + 2 + 1 + 1 + 2\n\n/**\n * Compression info embedded in light mint\n */\nexport interface CompressionInfo {\n /** Config account version (0 = uninitialized) */\n configAccountVersion: number;\n /** Whether to compress to pubkey instead of owner */\n compressToPubkey: number;\n /** Account version for hashing scheme */\n accountVersion: number;\n /** Lamports to top up per write */\n lamportsPerWrite: number;\n /** Authority that can compress the account */\n compressionAuthority: PublicKey;\n /** Recipient for rent on closure */\n rentSponsor: PublicKey;\n /** Last slot rent was claimed */\n lastClaimedSlot: bigint;\n /** Rent exemption lamports paid at account creation */\n rentExemptionPaid: number;\n /** Reserved for future use */\n reserved: number;\n /** Rent configuration */\n rentConfig: RentConfig;\n}\n\n/** Byte length of CompressionInfo */\nexport const COMPRESSION_INFO_SIZE = 96; // 2 + 1 + 1 + 4 + 32 + 32 + 8 + 4 + 4 + 8\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 * @internal\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 * @internal\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 CompressionInfo from buffer at given offset\n * @returns Tuple of [CompressionInfo, bytesRead]\n * @internal\n */\nfunction deserializeCompressionInfo(\n buffer: Buffer,\n offset: number,\n): [CompressionInfo, number] {\n const startOffset = offset;\n\n const configAccountVersion = buffer.readUInt16LE(offset);\n offset += 2;\n\n const compressToPubkey = buffer.readUInt8(offset);\n offset += 1;\n\n const accountVersion = buffer.readUInt8(offset);\n offset += 1;\n\n const lamportsPerWrite = buffer.readUInt32LE(offset);\n offset += 4;\n\n const compressionAuthority = new PublicKey(\n buffer.slice(offset, offset + 32),\n );\n offset += 32;\n\n const rentSponsor = new PublicKey(buffer.slice(offset, offset + 32));\n offset += 32;\n\n const lastClaimedSlot = buffer.readBigUInt64LE(offset);\n offset += 8;\n\n // Read rent_exemption_paid (u32) and _reserved (u32)\n const rentExemptionPaid = buffer.readUInt32LE(offset);\n offset += 4;\n const reserved = buffer.readUInt32LE(offset);\n offset += 4;\n\n // Read RentConfig (8 bytes)\n const baseRent = buffer.readUInt16LE(offset);\n offset += 2;\n const compressionCost = buffer.readUInt16LE(offset);\n offset += 2;\n const lamportsPerBytePerEpoch = buffer.readUInt8(offset);\n offset += 1;\n const maxFundedEpochs = buffer.readUInt8(offset);\n offset += 1;\n const maxTopUp = buffer.readUInt16LE(offset);\n offset += 2;\n\n const rentConfig: RentConfig = {\n baseRent,\n compressionCost,\n lamportsPerBytePerEpoch,\n maxFundedEpochs,\n maxTopUp,\n };\n\n const compressionInfo: CompressionInfo = {\n configAccountVersion,\n compressToPubkey,\n accountVersion,\n lamportsPerWrite,\n compressionAuthority,\n rentSponsor,\n lastClaimedSlot,\n rentExemptionPaid,\n reserved,\n rentConfig,\n };\n\n return [compressionInfo, offset - startOffset];\n}\n\n/**\n * Deserialize a light 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 light mint\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 // 2b. Read mintSigner (32 bytes) and bump (1 byte)\n const mintSigner = buffer.slice(offset, offset + MINT_SIGNER_SIZE);\n offset += MINT_SIGNER_SIZE;\n const bump = buffer.readUInt8(offset);\n offset += BUMP_SIZE;\n\n // 3. Read reserved bytes (16 bytes) for T22 compatibility\n const reserved = buffer.slice(offset, offset + RESERVED_SIZE);\n offset += RESERVED_SIZE;\n\n // 4. Read account_type discriminator (1 byte)\n const accountType = buffer.readUInt8(offset);\n offset += ACCOUNT_TYPE_SIZE;\n\n // 5. Read CompressionInfo (96 bytes)\n const [compression, compressionBytesRead] = deserializeCompressionInfo(\n buffer,\n offset,\n );\n offset += compressionBytesRead;\n\n // 6. 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 cmintDecompressed: rawContext.cmintDecompressed !== 0,\n splMint: rawContext.splMint,\n mintSigner,\n bump,\n };\n\n const mint: CompressedMint = {\n base: baseMint,\n mintContext,\n reserved,\n accountType,\n compression,\n extensions,\n };\n\n return mint;\n}\n\n/**\n * Serialize CompressionInfo to buffer\n * @internal\n */\nfunction serializeCompressionInfo(compression: CompressionInfo): Buffer {\n const buffer = Buffer.alloc(COMPRESSION_INFO_SIZE);\n let offset = 0;\n\n buffer.writeUInt16LE(compression.configAccountVersion, offset);\n offset += 2;\n\n buffer.writeUInt8(compression.compressToPubkey, offset);\n offset += 1;\n\n buffer.writeUInt8(compression.accountVersion, offset);\n offset += 1;\n\n buffer.writeUInt32LE(compression.lamportsPerWrite, offset);\n offset += 4;\n\n compression.compressionAuthority.toBuffer().copy(buffer, offset);\n offset += 32;\n\n compression.rentSponsor.toBuffer().copy(buffer, offset);\n offset += 32;\n\n buffer.writeBigUInt64LE(compression.lastClaimedSlot, offset);\n offset += 8;\n\n // Write rent_exemption_paid (u32) and _reserved (u32)\n buffer.writeUInt32LE(compression.rentExemptionPaid, offset);\n offset += 4;\n buffer.writeUInt32LE(compression.reserved, offset);\n offset += 4;\n\n // Write RentConfig (8 bytes)\n buffer.writeUInt16LE(compression.rentConfig.baseRent, offset);\n offset += 2;\n buffer.writeUInt16LE(compression.rentConfig.compressionCost, offset);\n offset += 2;\n buffer.writeUInt8(compression.rentConfig.lamportsPerBytePerEpoch, offset);\n offset += 1;\n buffer.writeUInt8(compression.rentConfig.maxFundedEpochs, offset);\n offset += 1;\n buffer.writeUInt16LE(compression.rentConfig.maxTopUp, offset);\n offset += 2;\n\n return buffer;\n}\n\n/**\n * Serialize a light mint to buffer\n * Uses SPL's MintLayout for BaseMint, helper functions for context/metadata\n *\n * @param mint - The light mint 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 cmintDecompressed: mint.mintContext.cmintDecompressed ? 1 : 0,\n splMint: mint.mintContext.splMint,\n },\n contextBuffer,\n );\n buffers.push(contextBuffer);\n\n // 2b. Encode mintSigner (32 bytes) and bump (1 byte)\n buffers.push(Buffer.from(mint.mintContext.mintSigner));\n buffers.push(Buffer.from([mint.mintContext.bump]));\n\n // 3. Encode reserved bytes (16 bytes) - default to zeros\n const reserved = mint.reserved ?? new Uint8Array(RESERVED_SIZE);\n buffers.push(Buffer.from(reserved));\n\n // 4. Encode account_type (1 byte) - default to ACCOUNT_TYPE_MINT (1)\n const accountType = mint.accountType ?? ACCOUNT_TYPE_MINT;\n buffers.push(Buffer.from([accountType]));\n\n // 5. Encode CompressionInfo (96 bytes) - default to zeros\n if (mint.compression) {\n buffers.push(serializeCompressionInfo(mint.compression));\n } else {\n buffers.push(Buffer.alloc(COMPRESSION_INFO_SIZE));\n }\n\n // 6. 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 cmintDecompressed: boolean;\n version: number;\n /** Signer pubkey used to derive the mint PDA */\n mintSigner: Uint8Array;\n /** Bump seed for the mint PDA */\n bump: 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 light mint to MintInstructionData format\n * This extracts and flattens the data structure for instruction encoding\n *\n * @param compressedMint - Deserialized light mint from account data\n * @returns Flattened MintInstructionData for instruction encoding\n * @internal\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 cmintDecompressed: mintContext.cmintDecompressed,\n version: mintContext.version,\n mintSigner: mintContext.mintSigner,\n bump: mintContext.bump,\n metadata,\n };\n}\n\n/**\n * Convert a deserialized light mint to MintInstructionDataWithMetadata\n * Throws if the mint doesn't have metadata extension\n *\n * @param compressedMint - Deserialized light mint from account data\n * @returns MintInstructionDataWithMetadata for metadata update instructions\n * @throws Error if metadata extension is not present\n * @internal\n */\nexport function toMintInstructionDataWithMetadata(\n compressedMint: CompressedMint,\n): MintInstructionDataWithMetadata {\n const data = toMintInstructionData(compressedMint);\n\n if (!data.metadata) {\n throw new Error('light mint 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 LIGHT_TOKEN_PROGRAM_ID,\n getDefaultAddressTreeInfo,\n MerkleContext,\n assertBetaEnabled,\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 TokenAccountNotFoundError,\n TokenInvalidAccountOwnerError,\n} from '@solana/spl-token';\nimport {\n deserializeMint,\n MintContext,\n TokenMetadata,\n MintExtension,\n extractTokenMetadata,\n CompressionInfo,\n CompressedMint,\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 /** Compression info for light-token mints */\n compression?: CompressionInfo;\n}\n\nfunction toErrorMessage(error: unknown): string {\n if (error instanceof Error) return error.message;\n return String(error);\n}\n\n/**\n * Get unified mint info for SPL/T22/light-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 assertBetaEnabled();\n\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(\n rpc,\n address,\n commitment,\n LIGHT_TOKEN_PROGRAM_ID,\n ),\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 const errors = [tokenResult, token2022Result, compressedResult]\n .filter(\n (result): result is PromiseRejectedResult =>\n result.status === 'rejected',\n )\n .map(result => result.reason);\n\n const ownerMismatch = errors.find(\n error => error instanceof TokenInvalidAccountOwnerError,\n );\n if (ownerMismatch) {\n throw ownerMismatch;\n }\n\n const allNotFound =\n errors.length > 0 &&\n errors.every(error => error instanceof TokenAccountNotFoundError);\n if (allNotFound) {\n throw new TokenAccountNotFoundError(\n `Mint not found: ${address.toString()}. ` +\n `Tried TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, and LIGHT_TOKEN_PROGRAM_ID.`,\n );\n }\n\n const unexpected = errors.find(\n error =>\n !(error instanceof TokenAccountNotFoundError) &&\n !(error instanceof TokenInvalidAccountOwnerError),\n );\n if (unexpected) {\n throw new Error(\n `Failed to fetch mint data from RPC: ${toErrorMessage(unexpected)}`,\n );\n }\n\n throw new TokenAccountNotFoundError(\n `Mint not found: ${address.toString()}. ` +\n `Tried TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, and LIGHT_TOKEN_PROGRAM_ID.`,\n );\n }\n\n if (programId.equals(LIGHT_TOKEN_PROGRAM_ID)) {\n const addressTree = getDefaultAddressTreeInfo().tree;\n const compressedAddress = deriveAddressV2(\n address.toBytes(),\n addressTree,\n LIGHT_TOKEN_PROGRAM_ID,\n );\n const compressedAccount = await rpc.getCompressedAccount(\n bn(compressedAddress.toBytes()),\n );\n\n if (!compressedAccount?.data?.data) {\n throw new TokenAccountNotFoundError(\n `Light mint not found for ${address.toString()}`,\n );\n }\n if (!compressedAccount.owner.equals(LIGHT_TOKEN_PROGRAM_ID)) {\n throw new TokenInvalidAccountOwnerError();\n }\n\n const compressedData = Buffer.from(compressedAccount.data.data);\n\n // After decompressMint, the compressed account contains sentinel data (just hash ~32 bytes).\n // The actual mint data lives in the light mint account.\n // Minimum light mint size is 82 (base) + 34 (context) + 33 (signer+bump) = 149+ bytes.\n const SENTINEL_THRESHOLD = 64;\n const isDecompressed = compressedData.length < SENTINEL_THRESHOLD;\n\n let compressedMintData: CompressedMint;\n\n if (isDecompressed) {\n // Light mint account exists - read from light mint account\n const cmintAccountInfo = await rpc.getAccountInfo(\n address,\n commitment,\n );\n if (!cmintAccountInfo?.data) {\n throw new TokenAccountNotFoundError(\n `Decompressed light mint account not found on-chain for ${address.toString()}`,\n );\n }\n if (!cmintAccountInfo.owner.equals(LIGHT_TOKEN_PROGRAM_ID)) {\n throw new TokenInvalidAccountOwnerError();\n }\n compressedMintData = deserializeMint(\n Buffer.from(cmintAccountInfo.data),\n );\n } else {\n // Mint is still compressed - use compressed account data\n compressedMintData = deserializeMint(compressedData);\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 compression: compressedMintData.compression,\n };\n\n if (!result.merkleContext) {\n throw new Error(\n `Invalid light mint: merkleContext is required for LIGHT_TOKEN_PROGRAM_ID`,\n );\n }\n if (!result.mintContext) {\n throw new Error(\n `Invalid light mint: mintContext is required for LIGHT_TOKEN_PROGRAM_ID`,\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/light-token.\n *\n * @param address The mint pubkey\n * @param data The raw account data or AccountInfo\n * @param programId Token program ID. Default light-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 light-token program, deserialize as light mint\n if (programId.equals(LIGHT_TOKEN_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 compression: compressedMintData.compression,\n };\n\n // Validate: light-token requires mintContext\n if (!result.mintContext) {\n throw new Error(\n `Invalid light mint: mintContext is required for LIGHT_TOKEN_PROGRAM_ID`,\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 light-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 LIGHT_TOKEN_PROGRAM_ID,\n assertBetaEnabled,\n} from '@lightprotocol/stateless.js';\nimport {\n createUpdateMintAuthorityInstruction,\n createUpdateFreezeAuthorityInstruction,\n} from '../instructions/update-mint';\nimport { getMintInterface } from '../get-mint-interface';\nimport { ERR_MINT_MISSING_MERKLE_CONTEXT } from '../errors';\n\n/**\n * Update the mint authority of a light-token mint.\n * Works for both compressed and decompressed light mints.\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 assertBetaEnabled();\n\n const mintInterface = await getMintInterface(\n rpc,\n mint,\n confirmOptions?.commitment,\n LIGHT_TOKEN_PROGRAM_ID,\n );\n\n if (!mintInterface.merkleContext) {\n throw new Error(ERR_MINT_MISSING_MERKLE_CONTEXT);\n }\n\n // When light mint account exists (decompressed), no validity proof needed - program reads from light mint account\n const merkleContext = mintInterface.merkleContext;\n const isDecompressed =\n mintInterface.mintContext?.cmintDecompressed ?? false;\n const validityProof = isDecompressed\n ? null\n : await rpc.getValidityProofV2(\n [\n {\n hash: bn(merkleContext.hash),\n leafIndex: merkleContext.leafIndex,\n treeInfo: merkleContext.treeInfo,\n proveByIndex: 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 light-token mint.\n * Works for both compressed and decompressed light mints.\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 assertBetaEnabled();\n\n const mintInterface = await getMintInterface(\n rpc,\n mint,\n confirmOptions?.commitment,\n LIGHT_TOKEN_PROGRAM_ID,\n );\n\n if (!mintInterface.merkleContext) {\n throw new Error(ERR_MINT_MISSING_MERKLE_CONTEXT);\n }\n\n // When light mint account exists (decompressed), no validity proof needed - program reads from light mint account\n const merkleContext = mintInterface.merkleContext;\n const isDecompressed =\n mintInterface.mintContext?.cmintDecompressed ?? false;\n const validityProof = isDecompressed\n ? null\n : await rpc.getValidityProofV2(\n [\n {\n hash: bn(merkleContext.hash),\n leafIndex: merkleContext.leafIndex,\n treeInfo: merkleContext.treeInfo,\n proveByIndex: 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 LIGHT_TOKEN_PROGRAM_ID,\n assertBetaEnabled,\n} from '@lightprotocol/stateless.js';\nimport {\n createUpdateMetadataFieldInstruction,\n createUpdateMetadataAuthorityInstruction,\n createRemoveMetadataKeyInstruction,\n} from '../instructions/update-metadata';\nimport { getMintInterface } from '../get-mint-interface';\nimport {\n ERR_MINT_MISSING_MERKLE_CONTEXT,\n ERR_MINT_MISSING_TOKEN_METADATA,\n} from '../errors';\n\ntype MintInterfaceWithMetadataContext = Awaited<\n ReturnType<typeof getMintInterface>\n> & {\n tokenMetadata: NonNullable<\n Awaited<ReturnType<typeof getMintInterface>>['tokenMetadata']\n >;\n merkleContext: NonNullable<\n Awaited<ReturnType<typeof getMintInterface>>['merkleContext']\n >;\n};\n\nfunction assertMintMetadataContext(\n mintInterface: Awaited<ReturnType<typeof getMintInterface>>,\n): asserts mintInterface is MintInterfaceWithMetadataContext {\n if (!mintInterface.tokenMetadata) {\n throw new Error(ERR_MINT_MISSING_TOKEN_METADATA);\n }\n if (!mintInterface.merkleContext) {\n throw new Error(ERR_MINT_MISSING_MERKLE_CONTEXT);\n }\n}\n\n/**\n * Update a metadata field on a light-token mint.\n * Works for both compressed and decompressed light mints.\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 assertBetaEnabled();\n\n const mintInterface = await getMintInterface(\n rpc,\n mint,\n confirmOptions?.commitment,\n LIGHT_TOKEN_PROGRAM_ID,\n );\n\n assertMintMetadataContext(mintInterface);\n\n // When light mint account exists (decompressed), no validity proof needed - program reads from light mint account\n const merkleContext = mintInterface.merkleContext;\n const isDecompressed =\n mintInterface.mintContext?.cmintDecompressed ?? false;\n const validityProof = isDecompressed\n ? null\n : await rpc.getValidityProofV2(\n [\n {\n hash: bn(merkleContext.hash),\n leafIndex: merkleContext.leafIndex,\n treeInfo: merkleContext.treeInfo,\n proveByIndex: 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 light-token mint.\n * Works for both compressed and decompressed light mints.\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 assertBetaEnabled();\n\n const mintInterface = await getMintInterface(\n rpc,\n mint,\n confirmOptions?.commitment,\n LIGHT_TOKEN_PROGRAM_ID,\n );\n\n assertMintMetadataContext(mintInterface);\n\n // When light mint account exists (decompressed), no validity proof needed - program reads from light mint account\n const merkleContext = mintInterface.merkleContext;\n const isDecompressed =\n mintInterface.mintContext?.cmintDecompressed ?? false;\n const validityProof = isDecompressed\n ? null\n : await rpc.getValidityProofV2(\n [\n {\n hash: bn(merkleContext.hash),\n leafIndex: merkleContext.leafIndex,\n treeInfo: merkleContext.treeInfo,\n proveByIndex: 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 light-token mint.\n * Works for both compressed and decompressed light mints.\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 assertBetaEnabled();\n\n const mintInterface = await getMintInterface(\n rpc,\n mint,\n confirmOptions?.commitment,\n LIGHT_TOKEN_PROGRAM_ID,\n );\n\n assertMintMetadataContext(mintInterface);\n\n // When light mint account exists (decompressed), no validity proof needed - program reads from light mint account\n const merkleContext = mintInterface.merkleContext;\n const isDecompressed =\n mintInterface.mintContext?.cmintDecompressed ?? false;\n const validityProof = isDecompressed\n ? null\n : await rpc.getValidityProofV2(\n [\n {\n hash: bn(merkleContext.hash),\n leafIndex: merkleContext.leafIndex,\n treeInfo: merkleContext.treeInfo,\n proveByIndex: 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 LIGHT_TOKEN_PROGRAM_ID,\n buildAndSignTx,\n sendAndConfirmTx,\n assertBetaEnabled,\n} from '@lightprotocol/stateless.js';\nimport {\n createAssociatedTokenAccountInterfaceInstruction,\n createAssociatedTokenAccountInterfaceIdempotentInstruction,\n LightTokenConfig,\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 { LightTokenConfig };\n\n/**\n * Create an associated token account for SPL/T22/light-token. Defaults to\n * light-token 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 * LIGHT_TOKEN_PROGRAM_ID)\n * @param associatedTokenProgramId associated token account program ID\n * (auto-derived if not provided)\n * @param lightTokenConfig 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 = LIGHT_TOKEN_PROGRAM_ID,\n associatedTokenProgramId?: PublicKey,\n lightTokenConfig?: LightTokenConfig,\n): Promise<PublicKey> {\n assertBetaEnabled();\n\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 lightTokenConfig,\n );\n\n if (programId.equals(LIGHT_TOKEN_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/light-token.\n * Defaults to light-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 * LIGHT_TOKEN_PROGRAM_ID)\n * @param associatedTokenProgramId associated token account program ID\n * (auto-derived if not provided)\n * @param lightTokenConfig Optional light-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 = LIGHT_TOKEN_PROGRAM_ID,\n associatedTokenProgramId?: PublicKey,\n lightTokenConfig?: LightTokenConfig,\n): Promise<PublicKey> {\n assertBetaEnabled();\n\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 lightTokenConfig,\n );\n\n if (programId.equals(LIGHT_TOKEN_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 assertBetaEnabled,\n} from '@lightprotocol/stateless.js';\nimport { MAX_TOP_UP } from '../../constants';\nimport { createMintToInstruction } from '../instructions/mint-to';\n\n/**\n * Mint tokens to a light-token account.\n *\n * This is a simple mint instruction for minting to light-token associated token accounts (hot).\n * The light mint account must exist (mint must be decompressed first).\n *\n * @param rpc - RPC connection\n * @param payer - Fee payer (signer)\n * @param mint - Mint address (light mint account)\n * @param destination - Destination light-token account\n * @param authority - Mint authority (signer)\n * @param amount - Amount to mint\n * @param maxTopUp - Optional maximum lamports for rent top-up\n * @param confirmOptions - Optional confirm options\n * @returns Transaction signature\n */\nexport async function mintTo(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n destination: PublicKey,\n authority: Signer,\n amount: number | bigint,\n maxTopUp?: number,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n assertBetaEnabled();\n\n // Use payer as fee payer for top-ups if authority is different from payer\n const feePayer = authority.publicKey.equals(payer.publicKey)\n ? undefined\n : payer.publicKey;\n\n const ix = createMintToInstruction({\n mint,\n destination,\n amount,\n authority: authority.publicKey,\n maxTopUp: maxTopUp ?? MAX_TOP_UP,\n feePayer,\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: 200_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 LIGHT_TOKEN_PROGRAM_ID,\n selectStateTreeInfo,\n TreeInfo,\n assertBetaEnabled,\n} from '@lightprotocol/stateless.js';\nimport { createMintToCompressedInstruction } from '../instructions/mint-to-compressed';\nimport { getMintInterface } from '../get-mint-interface';\nimport {\n ERR_MINT_MISSING_MERKLE_CONTEXT,\n ERR_MINT_MISSING_MINT_CONTEXT,\n} from '../errors';\n\n/**\n * Mint light-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 maxTopUp Optional: cap on rent top-up (units of 1k lamports; default no cap)\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 maxTopUp?: number,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n assertBetaEnabled();\n\n const mintInfo = await getMintInterface(\n rpc,\n mint,\n confirmOptions?.commitment,\n LIGHT_TOKEN_PROGRAM_ID,\n );\n\n if (!mintInfo.merkleContext) {\n throw new Error(ERR_MINT_MISSING_MERKLE_CONTEXT);\n }\n if (!mintInfo.mintContext) {\n throw new Error(ERR_MINT_MISSING_MINT_CONTEXT);\n }\n const merkleContext = mintInfo.merkleContext;\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(merkleContext.hash),\n leafIndex: merkleContext.leafIndex,\n treeInfo: merkleContext.treeInfo,\n proveByIndex: merkleContext.proveByIndex,\n },\n ],\n [],\n DerivationMode.compressible,\n );\n\n const ix = createMintToCompressedInstruction(\n authority.publicKey,\n payer.publicKey,\n validityProof,\n 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 cmintDecompressed: mintInfo.mintContext.cmintDecompressed,\n version: mintInfo.mintContext.version,\n mintSigner: mintInfo.mintContext.mintSigner,\n bump: mintInfo.mintContext.bump,\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 maxTopUp,\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 assertBetaEnabled,\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 light-token mints.\n *\n * This function ONLY mints to light-token associated token accounts (hot), never to compressed light-token accounts (cold).\n * For light-token mints, the light mint account must exist (mint must be decompressed first).\n *\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 light-token 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. 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 assertBetaEnabled();\n\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 // 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 undefined, // validityProof - not needed for simple LightTokenMintTo\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: 200_000 }), ix],\n payer,\n blockhash,\n signers,\n );\n\n return await sendAndConfirmTx(rpc, tx, confirmOptions);\n}\n","import {\n Rpc,\n buildAndSignTx,\n sendAndConfirmTx,\n dedupeSigner,\n assertBetaEnabled,\n} from '@lightprotocol/stateless.js';\nimport {\n PublicKey,\n Signer,\n TransactionSignature,\n ConfirmOptions,\n} from '@solana/web3.js';\nimport { createLoadAtaInstructions } from '../instructions/load-ata';\nimport { InterfaceOptions } from './transfer-interface';\nimport { getMintInterface } from '../get-mint-interface';\n\nexport {\n createLoadAtaInstructions,\n selectInputsForAmount,\n getCompressedTokenAccountsFromAtaSources,\n MAX_INPUT_ACCOUNTS,\n InternalLoadBatch,\n rawLoadBatchComputeUnits,\n calculateLoadBatchComputeUnits,\n _buildLoadBatches,\n AtaType,\n} from '../instructions/load-ata';\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 decimals?: number,\n): Promise<TransactionSignature | null> {\n assertBetaEnabled();\n\n payer ??= owner;\n\n const resolvedDecimals =\n decimals ?? (await getMintInterface(rpc, mint)).mint.decimals;\n const batches = await createLoadAtaInstructions(\n rpc,\n ata,\n owner.publicKey,\n mint,\n resolvedDecimals,\n payer.publicKey,\n interfaceOptions,\n wrap,\n );\n\n if (batches.length === 0) {\n return null;\n }\n\n const additionalSigners = dedupeSigner(payer, [owner]);\n\n const txPromises = batches.map(async ixs => {\n const { blockhash } = await rpc.getLatestBlockhash();\n const tx = buildAndSignTx(ixs, payer!, blockhash, additionalSigners);\n return sendAndConfirmTx(rpc, tx, confirmOptions);\n });\n\n const results = await Promise.all(txPromises);\n return results[results.length - 1];\n}\n","import {\n Rpc,\n LIGHT_TOKEN_PROGRAM_ID,\n buildAndSignTx,\n sendAndConfirmTx,\n assertBetaEnabled,\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 compressed light-tokens (cold balance), 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 * LIGHT_TOKEN_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 = LIGHT_TOKEN_PROGRAM_ID,\n associatedTokenProgramId = getAtaProgramId(programId),\n): Promise<AccountInterface> {\n assertBetaEnabled();\n\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/** @internal */\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/** @internal */\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 light-token, use getAtaInterface which properly aggregates hot+cold balances\n // When wrap=true (unified path), also includes SPL/T22 balances\n if (programId.equals(LIGHT_TOKEN_PROGRAM_ID)) {\n return getOrCreateLightTokenAta(\n rpc,\n payer,\n mint,\n owner,\n associatedToken,\n commitment,\n confirmOptions,\n wrap,\n allowOwnerOffCurve,\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 light-token associated token account with proper compressed balance handling.\n *\n * Like SPL's getOrCreateAssociatedTokenAccount, this is a write operation:\n * 1. Creates hot associated token account if it doesn't exist\n * 2. If owner is Signer: loads compressed light-tokens (cold balance) into light-token associated token account\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 associated token account and ready\n * to use.\n *\n * @internal\n */\nasync function getOrCreateLightTokenAta(\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 allowOwnerOffCurve = 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 LIGHT_TOKEN_PROGRAM_ID,\n wrap,\n allowOwnerOffCurve,\n );\n\n // Check if we have a hot account\n hasHotAccount =\n accountInterface._sources?.some(\n s => s.type === TokenAccountSourceType.LightTokenHot,\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 associated token account\n await createLightTokenAtaIdempotent(\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 LIGHT_TOKEN_PROGRAM_ID,\n wrap,\n allowOwnerOffCurve,\n );\n hasHotAccount = true;\n } else {\n throw error;\n }\n }\n\n // If we only have cold balance (no hot associated token account), create the hot associated token account first\n if (!hasHotAccount) {\n await createLightTokenAtaIdempotent(\n rpc,\n payer,\n mint,\n ownerPubkey,\n associatedToken,\n confirmOptions,\n );\n }\n\n const ownerSigner: Signer | null = isSigner(owner)\n ? owner\n : payer.publicKey.equals(ownerPubkey)\n ? payer\n : null;\n\n if (ownerSigner) {\n const sources = accountInterface._sources ?? [];\n const hasCold = sources.some(\n s =>\n s.type === TokenAccountSourceType.LightTokenCold &&\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 if (\n !(ownerSigner.secretKey instanceof Uint8Array) ||\n ownerSigner.secretKey.length === 0\n ) {\n throw new Error(\n 'Owner must be a valid Signer with secretKey to auto-load',\n );\n }\n\n await loadAta(\n rpc,\n associatedToken,\n ownerSigner,\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 LIGHT_TOKEN_PROGRAM_ID,\n wrap,\n allowOwnerOffCurve,\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 light-token associated token account idempotently.\n * @internal\n */\nasync function createLightTokenAtaIdempotent(\n rpc: Rpc,\n payer: Signer,\n mint: PublicKey,\n owner: PublicKey,\n associatedToken: PublicKey,\n confirmOptions?: ConfirmOptions,\n): Promise<void> {\n const ix = createAssociatedTokenAccountInterfaceIdempotentInstruction(\n payer.publicKey,\n associatedToken,\n owner,\n mint,\n LIGHT_TOKEN_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}\n\n/**\n * Get or create SPL/T22 associated token account.\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 (createError) {\n // Accept race-condition \"already exists\" only if account can now be fetched.\n try {\n await getAccountInterface(\n rpc,\n associatedToken,\n commitment,\n programId,\n );\n } catch {\n throw createError;\n }\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","export function sliceLast<T>(items: T[]): { rest: T[]; last: T } {\n if (items.length === 0) {\n throw new Error('sliceLast: array must not be empty');\n }\n return { rest: items.slice(0, -1), last: items.at(-1)! };\n}\n","import {\n ConfirmOptions,\n PublicKey,\n Signer,\n TransactionSignature,\n} from '@solana/web3.js';\nimport {\n Rpc,\n buildAndSignTx,\n sendAndConfirmTx,\n dedupeSigner,\n assertBetaEnabled,\n LIGHT_TOKEN_PROGRAM_ID,\n} from '@lightprotocol/stateless.js';\nimport BN from 'bn.js';\nimport { createTransferInterfaceInstructions } from '../instructions/transfer-interface';\nimport { getAssociatedTokenAddressInterface } from '../get-associated-token-address-interface';\nimport { getMintInterface } from '../get-mint-interface';\nimport { type SplInterfaceInfo } from '../../utils/get-token-pool-infos';\nimport { sliceLast } from './slice-last';\n\nexport interface InterfaceOptions {\n splInterfaceInfos?: SplInterfaceInfo[];\n /**\n * ATA owner (authority owner) used to derive the ATA when the signer is a\n * delegate. For owner-signed flows, omit this field.\n */\n owner?: PublicKey;\n}\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 = LIGHT_TOKEN_PROGRAM_ID,\n confirmOptions?: ConfirmOptions,\n options?: InterfaceOptions,\n wrap = false,\n decimals?: number,\n): Promise<TransactionSignature> {\n assertBetaEnabled();\n\n const effectiveOwner = options?.owner ?? owner.publicKey;\n const expectedSource = getAssociatedTokenAddressInterface(\n mint,\n effectiveOwner,\n false,\n programId,\n );\n if (!source.equals(expectedSource)) {\n throw new Error(\n `Source mismatch. Expected ${expectedSource.toBase58()}, got ${source.toBase58()}`,\n );\n }\n\n const amountBigInt = BigInt(amount.toString());\n\n const resolvedDecimals =\n decimals ?? (await getMintInterface(rpc, mint)).mint.decimals;\n const batches = await createTransferInterfaceInstructions(\n rpc,\n payer.publicKey,\n mint,\n amountBigInt,\n owner.publicKey,\n destination,\n resolvedDecimals,\n {\n ...options,\n wrap,\n programId,\n },\n );\n\n const additionalSigners = dedupeSigner(payer, [owner]);\n const { rest: loads, last: transferIxs } = sliceLast(batches);\n\n await Promise.all(\n loads.map(async ixs => {\n const { blockhash } = await rpc.getLatestBlockhash();\n const tx = buildAndSignTx(ixs, payer, blockhash, additionalSigners);\n return sendAndConfirmTx(rpc, tx, confirmOptions);\n }),\n );\n\n const { blockhash } = await rpc.getLatestBlockhash();\n const tx = buildAndSignTx(transferIxs, payer, blockhash, additionalSigners);\n return sendAndConfirmTx(rpc, tx, confirmOptions);\n}\n\nexport interface TransferOptions extends InterfaceOptions {\n wrap?: boolean;\n programId?: PublicKey;\n}\n\nexport { sliceLast } from './slice-last';\n\nexport {\n createTransferInterfaceInstructions,\n calculateTransferCU,\n} from '../instructions/transfer-interface';\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 assertBetaEnabled,\n} from '@lightprotocol/stateless.js';\nimport { getMint } from '@solana/spl-token';\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 light-token account.\n *\n * This is an agnostic action that takes explicit account addresses (spl-token style).\n * Use getAssociatedTokenAddressSync() to derive associated token account 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 associated token account)\n * @param destination Destination light-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 maxTopUp Optional: cap on rent top-up (units of 1k lamports; default no cap)\n * @param confirmOptions Optional: Confirm options\n *\n * @example\n * const splAta = getAssociatedTokenAddressSync(mint, owner.publicKey, false, TOKEN_PROGRAM_ID);\n * const lightTokenAta = getAssociatedTokenAddressInterface(mint, owner.publicKey); // defaults to light-token\n *\n * await wrap(\n * rpc,\n * payer,\n * splAta,\n * lightTokenAta,\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 maxTopUp?: number,\n confirmOptions?: ConfirmOptions,\n): Promise<TransactionSignature> {\n assertBetaEnabled();\n\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 // Get mint info to get decimals\n const mintInfo = await getMint(\n rpc,\n mint,\n undefined,\n resolvedSplInterfaceInfo.tokenProgram,\n );\n\n // Build wrap instruction\n const ix = createWrapInstruction(\n source,\n destination,\n owner.publicKey,\n mint,\n amount,\n resolvedSplInterfaceInfo,\n mintInfo.decimals,\n payer.publicKey,\n maxTopUp,\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 light-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 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 selectTokenAccountsForApprove,\n selectAccountsByPreferredTreeType,\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 // Select accounts from preferred tree type (V2 in V2 mode) with fallback\n const { accounts: accountsToUse } = selectAccountsByPreferredTreeType(\n compressedTokenAccounts.items,\n amount,\n );\n\n const [inputAccounts] = selectTokenAccountsForApprove(\n accountsToUse,\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.createSplInterface({\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 {\n selectMinCompressedTokenAccountsForTransfer,\n selectAccountsByPreferredTreeType,\n} 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 { mint },\n );\n\n // Select accounts from preferred tree type (V2 in V2 mode) with fallback\n const { accounts: accountsToUse } = selectAccountsByPreferredTreeType(\n compressedTokenAccounts.items,\n amount,\n );\n\n const [inputAccounts] = selectMinCompressedTokenAccountsForTransfer(\n accountsToUse,\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 TreeType,\n} from '@lightprotocol/stateless.js';\nimport { CompressedTokenProgram } from '../program';\nimport { selectAccountsByPreferredTreeType } from '../utils';\n\n/**\n * Max input accounts per merge.\n *\n * Even though V2 supports larger merges, we keep this at 4 to avoid oversized\n * transactions / RPC payload limits under heavy test load.\n */\nconst MAX_MERGE_ACCOUNTS = 4;\n\n/**\n * Merge multiple compressed token accounts for a given mint into fewer\n * accounts. Each call merges up to 4 accounts at a time.\n *\n * Supports automatic V1 -> V2 migration: when running in V2 mode,\n * merging V1 token accounts will produce a V2 output.\n *\n * IMPORTANT: Only accounts from the same tree type can be merged in one\n * transaction. If you have mixed V1+V2 accounts, merge them separately.\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 if (compressedTokenAccounts.items.length === 1) {\n throw new Error('Only one token account exists, nothing to merge');\n }\n\n // Select accounts from preferred tree type (V2 in V2 mode) - for merge need at least 2\n const { accounts: preferredAccounts, treeType: preferredTreeType } =\n selectAccountsByPreferredTreeType(compressedTokenAccounts.items);\n\n let selectedAccounts = preferredAccounts;\n let selectedTreeType = preferredTreeType;\n\n // For merge, need at least 2 accounts of the same type\n // If preferred type has < 2, try fallback type\n if (selectedAccounts.length < 2) {\n const fallbackType =\n preferredTreeType === TreeType.StateV2\n ? TreeType.StateV1\n : TreeType.StateV2;\n const fallbackAccounts = compressedTokenAccounts.items.filter(\n acc => acc.compressedAccount.treeInfo.treeType === fallbackType,\n );\n\n if (fallbackAccounts.length >= 2) {\n selectedAccounts = fallbackAccounts;\n selectedTreeType = fallbackType;\n } else if (\n selectedAccounts.length === 1 &&\n fallbackAccounts.length === 1\n ) {\n // Have 1 V1 and 1 V2 - can't merge mixed types\n throw new Error(\n 'Cannot merge accounts from different tree types (V1/V2). ' +\n 'You have 1 V1 and 1 V2 account - nothing to merge within same type.',\n );\n } else {\n throw new Error(\n `Not enough accounts of the same tree type to merge. ` +\n `Found: ${selectedAccounts.length} ${selectedTreeType === TreeType.StateV1 ? 'V1' : 'V2'} accounts.`,\n );\n }\n }\n\n // Take up to MAX_MERGE_ACCOUNTS to merge in this transaction\n const batch = selectedAccounts.slice(0, MAX_MERGE_ACCOUNTS);\n\n const proof = await rpc.getValidityProof(\n batch.map(account => bn(account.compressedAccount.hash)),\n );\n\n // V1→V2 migration handled inside CompressedTokenProgram.mergeTokenAccounts\n const mergeInstructions = 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 const instructions = [\n ComputeBudgetProgram.setComputeUnitLimit({ units: 1_000_000 }),\n ...mergeInstructions,\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';\nimport { groupAccountsByTreeType } from '../utils';\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 * (must all be from the same tree type)\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 // Validate all accounts are from the same tree type\n const accountsByTreeType = groupAccountsByTreeType(accounts);\n if (accountsByTreeType.size > 1) {\n throw new Error(\n 'Cannot revoke accounts from different tree types (V1/V2) in the same transaction. ' +\n 'Revoke V1 and V2 accounts separately.',\n );\n }\n\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} from '@lightprotocol/stateless.js';\nimport BN from 'bn.js';\nimport { CompressedTokenProgram } from '../program';\nimport {\n selectMinCompressedTokenAccountsForTransfer,\n selectAccountsByPreferredTreeType,\n} from '../utils';\n\n/**\n * Transfer compressed tokens from one owner to another.\n *\n * Supports automatic V1 -> V2 migration: when running in V2 mode,\n * V1 token inputs will produce V2 token outputs.\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\n const compressedTokenAccounts = await rpc.getCompressedTokenAccountsByOwner(\n owner.publicKey,\n { mint },\n );\n\n // Select accounts from preferred tree type (V2 in V2 mode) with fallback\n const { accounts: accountsToUse } = selectAccountsByPreferredTreeType(\n compressedTokenAccounts.items,\n amount,\n );\n\n const [inputAccounts] = selectMinCompressedTokenAccountsForTransfer(\n accountsToUse,\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 // V1→V2 migration handled inside CompressedTokenProgram.transfer\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 {\n selectMinCompressedTokenAccountsForTransfer,\n selectAccountsByPreferredTreeType,\n} 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 // Select accounts from preferred tree type (V2 in V2 mode) with fallback\n const { accounts: accountsToUse } = selectAccountsByPreferredTreeType(\n compressedTokenAccounts.items,\n amount,\n );\n\n const [inputAccounts] = selectMinCompressedTokenAccountsForTransfer(\n accountsToUse,\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 {\n selectMinCompressedTokenAccountsForTransfer,\n selectAccountsByPreferredTreeType,\n} 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 // Select accounts from preferred tree type (V2 in V2 mode) with fallback\n const { accounts: accountsToUse } = selectAccountsByPreferredTreeType(\n compressedTokenAccounts.items,\n amount,\n );\n\n const [inputAccounts] = selectMinCompressedTokenAccountsForTransfer(\n accountsToUse,\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":["LIGHT_TOKEN_CONFIG","PublicKey","LIGHT_TOKEN_RENT_SPONSOR","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","MAX_TOP_UP","BASE_RENT_PER_EPOCH","RENT_PER_BYTE_PER_EPOCH","SLOTS_PER_RENT_EPOCH","COMPRESSION_COST","COMPRESSION_INCENTIVE","TOTAL_COMPRESSION_COST","COMPRESSIBLE_LIGHT_TOKEN_ACCOUNT_SIZE","rentPerEpoch","bytes","COMPRESSIBLE_LIGHT_TOKEN_RENT_PER_EPOCH","DEFAULT_PREPAY_EPOCHS","DEFAULT_WRITE_TOP_UP","calculateFeePayerCostAtCreation","prepayEpochs","accountBytes","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","ERROR_MIXED_TREE_TYPES","filterByTreeType","accounts","treeType","acc","compressedAccount","treeInfo","validateSameTreeType","accountsWithTreeInfo","firstTreeType","some","groupAccountsByTreeType","groups","Map","account","existing","get","push","set","selectAccountsByPreferredTreeType","requiredAmount","preferredTreeType","featureFlags","isV2","TreeType","StateV2","StateV1","accountsByTreeType","selectedTreeType","selectedAccounts","totalBalance","reduce","sum","add","parsed","lt","fallbackType","fallbackAccounts","fallbackBalance","selectTokenAccountsForApprove","approveAmount","maxInputs","options","filteredAccounts","exactMatch","eq","lamports","selectMinCompressedTokenAccountsForTransfer","selectMinCompressedTokenAccountsForDecompression","total","totalLamports","maxPossibleAmount","transferAmount","accumulatedAmount","accumulatedLamports","selectMinCompressedTokenAccountsForTransferOrPartial","cmp","slice","console","log","selectSmartCompressedTokenAccountsForTransfer","selectSmartCompressedTokenAccountsForTransferOrPartial","nonZeroAccounts","remainingAccounts","smallestAccount","min","max","packCompressedTokenAccounts","params","inputCompressedTokenAccounts","outputStateTreeInfo","rootIndices","tokenTransferOutputs","_remainingAccounts","delegateIndex","delegate","getIndexOrAdd","packedInputTokenData","outputTreeInfo","forEach","index","merkleTreePubkeyIndex","tree","queuePubkeyIndex","queue","merkleContext","leafIndex","proveByIndex","rootIndex","tlv","activeTreeInfo","nextTreeInfo","activeTreeOrQueue","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","DEFAULT_V2_MIGRATION_TREE","batchMerkleTree1","batchQueue1","batchCpiContext1","getTokenPoolPda","sumUpTokenAmount","validateSameTokenOwner","parseTokenData","currentOwner","parseMaybeDelegatedTransfer","inputs","outputs","delegatedAccountsIndex","findIndex","delegatedTransfer","delegateChangeAccountIndex","createTransferOutputState","toAddress","inputAmount","inputLamports","sumUpLamports","changeAmount","sub","validateSufficientBalance","validateSameOwner","createDecompressOutputState","constructor","static","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","createSplInterface","keys","TransactionInstruction","createTokenPool","addTokenPool","existingSplInterfacePda","mintTo","toPubkey","systemKeys","defaultStaticAccountsStruct","toArray","toPubkeys","LightSystemProgram","approveAndMintTo","authorityTokenAccount","amountBigInt","BigInt","createMintToInstruction","compress","payer","source","transfer","recentValidityProof","recentInputStateRootIndices","inputTreeType","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","decompress","tokenPoolInfos","tokenPoolInfosArray","mergeTokenAccounts","maxAccounts","compressSplTokenAccount","tokenAccount","getMintProgramId","connection","getAccountInfo","approve","CHANGE_INDEX","delegatedAmount","delegateMerkleTreeIndex","changeAccountMerkleTreeIndex","delegateLamports","revoke","outputAccountMerkleTreeIndex","deriveCMintAddress","mintSeed","addressTreeInfo","deriveAddressV2","findMintAddress","toBytes","LIGHT_TOKEN_PROGRAM_ID","COMPRESSED_MINT_SEED","mintSigner","getAssociatedLightTokenAddressAndBump","getAssociatedLightTokenAddress","MINT_ACTION_DISCRIMINATOR","RecipientLayout","MintToCompressedActionLayout","UpdateAuthorityLayout","MintToLightTokenActionLayout","UpdateMetadataFieldActionLayout","UpdateMetadataAuthorityActionLayout","RemoveMetadataKeyActionLayout","DecompressMintActionLayout","CompressAndCloseCMintActionLayout","ActionLayout","rustEnum","replicate","CreateMintLayout","AdditionalMetadataLayout","TokenMetadataInstructionDataLayout","PlaceholderLayout","ExtensionInstructionDataLayout","CompressedMintMetadataLayout","MintInstructionDataLayout","MintActionCompressedInstructionDataLayout","encodeMintActionInstructionData","convertedActions","actions","action","mintToCompressed","r","mintToLightToken","encodableData","supply","createTokenMetadata","name","symbol","uri","updateAuthority","additionalMetadata","createMintInstruction","mintAuthority","validityProof","metadata","maxTopUp","sys","splMintPda","buildCreateMintIx","extensions","tokenMetadata","validatedProof","validateProofArrays","readOnlyAddressTrees","readOnlyAddressTreeRootIndices","decompressMint","rentPayment","writeTopUp","version","ShaFlat","cmintDecompressed","encodeCreateMintInstructionData","outputQueue","compressedProof","encodeUpdateMintInstructionData","actionType","updateMintAuthority","newAuthority","updateFreezeAuthority","isDecompressed","mintInterface","mintContext","splMint","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","DEFAULT_COMPRESSIBLE_CONFIG","tokenAccountVersion","compressionOnly","compressToAccountPubkey","encodeCreateAssociatedLightTokenAccountData","compressibleConfig","discriminator","createAssociatedLightTokenAccountInstruction","configAccount","rentPayerPda","associatedTokenAccount","createAssociatedLightTokenAccountIdempotentInstruction","getAtaProgramId","ASSOCIATED_TOKEN_PROGRAM_ID","checkAtaAddress","ata","allowOwnerOffCurve","expected","getAssociatedTokenAddressSync","valid","programIdToAtaType","lightTokenExpected","splExpected","t22Expected","createAssociatedTokenAccountInterfaceInstruction","associatedToken","associatedTokenProgramId","lightTokenConfig","effectiveAssociatedTokenProgramId","createSplAssociatedTokenAccountInstruction","createAssociatedTokenAccountInterfaceIdempotentInstruction","createSplAssociatedTokenAccountIdempotentInstruction","createAtaInterfaceIdempotentInstruction","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","size","_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","t","_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","mode","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","ERR_FETCH_BY_OWNER_REQUIRED","ERR_NO_LIGHT_TOKEN_BALANCE_UNWRAP","ERR_MINT_MISSING_MERKLE_CONTEXT","ERR_MINT_MISSING_TOKEN_METADATA","TokenAccountSourceType","Spl","Token2022","SplCold","Token2022Cold","LightTokenHot","LightTokenCold","COLD_SOURCE_TYPES","Set","isColdSourceType","has","throwIfUnexpectedRpcErrors","context","unexpectedErrors","error","message","String","toErrorMessage","throwRpcFetchFailure","checkNotFrozen","iface","operation","_anyFrozen","EXTENSION_DATA_SIZES","COMPRESSED_ONLY_DISCRIMINATOR","convertTokenDataToAccount","tokenData","extensionDelegatedAmount","offset","vecLen","readUInt32LE","extractDelegatedAmountFromTlv","state","AccountState","Uninitialized","isFrozen","Frozen","isNative","rentExemptReserve","closeAuthority","tlvData","toAccountInfo","dataDiscriminatorBuffer","executable","rentEpoch","parseLightTokenHot","accountInfo","loadContext","unpackAccountSPL","isCold","parseLightTokenCold","delegateOption","tlvOption","hash","getAccountInterface","assertBetaEnabled","_getAccountInterface","getAtaInterface","wrap","validation","result","_isAta","_owner","_mint","fetchByOwner","lightTokenAta","fetchPromises","fetchTypes","fetchAddresses","TokenInvalidAccountOwnerError","_tryFetchLightTokenHot","splTokenAta","token2022Ata","_tryFetchSpl","_tryFetchToken2022","coldAccountsPromise","getCompressedTokenAccountsByOwner","hotResults","Promise","allSettled","ownerMismatchErrors","coldResult","sources","status","reason","item","items","TokenAccountNotFoundError","priority","indexOf","buildAccountInterfaceFromSources","getUnifiedAccountInterface","onchainResult","compressedResult","onchainAccount","compressedAccounts","getLightTokenAccountInterface","hotType","coldType","hotResult","resolve","hotInfo","coldAccounts","parsedCold","getSplOrToken2022AccountInterface","canonicalAddress","totalAmount","primarySource","hasDelegate","anyFrozen","hasColdSource","needsConsolidation","sumForDelegate","candidate","scope","delegated","delegatedContribution","hotDelegatedSource","coldDelegatedSources","canonicalDelegate","canonicalDelegatedAmount","unifiedAccount","_sources","_needsConsolidation","_hasDelegate","spendableAmountForAuthority","isAuthorityForInterface","filterInterfaceForAuthority","spendable","filtered","primary","getAssociatedTokenAddressInterface","effectiveAssociatedProgramId","TRANSFER2_DISCRIMINATOR","EXTENSION_DISCRIMINANT_TOKEN_METADATA","EXTENSION_DISCRIMINANT_COMPRESSED_ONLY","EXTENSION_DISCRIMINANT_COMPRESSIBLE","COMPRESSION_MODE_COMPRESS","COMPRESSION_MODE_DECOMPRESS","CompressedOnlyExtensionInstructionDataLayout","RentConfigLayout","CompressionInfoLayout","serializeExtensionInstructionData","ext","writeUInt8","withheldTransferFee","compressionIndex","isAta","ownerIndex","configAccountVersion","compressToPubkey","accountVersion","lamportsPerWrite","compressionAuthority","rentSponsor","lastClaimedSlot","rentExemptionPaid","reserved","rentConfig","serializeExtensionTlv","chunks","outerLenBuf","innerVec","innerLenBuf","CompressionLayout","PackedMerkleContextLayout","MultiInputTokenDataWithContextLayout","MultiTokenTransferOutputDataLayout","CompressedCpiContextLayout","Transfer2InstructionDataBaseLayout","encodeTransfer2InstructionData","baseData","withTransactionHash","withLamportsChangeAccountMerkleTreeIndex","lamportsChangeAccountOwnerIndex","compressions","inTokenData","outTokenData","inLamports","v","outLamports","baseBuffer","baseLen","inTlv","serialized","outTlv","createCompressSpl","mintIndex","sourceIndex","authorityIndex","poolAccountIndex","sourceOrRecipient","createDecompressLightToken","recipientIndex","tokenProgramIndex","createCompressLightToken","createDecompressSpl","createWrapInstruction","destination","COMPRESSED_ONLY_DISC","COMPRESSED_ONLY_SIZE","parseCompressedOnlyFromTlv","disc","buildInTlv","hasAny","co","getVersionFromDiscriminator","V1","V2","createDecompressInterfaceInstruction","packedAccountIndices","packedAccounts","treeSet","queueSet","firstQueueIndex","isFirstQueue","destinationIndex","delegateKey","poolBump","ownerKey","mintKey","buildInputTokenData","signerIndex","isTreeOrQueue","isDestination","isPool","MAX_INPUT_ACCOUNTS","selectInputsForAmount","neededAmount","sorted","amtA","amtB","accumulated","countNeeded","selectCount","createLoadAtaInstructions","interfaceOptions","effectiveOwner","accountInterface","_getAtaInterface","_buildLoadBatches","batch","setComputeUnitLimit","units","calculateLoadBatchComputeUnits","CU_ATA_CREATION","CU_WRAP","CU_DECOMPRESS_BASE","CU_FULL_PROOF","CU_PER_ACCOUNT_PROVE_BY_INDEX","CU_PER_ACCOUNT_FULL_PROOF","CU_BUFFER_FACTOR","CU_MIN","CU_MAX","rawLoadBatchComputeUnits","cu","hasAtaCreation","wrapCount","targetAta","targetAmount","allCompressedAccounts","fullData","discriminatorBytes","accountDataBytes","dataHash","readOnly","getCompressedTokenAccountsFromAtaSources","lightTokenAtaAddress","splAta","t22Ata","ataType","splSource","t22Source","lightTokenHotSource","coldSources","splBalance","t22Balance","coldBalance","splInterfaceInfos","setupInstructions","decompressSplInfo","needsAtaCreation","decompressTarget","canDecompress","createAssociatedTokenAccountIdempotentInstruction","accountsToLoad","isDelegate","hotBalance","effectiveHotAfterSetup","neededFromCold","v1Count","assertV2Only","chunkSize","chunkArray","seen","hashStr","assertUniqueInputHashes","proofs","all","proofInputs","getValidityProofV0","idempotentAtaIx","batches","chunkAmount","batchIxs","batchWrapCount","batchHasAtaCreation","authorityForDecompress","dataSize","writeBigUInt64LE","writeUInt16LE","createMintToCompressedInstruction","mintData","recipient","encodeCompressedMintToInstructionData","createMintToInterfaceInstruction","multiSigners","createSplMintToInstruction","createLightTokenMintToInstruction","MAX_TRANSACTION_SIZE","MAX_COMBINED_BATCH_BYTES","MAX_LOAD_ONLY_BATCH_BYTES","assertTransactionSizeWithinLimit","numSigners","estimateTransactionSize","compactU16Size","uniqueKeys","ix","numKeys","signaturesSize","accountKeysSize","instructionsSize","calculateCombinedCU","baseCu","loadBatch","rawLoadCu","LIGHT_TOKEN_TRANSFER_CHECKED_DISCRIMINATOR","TRANSFER_BASE_CU","calculateTransferCU","createLightTokenTransferInstruction","effectiveFeePayer","createLightTokenTransferCheckedInstruction","createTransferInterfaceInstructions","sender","optionsOwner","isSplOrT22","senderAta","senderInterface","internalBatches","transferIx","createTransferCheckedInstruction","txIxs","lastBatch","lastCu","lastTxIxs","UNWRAP_BASE_CU","calculateUnwrapCU","createUnwrapInstruction","createUnwrapInstructions","resolvedSplInterfaceInfo","unwrapAmount","LIGHT_TOKEN_FREEZE_ACCOUNT_DISCRIMINATOR","LIGHT_TOKEN_THAW_ACCOUNT_DISCRIMINATOR","createLightTokenFreezeAccountInstruction","createLightTokenThawAccountInstruction","keypair","Keypair","generate","confirmOptions","getMinimumBalanceForRentExemption","resolvedTokenProgramId","ixs","blockhash","getLatestBlockhash","additionalSigners","dedupeSigner","signer","tx","buildAndSignTx","txId","sendAndConfirmTx","transactionSignature","createMintInterface","resolvedFreezeAuthority","getBatchAddressTreeInfo","selectStateTreeInfo","getStateTreeInfos","compressedMintAddress","getValidityProofV2","DerivationMode","standard","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","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","variant","vb","fixBitwiseResult","msb","_packedSetValue","_packedGetValue","addField","bf","BitField","addBoolean","fieldFor","container","totalBits","usedBits","valueMask","wordMask","wordValue","srcBuffer","write","CString","srcb","maxSpan","u48","u24be","s8","ns64","s48be","f64be","seq","utf8","TokenMetadataLayout","borshStruct","borshPublicKey","MintContextLayout","encodeDecode","publicKeyLayout","MINT_CONTEXT_SIZE","MINT_SIGNER_SIZE","BUMP_SIZE","RESERVED_SIZE","ACCOUNT_TYPE_SIZE","getExtensionByteLength","extensionType","dataStartOffset","ExtensionType","TokenMetadata","startOffset","additionalCount","getTokenMetadataByteLength","deserializeMint","rawMint","MintLayout","rawContext","readUInt8","accountType","compression","compressionBytesRead","readUInt16LE","readBigUInt64LE","baseRent","compressionCost","lamportsPerBytePerEpoch","maxFundedEpochs","deserializeCompressionInfo","hasExtensions","dataLength","extensionData","mintAuthorityOption","freezeAuthorityOption","serializeMint","buffers","baseMintBuffer","contextBuffer","serializeCompressionInfo","vecLenBuf","decodeTokenMetadata","decoded","encodeTokenMetadata","parseTokenMetadata","extractTokenMetadata","metadataExt","getMintInterface","tokenResult","token2022Result","errors","ownerMismatch","allNotFound","unexpected","compressedAddress","getCompressedAccount","compressedData","SENTINEL_THRESHOLD","compressedMintData","cmintAccountInfo","getSplMint","unpackMintInterface","unpackSplMint","unpackMintData","compressedMint","compressible","assertMintMetadataContext","createAtaInterface","effectiveAtaProgramId","transaction","Transaction","sendAndConfirmTransaction","createAtaInterfaceIdempotent","mintInfo","trees","mintToInterface","authorityPubkey","multiSignerPubkeys","signers","loadAta","resolvedDecimals","txPromises","results","getOrCreateAtaInterface","_getOrCreateAtaInterface","secretKey","getOwnerPublicKey","ownerPubkey","hasHotAccount","createLightTokenAtaIdempotent","ownerSigner","hasCold","hasSplToWrap","TokenInvalidMintError","TokenInvalidOwnerError","getOrCreateLightTokenAta","createError","getOrCreateSplAta","sliceLast","rest","last","at","transferInterface","expectedSource","loads","transferIxs","getMint","toOffChainMetadataJson","meta","json","description","image","accountsToUse","inputAccounts","signedTx","getOrCreateAssociatedTokenAccount","sourceTokenAccount","compressIx","blockhashCtx","addSplInterfaces","numMaxAdditionalPools","uninitializedIndices","addTokenPools","additionalAccounts","getSlot","txIds","instruction","selectedSplInterfaceInfos","preferredAccounts","getValidityProof","mergeInstructions","checkOwner","checkIsDelegated","transferDelegated","getCompressedTokenAccountsByDelegate","decompressDelegated","splInterfaceInfosToUse","IDL","docs","isMut","args","isOptional","defined","types","kind","variants","code","isSingleSplInterfaceInfo","isSingleTokenPoolInfo"],"mappings":"0kuBAIaA,GAAqB,IAAIC,EAClC,gDAISC,GAA2B,IAAID,EACxC,mDAOQE,IAAZ,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,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ACNupC,MAAO,EACPn5C,SAAU,EACVk5C,KAAM,CAAC,+BAEX,CACItpC,KAAM,YACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,kBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,OACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,eACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,eACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,qBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,uBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,cACNupC,MAAO,EACPn5C,SAAU,EACVk5C,KAAM,CAAC,aAEX,CACItpC,KAAM,8BACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,4BACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,aACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,cACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,gBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,aACNupC,MAAO,EACPn5C,SAAU,EACVq5C,WAAY,IAGpBD,KAAM,CACF,CACIxpC,KAAM,aACN8C,KAAM,CACFvR,IAAK,cAGb,CACIyO,KAAM,UACN8C,KAAM,CACFvR,IAAK,QAGb,CACIyO,KAAM,WACN8C,KAAM,CACFhS,OAAQ,UAKxB,CACIkP,KAAM,0BACNspC,KAAM,CACF,2EACA,0EACA,2EAEJp/C,SAAU,CACN,CACI8V,KAAM,WACNupC,MAAO,EACPn5C,SAAU,EACVk5C,KAAM,CAAC,+BAEX,CACItpC,KAAM,YACNupC,MAAO,EACPn5C,SAAU,EACVk5C,KAAM,CACF,oEACA,sEACA,oBAGR,CACItpC,KAAM,kBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,qBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,uBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,cACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,8BACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,4BACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,cACNupC,MAAO,EACPn5C,SAAU,EACVk5C,KAAM,CAAC,2CAEX,CACItpC,KAAM,eACNupC,MAAO,EACPn5C,SAAU,EACVq5C,WAAY,GAEhB,CACIzpC,KAAM,mCACNupC,MAAO,EACPn5C,SAAU,EACVq5C,WAAY,GAEhB,CACIzpC,KAAM,eACNupC,MAAO,EACPn5C,SAAU,EACVq5C,WAAY,GAEhB,CACIzpC,KAAM,gBACNupC,MAAO,EACPn5C,SAAU,IAGlBo5C,KAAM,CACF,CACIxpC,KAAM,QACN8C,KAAM,aAEV,CACI9C,KAAM,kBACN8C,KAAM,CACFhS,OAAQ,QAGhB,CACIkP,KAAM,aACN8C,KAAM,CACFhS,OAAQ,CACJ44C,QAAS,4BAM7B,CACI1pC,KAAM,WACNspC,KAAM,CACF,wEACA,uEACA,wEACA,0EACA,wEACA,uEACA,wEACA,kBAEJp/C,SAAU,CACN,CACI8V,KAAM,WACNupC,MAAO,EACPn5C,SAAU,EACVk5C,KAAM,CAAC,+BAEX,CACItpC,KAAM,YACNupC,MAAO,EACPn5C,SAAU,EACVk5C,KAAM,CACF,oEACA,sEACA,oBAGR,CACItpC,KAAM,kBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,qBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,uBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,cACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,8BACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,4BACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,cACNupC,MAAO,EACPn5C,SAAU,EACVk5C,KAAM,CAAC,2CAEX,CACItpC,KAAM,eACNupC,MAAO,EACPn5C,SAAU,EACVq5C,WAAY,GAEhB,CACIzpC,KAAM,mCACNupC,MAAO,EACPn5C,SAAU,EACVq5C,WAAY,GAEhB,CACIzpC,KAAM,eACNupC,MAAO,EACPn5C,SAAU,EACVq5C,WAAY,GAEhB,CACIzpC,KAAM,gBACNupC,MAAO,EACPn5C,SAAU,IAGlBo5C,KAAM,CACF,CACIxpC,KAAM,SACN8C,KAAM,WAIlB,CACI9C,KAAM,UACNspC,KAAM,CACF,0EACA,yEACA,2BACA,+CACA,uCACA,gDAEJp/C,SAAU,CACN,CACI8V,KAAM,WACNupC,MAAO,EACPn5C,SAAU,EACVk5C,KAAM,CAAC,+BAEX,CACItpC,KAAM,YACNupC,MAAO,EACPn5C,SAAU,EACVk5C,KAAM,CACF,oEACA,sEACA,oBAGR,CACItpC,KAAM,kBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,qBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,uBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,cACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,8BACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,4BACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,cACNupC,MAAO,EACPn5C,SAAU,EACVk5C,KAAM,CAAC,2CAEX,CACItpC,KAAM,gBACNupC,MAAO,EACPn5C,SAAU,IAGlBo5C,KAAM,CACF,CACIxpC,KAAM,SACN8C,KAAM,WAIlB,CACI9C,KAAM,SACNspC,KAAM,CACF,0EACA,yEAEJp/C,SAAU,CACN,CACI8V,KAAM,WACNupC,MAAO,EACPn5C,SAAU,EACVk5C,KAAM,CAAC,+BAEX,CACItpC,KAAM,YACNupC,MAAO,EACPn5C,SAAU,EACVk5C,KAAM,CACF,oEACA,sEACA,oBAGR,CACItpC,KAAM,kBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,qBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,uBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,cACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,8BACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,4BACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,cACNupC,MAAO,EACPn5C,SAAU,EACVk5C,KAAM,CAAC,2CAEX,CACItpC,KAAM,gBACNupC,MAAO,EACPn5C,SAAU,IAGlBo5C,KAAM,CACF,CACIxpC,KAAM,SACN8C,KAAM,WAIlB,CACI9C,KAAM,SACNspC,KAAM,CACF,2EACA,iEAEJp/C,SAAU,CACN,CACI8V,KAAM,WACNupC,MAAO,EACPn5C,SAAU,EACVk5C,KAAM,CAAC,+BAEX,CACItpC,KAAM,YACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,kBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,qBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,uBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,cACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,8BACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,4BACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,cACNupC,MAAO,EACPn5C,SAAU,EACVk5C,KAAM,CAAC,gDAEX,CACItpC,KAAM,gBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,OACNupC,MAAO,EACPn5C,SAAU,IAGlBo5C,KAAM,CACF,CACIxpC,KAAM,SACN8C,KAAM,WAIlB,CACI9C,KAAM,OACNspC,KAAM,CACF,yEACA,oEAEJp/C,SAAU,CACN,CACI8V,KAAM,WACNupC,MAAO,EACPn5C,SAAU,EACVk5C,KAAM,CAAC,+BAEX,CACItpC,KAAM,YACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,kBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,qBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,uBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,cACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,8BACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,4BACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,cACNupC,MAAO,EACPn5C,SAAU,EACVk5C,KAAM,CAAC,gDAEX,CACItpC,KAAM,gBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,OACNupC,MAAO,EACPn5C,SAAU,IAGlBo5C,KAAM,CACF,CACIxpC,KAAM,SACN8C,KAAM,WAIlB,CACI9C,KAAM,OACNspC,KAAM,CACF,0EACA,0EACA,gDAEJp/C,SAAU,CACN,CACI8V,KAAM,WACNupC,MAAO,EACPn5C,SAAU,EACVk5C,KAAM,CAAC,+BAEX,CACItpC,KAAM,YACNupC,MAAO,EACPn5C,SAAU,EACVk5C,KAAM,CACF,oEACA,sEACA,oBAGR,CACItpC,KAAM,kBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,OACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,eACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,eACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,qBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,uBACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,cACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,8BACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,4BACNupC,MAAO,EACPn5C,SAAU,GAEd,CACI4P,KAAM,cACNupC,MAAO,EACPn5C,SAAU,GAEd,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CACI1pC,KAAM,MACNspC,KAAM,CACF,2DAEJxmC,KAAM,CACFhS,OAAQ,cAOhCgzC,OAAQ,CACJ,CACIgG,KAAM,IACN9pC,KAAM,2BACNuG,IAAK,kDAET,CACIujC,KAAM,KACN9pC,KAAM,wBACNuG,IAAK,yBAET,CACIujC,KAAM,KACN9pC,KAAM,yBACNuG,IAAK,0BAET,CACIujC,KAAM,KACN9pC,KAAM,2BACNuG,IAAK,4BAET,CACIujC,KAAM,KACN9pC,KAAM,6BACNuG,IAAK,8BAET,CACIujC,KAAM,KACN9pC,KAAM,iBACNuG,IAAK,kBAET,CACIujC,KAAM,KACN9pC,KAAM,4CACNuG,IAAK,6CAET,CACIujC,KAAM,KACN9pC,KAAM,sCACNuG,IAAK,uCAET,CACIujC,KAAM,KACN9pC,KAAM,yCACNuG,IAAK,0CAET,CACIujC,KAAM,KACN9pC,KAAM,oCACNuG,IAAK,qCAET,CACIujC,KAAM,KACN9pC,KAAM,uCACNuG,IAAK,wCAET,CACIujC,KAAM,KACN9pC,KAAM,4BACNuG,IAAK,6BAET,CACIujC,KAAM,KACN9pC,KAAM,eACNuG,IAAK,uCAET,CACIujC,KAAM,KACN9pC,KAAM,yBACNuG,IAAK,0BAET,CACIujC,KAAM,KACN9pC,KAAM,wBACNuG,IAAK,yBAET,CACIujC,KAAM,KACN9pC,KAAM,yBACNuG,IAAK,mCAET,CACIujC,KAAM,KACN9pC,KAAM,sBACNuG,IAAK,uBAET,CACIujC,KAAM,KACN9pC,KAAM,mBACNuG,IAAK,oBAET,CACIujC,KAAM,KACN9pC,KAAM,uBACNuG,IAAK,sDAET,CACIujC,KAAM,KACN9pC,KAAM,yBACNuG,IAAK,kDAET,CACIujC,KAAM,KACN9pC,KAAM,wBAEV,CACI8pC,KAAM,KACN9pC,KAAM,yBAEV,CACI8pC,KAAM,KACN9pC,KAAM,iBACNuG,IAAK,+EAET,CACIujC,KAAM,KACN9pC,KAAM,uBAEV,CACI8pC,KAAM,KACN9pC,KAAM,gCAEV,CACI8pC,KAAM,KACN9pC,KAAM,oBAEV,CACI8pC,KAAM,KACN9pC,KAAM,4BAEV,CACI8pC,KAAM,KACN9pC,KAAM,4BAEV,CACI8pC,KAAM,KACN9pC,KAAM,kCACNuG,IAAK,gEAET,CACIujC,KAAM,KACN9pC,KAAM,uBACNuG,IAAK,sCAET,CACIujC,KAAM,KACN9pC,KAAM,sBAEV,CACI8pC,KAAM,KACN9pC,KAAM,sCAEV,CACI8pC,KAAM,KACN9pC,KAAM,yBC3/GZ,SAAU+pC,GACZtb,GAEA,OAAQrnC,MAAM+U,QAAQsyB,EAC1B,CAKO,MAAMub,GAAwBD","x_google_ignoreList":[15,34,35,37]}
|