@gabox-labs/sdk 0.2.0 → 0.7.0

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/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["base64","wsolPreparation","SPL_TOKEN_PROGRAM_ADDRESS","wsolPreparation","SPL_TOKEN_PROGRAM_ADDRESS","SPL_TOKEN_PROGRAM_ADDRESS"],"sources":["../src/math.ts","../src/pdas.ts","../src/accounts.ts","../src/compute.ts","../src/events.ts","../src/lookupTables.ts","../src/offer.ts","../src/rpc.ts","../src/tx/message.ts","../src/referral.ts","../src/tx/buyPack.ts","../src/tx/createMachine.ts","../src/tx/draw.ts","../src/tx/fundPrizes.ts","../src/tx/redeem.ts","../src/vrf.ts"],"sourcesContent":["/**\n * A bigint port of `programs/gabox-v2/src/math.rs`.\n *\n * The point is that a client can show a buyer the exact prize table the program will freeze into\n * their `Draw`, before they pay. Every rounding step here matches the Rust, including the direction\n * of each division. `test/math.test.ts` runs the same vectors as `programs/gabox-v2/tests/\n * economics.rs`.\n *\n * All amounts are `bigint`, in the mint's smallest unit. `multiplierBps` and `tickets` are numbers\n * because both are `u32` in the program and both stay small.\n */\n\n/** Basis points. A multiplier of 10_000 pays back exactly one pack. */\nexport const BPS = 10_000n;\n\n/** `math::share`. `bps` basis points of `amount`, rounded down. */\nexport function share(amount: bigint, bps: bigint): bigint {\n return (amount * bps) / BPS;\n}\n\n/** Ticket counts must sum to this. A uniform 16-bit word then maps with no modulo bias. */\nexport const TICKETS = 65_536;\n\n/** The prize table has exactly this many slots. Unused slots are all-zero. */\nexport const TIERS = 8;\n\n/** One row of the immutable prize table. Counts, not cumulative thresholds. */\nexport type Tier = {\n /** `floor(base * multiplierBps / 10_000)` tokens. `0` only on an unused row. */\n multiplierBps: number;\n /** Out of 65,536. `0` marks the row unused, and then `multiplierBps` must be `0` too. */\n tickets: number;\n};\n\n/** One row of a frozen offer: a real token amount, already capped by inventory. */\nexport type Prize = {\n amount: bigint;\n tickets: number;\n};\n\n/** What `buy_pack` writes into the `Draw`. `minimum` is also the timeout payout. */\nexport type Offer = {\n prizes: Prize[];\n maximum: bigint;\n minimum: bigint;\n};\n\n/** Thrown by every function here. `code` matches a `GaboxError` variant name. */\nexport class GaboxMathError extends Error {\n readonly code: string;\n constructor(code: string, message: string) {\n super(`${code}: ${message}`);\n this.name = \"GaboxMathError\";\n this.code = code;\n }\n}\n\nconst U64_MAX = (1n << 64n) - 1n;\nconst U32_MAX = 0xffff_ffff;\n\n/**\n * The default prize table. The program does not enforce this table: it accepts any table that\n * passes `validateTiers`. This is only the table the Gabox app creates its pools with, and the\n * starting point for a client that has no reason to pick another one.\n *\n * Common 75% at 0.52x, Rare 20% at 1.2x, Epic 4% at 3x, Mythic 1% at 20x. Expected payout is\n * 0.9499x of a pack, so the seed is 19 packs.\n */\nexport const DEFAULT_TIERS: readonly Readonly<Tier>[] = Object.freeze([\n Object.freeze({ multiplierBps: 5_201, tickets: 49_153 }),\n Object.freeze({ multiplierBps: 12_000, tickets: 13_107 }),\n Object.freeze({ multiplierBps: 30_000, tickets: 2_621 }),\n Object.freeze({ multiplierBps: 200_000, tickets: 655 }),\n Object.freeze({ multiplierBps: 0, tickets: 0 }),\n Object.freeze({ multiplierBps: 0, tickets: 0 }),\n Object.freeze({ multiplierBps: 0, tickets: 0 }),\n Object.freeze({ multiplierBps: 0, tickets: 0 }),\n]);\n\nfunction checkedU64(value: bigint, what: string): bigint {\n if (value < 0n || value > U64_MAX) {\n throw new GaboxMathError(\"Arithmetic\", `${what} does not fit in u64`);\n }\n return value;\n}\n\n/** Tier fields encode as program `u32`s. Reject JavaScript-only values before `BigInt` or codecs. */\nfunction checkedU32(value: number, what: string): number {\n if (!Number.isInteger(value) || value < 0 || value > U32_MAX) {\n throw new GaboxMathError(\n \"InvalidDistribution\",\n `${what} must be an integer from 0 to ${U32_MAX}`,\n );\n }\n return value;\n}\n\n/** `math::tokens`. Floor division, and an overflow past u64 is an error, not a wrap. */\nexport function tierAmount(base: bigint, multiplierBps: number): bigint {\n return checkedU64((base * BigInt(checkedU32(multiplierBps, \"multiplierBps\"))) / BPS, \"tier amount\");\n}\n\n/**\n * `math::validate`. Checks the table alone, with no base.\n *\n * Three rules, and each one closes a way to sell a bad ticket:\n * - ticket counts sum to exactly 65,536, so the 16-bit draw is uniform;\n * - an unused row is all-zero, so a hidden multiplier cannot ride along;\n * - the expected multiplier over all tickets is at most 1x, so the table cannot promise more\n * tokens than a pack buys. This bounds tokens, not cash value.\n */\nexport function validateTiers(tiers: readonly Readonly<Tier>[]): void {\n if (tiers.length !== TIERS) {\n throw new GaboxMathError(\n \"InvalidDistribution\",\n `expected ${TIERS} tiers, got ${tiers.length}`,\n );\n }\n let count = 0n;\n let expected = 0n;\n for (const [index, tier] of tiers.entries()) {\n checkedU32(tier.tickets, `tier ${index} tickets`);\n checkedU32(tier.multiplierBps, `tier ${index} multiplierBps`);\n if (tier.tickets === 0) {\n if (tier.multiplierBps !== 0) {\n throw new GaboxMathError(\n \"InvalidDistribution\",\n \"a tier with no tickets must have no multiplier\",\n );\n }\n continue;\n }\n if (tier.multiplierBps <= 0) {\n throw new GaboxMathError(\n \"InvalidDistribution\",\n \"a ticketed tier must pay something; it would sell a ticket that can only win zero\",\n );\n }\n count += BigInt(tier.tickets);\n expected += BigInt(tier.multiplierBps) * BigInt(tier.tickets);\n }\n if (count !== BigInt(TICKETS)) {\n throw new GaboxMathError(\n \"InvalidDistribution\",\n `tickets must sum to ${TICKETS}, they sum to ${count}`,\n );\n }\n if (expected > BPS * BigInt(TICKETS)) {\n throw new GaboxMathError(\n \"UnfundedExpectation\",\n \"the expected token award exceeds the tokens a pack buys\",\n );\n }\n}\n\n/**\n * `math::validate_pack`. Every ticketed tier must pay at least one token for a pack of this size.\n *\n * The program checks this once at creation. At `PACK_TOKENS` no sane table fails it; it exists so\n * a table cannot sell a ticket that can only win zero.\n */\nexport function validatePack(packTokens: bigint, tiers: readonly Readonly<Tier>[]): void {\n if (packTokens <= 0n) throw new GaboxMathError(\"ZeroAmount\", \"packTokens must be positive\");\n checkedU64(packTokens, \"pack tokens\");\n validateTiers(tiers);\n for (const [i, tier] of tiers.entries()) {\n if (tier.tickets === 0) continue;\n if (tierAmount(packTokens, tier.multiplierBps) === 0n) {\n throw new GaboxMathError(\"PackTooSmall\", `tier ${i} rounds to zero tokens at this pack size`);\n }\n }\n}\n\n/**\n * `math::seed_tokens`. The seed a table needs, in tokens.\n *\n * The first pack must be able to pay the largest tier in full. The pack itself brings `packTokens`\n * into the vault, so the vault has to hold the rest beforehand:\n *\n * seedTokens = uncappedMaximum(packTokens, tiers) - packTokens\n *\n * A 5x jackpot on a 1M-token pack needs a 4M-token seed. A table whose top tier pays exactly one\n * pack needs no seed. A top tier below one pack is refused: every ticket would lose.\n *\n * `initialize_pool` computes this number itself and buys exactly that many tokens on the curve.\n * The creator only signs a maximum SOL cost.\n */\nexport function seedTokens(packTokens: bigint, tiers: readonly Readonly<Tier>[]): bigint {\n validateTiers(tiers);\n const largest = uncappedMaximum(packTokens, tiers);\n if (largest < packTokens) {\n throw new GaboxMathError(\n \"JackpotBelowOnePack\",\n \"the largest tier must pay at least one pack\",\n );\n }\n return largest - packTokens;\n}\n\n/**\n * `math::uncapped_maximum`. The largest tier's award for this base, before any inventory cap.\n *\n * At `packTokens` this is the jackpot in tokens. `seedTokens` is this minus one pack.\n */\nexport function uncappedMaximum(base: bigint, tiers: readonly Readonly<Tier>[]): bigint {\n validateTiers(tiers);\n let largest = 0n;\n for (const tier of tiers) {\n if (tier.tickets === 0) continue;\n const amount = tierAmount(base, tier.multiplierBps);\n if (amount > largest) largest = amount;\n }\n return largest;\n}\n\n/**\n * `math::quote`. The offer a pack of `base` tokens would freeze right now. `base` is always\n * `pool.packTokens`; the parameter stays general so the vectors can use small numbers.\n *\n * `inventory` is the vault's token balance and `reserved` is `pool.reserved`. The difference is\n * free inventory. This pack's own `base` is added to it, because the purchase and the offer are\n * one transaction — the tokens are in the vault before the draw is written.\n *\n * Every amount is capped at what is actually available. A tier that rounds to zero tokens is an\n * error: the pool must not sell a ticket that can only win nothing.\n */\nexport function quote(\n base: bigint,\n tiers: readonly Readonly<Tier>[],\n inventory: bigint,\n reserved: bigint,\n): Offer {\n validateTiers(tiers);\n if (inventory < reserved) {\n throw new GaboxMathError(\n \"InsolventInventory\",\n \"the vault holds less than the pool has already reserved\",\n );\n }\n const available = checkedU64(\n inventory - reserved + base,\n \"available inventory\",\n );\n\n const prizes: Prize[] = Array.from({ length: TIERS }, () => ({\n amount: 0n,\n tickets: 0,\n }));\n let maximum = 0n;\n let minimum = U64_MAX;\n\n for (const [i, tier] of tiers.entries()) {\n if (tier.tickets === 0) continue;\n const uncapped = tierAmount(base, tier.multiplierBps);\n if (uncapped === 0n) {\n throw new GaboxMathError(\n \"PackTooSmall\",\n `tier ${i} rounds to zero tokens at this pack size`,\n );\n }\n const amount = uncapped < available ? uncapped : available;\n prizes[i] = { amount, tickets: tier.tickets };\n if (amount > maximum) maximum = amount;\n if (amount < minimum) minimum = amount;\n }\n\n return { prizes, maximum, minimum };\n}\n\n/**\n * `math::choose`. Which prize a 16-bit ticket wins.\n *\n * The rows are consecutive ranges in table order, so this is a running total and a comparison.\n * A ticket past the last row returns `0`, which cannot happen for a validated table.\n */\nexport function choose(prizes: readonly Prize[], ticket: number): bigint {\n let end = 0;\n for (const prize of prizes) {\n end += prize.tickets;\n if (ticket < end) return prize.amount;\n }\n return 0n;\n}\n\n/** `math::resolve_reservation`. Release the unwon part of a maximum, keep the award reserved. */\nexport function resolveReservation(\n reserved: bigint,\n maximum: bigint,\n award: bigint,\n): bigint {\n if (award > maximum) {\n throw new GaboxMathError(\n \"InsolventInventory\",\n \"the award exceeds the reserved maximum\",\n );\n }\n if (reserved < maximum) {\n throw new GaboxMathError(\n \"Arithmetic\",\n \"the pool has reserved less than this draw holds\",\n );\n }\n return checkedU64(reserved - maximum + award, \"reserved\");\n}\n\n/** The largest `multiplierBps` on any ticketed row. `0` for a table with no rows. */\nexport function maxMultiplierBps(tiers: readonly Readonly<Tier>[]): number {\n validateTiers(tiers);\n let largest = 0;\n for (const tier of tiers) {\n if (tier.tickets === 0) continue;\n if (tier.multiplierBps > largest) largest = tier.multiplierBps;\n }\n return largest;\n}\n\n/**\n * The expected multiplier over all 65,536 tickets, in basis points. Rounded down.\n *\n * `validateTiers` caps this at 10,000. A table at 9,800 keeps 2% of every pack's tokens in the\n * vault on average, which is what lets a pool survive a run of top-tier wins.\n */\nexport function averageMultiplierBps(tiers: readonly Readonly<Tier>[]): number {\n validateTiers(tiers);\n let weighted = 0n;\n for (const tier of tiers) {\n if (tier.tickets === 0) continue;\n weighted += BigInt(tier.multiplierBps) * BigInt(tier.tickets);\n }\n return Number(weighted / BigInt(TICKETS));\n}\n","/**\n * Every program-derived address a client needs.\n *\n * The three gabox PDAs come from the generated tree, which Codama built from the IDL's own seed\n * metadata. Re-exported here so callers have one import, and so the seeds stay in exactly one\n * place. The two written by hand are the ones Codama cannot generate: an ATA, and a PDA that lives\n * under a program other than ours.\n */\n\nimport {\n getAddressEncoder,\n getBytesEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from '@solana/kit';\n\nimport {\n ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n GABOX_PROGRAM_ID,\n IDENTITY_SEED,\n PROTOCOL_FEE_COLLECTOR,\n TOKEN_2022_PROGRAM_ADDRESS,\n TOKEN_PROGRAM_ADDRESS,\n VRF_PROGRAM_ADDRESS,\n WSOL_MINT,\n} from './ids';\nimport { findDrawPda } from './generated/pdas/draw';\nimport { findIdentityPda } from './generated/pdas/identity';\nimport { findPoolPda } from './generated/pdas/pool';\nimport { findReferralPda } from './generated/pdas/referral';\nimport { findReferralLinkPda } from './generated/pdas/referralLink';\n\nexport { findDrawPda, findIdentityPda, findPoolPda, findReferralLinkPda };\n\n/** `['referral', referee]`. A wallet's permanent referral binding. */\nexport async function referralLinkAddress(referee: Address): Promise<Address> {\n return (await findReferralLinkPda({ purchaser: referee }))[0];\n}\n\n/** `['referral', pool, referrer]`. A referrer's accrued rewards for one pool. */\nexport async function referralAddress(pool: Address, referrer: Address): Promise<Address> {\n // The generated seed is named referralLink because Anchor cannot express the field read from\n // that optional account. The on-chain seed is the referrer's address, so pass it explicitly.\n return (await findReferralPda({ pool, referralLink: referrer }))[0];\n}\n\n/** `[\"pool\", mint]`. One pool per coin, and the mint alone is the seed. */\nexport async function poolAddress(mint: Address): Promise<Address> {\n return (await findPoolPda({ mint }))[0];\n}\n\n/** `[\"draw\", pool, seq_u64_le]`. `seq` is `pool.nextSeq` at the moment of the purchase. */\nexport async function drawAddress(pool: Address, seq: bigint): Promise<Address> {\n return (await findDrawPda({ pool, seq }))[0];\n}\n\n/**\n * `[\"identity\"]` under gabox. This is the PDA gabox signs the VRF request with — the `identity`\n * account of the `Oracle` group on `buy_pack` and `retry_draw`.\n */\nexport async function vrfIdentityAddress(): Promise<Address> {\n return (await findIdentityPda())[0];\n}\n\n/**\n * `[\"identity\", gabox_program_id]` under the **VRF program**. A different address from\n * `vrfIdentityAddress`, and it belongs to the other side: MagicBlock signs the `deliver_draw`\n * callback with it. A client never puts it in an instruction. It is here so a client can recognise\n * the signer on a callback transaction.\n */\nexport async function scopedVrfIdentityAddress(): Promise<ProgramDerivedAddress> {\n return await getProgramDerivedAddress({\n programAddress: VRF_PROGRAM_ADDRESS,\n seeds: [getBytesEncoder().encode(IDENTITY_SEED), getAddressEncoder().encode(GABOX_PROGRAM_ID)],\n });\n}\n\n/**\n * An associated token account. The seed order is `[owner, token_program, mint]`, which is the ATA\n * program's own order and not the argument order most callers remember.\n */\nexport async function associatedTokenAddress(\n owner: Address,\n mint: Address,\n tokenProgram: Address = TOKEN_2022_PROGRAM_ADDRESS,\n): Promise<Address> {\n const encoder = getAddressEncoder();\n const [address] = await getProgramDerivedAddress({\n programAddress: ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n seeds: [encoder.encode(owner), encoder.encode(tokenProgram), encoder.encode(mint)],\n });\n return address;\n}\n\n/**\n * The protocol fee collector's WSOL ATA, under classic SPL Token. A sale on PumpSwap pays its\n * protocol fee here. The account must exist before the first PumpSwap sale; see `DEPLOYMENT.md`.\n */\nexport async function feeCollectorWsolAddress(): Promise<Address> {\n return await associatedTokenAddress(PROTOCOL_FEE_COLLECTOR, WSOL_MINT, TOKEN_PROGRAM_ADDRESS);\n}\n\n/**\n * The pool's prize inventory: the pool PDA's ATA for the mint's own token program.\n *\n * `tokenProgram` defaults to Token-2022 because Pump `create_v2` mints there, and every machine is\n * built on a coin Pump created. Pass the mint's real owner if you have it.\n */\nexport async function vaultAddress(\n mint: Address,\n tokenProgram: Address = TOKEN_2022_PROGRAM_ADDRESS,\n): Promise<Address> {\n return await associatedTokenAddress(await poolAddress(mint), mint, tokenProgram);\n}\n","/**\n * Reading gabox state: pools, draws, and the vault balance that turns a pool into an offer.\n *\n * The decoders are the generated ones. What this file adds is the queries — the discriminator and\n * `memcmp` filters that let a client list every machine, or every draw a wallet is waiting on,\n * without an indexer.\n *\n * # The offsets are computed, not counted\n *\n * A `memcmp` filter is a byte offset into an account. Counting field widths by hand is how a filter\n * silently matches nothing. Each offset below is built from the widths of the fields before it, in\n * the same order `state.rs` declares them, so the arithmetic is visible and a field inserted in the\n * middle changes it.\n */\n\nimport {\n fetchEncodedAccount,\n fetchEncodedAccounts,\n getBase58Decoder,\n getBase64Encoder,\n type Address,\n type Base58EncodedBytes,\n type MaybeAccount,\n type MaybeEncodedAccount,\n} from '@solana/kit';\n\nimport { DRAW_DISCRIMINATOR, decodeDraw, fetchMaybeDraw, type Draw } from './generated/accounts/draw';\nimport { POOL_DISCRIMINATOR, decodePool, getPoolSize, type Pool } from './generated/accounts/pool';\nimport { fetchMaybeReferral, type Referral } from './generated/accounts/referral';\nimport {\n REFERRAL_LINK_DISCRIMINATOR,\n decodeReferralLink,\n getReferralLinkSize,\n type ReferralLink,\n} from './generated/accounts/referralLink';\nimport { GABOX_PROGRAM_ID } from './ids';\nimport { quote, type Offer, type Tier } from './math';\nimport { poolAddress, referralAddress, vaultAddress } from './pdas';\nimport { tokenAccountAmount } from './pump/venue';\nimport type { GaboxClient, GaboxRpc } from './rpc';\n\nexport { decodeDraw, decodePool, DRAW_DISCRIMINATOR, POOL_DISCRIMINATOR };\nexport type { Draw, Pool };\nexport type { Referral, ReferralLink };\n\nconst DISCRIMINATOR = 8;\nconst PUBKEY = 32;\n\n/** `Draw.pool` sits straight after the discriminator. */\nexport const DRAW_POOL_OFFSET = DISCRIMINATOR;\n/** `Draw.purchaser` sits after the discriminator and `pool`. */\nexport const DRAW_PURCHASER_OFFSET = DISCRIMINATOR + PUBKEY;\n/** `Pool.creator` sits straight after the discriminator. */\nexport const POOL_CREATOR_OFFSET = DISCRIMINATOR;\n/** `Pool.mint` sits after the discriminator and `creator`. */\nexport const POOL_MINT_OFFSET = DISCRIMINATOR + PUBKEY;\n/** `ReferralLink.referrer` sits after the discriminator and `referee`. */\nexport const REFERRAL_LINK_REFERRER_OFFSET = DISCRIMINATOR + PUBKEY;\n\nconst base58 = getBase58Decoder();\nconst base64 = getBase64Encoder();\n\n/** A `memcmp` filter wants base58, and both discriminators and addresses arrive as other things. */\nconst asBase58 = (bytes: Uint8Array): Base58EncodedBytes =>\n base58.decode(bytes) as Base58EncodedBytes;\n\ntype ProgramAccountFilter = {\n memcmp: { offset: bigint; bytes: Base58EncodedBytes; encoding: 'base58' };\n} | { dataSize: bigint };\n\nconst memcmp = (offset: number, bytes: Base58EncodedBytes): ProgramAccountFilter => ({\n memcmp: { offset: BigInt(offset), bytes, encoding: 'base58' },\n});\n\nasync function scan<T>(\n rpc: GaboxRpc,\n filters: ProgramAccountFilter[],\n decode: (account: { address: Address; data: Uint8Array }) => T,\n): Promise<T[]> {\n const accounts = await rpc\n .getProgramAccounts(GABOX_PROGRAM_ID, {\n encoding: 'base64',\n commitment: 'confirmed',\n filters,\n })\n .send();\n return accounts.map(({ pubkey, account }) =>\n decode({ address: pubkey, data: new Uint8Array(base64.encode(account.data[0])) }),\n );\n}\n\n/** Wrap raw bytes in the shape the generated decoders expect. */\nconst encoded = (address: Address, data: Uint8Array) => ({\n address,\n data,\n executable: false,\n lamports: 0n as never,\n programAddress: GABOX_PROGRAM_ID,\n space: BigInt(data.length),\n});\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Single accounts\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** The pool for a coin, or `null` when the coin has no machine. */\nexport async function fetchPoolByMint(client: GaboxClient, mint: Address): Promise<Pool | null> {\n return await fetchPoolAt(client, await poolAddress(mint));\n}\n\n/**\n * A pool by its own address, or `null`.\n *\n * `fetchPoolByMint` is the usual way in, because a coin's mint is the natural key. This one is for\n * the other direction: a `Draw` names its pool and not its mint, so a client holding a draw reads\n * the pool to learn which coin it belongs to.\n */\nexport async function fetchPoolAt(client: GaboxClient, address: Address): Promise<Pool | null> {\n const account = await fetchEncodedAccount(client.rpc, address, { commitment: 'confirmed' });\n return decodeCurrentPool(account);\n}\n\n/** `null` for a missing pool; an error for one on the older devnet layout. */\nfunction decodeCurrentPool(account: MaybeEncodedAccount): Pool | null {\n if (!account.exists) return null;\n if (account.data.length !== getPoolSize()) {\n throw new Error(`Machine ${account.address} uses an older devnet account layout and needs migration or recreation.`);\n }\n return decodePool(account).data;\n}\n\n/** A draw by address, or `null`. Delivered and legacy-claimed draws are closed. */\nexport async function fetchDraw(client: GaboxClient, address: Address): Promise<Draw | null> {\n const account: MaybeAccount<Draw> = await fetchMaybeDraw(client.rpc, address, {\n commitment: 'confirmed',\n });\n return account.exists ? account.data : null;\n}\n\n/** Accrued referral reward for one referrer and pool, or zero when no referred pack has settled. */\nexport async function fetchReferralReward(\n client: GaboxClient,\n pool: Address,\n referrer: Address,\n): Promise<Referral | null> {\n const address = await referralAddress(pool, referrer);\n const account = await fetchMaybeReferral(client.rpc, address, { commitment: 'confirmed' });\n return account.exists ? account.data : null;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Scans\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport type PoolRecord = { address: Address; data: Pool };\nexport type DrawRecord = { address: Address; data: Draw };\n\n/**\n * Every current-layout machine, by discriminator and account size. Older devnet\n * pools predate seed fields and must not be decoded with the current schema.\n *\n * There is no on-chain registry — the design says so on purpose — so discovery is this scan plus\n * the `PoolCreated` event. Public RPCs limit `getProgramAccounts`, so an app that lists machines\n * for users should cache the result rather than call this per page view.\n */\nexport async function listPools(client: GaboxClient): Promise<PoolRecord[]> {\n return await scan(client.rpc, [\n memcmp(0, asBase58(POOL_DISCRIMINATOR as Uint8Array)),\n { dataSize: BigInt(getPoolSize()) },\n ], ({ address, data }) => ({\n address,\n data: decodePool(encoded(address, data)).data,\n }));\n}\n\n/** Every draw of one pool, pending or ready. Closed draws are gone and never appear. */\nexport async function listDrawsByPool(client: GaboxClient, pool: Address): Promise<DrawRecord[]> {\n return await listDraws(client, { pool });\n}\n\n/**\n * Every open draw of one wallet, across all pools. This is the \"what am I owed\" query.\n *\n * An address is already base58, so it goes into the filter unchanged.\n */\nexport async function listDrawsByPurchaser(\n client: GaboxClient,\n purchaser: Address,\n): Promise<DrawRecord[]> {\n return await listDraws(client, { purchaser });\n}\n\nexport type DrawQuery = {\n /** A pool PDA. */\n pool?: Address;\n /** A buyer's wallet. */\n purchaser?: Address;\n};\n\n/**\n * Open draws, narrowed by pool, by purchaser, or by both.\n *\n * Both filters in one scan, because a UI asks for exactly that: \"my pulls on this machine\". Two\n * separate scans and an intersection in the client would move twice the bytes and could disagree\n * with itself, since the two reads happen at different slots. With neither filter this lists every\n * open draw of every machine.\n */\nexport async function listDraws(client: GaboxClient, query: DrawQuery = {}): Promise<DrawRecord[]> {\n const filters = [memcmp(0, asBase58(DRAW_DISCRIMINATOR as Uint8Array))];\n if (query.pool) {\n filters.push(memcmp(DRAW_POOL_OFFSET, query.pool as unknown as Base58EncodedBytes));\n }\n if (query.purchaser) {\n filters.push(memcmp(DRAW_PURCHASER_OFFSET, query.purchaser as unknown as Base58EncodedBytes));\n }\n return await scan(client.rpc, filters, ({ address, data }) => ({\n address,\n data: decodeDraw(encoded(address, data)).data,\n }));\n}\n\nexport type ReferralLinkRecord = { address: Address; data: ReferralLink };\n\n/**\n * Every wallet bound to one referrer. This is the \"who did I refer\" query.\n *\n * A scan, because a link is seeded on the referee and nothing on chain indexes it by referrer.\n * The list is small in practice, and a dashboard reads it once per load, not per poll.\n */\nexport async function listReferralLinksByReferrer(\n client: GaboxClient,\n referrer: Address,\n): Promise<ReferralLinkRecord[]> {\n return await scan(client.rpc, [\n memcmp(0, asBase58(REFERRAL_LINK_DISCRIMINATOR as Uint8Array)),\n { dataSize: BigInt(getReferralLinkSize()) },\n memcmp(REFERRAL_LINK_REFERRER_OFFSET, referrer as unknown as Base58EncodedBytes),\n ], ({ address, data }) => ({\n address,\n data: decodeReferralLink(encoded(address, data)).data,\n }));\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Inventory\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** The vault's token balance. `0` when the vault does not exist yet. */\nexport async function fetchVaultBalance(\n client: GaboxClient,\n mint: Address,\n tokenProgram?: Address,\n): Promise<bigint> {\n const vault = await vaultAddress(mint, tokenProgram);\n const { value } = await client.rpc\n .getAccountInfo(vault, { encoding: 'base64', commitment: 'confirmed' })\n .send();\n if (!value) return 0n;\n return tokenAccountAmount(new Uint8Array(base64.encode(value.data[0])));\n}\n\nexport type PoolInventory = {\n pool: Pool;\n poolAddress: Address;\n vault: Address;\n /** The vault's whole token balance. */\n inventory: bigint;\n /** `pool.reserved`: maximum awards reserved by pending draws. */\n reserved: bigint;\n /** `inventory - reserved`. What a new pack's prizes can be paid from, besides its own tokens. */\n free: bigint;\n};\n\n/**\n * A pool with its live inventory. This is the pair every price display needs: the tiers are\n * immutable, but what they actually pay depends on what is free in the vault right now.\n *\n * # Why one request reads both accounts\n *\n * The oracle callback lowers the vault and `pool.reserved` in one transaction, a few seconds after\n * a buy. Two separate reads can land on either side of it: the old `reserved` with the new, smaller\n * vault. That pair looks insolvent, and `quote` rightly refuses it. One `getMultipleAccounts` call\n * returns both accounts from the same slot, so the pair is always one the chain actually held.\n */\nexport async function fetchPoolInventory(\n client: GaboxClient,\n mint: Address,\n): Promise<PoolInventory | null> {\n const address = await poolAddress(mint);\n const readPair = async (vault: Address) => {\n // The explicit tuple type keeps the result a pair rather than an array of maybes.\n const [poolAccount, vaultAccount] = await fetchEncodedAccounts<[string, string]>(\n client.rpc,\n [address, vault],\n { commitment: 'confirmed' },\n );\n const pool = decodeCurrentPool(poolAccount);\n if (!pool) return null;\n const inventory = vaultAccount.exists ? tokenAccountAmount(vaultAccount.data) : 0n;\n return { pool, inventory };\n };\n // Every machine's coin is a Token-2022 mint, so this is the vault in practice. The pool is still\n // the authority: if it names a different vault, read that one together with the pool again.\n const expectedVault = await vaultAddress(mint);\n let pair = await readPair(expectedVault);\n if (pair && pair.pool.vault !== expectedVault) pair = await readPair(pair.pool.vault);\n if (!pair) return null;\n const { pool, inventory } = pair;\n const reserved = pool.reserved;\n\n return {\n pool,\n poolAddress: address,\n vault: pool.vault,\n inventory,\n reserved,\n // A vault below its reservations is an invariant break, not a negative number to show.\n free: inventory >= reserved ? inventory - reserved : 0n,\n };\n}\n\n/** The generated `Tier` uses the same field names as `math.ts`, so this is only a widening. */\nexport const tiersOf = (pool: Pool): Tier[] =>\n pool.tiers.map((t) => ({ multiplierBps: t.multiplierBps, tickets: t.tickets }));\n\n/**\n * The offer a pack of `base` tokens would freeze against this inventory. Pure — the same\n * computation `buy_pack` performs, and the reason a client can show real amounts before paying.\n */\nexport const offerFor = (inventory: PoolInventory, base: bigint): Offer =>\n quote(base, tiersOf(inventory.pool), inventory.inventory, inventory.reserved);\n","/**\n * The two `ComputeBudget` instructions the transaction builders prepend.\n *\n * # Why every gabox transaction needs one\n *\n * The default budget is 200,000 compute units for the whole transaction. `buy_pack` alone does a\n * CPI into Pump (which does its own CPIs into two token programs and its fee program), a\n * `transfer_checked`, an account init, a system transfer, and a CPI into MagicBlock's VRF program\n * that allocates a request account. `createMachine` adds Pump's `create_v2` to that, which mints a\n * Token-2022 coin with metadata. Neither fits in the default, and nothing on chain can raise its\n * own budget.\n *\n * # The numbers are headroom, not measurements\n *\n * They have not been measured on chain. They sit comfortably above what these instruction mixes\n * plausibly cost and comfortably below the 1,400,000 ceiling. **Measure them on devnet before they\n * matter**, because the prioritisation fee is `price x requested limit`: a request that is three\n * times too large costs three times too much on every pack. Until then, treat them as a starting\n * point a caller may override.\n */\n\nimport {\n getStructEncoder,\n getU32Encoder,\n getU64Encoder,\n getU8Encoder,\n type Address,\n type Instruction,\n type InstructionWithData,\n type ReadonlyUint8Array,\n} from '@solana/kit';\n\nexport const COMPUTE_BUDGET_PROGRAM_ADDRESS =\n 'ComputeBudget111111111111111111111111111111' as Address;\n\n/** The runtime's per-transaction ceiling. A larger request is rejected outright. */\nexport const MAX_COMPUTE_UNIT_LIMIT = 1_400_000;\n\n/** What an instruction gets when no `SetComputeUnitLimit` is present. */\nexport const DEFAULT_COMPUTE_UNIT_LIMIT = 200_000;\n\n/**\n * UNVERIFIED: none of the three figures below has been measured on chain. They are headroom, chosen\n * above what these instruction mixes plausibly cost. Measure them on devnet before they matter: the\n * prioritisation fee is `price x requested limit`, so a request three times too large costs three\n * times too much on every pack.\n */\n\n/** Pump `create_v2` plus `initialize_pool` plus a seed buy, in one transaction. */\nexport const CREATE_MACHINE_COMPUTE_UNITS = 600_000;\n\n/** A venue buy, an escrow transfer, a draw init and a VRF request. */\nexport const BUY_PACK_COMPUTE_UNITS = 500_000;\n\n/** A vault transfer, or a vault transfer plus a venue sale. */\nexport const REDEEM_COMPUTE_UNITS = 300_000;\n\n/** `bind_referrer` riding ahead of a pack: one small account init. */\nexport const BIND_REFERRER_COMPUTE_UNITS = 50_000;\n\n/** `ComputeBudgetInstruction`'s discriminants. Positional and append-only upstream. */\nconst SET_COMPUTE_UNIT_LIMIT = 2;\nconst SET_COMPUTE_UNIT_PRICE = 3;\n\n/** `[u8 discriminant, u32 units]` — five bytes. */\nconst LIMIT_ENCODER = getStructEncoder([\n ['discriminant', getU8Encoder()],\n ['units', getU32Encoder()],\n]);\n\n/** `[u8 discriminant, u64 microLamports]` — nine bytes. */\nconst PRICE_ENCODER = getStructEncoder([\n ['discriminant', getU8Encoder()],\n ['microLamports', getU64Encoder()],\n]);\n\n/** An instruction for the compute budget program: no accounts, all of it in the data. */\nexport type ComputeBudgetInstruction = Instruction<string, readonly []> &\n InstructionWithData<ReadonlyUint8Array>;\n\nexport function getSetComputeUnitLimitInstruction(units: number): ComputeBudgetInstruction {\n if (!Number.isInteger(units) || units < 0 || units > MAX_COMPUTE_UNIT_LIMIT) {\n throw new Error(\n `compute unit limit must be an integer in 0..=${MAX_COMPUTE_UNIT_LIMIT}, got ${units}`,\n );\n }\n return {\n programAddress: COMPUTE_BUDGET_PROGRAM_ADDRESS,\n accounts: [],\n data: LIMIT_ENCODER.encode({ discriminant: SET_COMPUTE_UNIT_LIMIT, units }),\n };\n}\n\n/**\n * `SetComputeUnitPrice(microLamports)` — the priority fee, per compute unit.\n *\n * No default, deliberately. The fee that lands a transaction is a property of the network at the\n * moment you send it. A hardcoded price is either money burnt on an idle chain or a transaction\n * that quietly stops landing under load. Sample `getRecentPrioritizationFees`, or take it from\n * config.\n */\nexport function getSetComputeUnitPriceInstruction(\n microLamports: number | bigint,\n): ComputeBudgetInstruction {\n const price = BigInt(microLamports);\n if (price < 0n) throw new Error(`compute unit price must not be negative, got ${price}`);\n return {\n programAddress: COMPUTE_BUDGET_PROGRAM_ADDRESS,\n accounts: [],\n data: PRICE_ENCODER.encode({ discriminant: SET_COMPUTE_UNIT_PRICE, microLamports: price }),\n };\n}\n\n/** The compute budget prefix a builder prepends: a limit, and a price only when one is asked for. */\nexport function computeBudgetInstructions(\n units: number,\n microLamports?: number | bigint,\n): ComputeBudgetInstruction[] {\n const instructions = [getSetComputeUnitLimitInstruction(units)];\n if (microLamports !== undefined) {\n instructions.push(getSetComputeUnitPriceInstruction(microLamports));\n }\n return instructions;\n}\n","/**\n * Events, and waiting for a draw to resolve.\n *\n * # Where the events are\n *\n * Anchor's `emit!` writes the event through `sol_log_data`, which the runtime renders as a log line\n * `Program data: <base64>`. So decoding an event is: find those lines, base64-decode each one,\n * match the first eight bytes against a discriminator, and hand the rest to the generated decoder.\n *\n * The design leans on this. There is no on-chain market registry, so `PoolCreated` is how a new\n * machine is discovered, and `DrawResolved` stays readable after the `Draw` account is closed and\n * its rent returned. The event is the audit trail; the account is only the pending state.\n *\n * # Waiting\n *\n * `watchDraw` subscribes to the draw account. A normal callback, retry callback, or expiry\n * delivers the prize and closes that account; the watcher then reconstructs the result from the\n * transaction's `PackBought` and `DrawResolved` events. It also accepts a legacy open `Ready`\n * account from a callback requested before automatic delivery.\n */\n\nimport {\n getBase64Encoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\n\nimport { DRAW_DISCRIMINATOR, decodeDraw, type Draw } from './generated/accounts/draw';\nimport {\n DRAW_RESOLVED_EVENT_DISCRIMINATOR,\n getDrawResolvedEventDecoder,\n type DrawResolvedEvent,\n} from './generated/events/drawResolved';\nimport {\n PACK_BOUGHT_EVENT_DISCRIMINATOR,\n getPackBoughtEventDecoder,\n type PackBoughtEvent,\n} from './generated/events/packBought';\nimport {\n POOL_CREATED_EVENT_DISCRIMINATOR,\n getPoolCreatedEventDecoder,\n type PoolCreatedEvent,\n} from './generated/events/poolCreated';\nimport {\n PRIZE_REDEEMED_EVENT_DISCRIMINATOR,\n getPrizeRedeemedEventDecoder,\n type PrizeRedeemedEvent,\n} from './generated/events/prizeRedeemed';\nimport {\n PRIZES_FUNDED_EVENT_DISCRIMINATOR,\n getPrizesFundedEventDecoder,\n type PrizesFundedEvent,\n} from './generated/events/prizesFunded';\nimport {\n RANDOMNESS_RETRIED_EVENT_DISCRIMINATOR,\n getRandomnessRetriedEventDecoder,\n type RandomnessRetriedEvent,\n} from './generated/events/randomnessRetried';\nimport {\n TOKENS_SOLD_EVENT_DISCRIMINATOR,\n getTokensSoldEventDecoder,\n type TokensSoldEvent,\n} from './generated/events/tokensSold';\nimport { GABOX_PROGRAM_ID } from './ids';\nimport { DrawStatus } from './generated/types/drawStatus';\nimport { findDrawPda } from './generated/pdas/draw';\nimport type { GaboxClient, GaboxRpc } from './rpc';\n\nexport type GaboxEvent =\n | { name: 'PoolCreated'; data: PoolCreatedEvent }\n | { name: 'PrizesFunded'; data: PrizesFundedEvent }\n | { name: 'PackBought'; data: PackBoughtEvent }\n | { name: 'RandomnessRetried'; data: RandomnessRetriedEvent }\n | { name: 'DrawResolved'; data: DrawResolvedEvent }\n | { name: 'PrizeRedeemed'; data: PrizeRedeemedEvent }\n | { name: 'TokensSold'; data: TokensSoldEvent };\n\nconst base64 = getBase64Encoder();\n\nconst startsWith = (data: Uint8Array, discriminator: ReadonlyUint8Array): boolean => {\n if (data.length < discriminator.length) return false;\n for (let i = 0; i < discriminator.length; i++) if (data[i] !== discriminator[i]) return false;\n return true;\n};\n\n/** The prefix Anchor's `emit!` produces. Anything else in the log is not an event. */\nconst PROGRAM_DATA = 'Program data: ';\n\n/** Decode one `Program data:` payload, or `null` when it is not one of ours. */\nexport function decodeEvent(data: Uint8Array): GaboxEvent | null {\n if (startsWith(data, POOL_CREATED_EVENT_DISCRIMINATOR)) {\n return { name: 'PoolCreated', data: getPoolCreatedEventDecoder().decode(data) };\n }\n if (startsWith(data, PRIZES_FUNDED_EVENT_DISCRIMINATOR)) {\n return { name: 'PrizesFunded', data: getPrizesFundedEventDecoder().decode(data) };\n }\n if (startsWith(data, PACK_BOUGHT_EVENT_DISCRIMINATOR)) {\n return { name: 'PackBought', data: getPackBoughtEventDecoder().decode(data) };\n }\n if (startsWith(data, RANDOMNESS_RETRIED_EVENT_DISCRIMINATOR)) {\n return { name: 'RandomnessRetried', data: getRandomnessRetriedEventDecoder().decode(data) };\n }\n if (startsWith(data, DRAW_RESOLVED_EVENT_DISCRIMINATOR)) {\n return { name: 'DrawResolved', data: getDrawResolvedEventDecoder().decode(data) };\n }\n if (startsWith(data, PRIZE_REDEEMED_EVENT_DISCRIMINATOR)) {\n return { name: 'PrizeRedeemed', data: getPrizeRedeemedEventDecoder().decode(data) };\n }\n if (startsWith(data, TOKENS_SOLD_EVENT_DISCRIMINATOR)) {\n return { name: 'TokensSold', data: getTokensSoldEventDecoder().decode(data) };\n }\n return null;\n}\n\n/**\n * Every gabox event in a transaction's logs, in order.\n *\n * A log line that is not `Program data:`, or whose payload matches no discriminator, is skipped\n * rather than reported. Another program in the same transaction emits its own events, and they are\n * not an error here.\n */\nexport function decodeEvents(logs: readonly string[]): GaboxEvent[] {\n const events: GaboxEvent[] = [];\n for (const line of logs) {\n if (!line.startsWith(PROGRAM_DATA)) continue;\n const payload = line.slice(PROGRAM_DATA.length).trim();\n let bytes: Uint8Array;\n try {\n bytes = new Uint8Array(base64.encode(payload));\n } catch {\n continue;\n }\n const event = decodeEvent(bytes);\n if (event) events.push(event);\n }\n return events;\n}\n\n/** Fetch a transaction and decode the gabox events it emitted. */\nexport async function fetchEvents(client: GaboxClient, signature: string): Promise<GaboxEvent[]> {\n return await readEvents(client.rpc, signature);\n}\n\n/** The RPC half of `fetchEvents`, for the internal readers that already hold one. */\nasync function readEvents(rpc: GaboxRpc, signature: string): Promise<GaboxEvent[]> {\n const transaction = await rpc\n .getTransaction(signature as never, {\n commitment: 'confirmed',\n encoding: 'json',\n maxSupportedTransactionVersion: 0,\n })\n .send();\n return decodeEvents(transaction?.meta?.logMessages ?? []);\n}\n\nexport { GABOX_PROGRAM_ID };\n\n// ─────────────────────────────────────────────────────────────────────────────\n// watchDraw\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport type WatchDrawOptions = {\n /** Stop watching. The returned promise then rejects with the abort reason. */\n signal?: AbortSignal;\n /** Called on every account change, including the ones that are still `Pending`. */\n onChange?: (draw: Draw) => void;\n};\n\n/**\n * Watch one draw and resolve when its callback delivers the prize.\n *\n * The first notification is the account as it is now, so a draw that resolved before the call\n * resolves the promise immediately. Automatic delivery closes the account, so the watcher rebuilds\n * the resolved snapshot from the purchase and resolution events when it sees that closure.\n *\n * There is no timeout here on purpose. The program's own deadline is 216,000 slots, which is about\n * a day, and a UI should decide its own patience rather than inherit one.\n */\nexport async function watchDraw(\n client: GaboxClient,\n address: Address,\n options: WatchDrawOptions = {},\n): Promise<Draw> {\n const { rpc, rpcSubscriptions } = client;\n const controller = new AbortController();\n const abort = () => controller.abort(options.signal?.reason);\n options.signal?.addEventListener('abort', abort, { once: true });\n\n try {\n const notifications = await rpcSubscriptions\n .accountNotifications(address, { encoding: 'base64', commitment: 'confirmed' })\n .subscribe({ abortSignal: controller.signal });\n\n // The subscription only fires on a change, so read the account once first. A draw that is\n // already `Ready` would otherwise wait for a notification that never comes.\n const current = await readDraw(rpc, address);\n if (current) {\n options.onChange?.(current);\n if (current.status === DrawStatus.Ready) return current;\n } else {\n const delivered = await readDeliveredDraw(rpc, address);\n if (delivered) return delivered;\n }\n\n for await (const notification of notifications) {\n const account = notification.value;\n if (!account || account.data[0] === '') {\n for (let attempt = 0; attempt < 10; attempt++) {\n const delivered = await readDeliveredDraw(rpc, address);\n if (delivered) return delivered;\n await new Promise((resolve) => setTimeout(resolve, 500));\n }\n throw new Error(`draw ${address} closed before its resolution event became readable`);\n }\n const draw = decodeDrawBytes(address, new Uint8Array(base64.encode(account.data[0])));\n options.onChange?.(draw);\n if (draw.status === DrawStatus.Ready) return draw;\n }\n throw new Error(`the subscription for draw ${address} ended before it resolved`);\n } finally {\n options.signal?.removeEventListener('abort', abort);\n controller.abort();\n }\n}\n\nfunction decodeDrawBytes(address: Address, data: Uint8Array): Draw {\n return decodeDraw({\n address,\n data,\n executable: false,\n lamports: 0n as never,\n programAddress: GABOX_PROGRAM_ID,\n space: BigInt(data.length),\n }).data;\n}\n\nasync function readDraw(rpc: GaboxRpc, address: Address): Promise<Draw | null> {\n const { value } = await rpc\n .getAccountInfo(address, { encoding: 'base64', commitment: 'confirmed' })\n .send();\n if (!value) return null;\n return decodeDrawBytes(address, new Uint8Array(base64.encode(value.data[0])));\n}\n\n/** Recover the final snapshot after automatic delivery closed the draw account. */\nasync function readDeliveredDraw(rpc: GaboxRpc, address: Address): Promise<Draw | null> {\n const signatures = await rpc\n .getSignaturesForAddress(address, { commitment: 'confirmed', limit: 10 })\n .send();\n const rows = await Promise.all(\n signatures\n .filter((row) => !row.err)\n .map(async (row) => ({\n slot: row.slot,\n events: await readEvents(rpc, row.signature),\n })),\n );\n const bought = rows.flatMap((row) =>\n row.events.flatMap((event) =>\n event.name === 'PackBought' ? [{ slot: row.slot, data: event.data }] : [],\n ),\n )[0];\n const resolved = rows.flatMap((row) =>\n row.events.flatMap((event) =>\n event.name === 'DrawResolved' ? [{ slot: row.slot, data: event.data }] : [],\n ),\n )[0];\n if (!bought || !resolved) return null;\n if (\n bought.data.pool !== resolved.data.pool ||\n bought.data.seq !== resolved.data.seq ||\n bought.data.purchaser !== resolved.data.purchaser\n ) return null;\n const [derived, bump] = await findDrawPda({ pool: bought.data.pool, seq: bought.data.seq });\n if (derived !== address) return null;\n const ticketed = bought.data.prizes.filter((prize) => prize.tickets > 0);\n if (ticketed.length === 0) return null;\n const retries = rows.flatMap((row) =>\n row.events.flatMap((event) =>\n event.name === 'RandomnessRetried' &&\n event.data.pool === bought.data.pool &&\n event.data.seq === bought.data.seq\n ? [{ slot: row.slot, attempt: event.data.attempt }]\n : [],\n ),\n );\n const lastRetry = retries.reduce<(typeof retries)[number] | null>(\n (latest, row) => !latest || row.slot > latest.slot ? row : latest,\n null,\n );\n return {\n discriminator: DRAW_DISCRIMINATOR,\n pool: bought.data.pool,\n purchaser: bought.data.purchaser,\n seq: bought.data.seq,\n bump,\n status: DrawStatus.Ready,\n requestSlot: bought.slot,\n lastAttemptSlot: lastRetry?.slot ?? bought.slot,\n attempts: lastRetry?.attempt ?? 1,\n maximum: ticketed.reduce((a, prize) => a > prize.amount ? a : prize.amount, 0n),\n minimum: ticketed.reduce((a, prize) => a < prize.amount ? a : prize.amount, ticketed[0]!.amount),\n prizes: bought.data.prizes,\n amount: resolved.data.amount,\n randomness: resolved.data.randomness,\n timedOut: resolved.data.timedOut,\n };\n}\n","/**\n * Shared devnet address lookup table, verified on 2026-09-10T13:05:37.919Z.\n * Generated by scripts/deploy-lookup-table.ts. Existing indices are immutable;\n * keep this table active while clients use it. Authority is the devnet deploy wallet.\n */\nimport { address, type Address, type AddressesByLookupTableAddress } from '@solana/kit';\n\nimport type { Cluster } from './rpc';\n\nexport const DEVNET_LOOKUP_TABLE_ADDRESS = address('Cx4ri1BU2bnDXPjnJykF3nbY2u4MD5pPvzFCJtNizWFa');\nexport const DEVNET_LOOKUP_TABLE_ADDRESSES: readonly Address[] = [\n address('GaBoxR9nYcK1zeu8EvSJVHV3SrYpCFmvbh2MLgobMcUA'),\n address('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'),\n address('TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'),\n address('ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'),\n address('6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P'),\n address('pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA'),\n address('pfeeUxB6jkeY1Hxd7CsFCAjcbHA9rWtchMGdZ6VojVZ'),\n address('11111111111111111111111111111111'),\n address('MAyhSmzXzV1pTf7LsNkrNwkWKTo4ougAJ1PPg47MD4e'),\n address('So11111111111111111111111111111111111111112'),\n address('Vrf1RNUjXmQGjmQrQLvJHs9SNkvDJEsRVFPkfSQUwGz'),\n address('Cuj97ggrhhidhbu39TijNVqE74xvKJ69gDervRUXAxGh'),\n address('SysvarS1otHashes111111111111111111111111111'),\n address('Sysvar1nstructions1111111111111111111111111'),\n address('4wTV1YmiEkRvAtNtsSGPtUrqRYQMe5SKy2uB4Jjaxnjf'),\n address('Ce6TQqeHC9p8KetsN6JsjHK7UTZk7nasjjnr7XxXp9F1'),\n address('8Wf5TiAheLUqBrKXeYg2JtAFFMWtKdG2BSFgqUcPVwTt'),\n address('Hq2wp8uJ9jCPsYgNHex8RtqdvMPfVGoYwjvF1ATiwn2Y'),\n address('TSLvdd1pWpHVjahSpsvCXUbgwsL3JAcvokwaKt1eokM'),\n address('13ec7XdrjF3h3YcqBTFDSReRcUFwbCnJaAQspM4j6DDJ'),\n address('BwWK17cbHxwWBKZkUYvzxLcNQ1YVyaFezduWbtm2de6s'),\n address('ADyA8hdefvWN2dbGGWFotbzWxrAvLW83WG6QCVXvJKqw'),\n address('GS4CU59F31iL7aR2Q8zVS8DRrcRnXX1yjQ66TqNVQnaR'),\n address('5PHirr8joyTMp9JMm6nW7hNDVyEYdkzDqazxPD7RaTjx'),\n address('C2aFPdENg4A2HQsmrd5rTw5TaYBX5Ku887cWjbFKtZpw'),\n address('7ahYg76P8bhifT1Uj3hNHGKRFPp6bLkx1ppNrWbnsfu2'),\n address('68yFSZxzLWJXkxxRGydZ63C6mHx1NLEDWmwN9Lb5yySg'),\n address('DLP9ADYpdQV4Z4UQDZof7iLHu2qqdzmMPjcAHDGe4jTt'),\n address('6QgPshH1egekJ2TURfakiiApDdv98qfRuRe7RectX8xs'),\n address('FmFPTNDmmVDhqzaqZYhnt4fj5fJP3pffcMWf2b5JnRTk'),\n address('78i5hpHxbtmosSJdfJ74WzwdUr3eKWg9RbCPpBeAF78t'),\n address('7611SPS3UkjsA43auxPpJpPVAkgEHg4dTVorK839GonW'),\n address('8RMFYhsVsfdGCuWPFLxMCbSpSesiofabDdNorGqFrBNe'),\n address('9GbQXDFHKLdr4BzZ8Cx2pkX2aM2Kg7yEeYnUCKjZGE4M'),\n address('9GDepfBcjJMvNgmijXWVWa97Am7VZYCqXx7kJV44E9ij'),\n address('3fyMEgHADGRrBnCVLU7u9AwpiMtmGDWViJzDQC8kgRa5'),\n address('9ppkS5madL2uXozoEnMnZi5bKDq9jgdKkSavjWTS5NfW'),\n address('C3PvwRFdKT6caSLxnwy8h67KWNevoboNDg6bwJZYzWB5'),\n address('DDMCfwbcaNYTeMk1ca8tr8BQKFaUfFCWFwBJq8JcnyCw'),\n address('FrYoobDtL7w1HrTjHAc8Ya7qQzEdJPhGXXFKskCDaA3p'),\n address('DRDBsRMst21CJUhwD16pncgiXnBrFaRAPvA2G6SUQceE'),\n address('J7JbDVnGKus2M9PKzH7ZbeCYugEYDgpGBfqKL85dQbU7'),\n address('5YxQFdt3Tr9zJLvkFccqXVUwhdTWJQc1fFg2YPbxvxeD'),\n address('HjQjngTDqoHE6aaGhUqfz9aQ7WZcBRjy5xB8PScLSr8i'),\n address('9M4giFFMxmFGXtc3feFzRai56WbBqehoSeRE5GK7gf7'),\n address('GAFuhgcd328SkkBYHpfadzmef9hTGAFRCi9QoCnsZQug'),\n address('GXPFM2caqTtQYC2cJ5yJRi9VDkpsYZXzYdwYpGnLmtDL'),\n address('AktftA98kSWAxn6kVSoqBXBELUArjKu2H9WmKB48ULFY'),\n address('3BpXnfJaUTiwXnJNe7Ej1rcbzqTTQUvLShZaWazebsVR'),\n address('6rVkF4HSgy1jrnC3HogfRgPHrq4CtLg5f11URpsC4i9D'),\n address('5cjcW9wExnJJiqgLjq7DEG75Pm6JBgE1hNv4B2vHXUW6'),\n address('GYH1Gae1wJytMSvMvw8JVcv7nuAbxi8i9erNVbERnzXd'),\n address('EHAAiTxcdDwQ3U4bU6YcMsQGaekdzLS3B5SmYo46kJtL'),\n address('CA7v8gHfbquYXyDnDx6QxWW8hmL1H7X6Y2RYDrGLnuck'),\n address('5eHhjP8JaYkz83CWwvGU2uMUXefd3AazWGx4gpcuEEYD'),\n address('CASRL2zkwDnppxEFQ4LgdwgR9pdz5Q8R8nEMKVZ9QoLp'),\n address('A7hAgCzFw14fejgCp387JUJRMNyz4j89JKnhtKU8piqW'),\n address('qkYdTGRPHbWTWuBMz45bCiU6a23axRqf6sBHm9295WY'),\n address('12e2F4DKkD3Lff6WPYsU7Xd76SHPEyN9T8XSsTJNF8oT'),\n address('GjJkcak9e4L2HsxSZqVsc81L7coChdR7F3ciJYnQcSnU'),\n address('2Ej38XSkmpvXzoUg5ZLma7Y9rCiZVgxzTdvE3Kph5juM'),\n address('2daQRytJgLzLLziPNQBNJ7w1Ltz3XqZG4dZxBamLAf7v'),\n address('3PAxmkxnM2vHno9amWQCsaaFjYnPGcD87HZGx1ChVjPj'),\n address('BWS634asUFdrpYpfofFA1CrGB9wEbh9gt8XswZ4AWz9J'),\n address('4QZqaBNm2F7viBDhhs8AQ5wC9FshgLJEiLLFGoxZZrTn'),\n address('4JaPhJE7WgQZ3xFbxn2spU97reA13SiM99wD3RF4Lqro'),\n address('9xvDPD6G7NRCEu7W2M9vCLeo8we23Ww7pzQEhXcuJAmA'),\n address('AHEgRGXFn8JbhXccWM4i1meRGPFbx8kzb9BGN6ocqRFL'),\n address('CdkG7sp1LT9YLsDaTWREaQcX6W4gZySk3o1eSjoL2uTh'),\n address('2pLUmsYktT7gR6P5hXs9Ldo6Vg1oQB2Q4NPbJqHUjZhq'),\n address('Freijj9xKLefjrb5fHgT6KMbYG1XBP2mA83tqeXYUMYM'),\n address('4uzPz9TPskXiiEZ6X78rqud8LvfdxkJBr5EKHgbx4azP'),\n address('Hxzab4UjjVH2KjsdAqzdxGdYUpNN5FKhpu7iikB869uH'),\n address('Frkwunr9dQM9d4TthfQ2unxC994XpkLMpkRP2e7yfirk'),\n];\nexport const DEVNET_ADDRESS_LOOKUP_TABLES: AddressesByLookupTableAddress = {\n [DEVNET_LOOKUP_TABLE_ADDRESS]: [...DEVNET_LOOKUP_TABLE_ADDRESSES],\n};\n\n/**\n * The tables a client compresses with when its config names none.\n *\n * Only devnet has a shared table today. Mainnet gets one when the program is deployed there; until\n * then a mainnet or localnet client compresses with nothing, and a message over 1,232 bytes fails\n * in `buildMessage` with a request for tables. Pass `addressLookupTables` to `createClient` to\n * supply your own.\n */\nexport function defaultAddressLookupTables(cluster: Cluster): AddressesByLookupTableAddress {\n return cluster === 'devnet' ? { ...DEVNET_ADDRESS_LOOKUP_TABLES } : {};\n}\n","/**\n * What one pack costs and what it can win, right now, for a real coin.\n *\n * This is the read every buyer-facing screen makes. It puts three things together that are useless\n * apart:\n *\n * 1. the venue's own quote — what `pool.packTokens` costs at this moment, fees included;\n * 2. `math.quote` over the pack size and the vault's live inventory — the exact prize amounts\n * `buy_pack` would freeze into the `Draw`;\n * 3. whether the pool can pay the whole table.\n *\n * The prize amounts only move when the inventory cap bites. The price moves with the coin.\n * Nothing here is an estimate of cash value. Every number is tokens or lamports.\n */\n\nimport type { Address } from '@solana/kit';\n\nimport { fetchPoolInventory, tiersOf, type PoolInventory } from './accounts';\nimport { PROTOCOL_FEE_BPS } from './ids';\nimport {\n averageMultiplierBps,\n maxMultiplierBps,\n quote,\n seedTokens,\n share,\n uncappedMaximum,\n type Offer,\n type Prize,\n} from './math';\nimport { resolveVenue, type VenueKind } from './pump/venue';\nimport type { GaboxClient } from './rpc';\n\nexport type PackOffer = {\n mint: Address;\n pool: Address;\n /** The fixed token count of one pack. Every prize is a multiple of this. */\n packTokens: bigint;\n /** What the venue charges for `packTokens` right now, its own fees included. The pack price. */\n quoteLamports: bigint;\n /** The creator's fee, in bps of `quoteLamports`. */\n feeBps: number;\n /** The creator's fee at this price, paid on top of `quoteLamports`. */\n feeLamports: bigint;\n /** The protocol's 1% of `quoteLamports`, also paid on top. */\n protocolLamports: bigint;\n /** What the seed cost the creator at creation. Display only. */\n seedLamports: bigint;\n /** Tokens the seed locked in the vault: `(maxMultiplier - 1x)` packs. */\n seedTokens: bigint;\n /** Which venue the buy would route to right now. */\n venue: VenueKind;\n /** The frozen prize table this pack would get: real amounts, already capped by inventory. */\n prizes: Prize[];\n /** The top prize, after the cap. Sign `minMaximum` just below this. */\n maximum: bigint;\n /** The smallest prize. Also what a timed-out draw pays. */\n minimum: bigint;\n /** The top prize with no inventory cap: the jackpot in tokens. Equal to `maximum` unless the\n * inventory cap bites. */\n uncapped: bigint;\n /** Vault balance, `pool.reserved`, and the difference. */\n inventory: bigint;\n reserved: bigint;\n free: bigint;\n /** `pool.nextSeq === 0`. No pack has been sold yet. */\n isFirstPack: boolean;\n /**\n * Does the pool pay the whole table right now?\n *\n * `offer.maximum === uncapped`. The seed guarantees this for the first pack. Later it is a\n * quality signal: a capped top prize is legal and the pool still sells the pack. It just pays\n * less than the table says, and a buyer should see that.\n */\n isSeeded: boolean;\n /** The largest and the ticket-weighted average multiplier of the immutable table, in bps. */\n maxMultiplierBps: number;\n averageMultiplierBps: number;\n};\n\nexport type GetOfferOptions = {\n /** Force a venue instead of reading the bonding curve's `complete` flag. */\n venue?: VenueKind;\n /** The buyer, when you already know it. Only changes the account list, never the numbers. */\n user?: Address;\n};\n\n/**\n * The full offer for one machine. Two round trips: the pool and its vault, then the venue.\n *\n * Throws when the coin has no pool.\n */\nexport async function getOffer(\n client: GaboxClient,\n mint: Address,\n options: GetOfferOptions = {},\n): Promise<PackOffer> {\n const inventory = await fetchPoolInventory(client, mint);\n if (!inventory) throw new Error(`no gabox pool for mint ${mint}`);\n\n const venue = await resolveVenue(client, {\n mint,\n user: options.user ?? inventory.pool.creator,\n ...(options.venue ? { venue: options.venue } : {}),\n });\n\n return offerFromState(inventory, venue.kind, venue.quoteBuy(inventory.pool.packTokens));\n}\n\n/**\n * The same computation with the reads already done. Useful when a caller holds a `ResolvedVenue`\n * and wants to re-price without touching the network. `quoteLamports` is\n * `venue.quoteBuy(pool.packTokens)`.\n */\nexport function offerFromState(\n inventory: PoolInventory,\n venue: VenueKind,\n quoteLamports: bigint,\n): PackOffer {\n const { pool } = inventory;\n const tiers = tiersOf(pool);\n const offer: Offer = quote(pool.packTokens, tiers, inventory.inventory, inventory.reserved);\n const uncapped = uncappedMaximum(pool.packTokens, tiers);\n\n return {\n mint: pool.mint,\n pool: inventory.poolAddress,\n packTokens: pool.packTokens,\n quoteLamports,\n feeBps: pool.feeBps,\n feeLamports: share(quoteLamports, BigInt(pool.feeBps)),\n protocolLamports: share(quoteLamports, PROTOCOL_FEE_BPS),\n seedLamports: pool.seedLamports,\n seedTokens: pool.seedTokens,\n venue,\n prizes: offer.prizes,\n maximum: offer.maximum,\n minimum: offer.minimum,\n uncapped,\n inventory: inventory.inventory,\n reserved: inventory.reserved,\n free: inventory.free,\n isFirstPack: pool.nextSeq === 0n,\n isSeeded: offer.maximum === uncapped,\n maxMultiplierBps: maxMultiplierBps(tiers),\n averageMultiplierBps: averageMultiplierBps(tiers),\n };\n}\n\n/**\n * How short of the top prize a pool is, in tokens. `0` when it pays the whole table.\n *\n * The pack brings its own `packTokens` into the vault before the offer is computed, so the vault\n * only has to hold `uncapped - packTokens` beforehand. Anything already reserved by another draw\n * does not count. A donation of this size through `fund_prizes` uncaps the top prize again.\n */\nexport function seedShortfall(offer: PackOffer): bigint {\n const needed = offer.uncapped > offer.packTokens ? offer.uncapped - offer.packTokens : 0n;\n return offer.free >= needed ? 0n : needed - offer.free;\n}\n\nexport { seedTokens };\n","/**\n * The client, and the cluster guard.\n *\n * `createClient` is the SDK's init step. It takes the cluster and the RPC endpoint once and returns\n * one object that every other chain-touching function in this SDK takes as its first argument: the\n * RPC, the subscriptions client, and the address lookup tables that cluster compresses with.\n *\n * # Why `cluster` has no default\n *\n * v1's simulator was one empty wallet away from running against mainnet. Nothing in the code said\n * which cluster it was pointed at; the answer lived in a shell variable and in the operator's head.\n * The failure would not have been a crash. It would have been real transactions on real money,\n * discovered afterwards.\n *\n * So the cluster is a property of the code, not of the environment. The caller names it in the\n * same call that names the URL, and the two are checked against each other:\n *\n * - `devnet` needs a URL that names devnet. A URL that names nothing is refused too, because\n * \"I thought this was devnet\" is exactly the accident this guard exists for.\n * - `mainnet-beta` and `localnet` refuse a URL that names a different cluster. A URL that names\n * nothing is allowed: private mainnet endpoints often do not say \"mainnet\", and a local\n * validator never says anything.\n *\n * Mainnet is one word away. It is a word the caller has to write.\n */\n\nimport {\n createSolanaRpc,\n createSolanaRpcSubscriptions,\n type AddressesByLookupTableAddress,\n type Rpc,\n type RpcSubscriptions,\n type SolanaRpcApi,\n type SolanaRpcSubscriptionsApi,\n} from '@solana/kit';\n\nimport { defaultAddressLookupTables } from './lookupTables';\n\nexport type Cluster = 'devnet' | 'mainnet-beta' | 'localnet';\n\n/** Solana's public endpoints, and the test validator's default ports. */\nexport const CLUSTER_ENDPOINTS: Readonly<Record<Cluster, { url: string; wsUrl: string }>> = {\n devnet: { url: 'https://api.devnet.solana.com', wsUrl: 'wss://api.devnet.solana.com' },\n 'mainnet-beta': {\n url: 'https://api.mainnet-beta.solana.com',\n wsUrl: 'wss://api.mainnet-beta.solana.com',\n },\n localnet: { url: 'http://127.0.0.1:8899', wsUrl: 'ws://127.0.0.1:8900' },\n};\n\nexport const DEVNET_HTTP = CLUSTER_ENDPOINTS.devnet.url;\nexport const DEVNET_WS = CLUSTER_ENDPOINTS.devnet.wsUrl;\n\nexport type GaboxRpc = Rpc<SolanaRpcApi>;\nexport type GaboxRpcSubscriptions = RpcSubscriptions<SolanaRpcSubscriptionsApi>;\n\nexport type ClientConfig = {\n /** The cluster this client talks to. Required: see the file comment. */\n cluster: Cluster;\n /** HTTP endpoint. Defaults to the cluster's entry in `CLUSTER_ENDPOINTS`. */\n url?: string;\n /**\n * WebSocket endpoint. Left out, it follows `url`: `https` becomes `wss`, `http` becomes `ws`.\n * When `url` is left out too, it is the cluster's default.\n */\n wsUrl?: string;\n /**\n * Address lookup tables every builder compresses with. Defaults to the cluster's shared table,\n * which only devnet has today; other clusters default to none. Pass `{}` to disable compression.\n */\n addressLookupTables?: AddressesByLookupTableAddress;\n};\n\n/**\n * Everything the SDK needs to talk to one cluster. Pass it to every chain-touching function.\n *\n * A plain object, so a caller who needs a custom transport can spread it:\n * `{ ...createClient({ cluster }), rpc: createSolanaRpcFromTransport(transport) }`.\n */\nexport type GaboxClient = Readonly<{\n cluster: Cluster;\n url: string;\n wsUrl: string;\n rpc: GaboxRpc;\n rpcSubscriptions: GaboxRpcSubscriptions;\n addressLookupTables: AddressesByLookupTableAddress;\n}>;\n\n/**\n * The cluster a URL names, from its text alone. A substring check, deliberately: providers spell\n * it many ways. `null` when the URL names none, which is a local validator or a private endpoint.\n */\nexport function clusterNamedBy(url: string): Cluster | 'testnet' | null {\n const lower = url.toLowerCase();\n if (lower.includes('devnet')) return 'devnet';\n if (lower.includes('mainnet')) return 'mainnet-beta';\n if (lower.includes('testnet')) return 'testnet';\n return null;\n}\n\n/**\n * Refuse a URL that contradicts the declared cluster. Exported so a script can check a URL before\n * it does anything else with it. The rules are in the file comment.\n */\nexport function assertClusterUrl(cluster: Cluster, url: string): void {\n const named = clusterNamedBy(url);\n if (cluster === 'devnet' && named !== 'devnet') {\n throw new Error(\n `refusing to use ${url} as a devnet endpoint: it does not name devnet.\\n` +\n 'Every address in this SDK — the Pump programs, the MagicBlock queue, the pools — exists ' +\n 'on every cluster, so a wrong URL is a live transaction, not an error. Pass ' +\n \"{ cluster: 'localnet' } for a local validator, or name the cluster the URL really is.\",\n );\n }\n if (cluster !== 'devnet' && named !== null && named !== cluster) {\n throw new Error(\n `refusing to use ${url} as a ${cluster} endpoint: the URL names ${named}.\\n` +\n 'Every address in this SDK exists on every cluster, so a wrong URL is a live transaction, ' +\n 'not an error. Pass the cluster the URL really names.',\n );\n }\n}\n\n/** `https://x` becomes `wss://x`, `http://x` becomes `ws://x`. Anything else is returned as is. */\nexport function websocketUrlFor(url: string): string {\n if (url.startsWith('https://')) return `wss://${url.slice('https://'.length)}`;\n if (url.startsWith('http://')) return `ws://${url.slice('http://'.length)}`;\n return url;\n}\n\n/**\n * The SDK's init step. Call it once and pass the result everywhere.\n *\n * Both RPC clients are created together because everything in this SDK that watches a draw needs\n * the pair: the subscription reports the change, and the RPC reads the account that changed.\n */\nexport function createClient(config: ClientConfig): GaboxClient {\n const { cluster } = config;\n const defaults = CLUSTER_ENDPOINTS[cluster];\n if (!defaults) {\n throw new Error(\n `unknown cluster ${JSON.stringify(cluster)}; expected 'devnet', 'mainnet-beta' or 'localnet'`,\n );\n }\n\n const url = config.url ?? defaults.url;\n assertClusterUrl(cluster, url);\n\n // A custom `url` without a `wsUrl` gets the same host over WebSocket. The cluster's default\n // pair is only used as a pair: the test validator serves WebSocket on a different port.\n const wsUrl = config.wsUrl ?? (config.url === undefined ? defaults.wsUrl : websocketUrlFor(url));\n assertClusterUrl(cluster, wsUrl);\n\n return {\n cluster,\n url,\n wsUrl,\n rpc: createSolanaRpc(url),\n rpcSubscriptions: createSolanaRpcSubscriptions(wsUrl),\n addressLookupTables: config.addressLookupTables ?? defaultAddressLookupTables(cluster),\n };\n}\n","/**\n * Assembling a transaction message.\n *\n * Every builder in this directory ends here: compute budget first, then the program instructions,\n * with a fee payer and a blockhash lifetime. The result is a message a wallet can sign and send —\n * nothing in this SDK signs or sends anything itself.\n */\n\nimport {\n appendTransactionMessageInstructions,\n compileTransaction,\n compressTransactionMessageUsingAddressLookupTables,\n createTransactionMessage,\n getTransactionEncoder,\n pipe,\n setTransactionMessageFeePayerSigner,\n setTransactionMessageLifetimeUsingBlockhash,\n type AddressesByLookupTableAddress,\n type Instruction,\n type TransactionMessage,\n type TransactionMessageWithBlockhashLifetime,\n type TransactionMessageWithFeePayerSigner,\n type TransactionSigner,\n} from '@solana/kit';\n\nimport { computeBudgetInstructions } from '../compute';\nimport type { GaboxClient } from '../rpc';\n\n/**\n * What every builder returns: a version 0 message with a fee-payer signer and a blockhash\n * lifetime, ready for `signTransactionMessageWithSigners`.\n *\n * Named, and built only from types `@solana/kit` exports, so the published declaration file\n * refers to kit's types instead of copying them. `pipe`'s inferred type is a long intersection\n * of kit-internal brands, and a copy of a branded type is not assignable to the original.\n */\nexport type GaboxTransactionMessage = Extract<TransactionMessage, { version: 0 }> &\n TransactionMessageWithFeePayerSigner &\n TransactionMessageWithBlockhashLifetime;\n\nexport type BuildOptions = {\n /** Compute units to request. Each builder passes its own default. */\n computeUnitLimit: number;\n /** Priority fee in micro-lamports per compute unit. Left out, no price instruction is added. */\n computeUnitPrice?: number | bigint;\n /** Defaults to the client's tables, which the cluster chose. Pass `{}` to disable compression. */\n addressLookupTables?: AddressesByLookupTableAddress;\n};\n\n/**\n * Build the message. One RPC read, for the blockhash.\n *\n * The blockhash expires in about a minute, so build the message when the user is ready to sign\n * rather than when the page loads.\n */\nexport async function buildMessage(\n client: GaboxClient,\n feePayer: TransactionSigner,\n instructions: Instruction[],\n options: BuildOptions,\n): Promise<GaboxTransactionMessage> {\n const { value: latestBlockhash } = await client.rpc\n .getLatestBlockhash({ commitment: 'confirmed' })\n .send();\n\n const budget = computeBudgetInstructions(\n options.computeUnitLimit,\n options.computeUnitPrice,\n ) as unknown as Instruction[];\n\n const message = pipe(\n createTransactionMessage({ version: 0 }),\n (m) => setTransactionMessageFeePayerSigner(feePayer, m),\n (m) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, m),\n (m) => appendTransactionMessageInstructions([...budget, ...instructions], m),\n (m) => compressTransactionMessageUsingAddressLookupTables(\n m,\n options.addressLookupTables ?? client.addressLookupTables,\n ),\n );\n const size = getTransactionEncoder().encode(compileTransaction(message)).length;\n if (size > 1232) {\n throw new Error(`Transaction is ${size} bytes; Solana allows 1232. Shorten metadata or supply additional address lookup tables.`);\n }\n return message;\n}\n\n/** Append `remainingAccounts` to a generated instruction, which is how a venue's list is passed. */\nexport function withRemainingAccounts<T extends Instruction>(\n instruction: T,\n remaining: readonly NonNullable<T['accounts']>[number][],\n): T {\n return {\n ...instruction,\n accounts: [...(instruction.accounts ?? []), ...remaining],\n };\n}\n","import type { Address, Instruction, TransactionSigner } from '@solana/kit';\n\nimport { fetchMaybeReferralLink } from './generated/accounts/referralLink';\nimport { getBindReferrerInstructionAsync } from './generated/instructions/bindReferrer';\nimport { getClaimReferralInstructionAsync } from './generated/instructions/claimReferral';\nimport { referralAddress, referralLinkAddress } from './pdas';\nimport type { GaboxClient } from './rpc';\nimport { buildMessage, type BuildOptions } from './tx/message';\n\nexport type ReferralResolution = Readonly<{\n link: Address;\n referrer: Address;\n referral: Address;\n}>;\n\n/** Resolve the purchaser's permanent referral binding for a pack purchase. */\nexport async function resolveReferral(\n client: GaboxClient,\n purchaser: Address,\n pool: Address,\n): Promise<ReferralResolution | null> {\n const link = await referralLinkAddress(purchaser);\n const account = await fetchMaybeReferralLink(client.rpc, link, { commitment: 'confirmed' });\n if (!account.exists) return null;\n const referrer = account.data.referrer;\n return { link, referrer, referral: await referralAddress(pool, referrer) };\n}\n\n/** Bind a wallet to a referrer. The purchaser signs and the binding is permanent. */\nexport async function bindReferrer(\n client: GaboxClient,\n referee: TransactionSigner,\n referrer: Address,\n options: Partial<BuildOptions> = {},\n) {\n const ix = await getBindReferrerInstructionAsync({ referee, referrer });\n return await buildMessage(client, referee, [ix as Instruction], {\n addressLookupTables: options.addressLookupTables,\n computeUnitLimit: options.computeUnitLimit ?? 80_000,\n ...(options.computeUnitPrice === undefined ? {} : { computeUnitPrice: options.computeUnitPrice }),\n });\n}\n\n/** Claim all accrued referral rewards for one pool. */\nexport async function claimReferral(\n client: GaboxClient,\n referrer: TransactionSigner,\n pool: Address,\n options: Partial<BuildOptions> = {},\n) {\n const ix = await getClaimReferralInstructionAsync({ referrer, pool });\n return await buildMessage(client, referrer, [ix as Instruction], {\n addressLookupTables: options.addressLookupTables,\n computeUnitLimit: options.computeUnitLimit ?? 80_000,\n ...(options.computeUnitPrice === undefined ? {} : { computeUnitPrice: options.computeUnitPrice }),\n });\n}\n","/**\n * Buying a pack.\n *\n * One instruction does the whole thing: buy exactly `pool.packTokens` at the venue, move the\n * tokens into gabox custody, freeze a prize table into a new `Draw`, pay the creator's fee and\n * the protocol's 1% of the venue cost, and ask MagicBlock for randomness. Either all of it happens\n * or none of it does.\n *\n * # The three numbers the buyer signs\n *\n * `maxQuoteIn` is the slippage cap at the venue, in lamports (WSOL on PumpSwap). The token count\n * is fixed by the pool, so the cost is the only thing that moves. Set it from `offer.quoteLamports`\n * plus a margin, for example 2%.\n *\n * `minMaximum` is a floor on the top prize, in tokens. The table is fixed, so only an inventory\n * cap can lower it. Set it from `offer.maximum`.\n *\n * `maxTotalDebit` caps the venue debit plus the creator fee plus the protocol fee plus the VRF\n * request, measured in SOL and WSOL together. Both fees are a share of the venue debit, so budget\n * them from `maxQuoteIn`. It does **not** cover the rent Anchor pays for the `Draw` and any ATA it\n * creates, nor the transaction fee: the runtime charges those before the handler runs. Budget for\n * them separately.\n *\n * # PumpSwap needs WSOL first\n *\n * On the curve, Pump spends native SOL. On PumpSwap the quote is a classic WSOL token account, so\n * the buyer's WSOL ATA must exist and hold enough before the pack instruction runs. This builder\n * adds the create/fund/sync instructions when the route is PumpSwap. They are the buyer's own\n * instructions, signed by the buyer, and gabox never touches that account.\n */\n\nimport {\n getCreateAssociatedTokenIdempotentInstruction,\n getSyncNativeInstruction,\n TOKEN_PROGRAM_ADDRESS as SPL_TOKEN_PROGRAM_ADDRESS,\n} from '@solana-program/token';\nimport { getTransferSolInstruction } from '@solana-program/system';\nimport type { Address, Instruction, TransactionSigner } from '@solana/kit';\n\nimport { fetchPoolInventory } from '../accounts';\nimport { resolveReferral } from '../referral';\nimport { BIND_REFERRER_COMPUTE_UNITS, BUY_PACK_COMPUTE_UNITS } from '../compute';\nimport { getBindReferrerInstructionAsync } from '../generated/instructions/bindReferrer';\nimport { getBuyPackInstruction } from '../generated/instructions/buyPack';\nimport { WSOL_MINT } from '../ids';\nimport { drawAddress, referralAddress, referralLinkAddress, vrfIdentityAddress } from '../pdas';\nimport { swapCashbackAccount } from '../pump/accounts';\nimport { resolveVenue, wsolAccountFor, type VenueKind } from '../pump/venue';\nimport type { GaboxClient } from '../rpc';\nimport { buildMessage, withRemainingAccounts, type BuildOptions } from './message';\n\nexport type BuyPackInput = {\n mint: Address;\n /** Pays for everything and signs. Becomes `draw.purchaser`. */\n purchaser: TransactionSigner;\n /** Slippage cap on the venue trade, in lamports (WSOL on PumpSwap). Must be positive. */\n maxQuoteIn: bigint;\n /** Floor on the top prize, in tokens. */\n minMaximum: bigint;\n /** Cap on venue debit + creator fee + protocol fee + VRF request, in lamports. Rent and tx fee\n * are extra. */\n maxTotalDebit: bigint;\n /** Force a venue. Left out, the bonding curve's `complete` flag decides. */\n venue?: VenueKind;\n /**\n * Pin the draw's sequence number instead of reading `pool.nextSeq` now.\n *\n * The draw's address is `[\"draw\", pool, seq]`, so a caller that has already told somebody which\n * draw this purchase will create has to keep that promise if it rebuilds the message - after a\n * stale blockhash, say. Rebuilding without a pin reads `nextSeq` again, and if the first attempt\n * actually landed, the second one buys a **second pack** at the next sequence number rather than\n * failing. With the pin it fails on the `init` constraint, which is the right outcome.\n */\n seq?: bigint;\n /**\n * Lamports to wrap into the buyer's WSOL account on the PumpSwap route. Left out, the builder\n * wraps `maxQuoteIn`: the venue never takes more than that, and any surplus stays in the buyer's\n * own WSOL account.\n */\n wrapLamports?: bigint;\n /** Append PumpSwap's optional cashback account. Only for a cashback coin. */\n cashback?: boolean;\n /**\n * A referrer to bind before the purchase, in the same transaction.\n *\n * A share link leaves the referrer's wallet in a cookie, and the first pack is where it matters:\n * `bind_referrer` runs one instruction ahead of `buy_pack`, so the pack that converts the buyer\n * is the pack that pays. Ignored when the buyer already has a link (the chain wins), when it\n * names the buyer, or when it is the all-zero address. The link's rent is extra, on top of\n * `maxTotalDebit`.\n */\n referrer?: Address;\n} & Partial<BuildOptions>;\n\nexport async function buyPack(client: GaboxClient, input: BuyPackInput) {\n const { mint, purchaser } = input;\n if (input.maxQuoteIn <= 0n) throw new Error('maxQuoteIn must be positive');\n\n const inventory = await fetchPoolInventory(client, mint);\n if (!inventory) throw new Error(`no gabox pool for mint ${mint}`);\n const { pool, poolAddress } = inventory;\n\n const venue = await resolveVenue(client, {\n mint,\n user: purchaser.address,\n ...(input.venue ? { venue: input.venue } : {}),\n });\n\n // `pool.nextSeq` is read now and used as the draw's seed, unless the caller pinned one. Another\n // buyer landing first makes this address wrong and the transaction fails on the `init`\n // constraint — which is the right outcome: two buyers must not share a draw.\n const seq = input.seq ?? pool.nextSeq;\n const draw = await drawAddress(poolAddress, seq);\n let referral = await resolveReferral(client, purchaser.address, poolAddress);\n let bind: Instruction | null = null;\n if (referral === null && input.referrer && canBind(purchaser.address, input.referrer)) {\n const referrer = input.referrer;\n bind = (await getBindReferrerInstructionAsync({ referee: purchaser, referrer })) as Instruction;\n // `resolveReferral` cannot answer here: the link does not exist yet. The bind one instruction\n // earlier in this very transaction creates it, so the accounts are derived by hand.\n referral = {\n link: await referralLinkAddress(purchaser.address),\n referrer,\n referral: await referralAddress(poolAddress, referrer),\n };\n }\n\n const buy = getBuyPackInstruction({\n purchaser,\n pool: poolAddress,\n creator: pool.creator,\n draw,\n mint,\n vault: pool.vault,\n userTokens: venueUserTokens(venue.buyAccounts, venue.kind),\n venue: venue.program,\n identity: await vrfIdentityAddress(),\n tokenProgram: pool.tokenProgram,\n maxQuoteIn: input.maxQuoteIn,\n minMaximum: input.minMaximum,\n maxTotalDebit: input.maxTotalDebit,\n referralLink: referral?.link,\n referral: referral?.referral,\n });\n\n const remaining = input.cashback\n ? [...venue.buyAccounts, swapCashbackAccount(purchaser.address)]\n : venue.buyAccounts;\n\n const instructions: Instruction[] = [\n ...(bind === null ? [] : [bind]),\n ...(venue.kind === 'pumpswap'\n ? wsolPreparation(purchaser, input.wrapLamports ?? input.maxQuoteIn)\n : []),\n withRemainingAccounts(buy as Instruction, remaining),\n ];\n\n return await buildMessage(client, purchaser, instructions, {\n addressLookupTables: input.addressLookupTables,\n computeUnitLimit:\n input.computeUnitLimit ??\n BUY_PACK_COMPUTE_UNITS + (bind === null ? 0 : BIND_REFERRER_COMPUTE_UNITS),\n ...(input.computeUnitPrice === undefined ? {} : { computeUnitPrice: input.computeUnitPrice }),\n });\n}\n\n/** The default `Pubkey`: all zero bytes. `bind_referrer` refuses a link pointing at it. */\nconst NO_REFERRER = '11111111111111111111111111111111' as Address;\n\n/**\n * The program refuses a self-referral and a link to the all-zero address. Both would take the\n * pack down with them, so the bind is skipped instead and the pack goes through unreferred.\n */\nfunction canBind(purchaser: Address, referrer: Address): boolean {\n return referrer !== purchaser && referrer !== NO_REFERRER;\n}\n\n/**\n * The purchaser's base-token ATA, taken out of the venue account list rather than re-derived.\n *\n * `market.rs` requires `user_tokens` to equal the venue list's own `associated_base_user` (Pump) or\n * `user_base_token_account` (PumpSwap). Reading it back from the list makes the two agree by\n * construction instead of by two derivations that happen to match.\n */\nfunction venueUserTokens(accounts: readonly { address: Address }[], kind: VenueKind): Address {\n // Pump: index 14 is `associated_base_user`. PumpSwap: index 5 is `user_base_token_account`.\n const index = kind === 'pump' ? 14 : 5;\n const account = accounts[index];\n if (!account) throw new Error(`the ${kind} account list is too short`);\n return account.address;\n}\n\n/**\n * Create the buyer's WSOL account if needed, fund it, and sync its balance.\n *\n * `SyncNative` is the step people forget. A plain SOL transfer into a WSOL account raises its\n * lamports but not the `amount` field the token program reads, so the venue sees an empty account\n * until this instruction copies one to the other.\n */\nfunction wsolPreparation(purchaser: TransactionSigner, lamports: bigint): Instruction[] {\n const wsol = wsolAccountFor(purchaser.address);\n return [\n getCreateAssociatedTokenIdempotentInstruction({\n payer: purchaser,\n ata: wsol,\n owner: purchaser.address,\n mint: WSOL_MINT,\n tokenProgram: SPL_TOKEN_PROGRAM_ADDRESS,\n }) as Instruction,\n getTransferSolInstruction({ source: purchaser, destination: wsol, amount: lamports }) as Instruction,\n getSyncNativeInstruction({ account: wsol }) as Instruction,\n ];\n}\n","/**\n * Creating a machine: one transaction, two instructions, two signers.\n *\n * # Why it has to be one transaction\n *\n * `initialize_pool` reads the Instructions sysvar and refuses to run unless the same transaction\n * also carries a Pump `create_v2` for the same mint, signed by the same creator. That is what makes\n * \"one pool per coin\" true and stops anyone wrapping an existing coin in a machine. The create must\n * come **first**: the mint account has to exist and deserialize before Anchor validates\n * `initialize_pool`'s accounts.\n *\n * # The seed\n *\n * The creator owns none of the coin yet — it does not exist until this transaction runs. So\n * `initialize_pool` buys the seed on the curve itself, into the creator's own ATA, and moves it\n * straight into the vault. The Pump buy accounts ride along as `remainingAccounts`, in the same\n * order `buy_pack` uses.\n *\n * The seed follows from the tier table. The program accepts any table that passes `math::validate`;\n * it does not enforce one table. A creator may pass their own `tiers`; the default is\n * `DEFAULT_TIERS`. The program buys exactly `largestTierAmount - PACK_TOKENS` tokens as the seed,\n * so the first pack can pay the top tier in full. The creator only signs a maximum SOL cost for\n * that buy. The seed buy moves the curve, so a bigger jackpot means a slightly higher starting\n * pack price. A fresh Pump curve only holds so many tokens (`Global.initialRealTokenReserves`),\n * so a table whose seed exceeds that cannot be created; `createMachine` and `seedCostEstimate`\n * both check this before spending anything.\n *\n * # Two signers\n *\n * The mint keypair signs `create_v2` — Pump takes it as a signer rather than deriving it — and the\n * creator signs both instructions and pays for everything.\n */\n\nimport {\n getBase64Encoder,\n type AccountMeta,\n type Address,\n type Instruction,\n type TransactionSigner,\n} from \"@solana/kit\";\n\nimport { CREATE_MACHINE_COMPUTE_UNITS } from \"../compute\";\nimport { getInitializePoolInstructionAsync } from \"../generated/instructions/initializePool\";\nimport {\n PUMP_CREATE_TOKEN_PROGRAM_ADDRESS,\n PUMP_PROGRAM_ADDRESS,\n} from \"../pump/abi\";\nimport { pumpBuyAccounts } from \"../pump/accounts\";\nimport { decodePumpGlobal, PUMP_GLOBAL } from \"../pump/adapter\";\nimport { getPumpCreateV2Instruction } from \"../pump/create\";\nimport { newCurveBuyCost } from \"../pump/venue\";\nimport { MAX_FEE_BPS, PACK_TOKENS } from \"../ids\";\nimport {\n DEFAULT_TIERS,\n seedTokens,\n validatePack,\n validateTiers,\n type Tier,\n} from \"../math\";\nimport type { GaboxClient } from \"../rpc\";\nimport {\n buildMessage,\n withRemainingAccounts,\n type BuildOptions,\n} from \"./message\";\n\nexport type CreateMachineInput = {\n /** Pays for everything and signs both instructions. Becomes `pool.creator`. */\n creator: TransactionSigner;\n /** A fresh keypair for the coin. Signs `create_v2` and is never needed again. */\n mintKeypair: TransactionSigner;\n name: string;\n symbol: string;\n /** The metadata URI Pump writes onto the mint. */\n uri: string;\n /** The creator's fee per pack, in bps of what the venue charges. `0` to `MAX_FEE_BPS`. Immutable. */\n feeBps: number;\n /**\n * The prize table. Immutable once the pool exists. Must pass `validateTiers` and\n * `validatePack(PACK_TOKENS, tiers)`; the program checks both again on-chain. Defaults to\n * `DEFAULT_TIERS`, the table the Gabox app uses.\n */\n tiers?: readonly Readonly<Tier>[];\n /**\n * The creator's slippage cap on the seed buy, in lamports. Pump fails the buy above it.\n * Take `seedCostEstimate` and add a margin. Ignored for a 1x jackpot, which buys nothing.\n */\n maxSeedLamports: bigint;\n /** Which Pump fee recipient to use, as an index. Left out, one is picked at random. */\n feeRecipientIndex?: number;\n /** Same, for the buyback recipient list. */\n buybackRecipientIndex?: number;\n} & Partial<BuildOptions>;\n\n/**\n * Build the transaction message. Sign it with both `creator` and `mintKeypair`.\n *\n * Reads Pump's `Global` account, because two of the buy accounts — the fee recipient and the\n * buyback fee recipient — are chosen from lists held there. Nothing else needs the chain: the coin\n * does not exist yet, so every other account is a derivation.\n */\nexport async function createMachine(client: GaboxClient, input: CreateMachineInput) {\n const {\n creator,\n mintKeypair,\n name,\n symbol,\n uri,\n feeBps,\n maxSeedLamports,\n } = input;\n\n if (!Number.isInteger(feeBps) || feeBps < 0 || feeBps > MAX_FEE_BPS) {\n throw new Error(`feeBps must be a whole number from 0 to ${MAX_FEE_BPS}`);\n }\n // Snapshot caller input before validation and the first await. A caller can otherwise mutate a\n // nested tier while Pump's Global account is loading, changing the transaction after validation.\n const tiers = cloneTiers(input.tiers ?? DEFAULT_TIERS);\n validateTiers(tiers);\n validatePack(PACK_TOKENS, tiers);\n const seed = seedTokens(PACK_TOKENS, tiers);\n if (seed > 0n && maxSeedLamports <= 0n) {\n throw new Error(\"maxSeedLamports must be positive when the jackpot needs a seed\");\n }\n await assertSeedFitsFreshCurve(client, seed);\n\n const mint = mintKeypair.address;\n\n const create = getPumpCreateV2Instruction({\n mint: mintKeypair,\n user: creator,\n name,\n symbol,\n uri,\n // gabox reads `bondingCurve.creator` to derive the creator vault on every later trade, so the\n // coin's Pump creator and the pool's creator are kept the same on purpose.\n creator: creator.address,\n mayhemMode: false,\n cashback: false,\n });\n\n const venueAccounts = await pumpSeedBuyAccounts(client, {\n mint,\n user: creator.address,\n ...(input.feeRecipientIndex === undefined\n ? {}\n : { feeRecipientIndex: input.feeRecipientIndex }),\n ...(input.buybackRecipientIndex === undefined\n ? {}\n : { buybackRecipientIndex: input.buybackRecipientIndex }),\n });\n\n const initialize = await getInitializePoolInstructionAsync({\n creator,\n mint,\n // Pump `create_v2` always mints Token-2022, so the vault and the creator's ATA live there.\n tokenProgram: PUMP_CREATE_TOKEN_PROGRAM_ADDRESS,\n venue: PUMP_PROGRAM_ADDRESS,\n feeBps,\n tiers,\n maxSeedLamports,\n });\n\n const instructions: Instruction[] = [\n create,\n withRemainingAccounts(initialize as Instruction, venueAccounts),\n ];\n\n return await buildMessage(client, creator, instructions, {\n addressLookupTables: input.addressLookupTables,\n computeUnitLimit: input.computeUnitLimit ?? CREATE_MACHINE_COMPUTE_UNITS,\n ...(input.computeUnitPrice === undefined\n ? {}\n : { computeUnitPrice: input.computeUnitPrice }),\n });\n}\n\n/**\n * What the seed for this table costs, fees included, and how many tokens it is.\n *\n * The coin does not exist yet, so the price is Pump's default new curve. Nothing else trades on\n * it before `initialize_pool` runs in the same transaction, so this is exact up to a change in\n * Pump's fee settings between the read and the send. Add a small margin for `maxSeedLamports`.\n *\n * Defaults to `DEFAULT_TIERS`. Throws if `tiers` fails `validateTiers`/`validatePack`, or if the\n * seed is bigger than a fresh Pump curve can sell in one buy.\n */\nexport async function seedCostEstimate(\n client: GaboxClient,\n tiers: readonly Readonly<Tier>[] = DEFAULT_TIERS,\n): Promise<{ tiers: readonly Tier[]; seedTokens: bigint; lamports: bigint }> {\n // Do not validate one mutable table and then quote another after an await. The result owns its\n // own mutable copy too, never a reference to DEFAULT_TIERS or the caller's array.\n const copiedTiers = cloneTiers(tiers);\n validateTiers(copiedTiers);\n validatePack(PACK_TOKENS, copiedTiers);\n const seed = seedTokens(PACK_TOKENS, copiedTiers);\n await assertSeedFitsFreshCurve(client, seed);\n const lamports = seed === 0n ? 0n : await newCurveBuyCost(client, seed);\n return { tiers: copiedTiers, seedTokens: seed, lamports };\n}\n\n/** A mutable encoded-table shape, owned by this call and safe to pass to Codama's builder. */\nfunction cloneTiers(tiers: readonly Readonly<Tier>[]): Tier[] {\n return tiers.map(({ multiplierBps, tickets }) => ({ multiplierBps, tickets }));\n}\n\n/**\n * Pump's quote silently caps at the curve's real token reserves, so a seed above them would look\n * cheap instead of failing. A fresh curve holds `Global.initialRealTokenReserves`\n * (793,100,000 tokens today), so a jackpot above about 794x of a 1,000,000-token pack cannot be\n * seeded. This throws before any buy is attempted.\n */\nasync function assertSeedFitsFreshCurve(client: GaboxClient, seed: bigint): Promise<void> {\n if (seed === 0n) return;\n const { value } = await client.rpc\n .getAccountInfo(PUMP_GLOBAL, { encoding: \"base64\", commitment: \"confirmed\" })\n .send();\n if (!value) throw new Error(`Pump's Global account is missing at ${PUMP_GLOBAL}`);\n const global = decodePumpGlobal(\n new Uint8Array(getBase64Encoder().encode(value.data[0])),\n );\n if (seed > global.initialRealTokenReserves) {\n throw new Error(\n `the seed (${seed} tokens) is bigger than a fresh Pump curve holds ` +\n `(${global.initialRealTokenReserves} tokens); this table's top tier cannot be seeded on a new coin`,\n );\n }\n}\n\n/**\n * The Pump buy accounts for the seed, built without reading the bonding curve.\n *\n * The curve does not exist yet — `create_v2` in the same transaction is what creates it — so\n * `resolveVenue` cannot be used here. Everything the account list needs is known anyway: the\n * creator vault follows from the `creator` argument that `create_v2` records on the curve, and the\n * two fee recipients come from `Global`.\n */\nexport async function pumpSeedBuyAccounts(\n client: GaboxClient,\n options: {\n mint: Address;\n user: Address;\n feeRecipientIndex?: number;\n buybackRecipientIndex?: number;\n },\n): Promise<AccountMeta[]> {\n const { value } = await client.rpc\n .getAccountInfo(PUMP_GLOBAL, {\n encoding: \"base64\",\n commitment: \"confirmed\",\n })\n .send();\n if (!value)\n throw new Error(`Pump's Global account is missing at ${PUMP_GLOBAL}`);\n\n const global = decodePumpGlobal(\n new Uint8Array(getBase64Encoder().encode(value.data[0])),\n );\n\n const recipients = [global.feeRecipient, ...global.feeRecipients];\n const feeRecipient =\n recipients[options.feeRecipientIndex ?? randomIndex(recipients.length)];\n const buyback =\n global.buybackFeeRecipients[\n options.buybackRecipientIndex ??\n randomIndex(global.buybackFeeRecipients.length)\n ];\n\n if (!feeRecipient) throw new Error(\"Pump Global holds no fee recipient\");\n if (!buyback) throw new Error(\"Pump Global holds no buyback fee recipient\");\n\n return pumpBuyAccounts({\n mint: options.mint,\n user: options.user,\n tokenProgram: PUMP_CREATE_TOKEN_PROGRAM_ADDRESS,\n creator: options.user,\n feeRecipient,\n buybackFeeRecipient: buyback,\n });\n}\n\nconst randomIndex = (length: number): number => {\n if (length === 0) throw new Error(\"the list is empty\");\n return Math.floor(Math.random() * length);\n};\n","/**\n * Keeping a draw moving: retry the oracle, or expire it.\n *\n * Both are permissionless. Anyone can send them, which is the point — a buyer whose draw is stuck\n * does not have to wait for an operator, and there is no crank service in this repository.\n *\n * # retryDraw\n *\n * Asks MagicBlock for randomness again. Up to three attempts in total, counting the one `buy_pack`\n * made, and at least 300 slots apart. The **signer pays the oracle fee**, which is why\n * `maxVrfDebit` exists: a permissionless crank must not be able to spend an unbounded amount of\n * someone else's wallet.\n *\n * A retry never extends the deadline. `expire_draw` still becomes available 216,000 slots after the\n * original purchase.\n *\n * # expireDraw\n *\n * Resolves an unanswered draw at its **committed minimum** award — the smallest prize on the table\n * it was sold with. Not a refund. The tokens were already bought, and paying the worst committed\n * outcome gives an exit without letting a buyer improve a losing result by withholding settlement.\n * It applies only while the draw is still `Pending`; a `Ready` draw must use normal delivery so its\n * resolved award cannot be closed unpaid.\n *\n * `expire_draw` takes no signer at all: it needs no payer and allocates nothing. A caller still\n * has to supply a fee payer for the transaction.\n */\n\nimport type { Address, Instruction, TransactionSigner } from '@solana/kit';\n\nimport { fetchDraw, fetchPoolAt } from '../accounts';\nimport { getExpireDrawInstruction } from '../generated/instructions/expireDraw';\nimport { getRetryDrawInstruction } from '../generated/instructions/retryDraw';\nimport { DrawStatus } from '../generated/types/drawStatus';\nimport { MAX_ATTEMPTS, RETRY_SLOTS, TIMEOUT_SLOTS } from '../ids';\nimport { associatedTokenAddress, vrfIdentityAddress } from '../pdas';\nimport type { GaboxClient } from '../rpc';\nimport { buildMessage, type BuildOptions } from './message';\n\n/** A retry and an expiry are both small. The default budget is plenty. */\nconst DRAW_COMPUTE_UNITS = 200_000;\n\nexport type RetryDrawInput = {\n /** Pays the oracle fee and the transaction fee. Any wallet. */\n payer: TransactionSigner;\n pool: Address;\n draw: Address;\n /** Cap on what the oracle request may take from `payer`, in lamports. */\n maxVrfDebit: bigint;\n} & Partial<BuildOptions>;\n\nexport async function retryDraw(client: GaboxClient, input: RetryDrawInput) {\n const retry = getRetryDrawInstruction({\n payer: input.payer,\n pool: input.pool,\n draw: input.draw,\n identity: await vrfIdentityAddress(),\n maxVrfDebit: input.maxVrfDebit,\n });\n\n return await buildMessage(client, input.payer, [retry as Instruction], {\n addressLookupTables: input.addressLookupTables,\n computeUnitLimit: input.computeUnitLimit ?? DRAW_COMPUTE_UNITS,\n ...(input.computeUnitPrice === undefined ? {} : { computeUnitPrice: input.computeUnitPrice }),\n });\n}\n\nexport type ExpireDrawInput = {\n /** Only pays the transaction fee. `expire_draw` itself has no signer account. */\n payer: TransactionSigner;\n pool: Address;\n draw: Address;\n} & Partial<BuildOptions>;\n\nexport async function expireDraw(client: GaboxClient, input: ExpireDrawInput) {\n const draw = await fetchDraw(client, input.draw);\n if (!draw) throw new Error(`no draw at ${input.draw}`);\n if (draw.pool !== input.pool) throw new Error(`draw ${input.draw} does not belong to ${input.pool}`);\n const pool = await fetchPoolAt(client, input.pool);\n if (!pool) throw new Error(`no pool at ${input.pool}`);\n const expire = getExpireDrawInstruction({\n pool: input.pool,\n draw: input.draw,\n purchaser: draw.purchaser,\n mint: pool.mint,\n vault: pool.vault,\n userTokens: await associatedTokenAddress(draw.purchaser, pool.mint, pool.tokenProgram),\n tokenProgram: pool.tokenProgram,\n });\n\n return await buildMessage(client, input.payer, [expire as Instruction], {\n addressLookupTables: input.addressLookupTables,\n computeUnitLimit: input.computeUnitLimit ?? DRAW_COMPUTE_UNITS,\n ...(input.computeUnitPrice === undefined ? {} : { computeUnitPrice: input.computeUnitPrice }),\n });\n}\n\nexport type DrawAvailability = {\n status: DrawStatus;\n attempts: number;\n /** Slots remaining before a retry is allowed. `0` when it is allowed now. */\n slotsUntilRetry: bigint;\n /** Slots remaining before an unanswered draw reaches its expiry deadline. */\n slotsUntilExpiry: bigint;\n /** All three conditions the program checks for `retry_draw`, together. */\n canRetry: boolean;\n /** True only when the draw is still `Pending` and its expiry deadline passed. */\n canExpire: boolean;\n};\n\n/**\n * What a client may do to a draw right now.\n *\n * Reads the draw and the current slot, and reproduces the program's three retry conditions and the\n * pending-status-plus-deadline expiry conditions. Showing a disabled button with a countdown beats\n * sending a transaction that fails with `RetryTooSoon` or `NotPending`.\n */\nexport async function drawAvailability(\n client: GaboxClient,\n draw: Address,\n): Promise<DrawAvailability | null> {\n const record = await fetchDraw(client, draw);\n if (!record) return null;\n\n const slot = await client.rpc.getSlot({ commitment: 'confirmed' }).send();\n const now = BigInt(slot);\n\n const retryAt = record.lastAttemptSlot + RETRY_SLOTS;\n const expireAt = record.requestSlot + TIMEOUT_SLOTS;\n const slotsUntilRetry = now >= retryAt ? 0n : retryAt - now;\n const slotsUntilExpiry = now >= expireAt ? 0n : expireAt - now;\n const pending = record.status === DrawStatus.Pending;\n\n return {\n status: record.status,\n attempts: record.attempts,\n slotsUntilRetry,\n slotsUntilExpiry,\n canRetry:\n pending &&\n slotsUntilRetry === 0n &&\n record.attempts < MAX_ATTEMPTS &&\n slotsUntilExpiry > 0n,\n canExpire: pending && slotsUntilExpiry === 0n,\n };\n}\n","/**\n * Donating prize inventory.\n *\n * `fund_prizes` moves tokens from any wallet into the pool's vault. It is a donation and it is\n * irrevocable: there is no withdrawal instruction, and no authority can move vault tokens. The only\n * way out of the vault is prize delivery.\n *\n * Funding raises what later packs can pay. It does not change the tiers, which are immutable, and\n * it does not change any draw that is already frozen — `math.quote` is computed at purchase time\n * and stored in the `Draw`.\n */\n\nimport {\n getCreateAssociatedTokenIdempotentInstruction,\n getSyncNativeInstruction,\n TOKEN_PROGRAM_ADDRESS as SPL_TOKEN_PROGRAM_ADDRESS,\n} from '@solana-program/token';\nimport { getTransferSolInstruction } from '@solana-program/system';\nimport type { Address, Instruction, TransactionSigner } from '@solana/kit';\n\nimport { fetchPoolByMint } from '../accounts';\nimport { getFundPrizesInstruction } from '../generated/instructions/fundPrizes';\nimport { WSOL_MINT } from '../ids';\nimport { associatedTokenAddress, poolAddress } from '../pdas';\nimport { venueBuyInstruction } from '../pump/trade';\nimport { resolveVenue, wsolAccountFor, type VenueKind } from '../pump/venue';\nimport type { GaboxClient } from '../rpc';\nimport { buildMessage, type BuildOptions } from './message';\n\nconst FUND_COMPUTE_UNITS = 200_000;\n\n/** A venue buy plus the vault transfer. The buy is the expensive half. */\nconst FUND_WITH_BUY_COMPUTE_UNITS = 400_000;\n\nexport type FundPrizesInput = {\n mint: Address;\n /** The donor. Signs, and the tokens leave its account. */\n funder: TransactionSigner;\n /** Tokens to donate, in the mint's smallest unit. Must be positive. */\n amount: bigint;\n /**\n * The account the tokens come from. Defaults to the funder's associated token account, which is\n * where a wallet holds them. Any token account the funder is the authority of works.\n */\n source?: Address;\n} & Partial<BuildOptions>;\n\nexport async function fundPrizes(client: GaboxClient, input: FundPrizesInput) {\n const { mint, funder, amount } = input;\n if (amount <= 0n) throw new Error('amount must be positive');\n\n const pool = await fetchPoolByMint(client, mint);\n if (!pool) throw new Error(`no gabox pool for mint ${mint}`);\n\n const fund = getFundPrizesInstruction({\n funder,\n pool: await poolAddress(mint),\n mint,\n source: input.source ?? (await associatedTokenAddress(funder.address, mint, pool.tokenProgram)),\n vault: pool.vault,\n tokenProgram: pool.tokenProgram,\n amount,\n });\n\n return await buildMessage(client, funder, [fund as Instruction], {\n addressLookupTables: input.addressLookupTables,\n computeUnitLimit: input.computeUnitLimit ?? FUND_COMPUTE_UNITS,\n ...(input.computeUnitPrice === undefined ? {} : { computeUnitPrice: input.computeUnitPrice }),\n });\n}\n\nexport type FundPrizesWithBuyInput = {\n mint: Address;\n /** The donor. Buys the tokens, then gives them away. Signs both instructions. */\n funder: TransactionSigner;\n /** Exact tokens to buy and donate. `seedShortfall(offer)` is the amount that uncaps the top prize. */\n tokens: bigint;\n /** The donor's slippage cap on the buy, in lamports (WSOL on PumpSwap). */\n maxQuoteIn: bigint;\n /** Force a venue. Left out, the bonding curve's `complete` flag decides. */\n venue?: VenueKind;\n /**\n * Lamports to wrap on the PumpSwap route. Left out, `maxQuoteIn`. The venue never takes more\n * than that, and any surplus stays in the donor's own WSOL account.\n */\n wrapLamports?: bigint;\n} & Partial<BuildOptions>;\n\n/**\n * Buy tokens at the venue with SOL and donate them to the vault, in one transaction.\n *\n * This is what a donor with SOL and no coins needs. `fundPrizes` moves tokens the donor already\n * holds; this one buys them first. Both are irrevocable — there is no withdrawal instruction, and\n * no authority can move vault tokens.\n *\n * Three instructions on the curve route: create the donor's token account if it is missing, buy,\n * donate. Pump creates the account itself, but the idempotent instruction costs nothing when it\n * already exists and it makes the transaction correct on its own terms. The PumpSwap route adds the\n * WSOL create/fund/sync prefix, for the same reason `buyPack` does: PumpSwap spends WSOL.\n */\nexport async function fundPrizesWithBuy(client: GaboxClient, input: FundPrizesWithBuyInput) {\n const { mint, funder, tokens, maxQuoteIn } = input;\n if (tokens <= 0n) throw new Error('tokens must be positive');\n if (maxQuoteIn <= 0n) throw new Error('maxQuoteIn must be positive');\n\n const pool = await fetchPoolByMint(client, mint);\n if (!pool) throw new Error(`no gabox pool for mint ${mint}`);\n\n const venue = await resolveVenue(client, {\n mint,\n user: funder.address,\n ...(input.venue ? { venue: input.venue } : {}),\n });\n\n const source = await associatedTokenAddress(funder.address, mint, pool.tokenProgram);\n\n const wsol: Instruction[] =\n venue.kind === 'pumpswap' ? wsolPreparation(funder, input.wrapLamports ?? maxQuoteIn) : [];\n\n const instructions: Instruction[] = [\n ...wsol,\n getCreateAssociatedTokenIdempotentInstruction({\n payer: funder,\n ata: source,\n owner: funder.address,\n mint,\n tokenProgram: pool.tokenProgram,\n }) as Instruction,\n venueBuyInstruction({ venue, user: funder, tokens, maxQuoteIn }),\n getFundPrizesInstruction({\n funder,\n pool: await poolAddress(mint),\n mint,\n source,\n vault: pool.vault,\n tokenProgram: pool.tokenProgram,\n amount: tokens,\n }) as Instruction,\n ];\n\n return await buildMessage(client, funder, instructions, {\n addressLookupTables: input.addressLookupTables,\n computeUnitLimit: input.computeUnitLimit ?? FUND_WITH_BUY_COMPUTE_UNITS,\n ...(input.computeUnitPrice === undefined ? {} : { computeUnitPrice: input.computeUnitPrice }),\n });\n}\n\n/** Create the donor's WSOL account if needed, fund it, and sync its balance. See `buyPack.ts`. */\nfunction wsolPreparation(funder: TransactionSigner, lamports: bigint): Instruction[] {\n const wsol = wsolAccountFor(funder.address);\n return [\n getCreateAssociatedTokenIdempotentInstruction({\n payer: funder,\n ata: wsol,\n owner: funder.address,\n mint: WSOL_MINT,\n tokenProgram: SPL_TOKEN_PROGRAM_ADDRESS,\n }) as Instruction,\n getTransferSolInstruction({ source: funder, destination: wsol, amount: lamports }) as Instruction,\n getSyncNativeInstruction({ account: wsol }) as Instruction,\n ];\n}\n","/**\n * Selling an automatically delivered prize, plus settlement helpers for legacy resolve-only draws.\n *\n * Every sale here goes through the program (`sell_tokens` or `sell_prize`), which does the venue\n * CPI and then pays the protocol 1% of what the sale returned. On Pump the proceeds and the fee are\n * native SOL. On PumpSwap both are WSOL: the proceeds land in the seller's WSOL account and the fee\n * moves from there to the collector's WSOL account. Add an unwrap afterwards if the seller wants\n * lamports.\n *\n * `minQuoteOutput` is the venue's own floor, checked before the fee. The seller keeps 99% of\n * whatever the venue paid above it.\n */\n\nimport {\n getCreateAssociatedTokenIdempotentInstruction,\n TOKEN_PROGRAM_ADDRESS as SPL_TOKEN_PROGRAM_ADDRESS,\n} from '@solana-program/token';\nimport type { Address, Instruction, TransactionSigner } from '@solana/kit';\n\nimport { fetchDraw, fetchPoolByMint } from '../accounts';\nimport { REDEEM_COMPUTE_UNITS } from '../compute';\nimport { getClaimPrizeInstruction } from '../generated/instructions/claimPrize';\nimport { getSellPrizeInstruction } from '../generated/instructions/sellPrize';\nimport { getSellTokensInstruction } from '../generated/instructions/sellTokens';\nimport { WSOL_MINT } from '../ids';\nimport { associatedTokenAddress, feeCollectorWsolAddress, poolAddress } from '../pdas';\nimport { resolveVenue, wsolAccountFor, type ResolvedVenue, type VenueKind } from '../pump/venue';\nimport type { GaboxClient } from '../rpc';\nimport { buildMessage, withRemainingAccounts, type BuildOptions } from './message';\n\nexport type SellTokensInput = {\n mint: Address;\n /** Wallet that owns the tokens and signs the venue sale. */\n seller: TransactionSigner;\n /** Exact token amount to sell. Must be positive. */\n amount: bigint;\n /** Floor on the venue's net output, in lamports or WSOL, before the protocol fee. Must be\n * positive: the program rejects zero, because a zero floor is not slippage protection. */\n minQuoteOutput: bigint;\n /** Force a venue. Left out, the bonding curve's `complete` flag decides. */\n venue?: VenueKind;\n} & Partial<BuildOptions>;\n\n/**\n * Sell a prize that the VRF callback already delivered to the wallet, through `sell_tokens`.\n *\n * The program needs the coin's pool: it keeps the vault out of the venue's account list. A mint\n * with no pool cannot be sold this way; use a plain venue trade for that.\n */\nexport async function sellTokens(client: GaboxClient, input: SellTokensInput) {\n const { mint, seller, amount, minQuoteOutput } = input;\n if (amount <= 0n) throw new Error('amount must be positive');\n if (minQuoteOutput <= 0n) throw new Error('minQuoteOutput must be positive');\n\n const pool = await fetchPoolByMint(client, mint);\n if (!pool) throw new Error(`no gabox pool for mint ${mint}`);\n\n const venue = await resolveVenue(client, {\n mint,\n user: seller.address,\n ...(input.venue ? { venue: input.venue } : {}),\n });\n\n const sell = getSellTokensInstruction({\n seller,\n pool: await poolAddress(mint),\n mint,\n userTokens: await associatedTokenAddress(seller.address, mint, pool.tokenProgram),\n venue: venue.program,\n feeCollectorWsol: await feeCollectorWsolAddress(),\n tokenProgram: pool.tokenProgram,\n amount,\n minQuoteOutput,\n });\n\n return await buildMessage(\n client,\n seller,\n [...wsolPreparation(seller, venue), withRemainingAccounts(sell as Instruction, venue.sellAccounts)],\n {\n addressLookupTables: input.addressLookupTables,\n computeUnitLimit: input.computeUnitLimit ?? REDEEM_COMPUTE_UNITS,\n ...(input.computeUnitPrice === undefined ? {} : { computeUnitPrice: input.computeUnitPrice }),\n },\n );\n}\n\nexport type ClaimPrizeInput = {\n mint: Address;\n /** The wallet that bought the legacy pack. Only it can settle the draw. */\n purchaser: TransactionSigner;\n /** The draw to redeem. */\n draw: Address;\n} & Partial<BuildOptions>;\n\n/** Transfer a legacy resolve-only award into the purchaser's token account and close the draw. */\nexport async function claimPrize(client: GaboxClient, input: ClaimPrizeInput) {\n const { mint, purchaser, draw } = input;\n const pool = await fetchPoolByMint(client, mint);\n if (!pool) throw new Error(`no gabox pool for mint ${mint}`);\n\n const claim = getClaimPrizeInstruction({\n purchaser,\n pool: await poolAddress(mint),\n draw,\n mint,\n vault: pool.vault,\n userTokens: await associatedTokenAddress(purchaser.address, mint, pool.tokenProgram),\n tokenProgram: pool.tokenProgram,\n });\n\n return await buildMessage(client, purchaser, [claim as Instruction], {\n addressLookupTables: input.addressLookupTables,\n computeUnitLimit: input.computeUnitLimit ?? REDEEM_COMPUTE_UNITS,\n ...(input.computeUnitPrice === undefined ? {} : { computeUnitPrice: input.computeUnitPrice }),\n });\n}\n\nexport type SellPrizeInput = ClaimPrizeInput & {\n /**\n * The seller's floor on the venue's net output, in lamports or WSOL. Must be positive: the\n * program rejects zero, because a zero floor is not slippage protection.\n *\n * This is the venue's own net quote, before the protocol fee. It is not net of the transaction\n * fee or of any rent the transaction pays.\n */\n minQuoteOutput: bigint;\n /** Force a venue. Left out, the bonding curve's `complete` flag decides. */\n venue?: VenueKind;\n};\n\n/**\n * Claim and sell a legacy resolve-only draw in one transaction.\n *\n * The award is read off the draw so the caller can price the sale before signing. A draw that has\n * not resolved has no award yet, and this throws rather than building a sale of zero tokens.\n */\nexport async function sellPrize(client: GaboxClient, input: SellPrizeInput) {\n const { mint, purchaser, draw, minQuoteOutput } = input;\n if (minQuoteOutput <= 0n) throw new Error('minQuoteOutput must be positive');\n\n const pool = await fetchPoolByMint(client, mint);\n if (!pool) throw new Error(`no gabox pool for mint ${mint}`);\n\n const record = await fetchDraw(client, draw);\n if (!record) throw new Error(`no draw at ${draw} — it may already be redeemed`);\n if (record.amount === 0n) {\n throw new Error(`draw ${draw} has no award yet; it has not resolved`);\n }\n\n const venue = await resolveVenue(client, {\n mint,\n user: purchaser.address,\n ...(input.venue ? { venue: input.venue } : {}),\n });\n\n const sell = getSellPrizeInstruction({\n purchaser,\n pool: await poolAddress(mint),\n draw,\n mint,\n vault: pool.vault,\n userTokens: await associatedTokenAddress(purchaser.address, mint, pool.tokenProgram),\n tokenProgram: pool.tokenProgram,\n venue: venue.program,\n feeCollectorWsol: await feeCollectorWsolAddress(),\n minQuoteOutput,\n });\n\n return await buildMessage(\n client,\n purchaser,\n [...wsolPreparation(purchaser, venue), withRemainingAccounts(sell as Instruction, venue.sellAccounts)],\n {\n addressLookupTables: input.addressLookupTables,\n computeUnitLimit: input.computeUnitLimit ?? REDEEM_COMPUTE_UNITS,\n ...(input.computeUnitPrice === undefined ? {} : { computeUnitPrice: input.computeUnitPrice }),\n },\n );\n}\n\n/**\n * On PumpSwap the proceeds land in the seller's WSOL account, so it has to exist before the sale.\n * Pump's own SDK does the same before its sells. The instruction is idempotent and the account is\n * the seller's own; gabox never touches it. Pump pays native SOL, so the curve route adds nothing.\n */\nfunction wsolPreparation(seller: TransactionSigner, venue: ResolvedVenue): Instruction[] {\n if (venue.kind !== 'pumpswap') return [];\n return [\n getCreateAssociatedTokenIdempotentInstruction({\n payer: seller,\n ata: wsolAccountFor(seller.address),\n owner: seller.address,\n mint: WSOL_MINT,\n tokenProgram: SPL_TOKEN_PROGRAM_ADDRESS,\n }) as Instruction,\n ];\n}\n\n/**\n * Quote the award held by a legacy open draw before the seller signs a floor.\n *\n * Read the draw, ask the venue, and subtract your own slippage tolerance to get `minQuoteOutput`.\n */\nexport async function quoteSellPrize(\n client: GaboxClient,\n mint: Address,\n draw: Address,\n user: Address,\n): Promise<{ award: bigint; grossOutput: bigint }> {\n const record = await fetchDraw(client, draw);\n if (!record) throw new Error(`no draw at ${draw}`);\n const venue = await resolveVenue(client, { mint, user });\n return { award: record.amount, grossOutput: venue.quoteSell(record.amount) };\n}\n","/**\n * The four oracle accounts.\n *\n * `buy_pack` and `retry_draw` both carry an `Oracle` account group. Anchor flattens it into four\n * slots, and the generated client takes them as `identity`, `queue`, `program` and `slotHashes`.\n * Three of the four are pinned by an `address` constraint, so the only one a client computes is the\n * identity PDA.\n *\n * # Why the queue is not a choice\n *\n * `vrf.rs` pins MagicBlock's default queue with `address = QUEUE` and `owner = ID`. A pool creator\n * therefore cannot point their pool's draws at an oracle they run. That is the reason the address\n * is a constant here rather than a parameter: making it configurable in the client would suggest a\n * freedom the program does not give.\n */\n\nimport type { Address } from '@solana/kit';\n\nimport { SLOT_HASHES_SYSVAR, VRF_DEFAULT_QUEUE, VRF_PROGRAM_ADDRESS } from './ids';\nimport { vrfIdentityAddress } from './pdas';\n\n/** The four accounts, named as the generated client names them. */\nexport type OracleAccounts = {\n /** `[\"identity\"]` under gabox. The PDA gabox signs the randomness request with. */\n identity: Address;\n /** MagicBlock's default queue. Writable. */\n queue: Address;\n /** The VRF program itself. */\n program: Address;\n /** The slot-hashes sysvar, which seeds the request. */\n slotHashes: Address;\n};\n\n/**\n * Build the group. Nothing here reads the chain, so it is safe to call on every render.\n *\n * The generated instruction builders default `queue`, `program` and `slotHashes` on their own, so\n * passing this whole object is belt and braces. It is worth having anyway: a caller can show the\n * four accounts a draw request will touch before asking for a signature.\n */\nexport async function oracleAccounts(): Promise<OracleAccounts> {\n return {\n identity: await vrfIdentityAddress(),\n queue: VRF_DEFAULT_QUEUE,\n program: VRF_PROGRAM_ADDRESS,\n slotHashes: SLOT_HASHES_SYSVAR,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAaA,MAAa,MAAM;;AAGnB,SAAgB,MAAM,QAAgB,KAAqB;CACzD,OAAQ,SAAS,MAAO;AAC1B;;AAGA,MAAa,UAAU;;AAGvB,MAAa,QAAQ;;AAwBrB,IAAa,iBAAb,cAAoC,MAAM;CACxC;CACA,YAAY,MAAc,SAAiB;EACzC,MAAM,GAAG,KAAK,IAAI,SAAS;EAC3B,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF;AAEA,MAAM,WAAW,MAAM,OAAO;AAC9B,MAAM,UAAU;;;;;;;;;AAUhB,MAAa,gBAA2C,OAAO,OAAO;CACpE,OAAO,OAAO;EAAE,eAAe;EAAO,SAAS;CAAO,CAAC;CACvD,OAAO,OAAO;EAAE,eAAe;EAAQ,SAAS;CAAO,CAAC;CACxD,OAAO,OAAO;EAAE,eAAe;EAAQ,SAAS;CAAM,CAAC;CACvD,OAAO,OAAO;EAAE,eAAe;EAAS,SAAS;CAAI,CAAC;CACtD,OAAO,OAAO;EAAE,eAAe;EAAG,SAAS;CAAE,CAAC;CAC9C,OAAO,OAAO;EAAE,eAAe;EAAG,SAAS;CAAE,CAAC;CAC9C,OAAO,OAAO;EAAE,eAAe;EAAG,SAAS;CAAE,CAAC;CAC9C,OAAO,OAAO;EAAE,eAAe;EAAG,SAAS;CAAE,CAAC;AAChD,CAAC;AAED,SAAS,WAAW,OAAe,MAAsB;CACvD,IAAI,QAAQ,MAAM,QAAQ,SACxB,MAAM,IAAI,eAAe,cAAc,GAAG,KAAK,qBAAqB;CAEtE,OAAO;AACT;;AAGA,SAA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AO,OAAO;EACd,MAAM;EACN,cAAcC;CAChB,CAAC,CACH;AACF;;;;;;AAOA,eAAsB,eACpB,QACA,MACA,MACA,MACiD;CACjD,MAAM,SAAS,MAAM,UAAU,QAAQ,IAAI;CAC3C,IAAI,CAAC,QAAQ,MAAM,IAAI,MAAM,cAAc,MAAM;CACjD,MAAM,QAAQ,MAAM,aAAa,QAAQ;EAAE;EAAM;CAAK,CAAC;CACvD,OAAO;EAAE,OAAO,OAAO;EAAQ,aAAa,MAAM,UAAU,OAAO,MAAM;CAAE;AAC7E;;;;;;;;;;AC9KA,eAAsB,iBAA0C;CAC9D,OAAO;EACL,UAAU,MAAM,mBAAmB;EACnC,OAAO;EACP,SAAS;EACT,YAAY;CACd;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/events.ts","../src/lookupTables.ts","../src/route/leg.ts","../src/offer.ts","../src/route/cpmm.ts","../src/route/jupiter.ts","../src/rpc.ts","../src/tx/wsol.ts","../src/tx/quoteLeg.ts","../src/tx/buyPack.ts","../src/tx/createMachine.ts","../src/tx/draw.ts","../src/tx/fundPrizes.ts","../src/tx/redeem.ts","../src/vrf.ts"],"sourcesContent":["/** Decode Gabox's Anchor events. Draw accounts are closed on delivery; use `DrawResolved` as final state. */\nimport { getBase64Encoder, type Address, type ReadonlyUint8Array, type Signature } from '@solana/kit';\nimport { DRAW_RESOLVED_EVENT_DISCRIMINATOR, getDrawResolvedEventDecoder, type DrawResolvedEvent } from './generated/events/drawResolved';\nimport { PACK_BOUGHT_EVENT_DISCRIMINATOR, getPackBoughtEventDecoder, type PackBoughtEvent } from './generated/events/packBought';\nimport { POOL_CREATED_EVENT_DISCRIMINATOR, getPoolCreatedEventDecoder, type PoolCreatedEvent } from './generated/events/poolCreated';\nimport { PRIZES_FUNDED_EVENT_DISCRIMINATOR, getPrizesFundedEventDecoder, type PrizesFundedEvent } from './generated/events/prizesFunded';\nimport { RANDOMNESS_RETRIED_EVENT_DISCRIMINATOR, getRandomnessRetriedEventDecoder, type RandomnessRetriedEvent } from './generated/events/randomnessRetried';\nimport { TOKENS_SOLD_EVENT_DISCRIMINATOR, getTokensSoldEventDecoder, type TokensSoldEvent } from './generated/events/tokensSold';\nimport { drawAddress } from './pdas';\nimport { GABOX_PROGRAM_ID } from './ids';\nimport type { GaboxClient, GaboxRpc } from './rpc';\n\nexport type GaboxEvent =\n | { name: 'PoolCreated'; data: PoolCreatedEvent }\n | { name: 'PrizesFunded'; data: PrizesFundedEvent }\n | { name: 'PackBought'; data: PackBoughtEvent }\n | { name: 'RandomnessRetried'; data: RandomnessRetriedEvent }\n | { name: 'DrawResolved'; data: DrawResolvedEvent }\n | { name: 'TokensSold'; data: TokensSoldEvent };\nconst b64 = getBase64Encoder();\nconst starts = (a: Uint8Array, b: ReadonlyUint8Array): boolean => a.length >= b.length && b.every((v, i) => a[i] === v);\nexport function decodeEvent(data: Uint8Array): GaboxEvent | null {\n if (starts(data, POOL_CREATED_EVENT_DISCRIMINATOR)) return { name: 'PoolCreated', data: getPoolCreatedEventDecoder().decode(data) };\n if (starts(data, PRIZES_FUNDED_EVENT_DISCRIMINATOR)) return { name: 'PrizesFunded', data: getPrizesFundedEventDecoder().decode(data) };\n if (starts(data, PACK_BOUGHT_EVENT_DISCRIMINATOR)) return { name: 'PackBought', data: getPackBoughtEventDecoder().decode(data) };\n if (starts(data, RANDOMNESS_RETRIED_EVENT_DISCRIMINATOR)) return { name: 'RandomnessRetried', data: getRandomnessRetriedEventDecoder().decode(data) };\n if (starts(data, DRAW_RESOLVED_EVENT_DISCRIMINATOR)) return { name: 'DrawResolved', data: getDrawResolvedEventDecoder().decode(data) };\n if (starts(data, TOKENS_SOLD_EVENT_DISCRIMINATOR)) return { name: 'TokensSold', data: getTokensSoldEventDecoder().decode(data) };\n return null;\n}\ntype EventFrame = { programId: string; pending: GaboxEvent[] };\nconst BASE58 = '[1-9A-HJ-NP-Za-km-z]+';\nconst INVOKE = new RegExp(`^Program (${BASE58}) invoke \\\\[(\\\\d+)\\\\]$`);\nconst SUCCESS = new RegExp(`^Program (${BASE58}) success$`);\nconst FAILED = new RegExp(`^Program (${BASE58}) failed: .*$`);\n\n/**\n * Decode only Gabox events committed by successful runtime frames. Program logs are emitted before\n * transaction commit and are forgeable by arbitrary programs, so `Program data` is authenticated\n * by the canonical invoke/success stack and buffered until every enclosing frame succeeds.\n */\nexport function decodeEvents(logs: readonly string[]): GaboxEvent[] {\n const committed: GaboxEvent[] = [];\n const stack: EventFrame[] = [];\n const discardOpenFrames = () => { stack.length = 0; };\n let malformed = false;\n let transactionFailed = false;\n for (const line of logs) {\n const invoke = INVOKE.exec(line);\n if (invoke) {\n const depth = Number(invoke[2]);\n if (depth !== stack.length + 1) { malformed = true; discardOpenFrames(); continue; }\n stack.push({ programId: invoke[1]!, pending: [] });\n continue;\n }\n const success = SUCCESS.exec(line);\n const failed = FAILED.exec(line);\n if (success || failed) {\n const programId = (success ?? failed)![1]!;\n const frame = stack.at(-1);\n if (!frame || frame.programId !== programId) { malformed = true; discardOpenFrames(); continue; }\n stack.pop();\n if (success) {\n const parent = stack.at(-1);\n if (parent) parent.pending.push(...frame.pending);\n else committed.push(...frame.pending);\n }\n // A failed frame's pending events are deliberately discarded, including caught CPI logs.\n // A depth-one failure rolls the entire transaction back, including earlier root frames.\n if (failed && stack.length === 0) transactionFailed = true;\n continue;\n }\n const frame = stack.at(-1);\n if (!line.startsWith('Program data: ') || frame?.programId !== GABOX_PROGRAM_ID) continue;\n try {\n const event = decodeEvent(new Uint8Array(b64.encode(line.slice(14).trim())));\n if (event) frame.pending.push(event);\n } catch { /* malformed or unrelated event bytes */ }\n }\n // A truncated/malformed lifecycle cannot authenticate any output. A failed root means the whole\n // transaction rolled back, even if a previous root instruction had logged an event successfully.\n return malformed || transactionFailed || stack.length !== 0 ? [] : committed;\n}\nexport async function fetchEvents(client: GaboxClient, signature: string): Promise<GaboxEvent[]> { return await readEvents(client.rpc, signature); }\nasync function readEvents(rpc: GaboxRpc, signature: string): Promise<GaboxEvent[]> {\n const tx = await rpc.getTransaction(signature as never, { commitment: 'confirmed', encoding: 'json', maxSupportedTransactionVersion: 0 }).send();\n const meta = tx?.meta;\n if (!tx || !meta || meta.err) return [];\n return decodeEvents(meta.logMessages ?? []);\n}\nexport type ResolvedDraw = DrawResolvedEvent & { address: Address };\n/** Poll final resolution events for one closed draw address. There is no separate Ready/claim state to poll instead. */\nexport async function findResolvedDraw(client: GaboxClient, address: Address): Promise<ResolvedDraw | null> {\n // Closed draw PDAs can still be mentioned by arbitrary transactions. Search a bounded 1,000\n // signatures rather than only the newest ten so that this convenience lookup is not trivially\n // buried. Production history/indexing should still persist `DrawResolved` events itself.\n let before: Signature | undefined;\n for (let page = 0; page < 10; page++) {\n const rows = await client.rpc.getSignaturesForAddress(address, {\n commitment: 'confirmed', limit: 100, ...(before ? { before } : {}),\n }).send();\n for (const row of rows) {\n if (row.err) continue;\n for (const event of await readEvents(client.rpc, row.signature)) {\n if (event.name !== 'DrawResolved') continue;\n // One transaction can resolve multiple draws; bind the decoded event, not just the\n // transaction signature, to the queried draw PDA.\n if (await drawAddress(event.data.pool, event.data.seq) === address) return { ...event.data, address };\n }\n }\n if (rows.length < 100) return null;\n before = rows.at(-1)?.signature;\n if (!before) return null;\n }\n return null;\n}\n","/**\n * Shared devnet address lookup table, verified on 2026-09-18T11:04:06.369Z.\n * Generated by scripts/deploy-lookup-table.ts. Existing indices are immutable;\n * keep this table active while clients use it. Authority is the devnet deploy wallet.\n */\nimport { address, getAddressDecoder, type Address, type AddressesByLookupTableAddress } from '@solana/kit';\n\nimport type { Cluster, GaboxClient } from './rpc';\n\nexport const DEVNET_LOOKUP_TABLE_ADDRESS = address('Cx4ri1BU2bnDXPjnJykF3nbY2u4MD5pPvzFCJtNizWFa');\nexport const DEVNET_LOOKUP_TABLE_ADDRESSES: readonly Address[] = [\n address('GaBoxR9nYcK1zeu8EvSJVHV3SrYpCFmvbh2MLgobMcUA'),\n address('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'),\n address('TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'),\n address('ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL'),\n address('6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P'),\n address('pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA'),\n address('pfeeUxB6jkeY1Hxd7CsFCAjcbHA9rWtchMGdZ6VojVZ'),\n address('11111111111111111111111111111111'),\n address('MAyhSmzXzV1pTf7LsNkrNwkWKTo4ougAJ1PPg47MD4e'),\n address('So11111111111111111111111111111111111111112'),\n address('Vrf1RNUjXmQGjmQrQLvJHs9SNkvDJEsRVFPkfSQUwGz'),\n address('Cuj97ggrhhidhbu39TijNVqE74xvKJ69gDervRUXAxGh'),\n address('SysvarS1otHashes111111111111111111111111111'),\n address('Sysvar1nstructions1111111111111111111111111'),\n address('4wTV1YmiEkRvAtNtsSGPtUrqRYQMe5SKy2uB4Jjaxnjf'),\n address('Ce6TQqeHC9p8KetsN6JsjHK7UTZk7nasjjnr7XxXp9F1'),\n address('8Wf5TiAheLUqBrKXeYg2JtAFFMWtKdG2BSFgqUcPVwTt'),\n address('Hq2wp8uJ9jCPsYgNHex8RtqdvMPfVGoYwjvF1ATiwn2Y'),\n address('TSLvdd1pWpHVjahSpsvCXUbgwsL3JAcvokwaKt1eokM'),\n address('13ec7XdrjF3h3YcqBTFDSReRcUFwbCnJaAQspM4j6DDJ'),\n address('BwWK17cbHxwWBKZkUYvzxLcNQ1YVyaFezduWbtm2de6s'),\n address('ADyA8hdefvWN2dbGGWFotbzWxrAvLW83WG6QCVXvJKqw'),\n address('GS4CU59F31iL7aR2Q8zVS8DRrcRnXX1yjQ66TqNVQnaR'),\n address('5PHirr8joyTMp9JMm6nW7hNDVyEYdkzDqazxPD7RaTjx'),\n address('C2aFPdENg4A2HQsmrd5rTw5TaYBX5Ku887cWjbFKtZpw'),\n address('7ahYg76P8bhifT1Uj3hNHGKRFPp6bLkx1ppNrWbnsfu2'),\n address('68yFSZxzLWJXkxxRGydZ63C6mHx1NLEDWmwN9Lb5yySg'),\n address('DLP9ADYpdQV4Z4UQDZof7iLHu2qqdzmMPjcAHDGe4jTt'),\n address('6QgPshH1egekJ2TURfakiiApDdv98qfRuRe7RectX8xs'),\n address('FmFPTNDmmVDhqzaqZYhnt4fj5fJP3pffcMWf2b5JnRTk'),\n address('78i5hpHxbtmosSJdfJ74WzwdUr3eKWg9RbCPpBeAF78t'),\n address('7611SPS3UkjsA43auxPpJpPVAkgEHg4dTVorK839GonW'),\n address('8RMFYhsVsfdGCuWPFLxMCbSpSesiofabDdNorGqFrBNe'),\n address('9GbQXDFHKLdr4BzZ8Cx2pkX2aM2Kg7yEeYnUCKjZGE4M'),\n address('9GDepfBcjJMvNgmijXWVWa97Am7VZYCqXx7kJV44E9ij'),\n address('3fyMEgHADGRrBnCVLU7u9AwpiMtmGDWViJzDQC8kgRa5'),\n address('9ppkS5madL2uXozoEnMnZi5bKDq9jgdKkSavjWTS5NfW'),\n address('C3PvwRFdKT6caSLxnwy8h67KWNevoboNDg6bwJZYzWB5'),\n address('DDMCfwbcaNYTeMk1ca8tr8BQKFaUfFCWFwBJq8JcnyCw'),\n address('FrYoobDtL7w1HrTjHAc8Ya7qQzEdJPhGXXFKskCDaA3p'),\n address('DRDBsRMst21CJUhwD16pncgiXnBrFaRAPvA2G6SUQceE'),\n address('J7JbDVnGKus2M9PKzH7ZbeCYugEYDgpGBfqKL85dQbU7'),\n address('5YxQFdt3Tr9zJLvkFccqXVUwhdTWJQc1fFg2YPbxvxeD'),\n address('HjQjngTDqoHE6aaGhUqfz9aQ7WZcBRjy5xB8PScLSr8i'),\n address('9M4giFFMxmFGXtc3feFzRai56WbBqehoSeRE5GK7gf7'),\n address('GAFuhgcd328SkkBYHpfadzmef9hTGAFRCi9QoCnsZQug'),\n address('GXPFM2caqTtQYC2cJ5yJRi9VDkpsYZXzYdwYpGnLmtDL'),\n address('AktftA98kSWAxn6kVSoqBXBELUArjKu2H9WmKB48ULFY'),\n address('3BpXnfJaUTiwXnJNe7Ej1rcbzqTTQUvLShZaWazebsVR'),\n address('6rVkF4HSgy1jrnC3HogfRgPHrq4CtLg5f11URpsC4i9D'),\n address('5cjcW9wExnJJiqgLjq7DEG75Pm6JBgE1hNv4B2vHXUW6'),\n address('GYH1Gae1wJytMSvMvw8JVcv7nuAbxi8i9erNVbERnzXd'),\n address('EHAAiTxcdDwQ3U4bU6YcMsQGaekdzLS3B5SmYo46kJtL'),\n address('CA7v8gHfbquYXyDnDx6QxWW8hmL1H7X6Y2RYDrGLnuck'),\n address('5eHhjP8JaYkz83CWwvGU2uMUXefd3AazWGx4gpcuEEYD'),\n address('CASRL2zkwDnppxEFQ4LgdwgR9pdz5Q8R8nEMKVZ9QoLp'),\n address('A7hAgCzFw14fejgCp387JUJRMNyz4j89JKnhtKU8piqW'),\n address('qkYdTGRPHbWTWuBMz45bCiU6a23axRqf6sBHm9295WY'),\n address('12e2F4DKkD3Lff6WPYsU7Xd76SHPEyN9T8XSsTJNF8oT'),\n address('GjJkcak9e4L2HsxSZqVsc81L7coChdR7F3ciJYnQcSnU'),\n address('2Ej38XSkmpvXzoUg5ZLma7Y9rCiZVgxzTdvE3Kph5juM'),\n address('2daQRytJgLzLLziPNQBNJ7w1Ltz3XqZG4dZxBamLAf7v'),\n address('3PAxmkxnM2vHno9amWQCsaaFjYnPGcD87HZGx1ChVjPj'),\n address('BWS634asUFdrpYpfofFA1CrGB9wEbh9gt8XswZ4AWz9J'),\n address('4QZqaBNm2F7viBDhhs8AQ5wC9FshgLJEiLLFGoxZZrTn'),\n address('4JaPhJE7WgQZ3xFbxn2spU97reA13SiM99wD3RF4Lqro'),\n address('9xvDPD6G7NRCEu7W2M9vCLeo8we23Ww7pzQEhXcuJAmA'),\n address('AHEgRGXFn8JbhXccWM4i1meRGPFbx8kzb9BGN6ocqRFL'),\n address('CdkG7sp1LT9YLsDaTWREaQcX6W4gZySk3o1eSjoL2uTh'),\n address('2pLUmsYktT7gR6P5hXs9Ldo6Vg1oQB2Q4NPbJqHUjZhq'),\n address('Freijj9xKLefjrb5fHgT6KMbYG1XBP2mA83tqeXYUMYM'),\n address('4uzPz9TPskXiiEZ6X78rqud8LvfdxkJBr5EKHgbx4azP'),\n address('Hxzab4UjjVH2KjsdAqzdxGdYUpNN5FKhpu7iikB869uH'),\n address('Frkwunr9dQM9d4TthfQ2unxC994XpkLMpkRP2e7yfirk'),\n address('E6ShohW57z5CJPBeEcFAEbvPqUyt6QxHcxnkh4hMaNrg'),\n address('6z6GDdfb2AjR9ZhJmAUQ5cipJCVxQvLJhB2H8mCwTFBP'),\n address('D9LwzTvJ5XoGxorcdaZvBgq7Qruqewu2P9WVsgSrKURd'),\n address('4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU'),\n address('GCow1cTVRa43v8EX1eVwVobiKXoyZjfQpwAvgpZ8B2KP'),\n address('65LkFkYo9gMD6AwXTbSsxR3d28pCVbJp5AtE9NK3634n'),\n address('8wDZLhae9WbNvm3eCgHVDrXUhJbd3gx6DnTnhsw45XEj'),\n address('CPgoAkfWjiUZfNLRp94hD7BjmDSFy96mS8xcQKoPFB4H'),\n address('GXVKyyXsoUihF1uzGCx7YXVqQ7kimUDAo3xyqULvgDyB'),\n address('5tpFHeni6NYD6pQpkuReVPGtCJLyaXDq97FTJJzyZMjt'),\n address('DNscAYMk2LW55Aq7FTj24mRbwVPZ6EgvCUoabhhtdVCW'),\n address('7Q2wpniGesAyAkjACpg58BAcDjBKcdcX9a6RAgszVh4M'),\n address('7gx9ZEwMSd1ifHBEgVaUsCkQmHTFJTWVs3C1bQABQ22T'),\n address('GsVBKjffkB769p9tHTZWoAX3r9T6dXoDTJr3f7XutJH7'),\n address('9NFrxdnmedHKHs1tnhYm9G5XTJh7Lt7xN6uxgZzwQNM7'),\n address('BhMknQ4j9RZUbJk6GS4QJh8MSKxcqZHS2x9MZh2AH9hA'),\n address('9NW32ymMo8Qx6DTbgkxtnD8Dh9hssQYpcyY2Brdpg2hs'),\n address('5a8Gfgwx4hrCtYKgvjtX57FsirXPRN7Jzm9aXmn6hQs8'),\n address('5KUNmCZatysY7fxLtTgo2bpkqevPRZZG8fkrh3e1P89F'),\n address('HPfEytxa5JGqmGiVwrSepAcNTkWboxvtQKbyWN9DNCoQ'),\n address('Gr5kHfDBd7GAdjK6Ct3EDC566XFPjCr3mLCkKVxJYrMD'),\n address('HzCwuA6T48enyWvCJWrLhNvMpJJR43kddjMGFf6LyA9L'),\n address('Do4esSd37h4uHz35piua8rRtcXDNt27re8NDqqZfjsGJ'),\n address('2GC6K75FS6MpRrMZYXifinC2sVXP3htsJpayerx7ACci'),\n address('FvEpzodkyvMzRHQo4q7fhvfa287hnjfr1oiumRtQXrse'),\n address('8SwxZnhYHeC9S93ZFzLTd9dC2c44hfCdGyoXYzA7U6Db'),\n address('6B1oS2LSDYHyXpRF9S8C6r5LffitosDrhie2WWsUtfRV'),\n address('F2pzDCn3vqXcNWF6osLxSvVtf3CyTkHd4tRxhGjyRZQ9'),\n address('DKESpHxobrT9Ra4snSXCD4cdhQMqpzmGhZN1HZ3sUYMY'),\n address('metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s'),\n address('SysvarRent111111111111111111111111111111111'),\n address('DRay6fNdQ5J82H7xV6uq2aV3mNrUZ1J4PgSKsWgptcm6'),\n address('5xqNaZXX5eUi4p5HU4oz9i5QnwRNT2y6oN7yyn4qENeq'),\n address('4uAB7seenFJKPUXqYewAdfra2u6baBgjiXU8x1SC7Ycz'),\n address('7ZR4zD7PYfY2XxoG1Gxcy2EgEeGYrpxrwzPuwdUBssEt'),\n address('DdEeCPXbCAzHE2PZSoR3RZng4WA4bSztrezQznrJ4ooB'),\n address('DRaycpLY18LhpbydsBWbVJtxpNv9oXPgjRSfpF2bWpYb'),\n address('CXniRufdq5xL8t8jZAPxsPZDpuudwuJSPWnbcD5Y5Nxq'),\n address('G7YfJJp1TX1VtzN4V2yhPNSU23AKPSy1U2miRdwAByK5'),\n address('5WcPTEQ59UqpQzjZUPbU8QRGCbj7NeQNLDa7DbsLkLKT'),\n address('USDCoctVLVnvTXBEuP9s8hntucdJokbo17RwHuNXemT'),\n address('4wHbNkobu7iARU9MbCEqDSAq6JuQreGupG2Jsf2R3DFP'),\n address('5Eu2G2USTy1pqphmQzQ2SBXWrBq5sdhgEh7hso9R2xix'),\n address('A9qBhPy4k5UYW72hSgAkh1Epr2do69P54yzzcMV3yv6b'),\n address('Aw93pmXP52u6WSW2HcafRxua1LDht5MZhhXaaR7qCjsN'),\n address('CPLUA2NTYSGjsB1E9iXT3MrPn69WRFJvKTdJZw5NdEjh'),\n address('7LnqjXdqJEdccWZQs5YJobQ8MDmcK4sG2oo4Ty4LBC8c'),\n];\nexport const DEVNET_ADDRESS_LOOKUP_TABLES: AddressesByLookupTableAddress = {\n [DEVNET_LOOKUP_TABLE_ADDRESS]: [...DEVNET_LOOKUP_TABLE_ADDRESSES],\n};\n\n/**\n * The tables a client compresses with when its config names none.\n *\n * Only devnet has a shared table today. Mainnet gets one when the program is deployed there; until\n * then a mainnet or localnet client compresses with nothing, and a message over 1,232 bytes fails\n * in `buildMessage` with a request for tables. Pass `addressLookupTables` to `createClient` to\n * supply your own.\n */\nexport function defaultAddressLookupTables(cluster: Cluster): AddressesByLookupTableAddress {\n return cluster === 'devnet' ? { ...DEVNET_ADDRESS_LOOKUP_TABLES } : {};\n}\n\n/** The address lookup table program. It owns every table account. */\nconst LOOKUP_TABLE_PROGRAM = address('AddressLookupTab1e1111111111111111111111111');\n\n/**\n * The fixed part of a table account, before its addresses: a 4-byte discriminator, the two slot\n * fields, the start index, the optional authority, and two padding bytes.\n */\nconst LOOKUP_TABLE_HEADER = 56;\n\n/**\n * Read lookup tables off chain by address, for compressing against tables this SDK does not pin.\n *\n * A router picks its own tables per quote, so their contents are only known at run time, and a\n * message can only be compressed against a table whose addresses are loaded. An address with no\n * account, a wrong owner, or a malformed body is skipped rather than failing the whole route: the\n * message then carries those accounts in full, which is correct, only larger.\n */\nexport async function fetchAddressLookupTables(\n client: GaboxClient,\n addresses: Address[],\n): Promise<AddressesByLookupTableAddress> {\n const wanted = [...new Set(addresses)];\n if (wanted.length === 0) return {};\n\n const { value } = await client.rpc\n .getMultipleAccounts(wanted, { encoding: 'base64', commitment: 'confirmed' })\n .send();\n\n const decoder = getAddressDecoder();\n const tables: AddressesByLookupTableAddress = {};\n for (const [index, account] of value.entries()) {\n if (!account || account.owner !== LOOKUP_TABLE_PROGRAM) continue;\n const data = Buffer.from(account.data[0], 'base64');\n const body = data.length - LOOKUP_TABLE_HEADER;\n if (body <= 0 || body % 32 !== 0) continue;\n const stored: Address[] = [];\n for (let at = LOOKUP_TABLE_HEADER; at < data.length; at += 32) {\n stored.push(decoder.decode(new Uint8Array(data.subarray(at, at + 32))));\n }\n tables[wanted[index]!] = stored;\n }\n return tables;\n}\n","/**\n * Turning a route provider into the one swap leg a Gabox transaction needs.\n *\n * Two directions, and they are not symmetric:\n *\n * - **Paying in SOL.** The pack costs an exact amount of the quote token, so `routeQuoteIn` asks\n * for exact-out first. When the pair has no exact-out route it falls back to exact-in, working\n * out the SOL that buys the amount at the exact-in price and adding a margin.\n * - **Receiving SOL.** A sale pays the quote token in, and the seller wants SOL out. The amount\n * is already known, so `routeQuoteOut` is a plain exact-in swap.\n *\n * # Why the leg is checked before it is used\n *\n * A route is built by code outside this SDK. Its instructions go into the same transaction as\n * `buy_pack`, which means they run with the buyer's signature. So two things are checked before\n * any route is composed:\n *\n * 1. no instruction may name a Gabox account or the Gabox program itself, so a route can never\n * touch a pool, a vault, a draw or the activity account;\n * 2. the swap has to name the user's own quote associated token account, which is the account\n * the program binds and measures the quote delta in. A swap that paid somewhere else would\n * leave the buy short.\n */\n\nimport type { Address } from '@solana/kit';\n\nimport type { GaboxClient } from '../rpc';\nimport { WSOL_MINT } from '../raydium/ids';\nimport type { Route, RouteProvider } from './types';\n\n/**\n * The margin added to an exact-in fallback, in basis points.\n *\n * An exact-in quote prices one spend. The spend that buys the amount wanted is worked out from that\n * price, and the price moves against a larger spend, so the result is always a little short without\n * a margin. 1% is the same order as the slippage a caller already signs for on the pack itself.\n */\nexport const EXACT_IN_MARGIN_BPS = 100n;\n\n/**\n * The first exact-in quote's size, in lamports, when a pair has no exact-out route.\n *\n * It exists only to learn a price, so it is small enough that its own impact on the route is\n * small, and large enough that a route quotes it at all. The real spend is worked out from the\n * price it returns and re-quoted.\n */\nconst PROBE_LAMPORTS = 100_000_000n;\n\n/** How many times the exact-in fallback re-quotes before it gives up. */\nconst EXACT_IN_ATTEMPTS = 3;\n\n/**\n * A swap that leaves at least `amount` of `quoteMint` in the user's quote account, paid for in SOL.\n *\n * Exact-out when the pair has such a route, so the buyer spends only what the pack costs. Exact-in\n * otherwise, which overshoots on purpose: the leftover quote stays in the buyer's own account.\n */\nexport async function routeQuoteIn(\n client: GaboxClient,\n provider: RouteProvider,\n input: { quoteMint: Address; amount: bigint; user: Address },\n): Promise<Route> {\n const { quoteMint, amount, user } = input;\n if (amount <= 0n) throw new Error('the quote amount to buy must be positive');\n if (quoteMint === WSOL_MINT) {\n throw new Error('a WSOL-quoted pool needs no route: the builders wrap SOL themselves');\n }\n\n try {\n const route = await provider.exactOut(client, WSOL_MINT, quoteMint, amount, user);\n if (route.outAmount < amount) {\n throw new Error(\n `the exact-out route buys ${route.outAmount} of ${quoteMint}, which is below the ` +\n `${amount} the pack costs`,\n );\n }\n return route;\n } catch (exactOutFailure) {\n return await exactInFallback(client, provider, quoteMint, amount, user, exactOutFailure);\n }\n}\n\n/**\n * Work out the SOL that buys `amount` of the quote at the exact-in price, then swap it.\n *\n * The first quote is a small probe, only to learn a price. Every later quote scales the last one by\n * what it actually returned, so an impact the probe did not show is corrected rather than guessed\n * at. Three quotes at most, and a route that still falls short is an error rather than a buy that\n * fails on chain.\n */\nasync function exactInFallback(\n client: GaboxClient,\n provider: RouteProvider,\n quoteMint: Address,\n amount: bigint,\n user: Address,\n exactOutFailure: unknown,\n): Promise<Route> {\n let spend = PROBE_LAMPORTS;\n let last: Route | undefined;\n for (let attempt = 0; attempt < EXACT_IN_ATTEMPTS; attempt++) {\n let route: Route;\n try {\n route = await provider.exactIn(client, WSOL_MINT, quoteMint, spend, user);\n } catch (exactInFailure) {\n throw new Error(\n `no route from SOL to ${quoteMint}. Exact-out failed with ` +\n `\"${messageOf(exactOutFailure)}\" and exact-in with \"${messageOf(exactInFailure)}\".`,\n );\n }\n last = route;\n if (route.outAmount >= amount) return route;\n if (route.outAmount <= 0n) break;\n // Scale the spend by what this quote actually returned, then add the margin.\n const scaled = ceilDiv(route.inAmount * amount, route.outAmount);\n const next = scaled + (scaled * EXACT_IN_MARGIN_BPS) / 10_000n;\n if (next <= spend) break;\n spend = next;\n }\n throw new Error(\n `no route from SOL to ${quoteMint} buys ${amount}. The best exact-in quote returned ` +\n `${last?.outAmount ?? 0n} for ${last?.inAmount ?? spend} lamports, and exact-out failed ` +\n `with \"${messageOf(exactOutFailure)}\".`,\n );\n}\n\n/**\n * A swap that turns exactly `amount` of `quoteMint` into SOL.\n *\n * `sellTokens` uses it on the proceeds floor it already signs for, so the amount swapped is one the\n * sale is guaranteed to have produced. Anything the sale paid above that floor stays in the\n * seller's quote account.\n */\nexport async function routeQuoteOut(\n client: GaboxClient,\n provider: RouteProvider,\n input: { quoteMint: Address; amount: bigint; user: Address },\n): Promise<Route> {\n const { quoteMint, amount, user } = input;\n if (amount <= 0n) throw new Error('the quote amount to sell must be positive');\n if (quoteMint === WSOL_MINT) {\n throw new Error('a WSOL-quoted pool needs no route: the builders unwrap SOL themselves');\n }\n return await provider.exactIn(client, quoteMint, WSOL_MINT, amount, user);\n}\n\n/**\n * Refuse a route that would touch Gabox state, or that does not settle in the account the program\n * binds.\n *\n * `forbidden` is every Gabox account the transaction itself uses, plus the Gabox program id.\n * `settlesIn` is the user's quote associated token account: the swap has to name it, because that\n * is where `buy_pack` measures the quote it spends and where `sell_tokens` measures the proceeds.\n */\nexport function assertRouteIsSafe(\n route: Route,\n expect: { forbidden: readonly Address[]; settlesIn: Address },\n): void {\n const forbidden = new Set<Address>(expect.forbidden);\n let settles = false;\n for (const instruction of route.instructions) {\n if (forbidden.has(instruction.programAddress as Address)) {\n throw new Error(\n `the route calls ${instruction.programAddress}, which is a Gabox program or account. A ` +\n 'route must never touch Gabox state.',\n );\n }\n for (const account of instruction.accounts ?? []) {\n if (forbidden.has(account.address)) {\n throw new Error(\n `the route names the Gabox account ${account.address}. A route must never touch Gabox ` +\n 'state.',\n );\n }\n if (account.address === expect.settlesIn) settles = true;\n }\n }\n if (!settles) {\n throw new Error(\n `the route never names ${expect.settlesIn}, the quote account the program settles in. The ` +\n 'swap would pay somewhere the buy cannot spend from.',\n );\n }\n}\n\n/**\n * What `amount` of a quote token costs in SOL, through the client's route provider.\n *\n * `null` when the client has no provider, or when the provider has no exact-out route. A price is a\n * display, so a missing one is not an error. A WSOL amount is already SOL and comes back unchanged.\n *\n * No fallback to exact-in here on purpose: an exact-in price answers a different question, and a\n * display that silently swapped the two would be wrong rather than missing.\n */\nexport async function solPriceOf(\n client: GaboxClient,\n quoteMint: Address,\n amount: bigint,\n): Promise<bigint | null> {\n if (quoteMint === WSOL_MINT) return amount;\n if (!client.route || amount <= 0n) return null;\n try {\n // The route is priced, never built, so any address gives a valid quote.\n const route = await client.route.exactOut(client, WSOL_MINT, quoteMint, amount, quoteMint);\n return route.inAmount;\n } catch {\n return null;\n }\n}\n\n/** `ceil(numerator / denominator)` for non-negative values. */\nfunction ceilDiv(numerator: bigint, denominator: bigint): bigint {\n return (numerator + denominator - 1n) / denominator;\n}\n\nconst messageOf = (cause: unknown): string =>\n cause instanceof Error ? cause.message : String(cause);\n","/**\n * What one pack costs and what it can win, right now, for a real coin.\n *\n * This is the read every buyer-facing screen makes. It puts three things together that are useless\n * apart:\n *\n * 1. the venue's own quote — what `pool.packTokens` costs at this moment, its fees included;\n * 2. `math.quote` over the pack size and the vault's live inventory — the exact prize amounts a\n * pack buy would freeze into the `Draw`;\n * 3. whether the pool can pay the whole table.\n *\n * The prize amounts only move when the inventory cap bites. The price moves with the coin.\n *\n * Gabox charges nothing, so `quoteAmount` is the whole pack price. It already includes what\n * Raydium takes: on the curve, 0.5% to the Gabox platform wallet and 0.5% to the coin creator, plus\n * Raydium's own trade fee; on a graduated coin, the CPMM pool fee and the pool creator fee.\n *\n * `quoteAmount` is in the pool's own quote token, which is not always SOL. `solAmount` is the same\n * price in SOL, priced through the client's route provider: the exact-out cost of buying\n * `quoteAmount` of the quote token. It is `null` when the client has no provider or the pair has no\n * route, because a price is a display and a missing one is not an error.\n *\n * Nothing here is an estimate of cash value. Every number is tokens or base units.\n */\n\nimport type { Address } from '@solana/kit';\n\nimport { fetchPoolInventory, tiersOf, type PoolInventory } from './accounts';\nimport { fetchQuoteDisplay } from './raydium/quote';\nimport { solPriceOf } from './route/leg';\nimport {\n averageMultiplierBps,\n maxMultiplierBps,\n quote,\n seedTokens,\n uncappedMaximum,\n type Offer,\n type Prize,\n} from './math';\nimport { resolveVenue, type VenueKind } from './raydium/venue';\nimport type { GaboxClient } from './rpc';\n\nexport type PackOffer = {\n mint: Address;\n pool: Address;\n /** The fixed token count of one pack. Every prize is a multiple of this. */\n packTokens: bigint;\n /** What the venue charges for `packTokens` right now, its own fees included. The pack price. */\n quoteAmount: bigint;\n /** The pool's quote asset. Both venues settle in it; there is no native-SOL path. */\n quoteMint: Address;\n /** The quote mint's decimals, so `quoteAmount` can be shown as a number. */\n quoteDecimals: number;\n /** The quote mint's symbol, from Metaplex or Token-2022 metadata. `null` when it has none. */\n quoteSymbol: string | null;\n /**\n * The same pack price in lamports, through the client's route provider. Equal to `quoteAmount` on\n * a WSOL pool, and `null` when no route can price it.\n */\n solAmount: bigint | null;\n /** What the seed cost the creator at creation, in the quote token. Display only. */\n seedQuoteAmount: bigint;\n /** Tokens the seed locked in the vault. Derived from the live table. */\n seedTokens: bigint;\n /** Which venue the buy would route to right now. */\n venue: VenueKind;\n /** The frozen prize table this pack would get: real amounts, already capped by inventory. */\n prizes: Prize[];\n /** The top prize, after the cap. Sign `minMaximum` just below this. */\n maximum: bigint;\n /** The smallest prize. Also what a timed-out draw pays. */\n minimum: bigint;\n /**\n * The top prize with no inventory cap: the jackpot in tokens. Equal to `maximum` unless the\n * inventory cap bites.\n */\n uncapped: bigint;\n /** Vault balance, `pool.reserved`, and the difference. */\n inventory: bigint;\n reserved: bigint;\n free: bigint;\n /** `pool.nextSeq === 0`. No pack has been sold yet. */\n isFirstPack: boolean;\n /**\n * Does the pool pay the whole table right now?\n *\n * `offer.maximum === uncapped`. The seed guarantees this for the first pack. Later it is a\n * quality signal: a capped top prize is legal and the pool still sells the pack. It just pays\n * less than the table says, and a buyer should see that.\n */\n isSeeded: boolean;\n /** The largest and the ticket-weighted average multiplier of the immutable table, in bps. */\n maxMultiplierBps: number;\n averageMultiplierBps: number;\n};\n\nexport type GetOfferOptions = {\n /** Force a venue instead of reading the LaunchLab pool's `status`. */\n venue?: VenueKind;\n /** The buyer, when you already know it. Only changes the account list, never the numbers. */\n user?: Address;\n};\n\n/**\n * The full offer for one machine. Three round trips: the pool and its vault, the venue, then the\n * quote mint and its metadata. A non-SOL pool adds one HTTP call to the route provider for\n * `solAmount`.\n *\n * Throws when the coin has no pool.\n */\nexport async function getOffer(\n client: GaboxClient,\n mint: Address,\n options: GetOfferOptions = {},\n): Promise<PackOffer> {\n const inventory = await fetchPoolInventory(client, mint);\n if (!inventory) throw new Error(`no gabox pool for mint ${mint}`);\n const { pool } = inventory;\n\n const venue = await resolveVenue(client, {\n mint,\n user: options.user ?? pool.creator,\n quote: {\n mint: pool.quoteMint,\n config: pool.quoteConfig,\n tokenProgram: pool.quoteTokenProgram,\n },\n ...(options.venue ? { venue: options.venue } : {}),\n });\n\n const quoteAmount = venue.quoteBuy(pool.packTokens);\n const display = await fetchQuoteDisplay(client, pool.quoteMint);\n return offerFromState(inventory, venue.kind, quoteAmount, {\n quoteDecimals: display.decimals,\n quoteSymbol: display.symbol,\n solAmount: await solPriceOf(client, pool.quoteMint, quoteAmount),\n });\n}\n\n/** The three display fields `getOffer` reads separately from the price. */\nexport type QuoteDisplayFields = {\n quoteDecimals: number;\n quoteSymbol: string | null;\n solAmount: bigint | null;\n};\n\n/**\n * The same computation with the reads already done. Useful when a caller holds a `ResolvedVenue`\n * and wants to re-price without touching the network. `quoteAmount` is\n * `venue.quoteBuy(pool.packTokens)`.\n *\n * `display` is optional: a caller that only wants the prize numbers can leave it out, and the three\n * display fields then report the quote's own base units with no symbol and no SOL price.\n */\nexport function offerFromState(\n inventory: PoolInventory,\n venue: VenueKind,\n quoteAmount: bigint,\n display: QuoteDisplayFields = { quoteDecimals: 0, quoteSymbol: null, solAmount: null },\n): PackOffer {\n const { pool } = inventory;\n const tiers = tiersOf(pool);\n const offer: Offer = quote(pool.packTokens, tiers, inventory.inventory, inventory.reserved);\n const uncapped = uncappedMaximum(pool.packTokens, tiers);\n\n return {\n mint: pool.mint,\n pool: inventory.poolAddress,\n packTokens: pool.packTokens,\n quoteAmount,\n quoteMint: pool.quoteMint,\n quoteDecimals: display.quoteDecimals,\n quoteSymbol: display.quoteSymbol,\n solAmount: display.solAmount,\n seedQuoteAmount: pool.seedQuoteAmount,\n seedTokens: seedTokens(pool.packTokens, tiers),\n venue,\n prizes: offer.prizes,\n maximum: offer.maximum,\n minimum: offer.minimum,\n uncapped,\n inventory: inventory.inventory,\n reserved: inventory.reserved,\n free: inventory.free,\n isFirstPack: pool.nextSeq === 0n,\n isSeeded: offer.maximum === uncapped,\n maxMultiplierBps: maxMultiplierBps(tiers),\n averageMultiplierBps: averageMultiplierBps(tiers),\n };\n}\n\n/**\n * How short of the top prize a pool is, in tokens. `0` when it pays the whole table.\n *\n * The pack brings its own `packTokens` into the vault before the offer is computed, so the vault\n * only has to hold `uncapped - packTokens` beforehand. Anything already reserved by another draw\n * does not count. A donation of this size through `fund_prizes` uncaps the top prize again.\n */\nexport function seedShortfall(offer: PackOffer): bigint {\n const needed = offer.uncapped > offer.packTokens ? offer.uncapped - offer.packTokens : 0n;\n return offer.free >= needed ? 0n : needed - offer.free;\n}\n\nexport { seedTokens };\n","/**\n * A route provider backed by one Raydium CPMM pool.\n *\n * Jupiter does not serve devnet, so a devnet machine quoted in a test token needs a route this SDK\n * can build itself. Given a CPMM pool that holds the SOL/quote pair, this provider swaps through\n * it with the same two instructions Gabox already forwards for a graduated coin, priced with the\n * same bigint port of Raydium's math.\n *\n * It works anywhere such a pool exists, mainnet included. It is not a router: it uses the one pool\n * the caller names and nothing else.\n *\n * # Wrapping\n *\n * CPMM settles in WSOL, never in native SOL. So the route wraps the SOL it spends and closes the\n * WSOL account afterwards, exactly as Jupiter's `wrapAndUnwrapSol` does. A sale into SOL creates\n * the WSOL account, swaps into it, and closes it, which is what turns the proceeds into SOL.\n *\n * # No signer objects\n *\n * The user is an address, not a signer. Every signing slot is marked as a signer and left for the\n * fee payer to sign, the same way a Jupiter instruction arrives. The wallet paying for the Gabox\n * transaction is the same wallet, so its one signature covers all of them.\n *\n * That is not a shortcut, it is required. Kit refuses to sign a message that carries two distinct\n * signer objects for one address: `signTransactionMessageWithSigners` fails with \"Multiple distinct\n * signers were identified for address\". The token and system builders below only accept a signer,\n * so `withoutSigners` strips the object again and keeps the role.\n */\n\nimport {\n createNoopSigner,\n getU64Encoder,\n type AccountMeta,\n type Address,\n type Instruction,\n type TransactionSigner,\n} from '@solana/kit';\nimport {\n getCloseAccountInstruction,\n getCreateAssociatedTokenIdempotentInstruction,\n getSyncNativeInstruction,\n} from '@solana-program/token';\nimport { getTransferSolInstruction } from '@solana-program/system';\n\nimport { decodeCpmmAmmConfig, decodeCpmmPool, tokenAccountAmount } from '../raydium/adapter';\nimport { CPMM_SWAP_BASE_INPUT, CPMM_SWAP_BASE_OUTPUT } from '../raydium/abi';\nimport { order } from '../raydium/accounts';\nimport {\n cpmmSwapBaseInput,\n cpmmSwapBaseOutput,\n type CpmmFeeRates,\n type CpmmSwapSides,\n} from '../raydium/curve';\nimport { WSOL_MINT, raydiumIds } from '../raydium/ids';\nimport { ata } from '../raydium/pdas';\nimport { readAccounts } from '../raydium/read';\nimport { creatorFeeOnInput } from '../raydium/venue';\nimport type { GaboxClient } from '../rpc';\nimport type { Route, RouteProvider } from './types';\n\nconst u64 = getU64Encoder();\n\n/**\n * The slippage this provider signs for on a pool swap, in basis points. 1%, the same as the\n * Jupiter provider's default. It only widens the on-chain bound; the price itself is exact.\n */\nexport const CPMM_ROUTE_SLIPPAGE_BPS = 100n;\n\n/**\n * The compute units one swap through this provider adds to a transaction.\n *\n * Measured on devnet on 2026-09-18 against one Raydium CPMM pool, as the difference from the same\n * builder with no route: `55,110` and `29,272` on `createMachine`, `21,488` and `52,980` on\n * `buyPack`, and `30,138` and `51,138` on `sellTokens`. The spread is wide because which token\n * accounts already exist changes from run to run, so this rounds up to the top of it.\n *\n * It is a safe figure here and nowhere else: this provider always uses exactly one pool. A router\n * that may pick several hops states its own number; see `JUPITER_DEFAULT_COMPUTE_UNITS`.\n */\nexport const CPMM_ROUTE_COMPUTE_UNITS = 75_000;\n\n/**\n * Swap through one named Raydium CPMM pool.\n *\n * The pool must hold the pair the route asks for. On devnet the SOL/USDC-test pool with the most\n * liquidity is `5Eu2G2USTy1pqphmQzQ2SBXWrBq5sdhgEh7hso9R2xix`, under the fee tier\n * `A9qBhPy4k5UYW72hSgAkh1Epr2do69P54yzzcMV3yv6b`.\n */\nexport function raydiumCpmmRoute(poolAddress: Address): RouteProvider {\n return {\n exactOut: async (client, input, output, amount, user) =>\n await swap(client, poolAddress, { input, output, amount, user, mode: 'exactOut' }),\n exactIn: async (client, input, output, amount, user) =>\n await swap(client, poolAddress, { input, output, amount, user, mode: 'exactIn' }),\n };\n}\n\nasync function swap(\n client: GaboxClient,\n poolAddress: Address,\n request: {\n input: Address;\n output: Address;\n amount: bigint;\n user: Address;\n mode: Route['mode'];\n },\n): Promise<Route> {\n const { input, output, amount, user, mode } = request;\n if (amount <= 0n) throw new Error('the route amount must be positive');\n const ids = raydiumIds(client.cluster);\n\n const [poolAccount] = await readAccounts(client.rpc, [poolAddress]);\n if (!poolAccount || poolAccount.owner !== ids.cpmm) {\n throw new Error(`${poolAddress} is not a Raydium CPMM pool on ${client.cluster}`);\n }\n const pool = decodeCpmmPool(poolAccount.data);\n\n const inputIsToken0 = pool.token0Mint === input;\n const holdsPair = inputIsToken0\n ? pool.token1Mint === output\n : pool.token1Mint === input && pool.token0Mint === output;\n if (!holdsPair) {\n throw new Error(\n `the CPMM pool at ${poolAddress} holds ${pool.token0Mint} and ${pool.token1Mint}, not ` +\n `${input} and ${output}`,\n );\n }\n\n const inputVault = inputIsToken0 ? pool.token0Vault : pool.token1Vault;\n const outputVault = inputIsToken0 ? pool.token1Vault : pool.token0Vault;\n const inputTokenProgram = inputIsToken0 ? pool.token0Program : pool.token1Program;\n const outputTokenProgram = inputIsToken0 ? pool.token1Program : pool.token0Program;\n\n const [configAccount, inputVaultAccount, outputVaultAccount] = await readAccounts(client.rpc, [\n pool.ammConfig,\n inputVault,\n outputVault,\n ]);\n if (!configAccount) throw new Error(`the CPMM pool at ${poolAddress} names a fee tier that is not on chain`);\n if (!inputVaultAccount || !outputVaultAccount) {\n throw new Error(`the CPMM pool at ${poolAddress} has no reserve accounts`);\n }\n const config = decodeCpmmAmmConfig(configAccount.data);\n\n // A swap may not spend what the pool already owes. Raydium subtracts the same three balances.\n const owed = (token0: boolean) =>\n token0\n ? pool.protocolFeesToken0 + pool.fundFeesToken0 + pool.creatorFeesToken0\n : pool.protocolFeesToken1 + pool.fundFeesToken1 + pool.creatorFeesToken1;\n const sides: CpmmSwapSides = {\n inputReserve: tokenAccountAmount(inputVaultAccount.data) - owed(inputIsToken0),\n outputReserve: tokenAccountAmount(outputVaultAccount.data) - owed(!inputIsToken0),\n };\n if (sides.inputReserve <= 0n || sides.outputReserve <= 0n) {\n throw new Error(`the CPMM pool at ${poolAddress} has no tradable reserves`);\n }\n const rates: CpmmFeeRates = {\n tradeFeeRate: config.tradeFeeRate,\n creatorFeeRate: pool.enableCreatorFee ? config.creatorFeeRate : 0n,\n creatorFeeOnInput: creatorFeeOnInput(pool, input),\n };\n\n const userInput = await ata(user, input, inputTokenProgram);\n const userOutput = await ata(user, output, outputTokenProgram);\n const abi = mode === 'exactOut' ? CPMM_SWAP_BASE_OUTPUT : CPMM_SWAP_BASE_INPUT;\n const accounts = order(abi, {\n payer: user,\n authority: ids.cpmmAuthority,\n amm_config: pool.ammConfig,\n pool_state: poolAddress,\n input_token_account: userInput,\n output_token_account: userOutput,\n input_vault: inputVault,\n output_vault: outputVault,\n input_token_program: inputTokenProgram,\n output_token_program: outputTokenProgram,\n input_token_mint: input,\n output_token_mint: output,\n observation_state: pool.observationKey,\n });\n\n // `swap_base_output` takes `(max_amount_in, amount_out)`; `swap_base_input` takes\n // `(amount_in, minimum_amount_out)`. The two orders are the reverse of each other.\n const exactOut = mode === 'exactOut';\n const priced = exactOut\n ? cpmmSwapBaseOutput(sides, rates, amount)\n : cpmmSwapBaseInput(sides, rates, amount);\n const inAmount = exactOut ? widen(priced) : amount;\n const outAmount = exactOut ? amount : narrow(priced);\n const swapInstruction = {\n programAddress: ids.cpmm,\n accounts,\n data: new Uint8Array([\n ...abi.discriminator,\n ...u64.encode(exactOut ? inAmount : amount),\n ...u64.encode(exactOut ? amount : outAmount),\n ]),\n } as Instruction;\n\n return {\n instructions: wrap({\n user,\n input,\n output,\n userInput,\n userOutput,\n inputTokenProgram,\n outputTokenProgram,\n lamportsIn: inAmount,\n middle: [swapInstruction],\n }),\n // The devnet lookup table already carries every Raydium address this route names.\n lookupTables: {},\n inAmount,\n outAmount,\n mode,\n computeUnits: CPMM_ROUTE_COMPUTE_UNITS,\n };\n}\n\n/** Add the slippage margin to a cost the caller signs as a maximum. */\nconst widen = (amount: bigint): bigint => amount + (amount * CPMM_ROUTE_SLIPPAGE_BPS) / 10_000n;\n/** Take the slippage margin off a payout the caller signs as a minimum. */\nconst narrow = (amount: bigint): bigint => amount - (amount * CPMM_ROUTE_SLIPPAGE_BPS) / 10_000n;\n\n/**\n * Create the two token accounts the swap needs, wrap the SOL it spends, and close the WSOL account\n * afterwards.\n *\n * Only one side is ever WSOL here: a Gabox pool quoted in WSOL never uses a route at all.\n */\nfunction wrap(input: {\n user: Address;\n input: Address;\n output: Address;\n userInput: Address;\n userOutput: Address;\n inputTokenProgram: Address;\n outputTokenProgram: Address;\n lamportsIn: bigint;\n middle: Instruction[];\n}): Instruction[] {\n // A placeholder, only so the builders below mark their signing slots. `withoutSigners` removes\n // the object again before the instruction leaves this file.\n const payer = createNoopSigner(input.user);\n const createAta = (account: Address, mint: Address, tokenProgram: Address): Instruction =>\n withoutSigners(\n getCreateAssociatedTokenIdempotentInstruction({\n payer,\n ata: account,\n owner: input.user,\n mint,\n tokenProgram,\n }) as Instruction,\n );\n\n const before: Instruction[] = [\n createAta(input.userInput, input.input, input.inputTokenProgram),\n createAta(input.userOutput, input.output, input.outputTokenProgram),\n ];\n const after: Instruction[] = [];\n\n if (input.input === WSOL_MINT) {\n before.push(\n withoutSigners(\n getTransferSolInstruction({\n source: payer,\n destination: input.userInput,\n amount: input.lamportsIn,\n }) as Instruction,\n ),\n // Without this the token account holds the lamports but still reports a zero balance.\n getSyncNativeInstruction({ account: input.userInput }) as Instruction,\n );\n after.push(closeWsol(input.userInput, payer));\n }\n if (input.output === WSOL_MINT) {\n after.push(closeWsol(input.userOutput, payer));\n }\n return [...before, ...input.middle, ...after];\n}\n\n/**\n * Close a WSOL account, sending every lamport in it back to the owner as SOL.\n *\n * The owner has to sign, so it goes in as a signer and comes out as a plain signing slot.\n */\nconst closeWsol = (account: Address, owner: TransactionSigner): Instruction =>\n withoutSigners(\n getCloseAccountInstruction({ account, destination: owner.address, owner }) as Instruction,\n );\n\n/**\n * Drop every attached signer object, keeping each account's address and role.\n *\n * A signing slot stays a signing slot: the compiled message still requires that signature, and the\n * wallet paying for the transaction provides it. What goes away is the second signer object for an\n * address the fee payer already covers, which kit refuses to sign.\n */\nfunction withoutSigners(instruction: Instruction): Instruction {\n const accounts: AccountMeta[] = (instruction.accounts ?? []).map((account) => ({\n address: account.address,\n role: account.role,\n }));\n return { ...instruction, accounts } as Instruction;\n}\n","/**\n * The Jupiter route provider.\n *\n * Jupiter is an HTTP service, not a program this SDK builds instructions for. Two calls per route:\n *\n * 1. `GET /swap/v1/quote` prices the swap and returns a quote object.\n * 2. `POST /swap/v1/swap-instructions` turns that quote into instructions.\n *\n * The response gives `setupInstructions`, `swapInstruction` and `cleanupInstruction`, each as a\n * program id, a list of accounts and base64 data. This module decodes those into kit instructions\n * and leaves everything else alone. Jupiter's own compute budget instructions are dropped: every\n * builder in this SDK sets its own budget, and two `SetComputeUnitLimit` instructions in one message\n * is one too many. Their **number** is kept, though: it is Jupiter's own answer to \"how much does\n * this route cost\", and a builder adds it to its own limit.\n *\n * `wrapAndUnwrapSol: true` is always sent, so Jupiter creates the wallet's WSOL account, funds it\n * from the wallet's lamports and closes it again inside its own instructions. That is what makes\n * \"pay in SOL\" true from the wallet's side.\n *\n * # No Jupiter package\n *\n * The public surface of this SDK is `@solana/kit` only. Nothing here imports a Jupiter package; the\n * response is plain JSON and the decoding below is a dozen lines.\n *\n * # Exact-out is not always available\n *\n * Jupiter answers `NO_ROUTES_FOUND` for an exact-out quote whenever the best route has more than\n * one hop. Verified on 2026-09-18: SOL to USDC quotes exact-out, while SOL to the stock token\n * `XsDoVfqeBukxuZHWhdvWHBhgEHjGNst4MLodqsJHzoB` only quotes exact-in. `routeQuoteIn` in `leg.ts`\n * handles that fallback; this file only reports the failure.\n */\n\nimport {\n AccountRole,\n getBase64Encoder,\n type AccountMeta,\n type Address,\n type Instruction,\n} from '@solana/kit';\n\nimport { fetchAddressLookupTables } from '../lookupTables';\nimport type { GaboxClient } from '../rpc';\nimport type { Route, RouteProvider } from './types';\n\n/** Jupiter's free endpoint. The keyed host `https://api.jup.ag/swap/v1` has the same shape. */\nexport const JUPITER_LITE_URL = 'https://lite-api.jup.ag/swap/v1';\n\n/** The slippage Jupiter prices a route with when the caller names none. 1%. */\nexport const JUPITER_DEFAULT_SLIPPAGE_BPS = 100;\n\n/**\n * The compute units a Jupiter route is assumed to need when the response carries no limit.\n *\n * Jupiter normally sends a `SetComputeUnitLimit` of its own, and that number is what this SDK uses.\n * When it does not, this is the fallback: enough for a route through several pools, and still far\n * below the 1,400,000-unit ceiling once the Gabox instruction's own budget is added. A caller who\n * knows better passes `computeUnitLimit` to the builder.\n */\nexport const JUPITER_DEFAULT_COMPUTE_UNITS = 400_000;\n\n/** `ComputeBudgetInstruction::SetComputeUnitLimit`, whose data is the tag then a u32 of units. */\nconst SET_COMPUTE_UNIT_LIMIT = 2;\n\nexport type JupiterRouteOptions = {\n /** The base URL of the swap API. Defaults to the free `lite-api` host. */\n url?: string;\n /** Slippage for the quote, in basis points. Defaults to 100, which is 1%. */\n slippageBps?: number;\n};\n\nconst base64 = getBase64Encoder();\n\n/** One account as the swap-instructions response writes it. */\ntype JupiterAccount = { pubkey: string; isSigner: boolean; isWritable: boolean };\ntype JupiterInstruction = { programId: string; accounts: JupiterAccount[]; data: string };\n\n/** The fields of a `swap-instructions` response this SDK reads. */\nexport type JupiterSwapInstructions = {\n /** Read for its unit limit only. These instructions are never copied into the message. */\n computeBudgetInstructions?: JupiterInstruction[] | null;\n setupInstructions?: JupiterInstruction[] | null;\n swapInstruction: JupiterInstruction;\n cleanupInstruction?: JupiterInstruction | null;\n addressLookupTableAddresses?: string[] | null;\n};\n\n/**\n * A route provider backed by Jupiter. Use it on mainnet, where Jupiter has the liquidity.\n *\n * It makes read-only HTTP calls and never sends a transaction: the instructions come back to the\n * caller, who signs them together with the Gabox instruction.\n */\nexport function jupiterRoute(options: JupiterRouteOptions = {}): RouteProvider {\n const url = (options.url ?? JUPITER_LITE_URL).replace(/\\/+$/, '');\n const slippageBps = options.slippageBps ?? JUPITER_DEFAULT_SLIPPAGE_BPS;\n\n const build = async (\n client: GaboxClient,\n input: Address,\n output: Address,\n amount: bigint,\n user: Address,\n swapMode: 'ExactOut' | 'ExactIn',\n ): Promise<Route> => {\n if (amount <= 0n) throw new Error('the route amount must be positive');\n const quote = await fetchQuote(url, { input, output, amount, swapMode, slippageBps });\n const response = await fetchSwapInstructions(url, quote, user);\n // `otherAmountThreshold` is the side the swap is bound to on chain: the most it will spend on\n // an exact-out route, the least it will pay out on an exact-in one. The other side is exact.\n // A `Route` states bounds, not hopes, so the threshold is what goes in it.\n const threshold = BigInt(String(quote.otherAmountThreshold));\n return await routeFrom(client, response, {\n inAmount: swapMode === 'ExactOut' ? threshold : BigInt(String(quote.inAmount)),\n outAmount: swapMode === 'ExactOut' ? BigInt(String(quote.outAmount)) : threshold,\n mode: swapMode === 'ExactOut' ? 'exactOut' : 'exactIn',\n });\n };\n\n return {\n exactOut: async (client, input, output, amount, user) =>\n await build(client, input, output, amount, user, 'ExactOut'),\n exactIn: async (client, input, output, amount, user) =>\n await build(client, input, output, amount, user, 'ExactIn'),\n };\n}\n\n/**\n * The quote object Jupiter returns. It is passed back to `swap-instructions` unchanged, so it\n * carries more fields than these three; only these are read.\n */\ntype JupiterQuote = {\n inAmount: string | number;\n outAmount: string | number;\n /** The bound the swap enforces on chain, once slippage is applied. */\n otherAmountThreshold: string | number;\n};\n\nasync function fetchQuote(\n url: string,\n input: {\n input: Address;\n output: Address;\n amount: bigint;\n swapMode: 'ExactOut' | 'ExactIn';\n slippageBps: number;\n },\n): Promise<JupiterQuote> {\n const query = new URLSearchParams({\n inputMint: input.input,\n outputMint: input.output,\n amount: input.amount.toString(),\n swapMode: input.swapMode,\n slippageBps: String(input.slippageBps),\n });\n const response = await fetch(`${url}/quote?${query.toString()}`);\n const body = (await response.json()) as JupiterQuote & { error?: string; errorCode?: string };\n if (!response.ok || body.error) {\n throw new Error(\n `Jupiter has no ${input.swapMode} route from ${input.input} to ${input.output}: ` +\n `${body.errorCode ?? response.status} ${body.error ?? ''}`.trim(),\n );\n }\n return body;\n}\n\nasync function fetchSwapInstructions(\n url: string,\n quoteResponse: JupiterQuote,\n userPublicKey: Address,\n): Promise<JupiterSwapInstructions> {\n const response = await fetch(`${url}/swap-instructions`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ quoteResponse, userPublicKey, wrapAndUnwrapSol: true }),\n });\n const body = (await response.json()) as JupiterSwapInstructions & { error?: string };\n if (!response.ok || body.error || !body.swapInstruction) {\n throw new Error(\n `Jupiter could not build the swap instructions: ${response.status} ${body.error ?? ''}`.trim(),\n );\n }\n return body;\n}\n\n/**\n * Turn a decoded `swap-instructions` response into a `Route`.\n *\n * Exported so a test can read a recorded response without making an HTTP call. The lookup tables\n * are read through the client, because the response names them by address only.\n */\nexport async function routeFrom(\n client: GaboxClient,\n response: JupiterSwapInstructions,\n amounts: { inAmount: bigint; outAmount: bigint; mode: Route['mode'] },\n): Promise<Route> {\n const instructions: Instruction[] = [\n ...(response.setupInstructions ?? []).map(toKitInstruction),\n toKitInstruction(response.swapInstruction),\n ...(response.cleanupInstruction ? [toKitInstruction(response.cleanupInstruction)] : []),\n ];\n const lookupTables = await fetchAddressLookupTables(\n client,\n (response.addressLookupTableAddresses ?? []) as Address[],\n );\n return { instructions, lookupTables, computeUnits: computeUnitsOf(response), ...amounts };\n}\n\n/**\n * The unit limit Jupiter asked for, or `JUPITER_DEFAULT_COMPUTE_UNITS` when it asked for none.\n *\n * `SetComputeUnitLimit` is five bytes: the tag `2`, then the units as a little-endian u32. Any other\n * compute budget instruction, such as a unit price, is skipped.\n */\nexport function computeUnitsOf(response: JupiterSwapInstructions): number {\n for (const instruction of response.computeBudgetInstructions ?? []) {\n const data = new Uint8Array(base64.encode(instruction.data));\n if (data.length < 5 || data[0] !== SET_COMPUTE_UNIT_LIMIT) continue;\n return new DataView(data.buffer, data.byteOffset).getUint32(1, true);\n }\n return JUPITER_DEFAULT_COMPUTE_UNITS;\n}\n\n/** One Jupiter instruction as a kit instruction. The roles come from the two booleans. */\nfunction toKitInstruction(instruction: JupiterInstruction): Instruction {\n const accounts: AccountMeta[] = instruction.accounts.map((account) => ({\n address: account.pubkey as Address,\n role: account.isSigner\n ? account.isWritable\n ? AccountRole.WRITABLE_SIGNER\n : AccountRole.READONLY_SIGNER\n : account.isWritable\n ? AccountRole.WRITABLE\n : AccountRole.READONLY,\n }));\n return {\n programAddress: instruction.programId as Address,\n accounts,\n data: new Uint8Array(base64.encode(instruction.data)),\n } as Instruction;\n}\n","/**\n * The client, and the cluster guard.\n *\n * `createClient` is the SDK's init step. It takes the cluster and the RPC endpoint once and returns\n * one object that every other chain-touching function in this SDK takes as its first argument: the\n * RPC, the subscriptions client, and the address lookup tables that cluster compresses with.\n *\n * # Why `cluster` has no default\n *\n * v1's simulator was one empty wallet away from running against mainnet. Nothing in the code said\n * which cluster it was pointed at; the answer lived in a shell variable and in the operator's head.\n * The failure would not have been a crash. It would have been real transactions on real money,\n * discovered afterwards.\n *\n * So the cluster is a property of the code, not of the environment. The caller names it in the\n * same call that names the URL, and the two are checked against each other:\n *\n * - `devnet` needs a URL that names devnet. A URL that names nothing is refused too, because\n * \"I thought this was devnet\" is exactly the accident this guard exists for.\n * - `mainnet-beta` and `localnet` refuse a URL that names a different cluster. A URL that names\n * nothing is allowed: private mainnet endpoints often do not say \"mainnet\", and a local\n * validator never says anything.\n *\n * Mainnet is one word away. It is a word the caller has to write.\n */\n\nimport {\n createSolanaRpc,\n createSolanaRpcSubscriptions,\n type AddressesByLookupTableAddress,\n type Rpc,\n type RpcSubscriptions,\n type SolanaRpcApi,\n type SolanaRpcSubscriptionsApi,\n} from '@solana/kit';\n\nimport { defaultAddressLookupTables } from './lookupTables';\nimport { jupiterRoute } from './route/jupiter';\nimport type { RouteProvider } from './route/types';\n\nexport type Cluster = 'devnet' | 'mainnet-beta' | 'localnet';\n\n/** Solana's public endpoints, and the test validator's default ports. */\nexport const CLUSTER_ENDPOINTS: Readonly<Record<Cluster, { url: string; wsUrl: string }>> = {\n devnet: { url: 'https://api.devnet.solana.com', wsUrl: 'wss://api.devnet.solana.com' },\n 'mainnet-beta': {\n url: 'https://api.mainnet-beta.solana.com',\n wsUrl: 'wss://api.mainnet-beta.solana.com',\n },\n localnet: { url: 'http://127.0.0.1:8899', wsUrl: 'ws://127.0.0.1:8900' },\n};\n\nexport const DEVNET_HTTP = CLUSTER_ENDPOINTS.devnet.url;\nexport const DEVNET_WS = CLUSTER_ENDPOINTS.devnet.wsUrl;\n\nexport type GaboxRpc = Rpc<SolanaRpcApi>;\nexport type GaboxRpcSubscriptions = RpcSubscriptions<SolanaRpcSubscriptionsApi>;\n\nexport type ClientConfig = {\n /** The cluster this client talks to. Required: see the file comment. */\n cluster: Cluster;\n /** HTTP endpoint. Defaults to the cluster's entry in `CLUSTER_ENDPOINTS`. */\n url?: string;\n /**\n * WebSocket endpoint. Left out, it follows `url`: `https` becomes `wss`, `http` becomes `ws`.\n * When `url` is left out too, it is the cluster's default.\n */\n wsUrl?: string;\n /**\n * Address lookup tables every builder compresses with. Defaults to the cluster's shared table,\n * which only devnet has today; other clusters default to none. Pass `{}` to disable compression.\n */\n addressLookupTables?: AddressesByLookupTableAddress;\n /**\n * How a buyer pays in SOL for a machine priced in another token.\n *\n * Mainnet defaults to Jupiter, which is where the liquidity is. Devnet and localnet default to\n * none, because Jupiter does not serve them: pass `raydiumCpmmRoute(pool)` with a CPMM pool that\n * holds the SOL/quote pair. `null` disables the swap leg, and `payWith: 'sol'` then fails on a\n * pool quoted in anything but WSOL.\n */\n route?: RouteProvider | null;\n};\n\n/**\n * Everything the SDK needs to talk to one cluster. Pass it to every chain-touching function.\n *\n * A plain object, so a caller who needs a custom transport can spread it:\n * `{ ...createClient({ cluster }), rpc: createSolanaRpcFromTransport(transport) }`.\n */\nexport type GaboxClient = Readonly<{\n cluster: Cluster;\n url: string;\n wsUrl: string;\n rpc: GaboxRpc;\n rpcSubscriptions: GaboxRpcSubscriptions;\n addressLookupTables: AddressesByLookupTableAddress;\n /** The swap provider a SOL payment routes through, or `null` when this cluster has none. */\n route: RouteProvider | null;\n}>;\n\n/**\n * The cluster a URL names, from its text alone. A substring check, deliberately: providers spell\n * it many ways. `null` when the URL names none, which is a local validator or a private endpoint.\n */\nexport function clusterNamedBy(url: string): Cluster | 'testnet' | null {\n const lower = url.toLowerCase();\n if (lower.includes('devnet')) return 'devnet';\n if (lower.includes('mainnet')) return 'mainnet-beta';\n if (lower.includes('testnet')) return 'testnet';\n return null;\n}\n\n/**\n * Refuse a URL that contradicts the declared cluster. Exported so a script can check a URL before\n * it does anything else with it. The rules are in the file comment.\n */\nexport function assertClusterUrl(cluster: Cluster, url: string): void {\n const named = clusterNamedBy(url);\n if (cluster === 'devnet' && named !== 'devnet') {\n throw new Error(\n `refusing to use ${url} as a devnet endpoint: it does not name devnet.\\n` +\n 'A Gabox program id, a MagicBlock queue and a pool address all exist on every cluster, so ' +\n 'a wrong URL is a live transaction, not an error. Pass ' +\n \"{ cluster: 'localnet' } for a local validator, or name the cluster the URL really is.\",\n );\n }\n if (cluster !== 'devnet' && named !== null && named !== cluster) {\n throw new Error(\n `refusing to use ${url} as a ${cluster} endpoint: the URL names ${named}.\\n` +\n 'A Gabox address exists on every cluster, so a wrong URL is a live transaction, not an ' +\n 'error. Pass the cluster the URL really names.',\n );\n }\n}\n\n/** `https://x` becomes `wss://x`, `http://x` becomes `ws://x`. Anything else is returned as is. */\nexport function websocketUrlFor(url: string): string {\n if (url.startsWith('https://')) return `wss://${url.slice('https://'.length)}`;\n if (url.startsWith('http://')) return `ws://${url.slice('http://'.length)}`;\n return url;\n}\n\n/**\n * The SDK's init step. Call it once and pass the result everywhere.\n *\n * Both RPC clients are created together because everything in this SDK that watches a draw needs\n * the pair: the subscription reports the change, and the RPC reads the account that changed.\n */\nexport function createClient(config: ClientConfig): GaboxClient {\n const { cluster } = config;\n const defaults = CLUSTER_ENDPOINTS[cluster];\n if (!defaults) {\n throw new Error(\n `unknown cluster ${JSON.stringify(cluster)}; expected 'devnet', 'mainnet-beta' or 'localnet'`,\n );\n }\n\n const url = config.url ?? defaults.url;\n assertClusterUrl(cluster, url);\n\n // A custom `url` without a `wsUrl` gets the same host over WebSocket. The cluster's default\n // pair is only used as a pair: the test validator serves WebSocket on a different port.\n const wsUrl = config.wsUrl ?? (config.url === undefined ? defaults.wsUrl : websocketUrlFor(url));\n assertClusterUrl(cluster, wsUrl);\n\n return {\n cluster,\n url,\n wsUrl,\n rpc: createSolanaRpc(url),\n rpcSubscriptions: createSolanaRpcSubscriptions(wsUrl),\n addressLookupTables: config.addressLookupTables ?? defaultAddressLookupTables(cluster),\n route: config.route === undefined ? defaultRoute(cluster) : config.route,\n };\n}\n\n/**\n * The swap provider a cluster gets when the caller names none.\n *\n * Jupiter on mainnet, nothing anywhere else. Jupiter's API only prices mainnet liquidity, and a\n * devnet caller has to say which pool to route through, so there is nothing to guess.\n */\nexport function defaultRoute(cluster: Cluster): RouteProvider | null {\n return cluster === 'mainnet-beta' ? jupiterRoute() : null;\n}\n","/**\n * Wrapping and unwrapping SOL around a venue trade.\n *\n * Both venues settle in WSOL, never in native SOL. So every builder in this directory does the same\n * three things around its Gabox instruction:\n *\n * 1. create the wallet's WSOL associated token account, if it is missing;\n * 2. move the lamports it is going to spend into that account and `syncNative` it, so the token\n * balance matches the lamports;\n * 3. close the account afterwards, which sends everything left back to the wallet as SOL.\n *\n * A sale needs no step 2: the proceeds arrive in the account, and the close is what turns them into\n * SOL.\n *\n * # Closing unwraps everything\n *\n * If the wallet already held WSOL in that account, the close turns that into SOL too. Nothing is\n * lost and the wallet still owns every lamport, but the balance moves out of the token account. A\n * wallet that keeps a WSOL position on purpose should build its own instructions instead of using\n * these builders.\n */\n\nimport {\n getCloseAccountInstruction,\n getCreateAssociatedTokenIdempotentInstruction,\n getSyncNativeInstruction,\n} from '@solana-program/token';\nimport { getTransferSolInstruction } from '@solana-program/system';\nimport type { Address, Instruction, TransactionSigner } from '@solana/kit';\n\nimport { TOKEN_PROGRAM_ADDRESS, WSOL_MINT } from '../ids';\nimport { wsolAccountFor } from '../raydium/venue';\n\n/** The wallet's WSOL account, and the instructions that put `lamports` of spendable WSOL in it. */\nexport async function fundWsol(\n owner: TransactionSigner,\n lamports: bigint,\n): Promise<{ account: Address; instructions: Instruction[] }> {\n if (lamports < 0n) throw new Error('lamports must not be negative');\n const account = await wsolAccountFor(owner.address);\n const instructions: Instruction[] = [\n getCreateAssociatedTokenIdempotentInstruction({\n payer: owner,\n ata: account,\n owner: owner.address,\n mint: WSOL_MINT,\n tokenProgram: TOKEN_PROGRAM_ADDRESS,\n }) as Instruction,\n ];\n if (lamports > 0n) {\n instructions.push(\n getTransferSolInstruction({\n source: owner,\n destination: account,\n amount: lamports,\n }) as Instruction,\n // Without this the token account holds the lamports but still reports a zero balance.\n getSyncNativeInstruction({ account }) as Instruction,\n );\n }\n return { account, instructions };\n}\n\n/** Close the WSOL account, sending every lamport in it back to the owner as SOL. */\nexport function unwrapWsol(owner: TransactionSigner, account: Address): Instruction {\n return getCloseAccountInstruction({\n account,\n destination: owner.address,\n owner,\n }) as Instruction;\n}\n","/**\n * Getting the quote token into, and out of, the wallet's own quote account.\n *\n * Gabox settles in the pool's quote asset and nothing else. Both venues move that token in and out\n * of one account: the wallet's associated token account for the quote mint, under the quote's own\n * token program. The program pins that address and measures the exact delta there. So every builder\n * in this directory has to make sure the account exists, and holds what the trade will spend.\n *\n * Three shapes, and which one applies follows from the pool's quote and the caller's choice:\n *\n * - **A WSOL pool.** The wallet pays in SOL already. Create the WSOL account, move the lamports\n * into it, `syncNative`, and close it afterwards so the change and any proceeds come back as\n * SOL. This is what every 0.6.0 flow did, unchanged.\n * - **Another quote, paying in that quote.** The wallet already holds the token. Create the\n * account if it is missing and leave it alone: it is not WSOL, so closing it would be wrong.\n * - **Another quote, paying in SOL.** A route turns SOL into the quote token in the same\n * transaction, before `buy_pack`. A sale does the reverse afterwards. `routeQuoteIn` and\n * `routeQuoteOut` build those, and `assertRouteIsSafe` checks the result before it is used.\n *\n * Nothing here ever splits the work across two transactions. A swap that settles separately would\n * leave the wallet holding a token it never asked for whenever the second half failed.\n */\n\nimport { getCreateAssociatedTokenIdempotentInstruction } from '@solana-program/token';\nimport type {\n Address,\n AddressesByLookupTableAddress,\n Instruction,\n TransactionSigner,\n} from '@solana/kit';\n\nimport { MAX_COMPUTE_UNIT_LIMIT } from '../compute';\nimport { GABOX_PROGRAM_ID } from '../ids';\nimport { WSOL_MINT } from '../raydium/ids';\nimport type { ResolvedVenue } from '../raydium/venue';\nimport { assertRouteIsSafe, routeQuoteIn, routeQuoteOut } from '../route/leg';\nimport type { RouteMode, RouteProvider } from '../route/types';\nimport type { GaboxClient } from '../rpc';\nimport { fundWsol, unwrapWsol } from './wsol';\n\n/** Where the money for a purchase comes from. */\nexport type PayWith = 'sol' | 'quote';\n/** What a sale pays out. */\nexport type Receive = 'sol' | 'quote';\n\n/** The instructions that go around the Gabox instruction, and what the route did. */\nexport type QuoteLeg = {\n /** Everything that runs before the Gabox instruction. */\n before: Instruction[];\n /** Everything that runs after it. */\n after: Instruction[];\n /** The lookup tables the route's own instructions need, on top of the client's. */\n lookupTables: AddressesByLookupTableAddress;\n /** Which swap mode the route used, or `null` when no route was needed. */\n mode: RouteMode | null;\n /** SOL the route spends, or `null` when no route was needed. */\n solAmount: bigint | null;\n /**\n * The compute units the route adds to the transaction, or `0` when there is no route.\n *\n * The builder adds this to its own limit, because the swap runs on the same budget. It comes from\n * the route itself, so a Jupiter route through several pools asks for more than a single-pool one.\n */\n computeUnits: number;\n};\n\n/** The Gabox accounts a route must never name. */\nexport type GaboxAccounts = readonly Address[];\n\n/** Create the wallet's quote account if it is missing. Idempotent, so a second create is free. */\nexport function createQuoteAccount(\n owner: TransactionSigner,\n venue: Pick<ResolvedVenue, 'quoteMint' | 'quoteTokenProgram' | 'userQuoteToken'>,\n): Instruction {\n return getCreateAssociatedTokenIdempotentInstruction({\n payer: owner,\n ata: venue.userQuoteToken,\n owner: owner.address,\n mint: venue.quoteMint,\n tokenProgram: venue.quoteTokenProgram,\n }) as Instruction;\n}\n\n/**\n * The leg that puts `maxQuoteIn` of the quote token in the buyer's quote account.\n *\n * `payWith` decides where it comes from. On a WSOL pool the choice makes no difference: the quote\n * token is SOL either way, so the builder wraps it.\n */\nexport async function quoteLegIn(\n client: GaboxClient,\n input: {\n venue: Pick<ResolvedVenue, 'quoteMint' | 'quoteTokenProgram' | 'userQuoteToken'>;\n payer: TransactionSigner;\n maxQuoteIn: bigint;\n payWith: PayWith;\n /** Gabox accounts a route must never name. The Gabox program id is added here. */\n gaboxAccounts: GaboxAccounts;\n },\n): Promise<QuoteLeg> {\n const { venue, payer, maxQuoteIn, payWith } = input;\n\n if (venue.quoteMint === WSOL_MINT) {\n const wsol = await fundWsol(payer, maxQuoteIn);\n return {\n before: wsol.instructions,\n after: [unwrapWsol(payer, wsol.account)],\n lookupTables: {},\n mode: null,\n solAmount: maxQuoteIn,\n computeUnits: 0,\n };\n }\n\n if (payWith === 'quote') {\n return {\n before: [createQuoteAccount(payer, venue)],\n after: [],\n lookupTables: {},\n mode: null,\n solAmount: null,\n computeUnits: 0,\n };\n }\n\n const route = await routeQuoteIn(client, providerOf(client, venue.quoteMint), {\n quoteMint: venue.quoteMint,\n amount: maxQuoteIn,\n user: payer.address,\n });\n assertRouteIsSafe(route, {\n forbidden: [GABOX_PROGRAM_ID, ...input.gaboxAccounts],\n settlesIn: venue.userQuoteToken,\n });\n return {\n before: route.instructions,\n after: [],\n lookupTables: route.lookupTables,\n mode: route.mode,\n solAmount: route.inAmount,\n computeUnits: route.computeUnits,\n };\n}\n\n/**\n * The leg around a sale: make sure the quote account exists, and turn the proceeds into SOL when\n * the seller asked for SOL.\n *\n * The swap is an exact-in of `minQuoteOutput`, the floor the seller already signs for on the sale\n * itself. Anything the venue pays above that floor stays in the seller's quote account: a swap can\n * only spend what the sale is guaranteed to have produced.\n */\nexport async function quoteLegOut(\n client: GaboxClient,\n input: {\n venue: Pick<ResolvedVenue, 'quoteMint' | 'quoteTokenProgram' | 'userQuoteToken'>;\n seller: TransactionSigner;\n minQuoteOutput: bigint;\n receive: Receive;\n gaboxAccounts: GaboxAccounts;\n },\n): Promise<QuoteLeg> {\n const { venue, seller, minQuoteOutput, receive } = input;\n\n if (venue.quoteMint === WSOL_MINT) {\n // A sale needs the account to exist, not to hold anything. The close at the end is what turns\n // the proceeds into SOL.\n const wsol = await fundWsol(seller, 0n);\n return {\n before: wsol.instructions,\n after: [unwrapWsol(seller, wsol.account)],\n lookupTables: {},\n mode: null,\n solAmount: null,\n computeUnits: 0,\n };\n }\n\n const create = createQuoteAccount(seller, venue);\n if (receive === 'quote') {\n return {\n before: [create],\n after: [],\n lookupTables: {},\n mode: null,\n solAmount: null,\n computeUnits: 0,\n };\n }\n\n const route = await routeQuoteOut(client, providerOf(client, venue.quoteMint), {\n quoteMint: venue.quoteMint,\n amount: minQuoteOutput,\n user: seller.address,\n });\n assertRouteIsSafe(route, {\n forbidden: [GABOX_PROGRAM_ID, ...input.gaboxAccounts],\n settlesIn: venue.userQuoteToken,\n });\n return {\n before: [create],\n after: route.instructions,\n lookupTables: route.lookupTables,\n mode: route.mode,\n solAmount: route.outAmount,\n computeUnits: route.computeUnits,\n };\n}\n\n/** The client's route provider, with a message that says what to do when it has none. */\nexport function providerOf(client: GaboxClient, quoteMint: Address): RouteProvider {\n if (!client.route) {\n throw new Error(\n `this ${client.cluster} client has no route provider, so it cannot pay in SOL for a pool ` +\n `quoted in ${quoteMint}. Pass \\`route\\` to createClient — raydiumCpmmRoute(pool) for a ` +\n \"CPMM pool that holds the SOL pair — or pay in the quote token itself.\",\n );\n }\n return client.route;\n}\n\n/**\n * The compute limit a builder asks for: its own budget plus whatever the route needs.\n *\n * Capped at the runtime's ceiling. Jupiter often asks for the whole 1,400,000 units rather than\n * estimating, and a request above the ceiling is rejected outright, so the sum has to be clamped\n * rather than passed through.\n */\nexport function computeUnitsWithRoute(own: number, leg: QuoteLeg): number {\n return Math.min(own + leg.computeUnits, MAX_COMPUTE_UNIT_LIMIT);\n}\n\n/**\n * Add the route to a \"transaction is too large\" error.\n *\n * `buildMessage` already refuses a message above the 1,232-byte limit. When a swap is in the same\n * message, the reason is usually the swap, and the fix is not to split the transaction: the two\n * halves have to settle together. So the message says what a caller can actually do instead.\n */\nexport function routeSizeHint(cause: unknown, leg: QuoteLeg): unknown {\n if (leg.mode === null) return cause;\n if (!(cause instanceof Error) || !cause.message.includes('Solana allows 1232')) return cause;\n return new Error(\n `${cause.message} The swap and the Gabox instruction share one transaction on purpose, so ` +\n 'this SDK never splits them. Supply more address lookup tables, or pay in the quote token.',\n { cause },\n );\n}\n","/**\n * Buying one pack.\n *\n * The Gabox instruction is always the same. What goes around it follows the pool's quote asset:\n *\n * - **A WSOL pool.** Create the purchaser's WSOL account, move `maxQuoteIn` lamports into it,\n * `syncNative`, buy, then close the account so the change comes back as SOL.\n * - **Another quote, `payWith: 'quote'`.** Create the purchaser's quote account if it is missing\n * and buy. The purchaser must already hold at least the pack price.\n * - **Another quote, `payWith: 'sol'` (the default).** A route turns SOL into `maxQuoteIn` of the\n * quote token first, in the same transaction, and `buy_pack` then spends only what the pack\n * costs. Anything the route bought above that stays in the purchaser's quote account.\n *\n * One transaction and one signature in every case. The swap and the buy are never split: a swap\n * that settled on its own would leave the buyer holding a token they never asked for whenever the\n * buy failed.\n *\n * Closing the WSOL account also unwraps any WSOL the wallet already held. See `tx/wsol.ts`.\n *\n * # The purchaser's coin account\n *\n * The program declares `user_tokens` as `init_if_needed`, so Anchor creates the account when it is\n * missing and the purchaser pays its rent. There is no idempotent create here on purpose: two paths\n * that both create the same account make the transaction longer for no gain, and the program's own\n * path is the one that has to work anyway.\n *\n * # The two caps\n *\n * `maxQuoteIn` is the buyer's slippage cap at the venue, in the quote token. `maxNativeDebit` is a\n * separate cap on the lamports the handler watches: the venue's account rent, which LaunchLab\n * charges on a coin's first trade, plus the VRF request fee. Gabox itself charges nothing.\n */\n\nimport type { Address, Instruction, TransactionSigner } from '@solana/kit';\n\nimport { fetchPoolInventory } from '../accounts';\nimport { BUY_PACK_COMPUTE_UNITS } from '../compute';\nimport { getBuyPackInstructionAsync } from '../generated/instructions/buyPack';\nimport { activityAddress, associatedTokenAddress, drawAddress } from '../pdas';\nimport { resolveVenue, type VenueKind } from '../raydium/venue';\nimport type { GaboxClient } from '../rpc';\nimport { buildMessage, withRemainingAccounts, type BuildOptions } from './message';\nimport { computeUnitsWithRoute, quoteLegIn, routeSizeHint, type PayWith } from './quoteLeg';\n\nexport type BuyPackInput = {\n mint: Address;\n purchaser: TransactionSigner;\n /**\n * The venue slippage cap, in the pool's quote token. The transaction puts this much of the quote\n * token in the buyer's quote account before the buy, so it must cover the real price. Anything\n * left over stays there, or comes back as SOL on a WSOL pool.\n */\n maxQuoteIn: bigint;\n /** The floor on the top prize this pack may win. Refresh the offer if it fails. */\n minMaximum: bigint;\n /** Caps every lamport the handler sees: venue account rent and the VRF request. */\n maxNativeDebit: bigint;\n /**\n * Pay in SOL through a swap, or in the quote token the buyer already holds. Defaults to `'sol'`.\n * A WSOL pool ignores it: its quote token is SOL.\n */\n payWith?: PayWith;\n /** Force a venue instead of reading the LaunchLab pool's `status`. */\n venue?: VenueKind;\n /** Pin `pool.nextSeq` to make a rebuild fail rather than buy a second pack. */\n seq?: bigint;\n} & Partial<BuildOptions>;\n\nexport async function buyPack(client: GaboxClient, input: BuyPackInput) {\n if (input.maxQuoteIn <= 0n) throw new Error('maxQuoteIn must be positive');\n if (input.maxNativeDebit < 0n) throw new Error('maxNativeDebit must not be negative');\n\n const inventory = await fetchPoolInventory(client, input.mint);\n if (!inventory) throw new Error(`no Gabox pool for mint ${input.mint}`);\n const { pool, poolAddress } = inventory;\n const purchaser = input.purchaser.address;\n\n const venue = await resolveVenue(client, {\n mint: input.mint,\n user: purchaser,\n quote: {\n mint: pool.quoteMint,\n config: pool.quoteConfig,\n tokenProgram: pool.quoteTokenProgram,\n },\n ...(input.venue ? { venue: input.venue } : {}),\n });\n const draw = await drawAddress(poolAddress, input.seq ?? pool.nextSeq);\n\n const buy = await getBuyPackInstructionAsync({\n purchaser: input.purchaser,\n pool: poolAddress,\n draw,\n mint: input.mint,\n quoteMint: pool.quoteMint,\n vault: pool.vault,\n venue: venue.program,\n quoteTokenProgram: pool.quoteTokenProgram,\n maxQuoteIn: input.maxQuoteIn,\n minMaximum: input.minMaximum,\n maxNativeDebit: input.maxNativeDebit,\n });\n\n const leg = await quoteLegIn(client, {\n venue,\n payer: input.purchaser,\n maxQuoteIn: input.maxQuoteIn,\n payWith: input.payWith ?? 'sol',\n gaboxAccounts: [\n poolAddress,\n pool.vault,\n draw,\n await activityAddress(purchaser),\n await associatedTokenAddress(purchaser, input.mint),\n ],\n });\n\n const instructions: Instruction[] = [\n ...leg.before,\n withRemainingAccounts(buy as Instruction, venue.buyAccounts),\n ...leg.after,\n ];\n\n try {\n return await buildMessage(client, input.purchaser, instructions, {\n addressLookupTables: {\n ...(input.addressLookupTables ?? client.addressLookupTables),\n ...leg.lookupTables,\n },\n computeUnitLimit: input.computeUnitLimit ?? computeUnitsWithRoute(BUY_PACK_COMPUTE_UNITS, leg),\n ...(input.computeUnitPrice === undefined ? {} : { computeUnitPrice: input.computeUnitPrice }),\n });\n } catch (cause) {\n throw routeSizeHint(cause, leg);\n }\n}\n","/**\n * Creating a machine: one transaction, two signers.\n *\n * # Why it has to be one transaction\n *\n * `initialize_pool` reads the Instructions sysvar and refuses to run unless the same transaction\n * also carries a LaunchLab `initialize_v2` for the same mint, signed by the same creator, with the\n * pinned Gabox launch arguments. That is what makes \"one pool per coin\" true and stops anyone\n * wrapping an existing coin in a machine. The create must come **first**: the mint account has to\n * exist and deserialize before Anchor validates the pool accounts.\n *\n * # The instructions, in order\n *\n * 1. LaunchLab `initialize_v2`. The mint keypair signs; the creator pays.\n * 2. The quote leg: wrap SOL for a WSOL pool, create the quote account for another quote, or swap\n * SOL into the quote token when `payWith: 'sol'` on a non-SOL pool.\n * 3. `initialize_pool`, with the LaunchLab buy accounts as `remainingAccounts`.\n * 4. Close the WSOL account, on a WSOL pool only. Whatever the seed did not spend comes back as SOL.\n *\n * The seed is bought in the pool's quote token, so step 2 is not optional: `initialize_pool`\n * measures the creator's quote balance before and after the seed buy, and the buy cannot spend what\n * the account does not hold.\n *\n * Closing in step 4 also unwraps any WSOL the creator already held. See `tx/wsol.ts`.\n *\n * # The quote and the raise\n *\n * A machine is priced in one quote asset, fixed for its whole life. It defaults to wrapped SOL.\n * Any other quote Raydium enabled on LaunchLab works: pass `quote: { mint }`, and the SDK reads\n * Raydium's own global config for that mint to prove it and to price the curve.\n *\n * `raise` is `total_quote_fund_raising`, in the quote's own base units. A WSOL pool has it pinned\n * by the program, so the SDK supplies 85 SOL on mainnet and 3 SOL on devnet and refuses a different\n * value. Any other quote has no default: 3,000,000,000 means three SOL and three thousand USDC, so\n * the caller has to say. LaunchLab checks the number against `min_quote_fund_raising` in the\n * quote's own config, and this checks it too, before anything is built.\n *\n * # The seed\n *\n * The creator owns none of the coin yet — it does not exist until this transaction runs. So\n * `initialize_pool` buys the seed on the curve itself, into the creator's own coin account, and\n * moves it straight into the vault.\n *\n * The seed follows from the tier table. The program accepts any table that passes `math::validate`;\n * it does not enforce one table. A creator may pass their own `tiers`; the default is\n * `DEFAULT_TIERS`. The program buys a mandatory `seedTokens(PACK_TOKENS, tiers)` (see `math.ts`):\n * it makes a 3x top prize payable on the first pack, or pays the full top prize when the table's\n * top tier is below 3x. A table's top tier can be at most 20x; seed beyond what a 20x prize needs\n * stays in the vault as backup for the draws after a top-tier hit. A creator adds more on top with\n * `extraSeedTokens`; the program then buys `mandatory + extraSeedTokens` in the same seed trade.\n * The creator only signs a maximum cost for that buy.\n *\n * The seed buy moves the curve, so a bigger seed means a slightly higher starting pack price. The\n * curve only sells `LAUNCH_TOTAL_BASE_SELL` coins in total, so a seed above that cannot be bought;\n * `createMachine` and `seedCostEstimate` both check this before spending anything.\n *\n * # Two signers\n *\n * The mint keypair signs `initialize_v2` — LaunchLab takes it as a signer rather than deriving it —\n * and the creator signs everything and pays.\n */\n\nimport type { Address, Instruction, TransactionSigner } from '@solana/kit';\n\nimport { CREATE_MACHINE_COMPUTE_UNITS } from '../compute';\nimport { getInitializePoolInstructionAsync } from '../generated/instructions/initializePool';\nimport { PACK_TOKENS } from '../ids';\nimport { DEFAULT_TIERS, seedTokens, validatePack, validateTiers, type Tier } from '../math';\nimport { LAUNCH_TOTAL_BASE_SELL, WSOL_MINT, raydiumIds, type RaydiumIds } from '../raydium/ids';\nimport { getLaunchInstruction } from '../raydium/launch';\nimport { launchlabBuyAccounts } from '../raydium/accounts';\nimport { curveBuyExactOut } from '../raydium/curve';\nimport { fetchQuoteAsset, type QuoteAsset } from '../raydium/quote';\nimport { fetchCurveSettings, newCurveReserves, quoteAccountFor } from '../raydium/venue';\nimport {\n ata,\n creatorFeeVaultAddress,\n launchlabPoolAddress,\n launchlabVaultAddress,\n platformFeeVaultAddress,\n} from '../raydium/pdas';\nimport { poolAddress, vaultAddress } from '../pdas';\nimport type { GaboxClient } from '../rpc';\nimport { buildMessage, withRemainingAccounts, type BuildOptions } from './message';\nimport { solPriceOf } from '../route/leg';\nimport { computeUnitsWithRoute, quoteLegIn, routeSizeHint, type PayWith } from './quoteLeg';\n\n/** Which quote asset a new machine is priced in. Defaults to wrapped SOL. */\nexport type QuoteChoice = { mint: Address };\n\nexport type CreateMachineInput = {\n /** Pays for everything and signs both instructions. Becomes `pool.creator`. */\n creator: TransactionSigner;\n /** A fresh keypair for the coin. Signs `initialize_v2` and is never needed again. */\n mintKeypair: TransactionSigner;\n /** At most 32 UTF-8 bytes. */\n name: string;\n /** At most 10 UTF-8 bytes. */\n symbol: string;\n /** The metadata URI. At most 200 UTF-8 bytes. */\n uri: string;\n /**\n * The prize table. Immutable once the pool exists. Must pass `validateTiers` and\n * `validatePack(PACK_TOKENS, tiers)`; the program checks both again on chain. Defaults to\n * `DEFAULT_TIERS`, the table the Gabox app uses.\n */\n tiers?: readonly Readonly<Tier>[];\n /** The quote asset the machine is priced in. Defaults to wrapped SOL. */\n quote?: QuoteChoice;\n /**\n * `total_quote_fund_raising`, in the quote's own base units. Required for a quote other than\n * wrapped SOL; a WSOL pool uses the raise the program pins for this cluster.\n */\n raise?: bigint;\n /**\n * Pay for the seed in SOL through a swap, or in the quote token the creator already holds.\n * Defaults to `'sol'`. A WSOL pool ignores it: its quote token is SOL.\n */\n payWith?: PayWith;\n /**\n * Seed slippage cap in the quote token, for `mandatory + extraSeedTokens` together. The\n * transaction puts this much of the quote token in the creator's quote account before the buy, so\n * it must cover the real cost. Anything left over stays there, or comes back as SOL on a WSOL\n * pool.\n */\n maxSeedQuoteIn: bigint;\n /**\n * A separate cap on the lamports the seed buy itself spends. LaunchLab creates its platform and\n * creator fee vaults on a coin's first trade and charges that rent to the payer, which is the\n * only SOL the buy touches. It is not the price.\n */\n maxSeedNativeDebit: bigint;\n /**\n * Extra tokens to seed on top of the mandatory amount `seedTokens(PACK_TOKENS, tiers)` computes.\n * Defaults to `0n`. Must not be negative.\n */\n extraSeedTokens?: bigint;\n} & Partial<BuildOptions>;\n\n/**\n * Build the transaction message. Sign it with both `creator` and `mintKeypair`.\n *\n * Reads the quote's LaunchLab config, the quote mint, and the Gabox platform config, because the\n * seed price and every quote-side account depend on them. Nothing else needs the chain: the coin\n * does not exist yet, so every other account is a derivation.\n */\nexport async function createMachine(client: GaboxClient, input: CreateMachineInput) {\n const { creator, mintKeypair, name, symbol, uri, maxSeedQuoteIn, maxSeedNativeDebit } = input;\n\n // Snapshot caller input before validation and the first await. A caller can otherwise mutate a\n // nested tier while the config accounts are loading, changing the transaction after validation.\n const tiers = cloneTiers(input.tiers ?? DEFAULT_TIERS);\n validateTiers(tiers);\n validatePack(PACK_TOKENS, tiers);\n const extraSeedTokens = input.extraSeedTokens ?? 0n;\n if (extraSeedTokens < 0n) throw new Error('extraSeedTokens must not be negative');\n const mandatorySeed = seedTokens(PACK_TOKENS, tiers);\n const seed = mandatorySeed + extraSeedTokens;\n assertSeedFitsCurve(seed);\n if (seed > 0n && maxSeedQuoteIn <= 0n) {\n throw new Error('maxSeedQuoteIn must be positive when the jackpot needs a seed');\n }\n if (maxSeedQuoteIn < 0n) throw new Error('maxSeedQuoteIn must not be negative');\n if (maxSeedNativeDebit < 0n) throw new Error('maxSeedNativeDebit must not be negative');\n\n const ids = raydiumIds(client.cluster);\n const mint = mintKeypair.address;\n const quote = await fetchQuoteAsset(client, input.quote?.mint ?? WSOL_MINT, ids);\n const raise = resolveRaise(client, quote, input.raise, ids);\n\n const create = await getLaunchInstruction(\n {\n mint: mintKeypair,\n creator,\n name,\n symbol,\n uri,\n quoteMint: quote.mint,\n quoteConfig: quote.config,\n quoteTokenProgram: quote.tokenProgram,\n raise,\n },\n ids,\n );\n\n // The curve does not exist yet, so `resolveVenue` cannot build this list. Every address it needs\n // is a derivation anyway, and the creator is the wallet signing right here.\n const poolState = await launchlabPoolAddress(ids.launchlab, mint, quote.mint);\n const userQuoteToken = await quoteAccountFor(creator.address, quote.mint, quote.tokenProgram);\n const venueAccounts = launchlabBuyAccounts({\n launchlab: ids.launchlab,\n launchlabAuthority: ids.launchlabAuthority,\n launchlabEventAuthority: ids.launchlabEventAuthority,\n globalConfig: quote.config,\n platformConfig: ids.gaboxPlatform,\n poolState,\n mint,\n quoteMint: quote.mint,\n baseVault: await launchlabVaultAddress(ids.launchlab, poolState, mint),\n quoteVault: await launchlabVaultAddress(ids.launchlab, poolState, quote.mint),\n user: creator.address,\n userBaseToken: await ata(creator.address, mint),\n userQuoteToken,\n quoteTokenProgram: quote.tokenProgram,\n platformFeeVault: await platformFeeVaultAddress(ids.launchlab, ids.gaboxPlatform, quote.mint),\n creatorFeeVault: await creatorFeeVaultAddress(ids.launchlab, creator.address, quote.mint),\n });\n\n const initialize = await getInitializePoolInstructionAsync({\n creator,\n mint,\n quoteMint: quote.mint,\n quoteConfig: quote.config,\n quoteTokenProgram: quote.tokenProgram,\n venue: ids.launchlab,\n tiers,\n maxSeedQuoteIn,\n maxSeedNativeDebit,\n extraSeedTokens,\n });\n\n const leg = await quoteLegIn(client, {\n venue: { quoteMint: quote.mint, quoteTokenProgram: quote.tokenProgram, userQuoteToken },\n payer: creator,\n maxQuoteIn: maxSeedQuoteIn,\n // A 1x table needs no seed, so there is nothing to swap for. The quote account is still\n // created, because `initialize_pool` reads it either way.\n payWith: seed === 0n ? 'quote' : (input.payWith ?? 'sol'),\n gaboxAccounts: [\n await poolAddress(mint),\n await vaultAddress(mint),\n await ata(creator.address, mint),\n ],\n });\n\n const instructions: Instruction[] = [\n create,\n ...leg.before,\n withRemainingAccounts(initialize as Instruction, venueAccounts),\n ...leg.after,\n ];\n\n try {\n return await buildMessage(client, creator, instructions, {\n addressLookupTables: {\n ...(input.addressLookupTables ?? client.addressLookupTables),\n ...leg.lookupTables,\n },\n computeUnitLimit: input.computeUnitLimit ?? computeUnitsWithRoute(CREATE_MACHINE_COMPUTE_UNITS, leg),\n ...(input.computeUnitPrice === undefined ? {} : { computeUnitPrice: input.computeUnitPrice }),\n });\n } catch (cause) {\n throw routeSizeHint(cause, leg);\n }\n}\n\nexport type SeedCostEstimate = {\n tiers: readonly Tier[];\n /** The mandatory seed alone: `seedTokens(PACK_TOKENS, tiers)`. */\n seedTokens: bigint;\n /** `options.extraSeedTokens`, defaulted to `0n`. */\n extraSeedTokens: bigint;\n /** `seedTokens + extraSeedTokens`. What `createMachine` actually buys in the seed trade. */\n totalSeedTokens: bigint;\n /** Exact fresh-curve cost, in the quote token's base units, Raydium's fees included. */\n quoteAmount: bigint;\n /** The quote asset the machine would be priced in. */\n quoteMint: Address;\n quoteDecimals: number;\n /** The symbol Metaplex or Token-2022 records for the quote mint, when it has one. */\n quoteSymbol: string | null;\n /** `total_quote_fund_raising` the launch would use, in the quote's base units. */\n raise: bigint;\n /**\n * What `quoteAmount` costs in SOL through the client's route provider, or `null` when there is\n * no provider or no route. Equal to `quoteAmount` on a WSOL pool.\n */\n solAmount: bigint | null;\n};\n\n/**\n * What the seed for this table costs, fees included, and how many tokens it is.\n *\n * The coin does not exist yet, so the price comes from the starting reserves LaunchLab derives from\n * the launch shape and the raise. Nothing trades on the curve before `initialize_pool` runs in the\n * same transaction, so this is exact up to a change in Raydium's fee rates between the read and the\n * send.\n *\n * `solAmount` is the same cost in SOL, priced through the client's route provider. It is `null`\n * when the client has no provider, or when no route exists: a devnet client has none unless the\n * caller passes `raydiumCpmmRoute(pool)`.\n *\n * Defaults to `DEFAULT_TIERS`, wrapped SOL and no extra seed. Throws if `tiers` fails\n * `validateTiers`/`validatePack`, if `extraSeedTokens` is negative, if the total seed is bigger\n * than the curve sells, or if the raise is missing or below what LaunchLab accepts.\n */\nexport async function seedCostEstimate(\n client: GaboxClient,\n tiers: readonly Readonly<Tier>[] = DEFAULT_TIERS,\n options: { extraSeedTokens?: bigint; quote?: QuoteChoice; raise?: bigint } = {},\n): Promise<SeedCostEstimate> {\n // Do not validate one mutable table and then quote another after an await. The result owns its\n // own mutable copy too, never a reference to DEFAULT_TIERS or the caller's array.\n const copiedTiers = cloneTiers(tiers);\n validateTiers(copiedTiers);\n validatePack(PACK_TOKENS, copiedTiers);\n const extraSeedTokens = options.extraSeedTokens ?? 0n;\n if (extraSeedTokens < 0n) throw new Error('extraSeedTokens must not be negative');\n const mandatorySeed = seedTokens(PACK_TOKENS, copiedTiers);\n const seed = mandatorySeed + extraSeedTokens;\n assertSeedFitsCurve(seed);\n\n const ids = raydiumIds(client.cluster);\n const quote = await fetchQuoteAsset(client, options.quote?.mint ?? WSOL_MINT, ids);\n const raise = resolveRaise(client, quote, options.raise, ids);\n const settings = await fetchCurveSettings(client, quote.config, ids);\n const quoteAmount =\n seed === 0n\n ? 0n\n : curveBuyExactOut(newCurveReserves(raise, settings.migrateFee), settings.rates, seed);\n\n return {\n tiers: copiedTiers,\n seedTokens: mandatorySeed,\n extraSeedTokens,\n totalSeedTokens: seed,\n quoteAmount,\n quoteMint: quote.mint,\n quoteDecimals: quote.decimals,\n quoteSymbol: quote.symbol,\n raise,\n solAmount: await solPriceOf(client, quote.mint, quoteAmount),\n };\n}\n\n/**\n * The raise a launch uses, checked before anything is built.\n *\n * The program pins it for a WSOL pool, so a different value there is a launch that would be\n * refused on chain. Any other quote has no default and no pin: the caller names it, and LaunchLab's\n * own minimum for that quote is the floor.\n */\nfunction resolveRaise(\n client: GaboxClient,\n quote: QuoteAsset,\n raise: bigint | undefined,\n ids: RaydiumIds,\n): bigint {\n if (quote.mint === WSOL_MINT) {\n if (raise !== undefined && raise !== ids.launchQuoteRaise) {\n throw new Error(\n `a WSOL pool raises exactly ${ids.launchQuoteRaise} lamports on ${client.cluster}; the ` +\n `program refuses ${raise}. Leave \\`raise\\` out, or pick another quote asset.`,\n );\n }\n return ids.launchQuoteRaise;\n }\n if (raise === undefined) {\n throw new Error(\n `a pool quoted in ${quote.mint} needs a \\`raise\\`, in that token's base units. There is no ` +\n 'default, because the same number means a different amount in every token.',\n );\n }\n if (raise < quote.minQuoteFundRaising) {\n throw new Error(\n `LaunchLab takes at least ${quote.minQuoteFundRaising} base units of ${quote.mint} as a ` +\n `raise, and this launch asks for ${raise}`,\n );\n }\n return raise;\n}\n\n/** A mutable table shape, owned by this call and safe to pass to Codama's builder. */\nfunction cloneTiers(tiers: readonly Readonly<Tier>[]): Tier[] {\n return tiers.map(({ multiplierBps, tickets }) => ({ multiplierBps, tickets }));\n}\n\n/**\n * The curve sells `LAUNCH_TOTAL_BASE_SELL` coins in total, so a seed above that cannot be bought at\n * any price. A buy for more than the curve has left is capped rather than refused, so it would look\n * cheap instead of failing. This throws before any transaction is built.\n */\nfunction assertSeedFitsCurve(seed: bigint): void {\n if (seed > LAUNCH_TOTAL_BASE_SELL) {\n throw new Error(\n `the seed (${seed} base units) is bigger than the whole curve sells ` +\n `(${LAUNCH_TOTAL_BASE_SELL}); this table's top tier cannot be seeded on a new coin`,\n );\n }\n}\n","/** Permissionless draw recovery: retry VRF or deliver the committed minimum after timeout. */\nimport type { Address, Instruction, TransactionSigner } from '@solana/kit';\nimport { fetchDraw, fetchPoolAt } from '../accounts';\nimport { getExpireDrawInstruction } from '../generated/instructions/expireDraw';\nimport { getRetryDrawInstruction } from '../generated/instructions/retryDraw';\nimport { RETRY_SLOTS, TIMEOUT_SLOTS } from '../ids';\nimport { associatedTokenAddress, vrfIdentityAddress } from '../pdas';\nimport type { GaboxClient } from '../rpc';\nimport { buildMessage, type BuildOptions } from './message';\nconst DRAW_COMPUTE_UNITS = 200_000;\nexport type RetryDrawInput = { payer: TransactionSigner; pool: Address; draw: Address; maxVrfDebit: bigint } & Partial<BuildOptions>;\nexport async function retryDraw(client: GaboxClient, input: RetryDrawInput) {\n const ix = await getRetryDrawInstruction({ payer: input.payer, pool: input.pool, draw: input.draw, identity: await vrfIdentityAddress(), maxVrfDebit: input.maxVrfDebit });\n return await buildMessage(client, input.payer, [ix as Instruction], { addressLookupTables: input.addressLookupTables, computeUnitLimit: input.computeUnitLimit ?? DRAW_COMPUTE_UNITS, ...(input.computeUnitPrice === undefined ? {} : { computeUnitPrice: input.computeUnitPrice }) });\n}\nexport type ExpireDrawInput = { payer: TransactionSigner; pool: Address; draw: Address } & Partial<BuildOptions>;\nexport async function expireDraw(client: GaboxClient, input: ExpireDrawInput) {\n const draw = await fetchDraw(client, input.draw); if (!draw || draw.pool !== input.pool) throw new Error('draw does not belong to pool or was already delivered');\n const pool = await fetchPoolAt(client, input.pool); if (!pool) throw new Error(`no pool at ${input.pool}`);\n const ix = getExpireDrawInstruction({ pool: input.pool, draw: input.draw, purchaser: draw.purchaser, mint: pool.mint, vault: pool.vault, userTokens: await associatedTokenAddress(draw.purchaser, pool.mint) });\n return await buildMessage(client, input.payer, [ix as Instruction], { addressLookupTables: input.addressLookupTables, computeUnitLimit: input.computeUnitLimit ?? DRAW_COMPUTE_UNITS, ...(input.computeUnitPrice === undefined ? {} : { computeUnitPrice: input.computeUnitPrice }) });\n}\nexport type DrawAvailability = { attempts: number; slotsUntilRetry: bigint; slotsUntilExpiry: bigint; canRetry: boolean; canExpire: boolean };\nexport async function drawAvailability(client: GaboxClient, address: Address): Promise<DrawAvailability | null> {\n const draw = await fetchDraw(client, address); if (!draw) return null;\n const now = BigInt(await client.rpc.getSlot({ commitment: 'confirmed' }).send());\n const retryAt = draw.lastAttemptSlot + RETRY_SLOTS; const expireAt = draw.requestSlot + TIMEOUT_SLOTS;\n const slotsUntilRetry = now >= retryAt ? 0n : retryAt - now; const slotsUntilExpiry = now >= expireAt ? 0n : expireAt - now;\n return { attempts: draw.attempts, slotsUntilRetry, slotsUntilExpiry, canRetry: draw.attempts < 3 && slotsUntilRetry === 0n && slotsUntilExpiry > 0n, canExpire: slotsUntilExpiry === 0n };\n}\n","/** Irrevocably transfer existing base tokens into a Gabox prize vault. */\nimport type { Address, Instruction, TransactionSigner } from '@solana/kit';\nimport { fetchPoolByMint } from '../accounts';\nimport { getFundPrizesInstruction } from '../generated/instructions/fundPrizes';\nimport { associatedTokenAddress, poolAddress } from '../pdas';\nimport type { GaboxClient } from '../rpc';\nimport { buildMessage, type BuildOptions } from './message';\nconst FUND_COMPUTE_UNITS = 200_000;\nexport type FundPrizesInput = { mint: Address; funder: TransactionSigner; amount: bigint; source?: Address } & Partial<BuildOptions>;\nexport async function fundPrizes(client: GaboxClient, input: FundPrizesInput) {\n if (input.amount <= 0n) throw new Error('amount must be positive');\n const pool = await fetchPoolByMint(client, input.mint); if (!pool) throw new Error(`no Gabox pool for mint ${input.mint}`);\n const ix = getFundPrizesInstruction({\n funder: input.funder, pool: await poolAddress(input.mint), mint: input.mint,\n source: input.source ?? await associatedTokenAddress(input.funder.address, input.mint),\n vault: pool.vault, amount: input.amount,\n });\n return await buildMessage(client, input.funder, [ix as Instruction], {\n addressLookupTables: input.addressLookupTables, computeUnitLimit: input.computeUnitLimit ?? FUND_COMPUTE_UNITS,\n ...(input.computeUnitPrice === undefined ? {} : { computeUnitPrice: input.computeUnitPrice }),\n });\n}\n","/**\n * Selling tokens through Gabox.\n *\n * The seller keeps the full venue proceeds: Gabox charges nothing on a sale. `minQuoteOutput` is\n * the venue's own floor, in the pool's quote token, and the program checks it before it returns.\n *\n * What goes around the sale follows the pool's quote asset:\n *\n * - **A WSOL pool.** Create the seller's WSOL account, sell, close it. The proceeds land in the\n * wallet as SOL.\n * - **Another quote, `receive: 'sol'` (the default).** Sell, then swap `minQuoteOutput` of the\n * proceeds into SOL in the same transaction. Anything the venue paid above that floor stays in\n * the seller's quote account.\n * - **Another quote, `receive: 'quote'`.** Sell and stop. The proceeds stay in the quote token.\n *\n * Closing a WSOL account also unwraps any WSOL the wallet already held; see `tx/wsol.ts`.\n */\n\nimport type { Address, Instruction, TransactionSigner } from '@solana/kit';\n\nimport { fetchPoolByMint } from '../accounts';\nimport { REDEEM_COMPUTE_UNITS } from '../compute';\nimport { getSellTokensInstructionAsync } from '../generated/instructions/sellTokens';\nimport { associatedTokenAddress, poolAddress, vaultAddress } from '../pdas';\nimport { resolveVenue, type VenueKind } from '../raydium/venue';\nimport type { GaboxClient } from '../rpc';\nimport { buildMessage, withRemainingAccounts, type BuildOptions } from './message';\nimport { computeUnitsWithRoute, quoteLegOut, routeSizeHint, type Receive } from './quoteLeg';\n\nexport type SellTokensInput = {\n mint: Address;\n seller: TransactionSigner;\n amount: bigint;\n /** The venue's own floor on the quote token it pays out. Nothing else is taken out of the sale. */\n minQuoteOutput: bigint;\n /**\n * Caps the lamports the sale itself spends. A sale normally spends none, but LaunchLab charges\n * the payer for a fee vault it has to create on a coin's first trade.\n */\n maxNativeDebit: bigint;\n /**\n * Take the proceeds as SOL through a swap, or keep them in the quote token. Defaults to `'sol'`.\n * A WSOL pool ignores it: its quote token is SOL.\n */\n receive?: Receive;\n venue?: VenueKind;\n} & Partial<BuildOptions>;\n\nexport async function sellTokens(client: GaboxClient, input: SellTokensInput) {\n if (input.amount <= 0n || input.minQuoteOutput <= 0n) {\n throw new Error('amount and minQuoteOutput must be positive');\n }\n if (input.maxNativeDebit < 0n) throw new Error('maxNativeDebit must not be negative');\n\n const pool = await fetchPoolByMint(client, input.mint);\n if (!pool) throw new Error(`no Gabox pool for mint ${input.mint}`);\n\n const venue = await resolveVenue(client, {\n mint: input.mint,\n user: input.seller.address,\n quote: {\n mint: pool.quoteMint,\n config: pool.quoteConfig,\n tokenProgram: pool.quoteTokenProgram,\n },\n ...(input.venue ? { venue: input.venue } : {}),\n });\n\n const gaboxPool = await poolAddress(input.mint);\n const sell = await getSellTokensInstructionAsync({\n seller: input.seller,\n pool: gaboxPool,\n mint: input.mint,\n quoteMint: pool.quoteMint,\n venue: venue.program,\n quoteTokenProgram: pool.quoteTokenProgram,\n amount: input.amount,\n minQuoteOutput: input.minQuoteOutput,\n maxNativeDebit: input.maxNativeDebit,\n });\n\n const leg = await quoteLegOut(client, {\n venue,\n seller: input.seller,\n minQuoteOutput: input.minQuoteOutput,\n receive: input.receive ?? 'sol',\n gaboxAccounts: [\n gaboxPool,\n await vaultAddress(input.mint),\n await associatedTokenAddress(input.seller.address, input.mint),\n ],\n });\n\n const instructions: Instruction[] = [\n ...leg.before,\n withRemainingAccounts(sell as Instruction, venue.sellAccounts),\n ...leg.after,\n ];\n\n try {\n return await buildMessage(client, input.seller, instructions, {\n addressLookupTables: {\n ...(input.addressLookupTables ?? client.addressLookupTables),\n ...leg.lookupTables,\n },\n computeUnitLimit: input.computeUnitLimit ?? computeUnitsWithRoute(REDEEM_COMPUTE_UNITS, leg),\n ...(input.computeUnitPrice === undefined ? {} : { computeUnitPrice: input.computeUnitPrice }),\n });\n } catch (cause) {\n throw routeSizeHint(cause, leg);\n }\n}\n","/**\n * The four oracle accounts.\n *\n * `buy_pack` and `retry_draw` both carry an `Oracle` account group. Anchor flattens it into four\n * slots, and the generated client takes them as `identity`, `queue`, `program` and `slotHashes`.\n * Three of the four are pinned by an `address` constraint, so the only one a client computes is the\n * identity PDA.\n *\n * # Why the queue is not a choice\n *\n * `vrf.rs` pins MagicBlock's default queue with `address = QUEUE` and `owner = ID`. A pool creator\n * therefore cannot point their pool's draws at an oracle they run. That is the reason the address\n * is a constant here rather than a parameter: making it configurable in the client would suggest a\n * freedom the program does not give.\n */\n\nimport type { Address } from '@solana/kit';\n\nimport { SLOT_HASHES_SYSVAR, VRF_DEFAULT_QUEUE, VRF_PROGRAM_ADDRESS } from './ids';\nimport { vrfIdentityAddress } from './pdas';\n\n/** The four accounts, named as the generated client names them. */\nexport type OracleAccounts = {\n /** `[\"identity\"]` under gabox. The PDA gabox signs the randomness request with. */\n identity: Address;\n /** MagicBlock's default queue. Writable. */\n queue: Address;\n /** The VRF program itself. */\n program: Address;\n /** The slot-hashes sysvar, which seeds the request. */\n slotHashes: Address;\n};\n\n/**\n * Build the group. Nothing here reads the chain, so it is safe to call on every render.\n *\n * The generated instruction builders default `queue`, `program` and `slotHashes` on their own, so\n * passing this whole object is belt and braces. It is worth having anyway: a caller can show the\n * four accounts a draw request will touch before asking for a signature.\n */\nexport async function oracleAccounts(): Promise<OracleAccounts> {\n return {\n identity: await vrfIdentityAddress(),\n queue: VRF_DEFAULT_QUEUE,\n program: VRF_PROGRAM_ADDRESS,\n slotHashes: SLOT_HASHES_SYSVAR,\n };\n}\n"],"mappings":";;;;;;;;AAmBA,MAAM,MAAM,iBAAiB;AAC7B,MAAM,UAAU,GAAe,MAAmC,EAAE,UAAU,EAAE,UAAU,EAAE,OAAO,GAAG,MAAM,EAAE,OAAO,CAAC;AACtH,SAAgB,YAAY,MAAqC;CAC/D,IAAI,OAAO,MAAM,gCAAgC,GAAG,OAAO;EAAE,MAAM;EAAe,MAAM,2BAA2B,CAAC,CAAC,OAAO,IAAI;CAAE;CAClI,IAAI,OAAO,MAAM,iCAAiC,GAAG,OAAO;EAAE,MAAM;EAAgB,MAAM,4BAA4B,CAAC,CAAC,OAAO,IAAI;CAAE;CACrI,IAAI,OAAO,MAAM,+BAA+B,GAAG,OAAO;EAAE,MAAM;EAAc,MAAM,0BAA0B,CAAC,CAAC,OAAO,IAAI;CAA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