@gabox-labs/sdk 0.7.1 → 0.9.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/CHANGELOG.md +62 -0
- package/README.md +85 -23
- package/dist/{gabox-DGTCh34U.js → gabox-CuyJYmrS.js} +669 -309
- package/dist/gabox-CuyJYmrS.js.map +1 -0
- package/dist/generated/index.d.ts +458 -92
- package/dist/generated/index.js +214 -54
- package/dist/generated/index.js.map +1 -1
- package/dist/{index-CA0m7AKk.d.ts → index-CQcBMEah.d.ts} +189 -4
- package/dist/index.d.ts +226 -30
- package/dist/index.js +182 -40
- package/dist/index.js.map +1 -1
- package/dist/raydium/index.d.ts +2 -2
- package/dist/raydium/index.js +2 -2
- package/dist/{raydium-CU-tZzIk.js → raydium-DXUJ-g1p.js} +835 -105
- package/dist/raydium-DXUJ-g1p.js.map +1 -0
- package/llms.txt +4 -0
- package/package.json +1 -1
- package/skills/gabox-sdk/SKILL.md +21 -13
- package/skills/gabox-sdk/references/api.md +47 -18
- package/dist/gabox-DGTCh34U.js.map +0 -1
- package/dist/raydium-CU-tZzIk.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"raydium-DXUJ-g1p.js","names":["address","u8","DISCRIMINATOR","u64","borshString","base64","memcmp","wrapAround","withSigner","quoteOf","u64"],"sources":["../src/raydium/abi.ts","../src/raydium/ids.ts","../src/math.ts","../src/ids.ts","../src/raydium/pdas.ts","../src/pdas.ts","../src/raydium/adapter.ts","../src/accounts.ts","../src/compute.ts","../src/raydium/read.ts","../src/raydium/quote.ts","../src/raydium/accounts.ts","../src/raydium/curve.ts","../src/raydium/venue.ts","../src/tx/message.ts","../src/raydium/launch.ts","../src/raydium/claim.ts","../src/raydium/platform.ts","../src/raydium/trade.ts","../src/raydium/index.ts"],"sourcesContent":["// GENERATED by scripts/codegen.mjs. Do not edit.\n//\n// The Raydium addresses Gabox pins, and the account order and `writable`/`signer` flags of every\n// Raydium instruction this SDK builds. `venue/trade.rs` checks the list `buy_pack` forwards\n// position by position, so this table and the program's own `venue/abi.rs` must describe the same\n// thing.\n//\n// Sources:\n// - the Rust program's programs/gabox/src/venue/ids.rs and constants.rs (the addresses)\n// - ../../idl/raydium_launchpad.json (LaunchLab)\n// - ../../idl/raydium_cp_swap.json (CPMM)\n//\n// Both IDL snapshots were checked against the SHA-256 that ../../idl/interfaces.json records, and\n// every trade instruction below was cross-checked against that file, index by index.\n// `test/venue-accounts.test.ts` checks the same thing on every test run.\n\nimport type { Address } from '@solana/kit';\n\n/** One account slot: its IDL name and the privileges the venue's own ABI gives it. */\nexport type VenueAccountSpec = {\n readonly name: string;\n readonly writable: boolean;\n readonly signer: boolean;\n};\n\nexport type VenueInstructionAbi = {\n readonly name: string;\n readonly discriminator: Uint8Array;\n readonly accounts: readonly VenueAccountSpec[];\n};\n\n/**\n * The Raydium deployment of one cluster. Mainnet and devnet run different programs, so every\n * address here differs between the two.\n *\n * Two things are deliberately absent, and both for the same reason: the program reads them from\n * the chain instead of pinning them. The CPMM fee tier comes from the Gabox platform config and\n * from the migrated pool's own data. The quote assets come from Raydium's own LaunchLab\n * `GlobalConfig` accounts, one per quote mint, so there is no list of quotes here.\n */\nexport type RaydiumClusterIds = {\n /** Raydium LaunchLab, the bonding curve a Gabox coin launches and trades on first. */\n readonly launchlab: Address;\n /** PDA([\"vault_auth_seed\"], launchlab). Signs LaunchLab's own vault transfers. */\n readonly launchlabAuthority: Address;\n /** PDA([\"__event_authority\"], launchlab). */\n readonly launchlabEventAuthority: Address;\n /** PDA([\"platform_config\", PLATFORM_ADMIN], launchlab). The Gabox platform on LaunchLab. */\n readonly gaboxPlatform: Address;\n /** Raydium CPMM, the pool a Gabox coin graduates into. */\n readonly cpmm: Address;\n /** PDA([\"vault_and_lp_mint_auth_seed\"], cpmm). */\n readonly cpmmAuthority: Address;\n /**\n * The raise a WSOL-quoted curve must reach before the coin graduates, in lamports.\n *\n * The program pins this one value, and only for a WSOL pool: it knows what SOL is worth to its\n * own product and cannot say the same about USDC or a stock token. A pool quoted in any other\n * asset picks its own raise, and LaunchLab checks it against `min_quote_fund_raising` in that\n * quote's own global config.\n */\n readonly launchQuoteRaise: bigint;\n};\n\nexport const RAYDIUM_MAINNET_IDS: RaydiumClusterIds = {\n launchlab: 'LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj' as Address,\n launchlabAuthority: 'WLHv2UAZm6z4KyaaELi5pjdbJh6RESMva1Rnn8pJVVh' as Address,\n launchlabEventAuthority: '2DPAtwB8L12vrMRExbLuyGnC7n2J5LNoZQSejeQGpwkr' as Address,\n gaboxPlatform: '8tXUG97CEpSKTNXdGtanYyC33RWmTTuSin4VdaWwNj8q' as Address,\n cpmm: 'CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C' as Address,\n cpmmAuthority: 'GpMZbSM2GgvTKHJirzeGfMFoaZ8UR2X7F4v8vHTvxFbL' as Address,\n launchQuoteRaise: 85000000000n,\n};\n\nexport const RAYDIUM_DEVNET_IDS: RaydiumClusterIds = {\n launchlab: 'DRay6fNdQ5J82H7xV6uq2aV3mNrUZ1J4PgSKsWgptcm6' as Address,\n launchlabAuthority: '5xqNaZXX5eUi4p5HU4oz9i5QnwRNT2y6oN7yyn4qENeq' as Address,\n launchlabEventAuthority: '4uAB7seenFJKPUXqYewAdfra2u6baBgjiXU8x1SC7Ycz' as Address,\n gaboxPlatform: 'DdEeCPXbCAzHE2PZSoR3RZng4WA4bSztrezQznrJ4ooB' as Address,\n cpmm: 'DRaycpLY18LhpbydsBWbVJtxpNv9oXPgjRSfpF2bWpYb' as Address,\n cpmmAuthority: 'CXniRufdq5xL8t8jZAPxsPZDpuudwuJSPWnbcD5Y5Nxq' as Address,\n launchQuoteRaise: 3000000000n,\n};\n\n/**\n * Wrapped SOL: the default quote, and the one every price in SOL is measured in. Gabox accepts any\n * quote Raydium enabled on LaunchLab, so this is not the only one.\n */\nexport const WSOL_MINT = 'So11111111111111111111111111111111111111112' as Address;\n/** Metaplex Token Metadata, which LaunchLab's create instruction writes to. */\nexport const METAPLEX_PROGRAM_ADDRESS = 'metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s' as Address;\n/**\n * `PLATFORM_ADMIN` in the program's constants.rs. The Gabox platform config PDA derives from this\n * wallet, and LaunchLab pays the platform share of every curve trade to it.\n */\nexport const PLATFORM_ADMIN = '5WcPTEQ59UqpQzjZUPbU8QRGCbj7NeQNLDa7DbsLkLKT' as Address;\n\n/** The coin supply every Gabox launch mints: 1,000,000,000 coins at 6 decimals. */\nexport const LAUNCH_SUPPLY = 1000000000000000n;\n/** The part of the supply the LaunchLab curve sells: 793,100,000 coins. */\nexport const LAUNCH_TOTAL_BASE_SELL = 793100000000000n;\n\n/** Classic SPL Token. The base coin is always under it, on both venues. */\nexport const TOKEN_PROGRAM_ADDRESS = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA' as Address;\n/**\n * Token-2022. A quote mint may be under it, inside the bounded profile the program's\n * `tokens::validate_quote_mint` accepts. The base coin never is.\n */\nexport const TOKEN_2022_PROGRAM_ADDRESS = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb' as Address;\nexport const ASSOCIATED_TOKEN_PROGRAM_ADDRESS = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' as Address;\nexport const SYSTEM_PROGRAM_ADDRESS = '11111111111111111111111111111111' as Address;\n/** The rent sysvar. LaunchLab's create instruction still takes it. */\nexport const RENT_SYSVAR_ADDRESS = 'SysvarRent111111111111111111111111111111111' as Address;\n\n/**\n * The first eight bytes of each Raydium account this SDK decodes. `adapter.ts` checks them before\n * it reads a field, so an account of the wrong type fails loudly instead of decoding as rubbish.\n *\n * LaunchLab and CPMM give their pool account the same eight bytes, because Anchor derives a\n * discriminator from the struct name alone and both are called `PoolState`. The two programs own\n * different accounts, so the pair never collides in practice.\n */\nexport const LAUNCHLAB_POOL_STATE_DISCRIMINATOR = new Uint8Array([247, 237, 227, 245, 215, 195, 222, 70]);\nexport const LAUNCHLAB_GLOBAL_CONFIG_DISCRIMINATOR = new Uint8Array([149, 8, 156, 202, 160, 252, 176, 217]);\nexport const LAUNCHLAB_PLATFORM_CONFIG_DISCRIMINATOR = new Uint8Array([160, 78, 128, 0, 248, 83, 230, 160]);\nexport const CPMM_POOL_STATE_DISCRIMINATOR = new Uint8Array([247, 237, 227, 245, 215, 195, 222, 70]);\nexport const CPMM_AMM_CONFIG_DISCRIMINATOR = new Uint8Array([218, 244, 33, 104, 203, 203, 43, 111]);\n/**\n * `initialize_v2` on `LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj` — cross-checked against interfaces.json.\n */\nexport const LAUNCHLAB_INITIALIZE: VenueInstructionAbi = {\n name: 'initialize_v2',\n discriminator: new Uint8Array([67, 153, 175, 39, 218, 16, 38, 32]),\n accounts: [\n { name: 'payer', writable: true, signer: true },\n { name: 'creator', writable: false, signer: false },\n { name: 'global_config', writable: false, signer: false },\n { name: 'platform_config', writable: false, signer: false },\n { name: 'authority', writable: false, signer: false },\n { name: 'pool_state', writable: true, signer: false },\n { name: 'base_mint', writable: true, signer: true },\n { name: 'quote_mint', writable: false, signer: false },\n { name: 'base_vault', writable: true, signer: false },\n { name: 'quote_vault', writable: true, signer: false },\n { name: 'metadata_account', writable: true, signer: false },\n { name: 'base_token_program', writable: false, signer: false },\n { name: 'quote_token_program', writable: false, signer: false },\n { name: 'metadata_program', writable: false, signer: false },\n { name: 'system_program', writable: false, signer: false },\n { name: 'rent_program', writable: false, signer: false },\n { name: 'event_authority', writable: false, signer: false },\n { name: 'program', writable: false, signer: false },\n ],\n};\n\n/**\n * `buy_exact_in` on `LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj` — not in interfaces.json (the program never builds it).\n * The last three accounts are not in the IDL. LaunchLab reads them from the remaining\n * accounts, in this order.\n */\nexport const LAUNCHLAB_BUY_EXACT_IN: VenueInstructionAbi = {\n name: 'buy_exact_in',\n discriminator: new Uint8Array([250, 234, 13, 123, 213, 156, 19, 236]),\n accounts: [\n { name: 'payer', writable: true, signer: true },\n { name: 'authority', writable: false, signer: false },\n { name: 'global_config', writable: false, signer: false },\n { name: 'platform_config', writable: false, signer: false },\n { name: 'pool_state', writable: true, signer: false },\n { name: 'user_base_token', writable: true, signer: false },\n { name: 'user_quote_token', writable: true, signer: false },\n { name: 'base_vault', writable: true, signer: false },\n { name: 'quote_vault', writable: true, signer: false },\n { name: 'base_token_mint', writable: false, signer: false },\n { name: 'quote_token_mint', writable: false, signer: false },\n { name: 'base_token_program', writable: false, signer: false },\n { name: 'quote_token_program', writable: false, signer: false },\n { name: 'event_authority', writable: false, signer: false },\n { name: 'program', writable: false, signer: false },\n { name: 'system_program', writable: false, signer: false },\n { name: 'platform_fee_vault', writable: true, signer: false },\n { name: 'creator_fee_vault', writable: true, signer: false },\n ],\n};\n\n/**\n * `buy_exact_out` on `LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj` — cross-checked against interfaces.json.\n * The last three accounts are not in the IDL. LaunchLab reads them from the remaining\n * accounts, in this order.\n */\nexport const LAUNCHLAB_BUY_EXACT_OUT: VenueInstructionAbi = {\n name: 'buy_exact_out',\n discriminator: new Uint8Array([24, 211, 116, 40, 105, 3, 153, 56]),\n accounts: [\n { name: 'payer', writable: true, signer: true },\n { name: 'authority', writable: false, signer: false },\n { name: 'global_config', writable: false, signer: false },\n { name: 'platform_config', writable: false, signer: false },\n { name: 'pool_state', writable: true, signer: false },\n { name: 'user_base_token', writable: true, signer: false },\n { name: 'user_quote_token', writable: true, signer: false },\n { name: 'base_vault', writable: true, signer: false },\n { name: 'quote_vault', writable: true, signer: false },\n { name: 'base_token_mint', writable: false, signer: false },\n { name: 'quote_token_mint', writable: false, signer: false },\n { name: 'base_token_program', writable: false, signer: false },\n { name: 'quote_token_program', writable: false, signer: false },\n { name: 'event_authority', writable: false, signer: false },\n { name: 'program', writable: false, signer: false },\n { name: 'system_program', writable: false, signer: false },\n { name: 'platform_fee_vault', writable: true, signer: false },\n { name: 'creator_fee_vault', writable: true, signer: false },\n ],\n};\n\n/**\n * `sell_exact_in` on `LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj` — cross-checked against interfaces.json.\n * The last three accounts are not in the IDL. LaunchLab reads them from the remaining\n * accounts, in this order.\n */\nexport const LAUNCHLAB_SELL_EXACT_IN: VenueInstructionAbi = {\n name: 'sell_exact_in',\n discriminator: new Uint8Array([149, 39, 222, 155, 211, 124, 152, 26]),\n accounts: [\n { name: 'payer', writable: true, signer: true },\n { name: 'authority', writable: false, signer: false },\n { name: 'global_config', writable: false, signer: false },\n { name: 'platform_config', writable: false, signer: false },\n { name: 'pool_state', writable: true, signer: false },\n { name: 'user_base_token', writable: true, signer: false },\n { name: 'user_quote_token', writable: true, signer: false },\n { name: 'base_vault', writable: true, signer: false },\n { name: 'quote_vault', writable: true, signer: false },\n { name: 'base_token_mint', writable: false, signer: false },\n { name: 'quote_token_mint', writable: false, signer: false },\n { name: 'base_token_program', writable: false, signer: false },\n { name: 'quote_token_program', writable: false, signer: false },\n { name: 'event_authority', writable: false, signer: false },\n { name: 'program', writable: false, signer: false },\n { name: 'system_program', writable: false, signer: false },\n { name: 'platform_fee_vault', writable: true, signer: false },\n { name: 'creator_fee_vault', writable: true, signer: false },\n ],\n};\n\n/**\n * `claim_creator_fee` on `LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj` — not in interfaces.json (the program never builds it).\n */\nexport const LAUNCHLAB_CLAIM_CREATOR_FEE: VenueInstructionAbi = {\n name: 'claim_creator_fee',\n discriminator: new Uint8Array([26, 97, 138, 203, 132, 171, 141, 252]),\n accounts: [\n { name: 'creator', writable: true, signer: true },\n { name: 'fee_vault_authority', writable: false, signer: false },\n { name: 'creator_fee_vault', writable: true, signer: false },\n { name: 'recipient_token_account', writable: true, signer: false },\n { name: 'quote_mint', writable: false, signer: false },\n { name: 'token_program', writable: false, signer: false },\n { name: 'system_program', writable: false, signer: false },\n { name: 'associated_token_program', writable: false, signer: false },\n ],\n};\n\n/**\n * `claim_platform_fee_from_vault` on `LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj` — not in interfaces.json (the program never builds it).\n */\nexport const LAUNCHLAB_CLAIM_PLATFORM_FEE_FROM_VAULT: VenueInstructionAbi = {\n name: 'claim_platform_fee_from_vault',\n discriminator: new Uint8Array([117, 241, 198, 168, 248, 218, 80, 29]),\n accounts: [\n { name: 'platform_fee_wallet', writable: true, signer: true },\n { name: 'fee_vault_authority', writable: false, signer: false },\n { name: 'platform_config', writable: false, signer: false },\n { name: 'platform_fee_vault', writable: true, signer: false },\n { name: 'recipient_token_account', writable: true, signer: false },\n { name: 'quote_mint', writable: false, signer: false },\n { name: 'token_program', writable: false, signer: false },\n { name: 'system_program', writable: false, signer: false },\n { name: 'associated_token_program', writable: false, signer: false },\n ],\n};\n\n/**\n * `swap_base_output` on `CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C` — cross-checked against interfaces.json.\n */\nexport const CPMM_SWAP_BASE_OUTPUT: VenueInstructionAbi = {\n name: 'swap_base_output',\n discriminator: new Uint8Array([55, 217, 98, 86, 163, 74, 180, 173]),\n accounts: [\n { name: 'payer', writable: false, signer: true },\n { name: 'authority', writable: false, signer: false },\n { name: 'amm_config', writable: false, signer: false },\n { name: 'pool_state', writable: true, signer: false },\n { name: 'input_token_account', writable: true, signer: false },\n { name: 'output_token_account', writable: true, signer: false },\n { name: 'input_vault', writable: true, signer: false },\n { name: 'output_vault', writable: true, signer: false },\n { name: 'input_token_program', writable: false, signer: false },\n { name: 'output_token_program', writable: false, signer: false },\n { name: 'input_token_mint', writable: false, signer: false },\n { name: 'output_token_mint', writable: false, signer: false },\n { name: 'observation_state', writable: true, signer: false },\n ],\n};\n\n/**\n * `swap_base_input` on `CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C` — cross-checked against interfaces.json.\n */\nexport const CPMM_SWAP_BASE_INPUT: VenueInstructionAbi = {\n name: 'swap_base_input',\n discriminator: new Uint8Array([143, 190, 90, 218, 196, 30, 51, 222]),\n accounts: [\n { name: 'payer', writable: false, signer: true },\n { name: 'authority', writable: false, signer: false },\n { name: 'amm_config', writable: false, signer: false },\n { name: 'pool_state', writable: true, signer: false },\n { name: 'input_token_account', writable: true, signer: false },\n { name: 'output_token_account', writable: true, signer: false },\n { name: 'input_vault', writable: true, signer: false },\n { name: 'output_vault', writable: true, signer: false },\n { name: 'input_token_program', writable: false, signer: false },\n { name: 'output_token_program', writable: false, signer: false },\n { name: 'input_token_mint', writable: false, signer: false },\n { name: 'output_token_mint', writable: false, signer: false },\n { name: 'observation_state', writable: true, signer: false },\n ],\n};\n\n/**\n * `collect_creator_fee` on `CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C` — not in interfaces.json (the program never builds it).\n * The last account is not in the IDL snapshot; see `CPMM_CREATOR_FEE_SHARE_ACCOUNT` in\n * scripts/codegen.mjs. Derive it as PDA([\"creator_fee_share\", creator, amm_config]).\n */\nexport const CPMM_COLLECT_CREATOR_FEE: VenueInstructionAbi = {\n name: 'collect_creator_fee',\n discriminator: new Uint8Array([20, 22, 86, 123, 198, 28, 219, 132]),\n accounts: [\n { name: 'creator', writable: true, signer: true },\n { name: 'authority', writable: false, signer: false },\n { name: 'pool_state', writable: true, signer: false },\n { name: 'amm_config', writable: false, signer: false },\n { name: 'token_0_vault', writable: true, signer: false },\n { name: 'token_1_vault', writable: true, signer: false },\n { name: 'vault_0_mint', writable: false, signer: false },\n { name: 'vault_1_mint', writable: false, signer: false },\n { name: 'creator_token_0', writable: true, signer: false },\n { name: 'creator_token_1', writable: true, signer: false },\n { name: 'token_0_program', writable: false, signer: false },\n { name: 'token_1_program', writable: false, signer: false },\n { name: 'associated_token_program', writable: false, signer: false },\n { name: 'system_program', writable: false, signer: false },\n { name: 'creator_fee_share', writable: false, signer: false },\n ],\n};\n","/**\n * The Raydium addresses and launch numbers Gabox pins, per cluster.\n *\n * Mainnet and devnet run different Raydium deployments. Every program id and every PDA differs, and\n * so does the raise a WSOL-quoted curve must reach. So nothing here is a global: a caller passes the\n * cluster, which comes from `createClient({ cluster })`.\n *\n * None of these strings is typed in this file. `scripts/codegen.mjs` reads them out of the Rust\n * program's `programs/gabox/src/venue/ids.rs` and writes `abi.ts`. The Rust file is the source of\n * truth, because the program checks every one of these addresses on chain.\n * `test/raydium-pdas.test.ts` derives each PDA again and compares.\n */\n\nimport { getAddressEncoder, type Address } from '@solana/kit';\n\nimport type { Cluster } from '../rpc';\nimport {\n LAUNCH_SUPPLY,\n LAUNCH_TOTAL_BASE_SELL,\n METAPLEX_PROGRAM_ADDRESS,\n PLATFORM_ADMIN,\n RAYDIUM_DEVNET_IDS,\n RAYDIUM_MAINNET_IDS,\n TOKEN_2022_PROGRAM_ADDRESS,\n TOKEN_PROGRAM_ADDRESS,\n WSOL_MINT,\n type RaydiumClusterIds,\n} from './abi';\n\nconst ADDRESS_ENCODER = getAddressEncoder();\n\nexport {\n LAUNCH_SUPPLY,\n LAUNCH_TOTAL_BASE_SELL,\n METAPLEX_PROGRAM_ADDRESS,\n PLATFORM_ADMIN,\n RAYDIUM_DEVNET_IDS,\n RAYDIUM_MAINNET_IDS,\n TOKEN_2022_PROGRAM_ADDRESS,\n TOKEN_PROGRAM_ADDRESS,\n WSOL_MINT,\n};\nexport type { RaydiumClusterIds };\n\n/**\n * Raydium's liquidity lock program and its authority, per cluster.\n *\n * LaunchLab locks every graduated pool's LP under this program and mints one fee NFT to the\n * platform NFT wallet. The Gabox program never calls it, so these two addresses are not in the Rust\n * `ids.rs` and are typed here instead. Verified 2026-09-19: the devnet migration of a Gabox coin\n * called the devnet program below, and `test/raydium-pdas.test.ts` derives both authorities.\n */\nexport type LockIds = {\n /** The lock program. `collect_cp_fees` on it pays the fee NFT holder. */\n lock: Address;\n /** `[\"lock_cp_authority_seed\"]` under `lock`. It owns the vault that holds the locked LP. */\n lockAuthority: Address;\n};\n\nconst LOCK_MAINNET_IDS: LockIds = {\n lock: 'LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE' as Address,\n lockAuthority: '3f7GcQFG397GAaEnv51zR6tsTVihYRydnydDD1cXekxH' as Address,\n};\n\nconst LOCK_DEVNET_IDS: LockIds = {\n lock: 'DRay25Usp3YJAi7beckgpGUC7mGJ2cR1AVPxhYfwVCUX' as Address,\n lockAuthority: '7qWVV8UY2bRJfDLP4s37YzBPKUkVB46DStYJBpYbQzu3' as Address,\n};\n\n/** The name the rest of the SDK uses for one cluster's Raydium deployment. */\nexport type RaydiumIds = RaydiumClusterIds & LockIds;\n\n/**\n * The decimals every Gabox coin is launched with. `venue/launch.rs` refuses any other value, and\n * `tokens.rs` refuses a pool mint that does not have exactly this many.\n */\nexport const LAUNCH_DECIMALS = 6;\n\n/**\n * The Raydium deployment of each cluster.\n *\n * `localnet` uses the mainnet set. A local validator normally clones the mainnet Raydium programs,\n * and the program's own default `anchor build` pins the mainnet addresses too; the `devnet` cargo\n * feature is what swaps them. Pass your own ids to a builder if your validator clones devnet.\n */\nexport const RAYDIUM_IDS: Readonly<Record<Cluster, RaydiumIds>> = {\n 'mainnet-beta': { ...RAYDIUM_MAINNET_IDS, ...LOCK_MAINNET_IDS },\n devnet: { ...RAYDIUM_DEVNET_IDS, ...LOCK_DEVNET_IDS },\n localnet: { ...RAYDIUM_MAINNET_IDS, ...LOCK_MAINNET_IDS },\n};\n\n/** The Raydium deployment one cluster trades on. Throws for a cluster this SDK does not know. */\nexport function raydiumIds(cluster: Cluster): RaydiumIds {\n const ids = RAYDIUM_IDS[cluster];\n if (!ids) {\n throw new Error(\n `unknown cluster ${JSON.stringify(cluster)}; expected 'devnet', 'mainnet-beta' or 'localnet'`,\n );\n }\n return ids;\n}\n\n/** LaunchLab's PDA seeds, and the two Gabox coins are always sorted against. */\nexport const LAUNCHLAB_SEEDS = {\n /** `[\"vault_auth_seed\"]`. */\n authority: 'vault_auth_seed',\n /** `[\"__event_authority\"]`. */\n eventAuthority: '__event_authority',\n /** `[\"global_config\", quote_mint, u8 curve_type, u16 big-endian index]`. */\n globalConfig: 'global_config',\n /** `[\"platform_config\", platform_admin]`. */\n platformConfig: 'platform_config',\n /** `[\"pool\", base_mint, quote_mint]`. */\n pool: 'pool',\n /** `[\"pool_vault\", pool_state, mint]`. */\n vault: 'pool_vault',\n /** `[\"creator_fee_vault_auth_seed\"]`, the authority over every creator fee vault. */\n creatorFeeVaultAuthority: 'creator_fee_vault_auth_seed',\n /** `[\"platform_fee_vault_auth_seed\"]`, the authority over every platform fee vault. */\n platformFeeVaultAuthority: 'platform_fee_vault_auth_seed',\n} as const;\n\n/** CPMM's PDA seeds. */\nexport const CPMM_SEEDS = {\n /** `[\"vault_and_lp_mint_auth_seed\"]`. */\n authority: 'vault_and_lp_mint_auth_seed',\n /** `[\"pool\", amm_config, token_0_mint, token_1_mint]`, the mints sorted by byte order. */\n pool: 'pool',\n /** `[\"pool_vault\", pool_state, mint]`. */\n vault: 'pool_vault',\n /** `[\"observation\", pool_state]`. */\n observation: 'observation',\n /** `[\"creator_fee_share\", creator, amm_config]`. */\n creatorFeeShare: 'creator_fee_share',\n} as const;\n\n/** The SPL Memo program. The lock program's `collect_cp_fees` lists it and never writes to it. */\nexport const MEMO_PROGRAM_ADDRESS = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr' as Address;\n\n/** The lock program's PDA seeds. */\nexport const LOCK_SEEDS = {\n /** `[\"lock_cp_authority_seed\"]`. */\n authority: 'lock_cp_authority_seed',\n /** `[\"locked_liquidity\", fee_nft_mint]`. One record per locked position. */\n lockedLiquidity: 'locked_liquidity',\n} as const;\n\n/** Metaplex's metadata PDA seed: `[\"metadata\", metaplex, mint]`. */\nexport const METADATA_SEED = 'metadata';\n\n/**\n * Every rate LaunchLab and CPMM state is out of 1,000,000, not out of 10,000. A `trade_fee_rate`\n * of 5,000 is 0.5%.\n */\nexport const RATE_DENOMINATOR = 1_000_000n;\n\n/** The share-fee receiver Gabox never passes, so its rate is always zero on every trade. */\nexport const SHARE_FEE_RATE = 0n;\n\n/** `CurveParams::Constant`, the only curve shape Gabox launches. */\nexport const CONSTANT_CURVE_TAG = 0;\n\n/** `migrate_type` 1: the coin graduates into a CPMM pool, not into an AMM pool. */\nexport const MIGRATE_TO_CPMM = 1;\n\n/** `AmmCreatorFeeOn::QuoteToken`, so the CPMM creator fee is paid in the pool's quote asset. */\nexport const CREATOR_FEE_ON_QUOTE = 0;\n\n/** LaunchLab pool `status`: still selling on the curve. */\nexport const LAUNCHLAB_STATUS_FUND = 0;\n/** LaunchLab pool `status`: the raise is complete and Raydium's bot is migrating the coin. */\nexport const LAUNCHLAB_STATUS_MIGRATE = 1;\n/** LaunchLab pool `status`: the coin has graduated and trades on its CPMM pool. */\nexport const LAUNCHLAB_STATUS_TRADE = 2;\n\n/** Metaplex's own limits on the three strings a creator picks, in UTF-8 bytes. */\nexport const METADATA_LIMITS = { name: 32, symbol: 10, uri: 200 } as const;\n\n/** Raydium sorts a CPMM pair by raw address byte order. */\nexport function sortedMints(a: Address, b: Address): [Address, Address] {\n return compareAddresses(a, b) <= 0 ? [a, b] : [b, a];\n}\n\n/** Compare two addresses the way the runtime does: by their 32 raw bytes, not by base58 text. */\nexport function compareAddresses(a: Address, b: Address): number {\n const left = ADDRESS_ENCODER.encode(a);\n const right = ADDRESS_ENCODER.encode(b);\n for (let i = 0; i < 32; i++) {\n const difference = (left[i] ?? 0) - (right[i] ?? 0);\n if (difference !== 0) return difference;\n }\n return 0;\n}\n","/**\n * A bigint port of `programs/gabox/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/tests/math.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/**\n * `constants::MIN_SEED_MULTIPLIER_BPS`. The mandatory seed makes a 3x top prize payable on the\n * first pack, or the full top prize when the table's top tier is below 3x. A creator can add more\n * seed on top through `extraSeedTokens`.\n */\nexport const MIN_SEED_MULTIPLIER_BPS = 30_000;\n\n/**\n * `constants::MAX_MULTIPLIER_BPS`. A table's top tier can be at most 20x. Seed beyond what a 20x\n * prize needs stays in the vault as backup for the draws after a top-tier hit.\n */\nexport const MAX_MULTIPLIER_BPS = 200_000;\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/**\n * `constants::MAX_BATCH_SIZE`. The most packs one `buy_packs` call opens. A limit per purchase,\n * not on pending packs: any number of buyers and overlapping purchases are fine, because every\n * pending draw carries its own reservation.\n */\nexport const MAX_BATCH_SIZE = 5;\n\n/** One pack's outcome inside a settled batch: the tier it landed on and the tokens it pays. */\nexport type PackResult = {\n tier: number;\n amount: bigint;\n};\n\n/** What a batch pays: every pack's result in order, and their sum. */\nexport type Settlement = {\n total: bigint;\n results: PackResult[];\n};\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 a pack buy 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 * Four 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 * - a ticketed tier's multiplier is from 1 to `MAX_MULTIPLIER_BPS` (20x);\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 if (tier.multiplierBps > MAX_MULTIPLIER_BPS) {\n throw new GaboxMathError(\n \"InvalidDistribution\",\n `tier ${index} multiplierBps exceeds the ${MAX_MULTIPLIER_BPS} maximum (20x)`,\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 mandatory seed a table needs, in tokens.\n *\n * The mandatory seed makes a 3x top prize payable on the first pack, or the full top prize when\n * the table's top tier is below 3x. A jackpot above 3x still shows the full table once later\n * packs grow the free vault; the mandatory seed alone does not have to fund it. The pack itself\n * brings `packTokens` into the vault, so the vault has to hold the rest beforehand:\n *\n * seedTokens = min(uncappedMaximum(packTokens, tiers), tierAmount(packTokens, MIN_SEED_MULTIPLIER_BPS)) - packTokens\n *\n * A 20x or a 3x top tier on a 1M-token pack both need a 2M-token seed, since the mandatory seed\n * stops at the 3x minimum. A 2x top tier needs a 1M-token seed, already below the minimum. A\n * table whose top tier pays exactly one pack needs no seed. A top tier below one pack is refused:\n * every ticket would lose. `createMachine` lets a creator add more seed on top of this mandatory\n * amount through `extraSeedTokens`, for example to fund a top tier above 3x from the first pack.\n *\n * Pool initialization 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 const minimum = tierAmount(packTokens, MIN_SEED_MULTIPLIER_BPS);\n const capped = largest < minimum ? largest : minimum;\n return capped - 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/** A ticket is a `u16`: the first two bytes of the pack's hash, little-endian. */\nfunction checkedTicket(ticket: number): number {\n if (!Number.isInteger(ticket) || ticket < 0 || ticket >= TICKETS) {\n throw new GaboxMathError(\"Arithmetic\", `a ticket is an integer from 0 to ${TICKETS - 1}`);\n }\n return ticket;\n}\n\n/** `count` is a `u8` the program bounds at `MAX_BATCH_SIZE`. Zero is refused before any trade. */\nexport function checkedCount(count: number): number {\n if (!Number.isInteger(count) || count < 1) {\n throw new GaboxMathError(\"ZeroAmount\", \"a purchase opens at least one pack\");\n }\n if (count > MAX_BATCH_SIZE) {\n throw new GaboxMathError(\"TooManyPacks\", `a purchase opens at most ${MAX_BATCH_SIZE} packs`);\n }\n return count;\n}\n\n/**\n * `math::uncapped`. Every tier's award for this base before any inventory cap, `0n` on an unused\n * row. A ticketed tier that would pay nothing is refused, the same as in `quote`.\n */\nexport function uncappedAmounts(base: bigint, tiers: readonly Readonly<Tier>[]): bigint[] {\n validateTiers(tiers);\n return tiers.map((tier, i) => {\n if (tier.tickets === 0) return 0n;\n const amount = tierAmount(base, tier.multiplierBps);\n if (amount === 0n) {\n throw new GaboxMathError(\"PackTooSmall\", `tier ${i} rounds to zero tokens at this pack size`);\n }\n return amount;\n });\n}\n\n/** `math::min_tier`. The ticketed tier with the smallest award. Expiry pays it for every pack. */\nexport function minTier(uncapped: readonly bigint[], tiers: readonly Readonly<Tier>[]): number {\n let best: number | null = null;\n for (const [i, tier] of tiers.entries()) {\n if (tier.tickets === 0) continue;\n if (best === null || uncapped[i]! < uncapped[best]!) best = i;\n }\n return best ?? 0;\n}\n\n/**\n * `math::choose_index`. Which tier a 16-bit ticket lands on: the rows are consecutive ranges in\n * table order. Exactly 65,536 tickets, so there is no modulo and no bias.\n */\nexport function chooseIndex(tiers: readonly Readonly<Tier>[], ticket: number): number {\n checkedTicket(ticket);\n let end = 0;\n let last = 0;\n for (const [i, tier] of tiers.entries()) {\n if (tier.tickets === 0) continue;\n last = i;\n end += tier.tickets;\n if (ticket < end) return i;\n }\n return last;\n}\n\n/**\n * `math::reserve_for`. What a purchase of `count` packs adds to `pool.reserved`:\n * `min(count * uncappedMax, free + count * packTokens)`. Settlement in order can never pay more\n * than either bound, so this is the least reservation that keeps the vault solvent whatever the\n * outcomes. With `count = 1` it is exactly the single pack's capped maximum.\n */\nexport function reserveFor(\n count: number,\n packTokens: bigint,\n uncappedMax: bigint,\n free: bigint,\n): bigint {\n checkedCount(count);\n const byPrizes = checkedU64(uncappedMax * BigInt(count), \"reservation\");\n const byVault = checkedU64(free + packTokens * BigInt(count), \"reservation\");\n return byPrizes < byVault ? byPrizes : byVault;\n}\n\n/**\n * `math::settle_with`. Settle a batch in order from explicit tickets.\n *\n * Pack k's table caps every tier at what the vault can pay after packs 1..k-1 paid out, counting\n * the batch's own tokens as they arrive: pack 1 sees `freeSnapshot + packTokens`, and every later\n * pack sees the remainder plus one more pack. So no pack can lose its own base to an earlier pack,\n * and the total never exceeds `reserveFor(...)`.\n *\n * With `timedOut` every pack pays its smallest tier, and `tickets` is ignored.\n */\nexport function settleWith(\n tiers: readonly Readonly<Tier>[],\n packTokens: bigint,\n freeSnapshot: bigint,\n count: number,\n tickets: readonly number[],\n timedOut = false,\n): Settlement {\n checkedCount(count);\n const uncapped = uncappedAmounts(packTokens, tiers);\n const fallback = minTier(uncapped, tiers);\n let avail = checkedU64(freeSnapshot + packTokens, \"available inventory\");\n let total = 0n;\n const results: PackResult[] = [];\n for (let k = 0; k < count; k++) {\n let tier: number;\n if (timedOut) {\n tier = fallback;\n } else {\n const ticket = tickets[k];\n if (ticket === undefined) {\n throw new GaboxMathError(\"Arithmetic\", `no ticket for pack ${k} of ${count}`);\n }\n tier = chooseIndex(tiers, ticket);\n }\n const cap = uncapped[tier]!;\n const amount = cap < avail ? cap : avail;\n results.push({ tier, amount });\n total = checkedU64(total + amount, \"settlement total\");\n avail = checkedU64(avail - amount + packTokens, \"available inventory\");\n }\n return { total, results };\n}\n\n/**\n * The top prize each pack of a purchase can still win if every pack before it won its own top\n * prize: the worst case for the later packs, which is what a buyer should see next to the first\n * pack's table. `caps[0]` is the first pack's capped maximum; on a deep vault every entry is the\n * uncapped jackpot, on a thin one the later entries fall towards one pack.\n */\nexport function perPackCaps(\n tiers: readonly Readonly<Tier>[],\n packTokens: bigint,\n freeSnapshot: bigint,\n count: number,\n): bigint[] {\n checkedCount(count);\n const uncapped = uncappedMaximum(packTokens, tiers);\n let avail = checkedU64(freeSnapshot + packTokens, \"available inventory\");\n const caps: bigint[] = [];\n for (let k = 0; k < count; k++) {\n const cap = uncapped < avail ? uncapped : avail;\n caps.push(cap);\n avail = checkedU64(avail - cap + packTokens, \"available inventory\");\n }\n return caps;\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 fixed address this SDK needs at the top level, in one place.\n *\n * None of these is typed twice. The gabox program id comes from the generated client, which Codama\n * took from `target/idl/gabox.json`. The Raydium addresses come from `src/raydium/abi.ts`, which\n * `scripts/codegen.mjs` read out of the Rust program's `venue/ids.rs`. Retyping a base58 string is\n * a way to be wrong that no test would catch, so the strings live where the generator put them.\n *\n * Raydium runs a different deployment on each cluster, so its addresses are not constants here.\n * They come from `raydiumIds(client.cluster)`; see `src/raydium/ids.ts`.\n */\n\nimport type { Address } from '@solana/kit';\n\nimport { GABOX_PROGRAM_ADDRESS } from './generated/programs/gabox';\nimport {\n ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n METAPLEX_PROGRAM_ADDRESS,\n PLATFORM_ADMIN,\n SYSTEM_PROGRAM_ADDRESS,\n TOKEN_PROGRAM_ADDRESS,\n WSOL_MINT,\n} from './raydium/abi';\nimport { LAUNCH_DECIMALS } from './raydium/ids';\n\n/** `declare_id!` in `programs/gabox/src/lib.rs`. */\nexport const GABOX_PROGRAM_ID = GABOX_PROGRAM_ADDRESS;\n\nexport {\n ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n LAUNCH_DECIMALS,\n METAPLEX_PROGRAM_ADDRESS,\n PLATFORM_ADMIN,\n SYSTEM_PROGRAM_ADDRESS,\n TOKEN_PROGRAM_ADDRESS,\n WSOL_MINT,\n};\n\n/** MagicBlock's ephemeral VRF program. `vrf.rs` pins it and refuses any other. */\nexport const VRF_PROGRAM_ADDRESS = 'Vrf1RNUjXmQGjmQrQLvJHs9SNkvDJEsRVFPkfSQUwGz' as Address;\n\n/**\n * MagicBlock's default oracle queue. The program pins this one address, so a pool creator cannot\n * point a draw at an oracle they control.\n */\nexport const VRF_DEFAULT_QUEUE = 'Cuj97ggrhhidhbu39TijNVqE74xvKJ69gDervRUXAxGh' as Address;\n\n/** The seed of both identity PDAs. See `pdas.ts` — there are two, under different programs. */\nexport const IDENTITY_SEED = new Uint8Array([0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79]); // \"identity\"\n\nexport const SLOT_HASHES_SYSVAR = 'SysvarS1otHashes111111111111111111111111111' as Address;\n\nexport const INSTRUCTIONS_SYSVAR = 'Sysvar1nstructions1111111111111111111111111' as Address;\n\n/** `constants.rs`. A retry may not run sooner than this after the last attempt. */\nexport const RETRY_SLOTS = 300n;\n\n/** `constants.rs`. After this many slots from the purchase, anyone may expire the draw. */\nexport const TIMEOUT_SLOTS = 216_000n;\n\n/** `constants.rs`. Three requests in total, counting the one `buy_packs` makes. */\nexport const MAX_ATTEMPTS = 3;\n\n/** `constants.rs`. The most packs one purchase opens. See `math.ts`. */\nexport { MAX_BATCH_SIZE } from './math';\n\n/**\n * `constants.rs`. Tokens in one pack, in base units: 1,000,000 tokens at the fixed 6 decimals, or\n * 0.1% of the 1,000,000,000 supply. Every pool sells packs of this size. The venue decides what a\n * pack costs, so the pack price follows the coin. Read `pool.packTokens` rather than this when a\n * pool is at hand: a later program version may change the constant.\n */\nexport const PACK_TOKENS = 1_000_000n * 1_000_000n;\n","/**\n * Every Raydium address a Gabox transaction derives.\n *\n * All of them are program-derived, so each one takes the program it lives under. Mainnet and devnet\n * run different Raydium programs, so the same seeds give different addresses on the two clusters.\n * Pass `raydiumIds(client.cluster)` and read the program out of it.\n *\n * `venue/trade.rs` and `venue/launch.rs` derive the same addresses on chain and refuse any account\n * that does not match. `test/raydium-pdas.test.ts` checks every one of these against the pinned\n * table in `abi.ts`, for both clusters.\n */\n\nimport {\n Endian,\n getAddressEncoder,\n getProgramDerivedAddress,\n getU16Encoder,\n getU8Encoder,\n getUtf8Encoder,\n type Address,\n} from '@solana/kit';\n\nimport {\n ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n METAPLEX_PROGRAM_ADDRESS,\n TOKEN_PROGRAM_ADDRESS,\n} from './abi';\nimport { CPMM_SEEDS, LAUNCHLAB_SEEDS, LOCK_SEEDS, METADATA_SEED, sortedMints } from './ids';\n\nconst address = getAddressEncoder();\nconst utf8 = getUtf8Encoder();\nconst u8 = getU8Encoder();\nconst u16be = getU16Encoder({ endian: Endian.Big });\n\nconst derive = async (programAddress: Address, seeds: Uint8Array[]): Promise<Address> =>\n (await getProgramDerivedAddress({ programAddress, seeds }))[0];\n\n// ─────────────────────────────────────────────────────────────────────────────\n// LaunchLab\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** `[\"vault_auth_seed\"]`. LaunchLab signs its own vault transfers with this PDA. */\nexport const launchlabAuthority = async (launchlab: Address): Promise<Address> =>\n await derive(launchlab, [utf8.encode(LAUNCHLAB_SEEDS.authority) as Uint8Array]);\n\n/** `[\"__event_authority\"]`. */\nexport const launchlabEventAuthority = async (launchlab: Address): Promise<Address> =>\n await derive(launchlab, [utf8.encode(LAUNCHLAB_SEEDS.eventAuthority) as Uint8Array]);\n\n/**\n * `[\"global_config\", quote_mint, u8 curve_type, u16 big-endian index]`. The curve settings for one\n * quote asset. Gabox uses curve type 0 (constant product) and index 0.\n */\nexport const launchlabGlobalConfig = async (\n launchlab: Address,\n quoteMint: Address,\n curveType = 0,\n index = 0,\n): Promise<Address> =>\n await derive(launchlab, [\n utf8.encode(LAUNCHLAB_SEEDS.globalConfig) as Uint8Array,\n address.encode(quoteMint) as Uint8Array,\n u8.encode(curveType) as Uint8Array,\n u16be.encode(index) as Uint8Array,\n ]);\n\n/** `[\"platform_config\", platform_admin]`. The Gabox platform on LaunchLab. */\nexport const launchlabPlatformConfig = async (\n launchlab: Address,\n platformAdmin: Address,\n): Promise<Address> =>\n await derive(launchlab, [\n utf8.encode(LAUNCHLAB_SEEDS.platformConfig) as Uint8Array,\n address.encode(platformAdmin) as Uint8Array,\n ]);\n\n/** `[\"pool\", base_mint, quote_mint]`. The curve pool of one coin. */\nexport const launchlabPoolAddress = async (\n launchlab: Address,\n baseMint: Address,\n quoteMint: Address,\n): Promise<Address> =>\n await derive(launchlab, [\n utf8.encode(LAUNCHLAB_SEEDS.pool) as Uint8Array,\n address.encode(baseMint) as Uint8Array,\n address.encode(quoteMint) as Uint8Array,\n ]);\n\n/** `[\"pool_vault\", pool_state, mint]`. One side of a curve pool's reserves. */\nexport const launchlabVaultAddress = async (\n launchlab: Address,\n poolState: Address,\n mint: Address,\n): Promise<Address> =>\n await derive(launchlab, [\n utf8.encode(LAUNCHLAB_SEEDS.vault) as Uint8Array,\n address.encode(poolState) as Uint8Array,\n address.encode(mint) as Uint8Array,\n ]);\n\n/**\n * `[platform_config, quote_mint]`. LaunchLab pays the platform share of every curve trade here.\n *\n * The seeds carry no text prefix. That is Raydium's own derivation, not a mistake.\n */\nexport const platformFeeVaultAddress = async (\n launchlab: Address,\n platformConfig: Address,\n quoteMint: Address,\n): Promise<Address> =>\n await derive(launchlab, [\n address.encode(platformConfig) as Uint8Array,\n address.encode(quoteMint) as Uint8Array,\n ]);\n\n/**\n * `[creator, quote_mint]`. LaunchLab pays the creator share of every curve trade here.\n *\n * One vault per wallet per quote asset, not one per coin. A creator with several coins collects\n * all of them with a single `claim_creator_fee`.\n */\nexport const creatorFeeVaultAddress = async (\n launchlab: Address,\n creator: Address,\n quoteMint: Address,\n): Promise<Address> =>\n await derive(launchlab, [\n address.encode(creator) as Uint8Array,\n address.encode(quoteMint) as Uint8Array,\n ]);\n\n/** `[\"creator_fee_vault_auth_seed\"]`. The authority `claim_creator_fee` signs the payout with. */\nexport const creatorFeeVaultAuthority = async (launchlab: Address): Promise<Address> =>\n await derive(launchlab, [utf8.encode(LAUNCHLAB_SEEDS.creatorFeeVaultAuthority) as Uint8Array]);\n\n/**\n * `[\"platform_fee_vault_auth_seed\"]`. The authority `claim_platform_fee_from_vault` signs the\n * payout with.\n */\nexport const platformFeeVaultAuthority = async (launchlab: Address): Promise<Address> =>\n await derive(launchlab, [utf8.encode(LAUNCHLAB_SEEDS.platformFeeVaultAuthority) as Uint8Array]);\n\n/** `[\"metadata\", metaplex, mint]` under Metaplex. LaunchLab's create instruction writes it. */\nexport const metadataAddress = async (mint: Address): Promise<Address> =>\n await derive(METAPLEX_PROGRAM_ADDRESS, [\n utf8.encode(METADATA_SEED) as Uint8Array,\n address.encode(METAPLEX_PROGRAM_ADDRESS) as Uint8Array,\n address.encode(mint) as Uint8Array,\n ]);\n\n// ─────────────────────────────────────────────────────────────────────────────\n// CPMM\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** `[\"vault_and_lp_mint_auth_seed\"]`. */\nexport const cpmmAuthority = async (cpmm: Address): Promise<Address> =>\n await derive(cpmm, [utf8.encode(CPMM_SEEDS.authority) as Uint8Array]);\n\n/**\n * `[\"pool\", amm_config, token_0, token_1]`, with the two mints sorted by raw byte order.\n *\n * This is where Raydium migrates a coin when the address is free. It is only a first guess: when the\n * account is taken, the migration lands somewhere else entirely. And the address alone proves\n * nothing, because anyone can open a CPMM pool for any pair under any config. `findCpmmPool` tries\n * this address, checks the account data, and scans for the real pool when it does not match.\n *\n * There are no vault or observation derivations here on purpose. `venue/trade.rs` reads those three\n * addresses out of the pool account, and so does this SDK: a migrated pool names its own vaults and\n * its own oracle, wherever it sits.\n */\nexport const cpmmPoolAddress = async (\n cpmm: Address,\n ammConfig: Address,\n mintA: Address,\n mintB: Address,\n): Promise<Address> => {\n const [token0, token1] = sortedMints(mintA, mintB);\n return await derive(cpmm, [\n utf8.encode(CPMM_SEEDS.pool) as Uint8Array,\n address.encode(ammConfig) as Uint8Array,\n address.encode(token0) as Uint8Array,\n address.encode(token1) as Uint8Array,\n ]);\n};\n\n/**\n * `[\"creator_fee_share\", creator, amm_config]`. Where CPMM tracks what one creator is owed under\n * one fee tier.\n *\n * `collect_creator_fee` takes this account after the fourteen the mainnet IDL lists. That snapshot\n * predates the account; Raydium's devnet build declares it and stops with `AccountNotEnoughKeys`\n * (3005) when it is missing. One account per creator per fee tier, not one per pool.\n */\nexport const cpmmCreatorFeeShare = async (\n cpmm: Address,\n creator: Address,\n ammConfig: Address,\n): Promise<Address> =>\n await derive(cpmm, [\n utf8.encode(CPMM_SEEDS.creatorFeeShare) as Uint8Array,\n address.encode(creator) as Uint8Array,\n address.encode(ammConfig) as Uint8Array,\n ]);\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Liquidity lock\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** `[\"lock_cp_authority_seed\"]`. The lock program's authority, which owns every locked LP vault. */\nexport const lockAuthority = async (lock: Address): Promise<Address> =>\n await derive(lock, [utf8.encode(LOCK_SEEDS.authority) as Uint8Array]);\n\n/**\n * `[\"locked_liquidity\", fee_nft_mint]`. The record of one locked position: which pool, how much LP,\n * and the checkpoint the next fee harvest is measured from.\n */\nexport const lockedLiquidityAddress = async (lock: Address, feeNftMint: Address): Promise<Address> =>\n await derive(lock, [\n utf8.encode(LOCK_SEEDS.lockedLiquidity) as Uint8Array,\n address.encode(feeNftMint) as Uint8Array,\n ]);\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Token accounts\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** An associated token account. Off-curve owners are allowed: pool PDAs are all off-curve. */\nexport const ata = async (\n owner: Address,\n mint: Address,\n tokenProgram: Address = TOKEN_PROGRAM_ADDRESS,\n): Promise<Address> =>\n await derive(ASSOCIATED_TOKEN_PROGRAM_ADDRESS, [\n address.encode(owner) as Uint8Array,\n address.encode(tokenProgram) as Uint8Array,\n address.encode(mint) as Uint8Array,\n ]);\n","/**\n * Gabox's own program-derived addresses.\n *\n * Raydium's live in `src/raydium/pdas.ts`, because they depend on the cluster. These do not: the\n * Gabox program id is the same everywhere.\n *\n * Classic SPL Token only. Both venues use it, and the accepted LaunchLab create instruction mints\n * the coin with it, so no derivation here takes a token program any more.\n */\n\nimport {\n getAddressEncoder,\n getBytesEncoder,\n getProgramDerivedAddress,\n type Address,\n type ProgramDerivedAddress,\n} from '@solana/kit';\n\nimport { findActivityPda } from './generated/pdas/activity';\nimport { findDrawPda } from './generated/pdas/draw';\nimport { findIdentityPda } from './generated/pdas/identity';\nimport { findPoolPda } from './generated/pdas/pool';\nimport { GABOX_PROGRAM_ID, IDENTITY_SEED, TOKEN_PROGRAM_ADDRESS, VRF_PROGRAM_ADDRESS } from './ids';\nimport { ata } from './raydium/pdas';\n\nexport { findActivityPda, findDrawPda, findIdentityPda, findPoolPda };\n\n/** `[\"pool\", mint]`. One pool per coin. */\nexport const poolAddress = async (mint: Address): Promise<Address> => (await findPoolPda({ mint }))[0];\n\n/**\n * `[\"draw\", pool, purchaser, nonce]`, with the nonce as eight little-endian bytes. The buyer's\n * client picks the nonce, so two buyers, or two purchases of one buyer, never name the same draw.\n * The pool's sequence counter is not in the address any more; the program assigns `seqStart`\n * when the purchase executes.\n */\nexport const drawAddress = async (pool: Address, purchaser: Address, nonce: bigint): Promise<Address> =>\n (await findDrawPda({ pool, purchaser, nonce }))[0];\n\n/**\n * A random `u64` nonce for one purchase. `buyPacks` draws one per build. A nonce that is still in\n * use fails the purchase at the program; one whose draw already closed names a new draw, so a\n * rebuilt transaction must never reuse the nonce of a purchase that may have landed.\n */\nexport function randomNonce(): bigint {\n const bytes = new Uint8Array(8);\n crypto.getRandomValues(bytes);\n let nonce = 0n;\n for (let i = 7; i >= 0; i--) nonce = (nonce << 8n) | BigInt(bytes[i]!);\n return nonce;\n}\n\n/** The per-wallet `WalletActivity` PDA. `buy_packs` derives it from the purchaser automatically. */\nexport const activityAddress = async (wallet: Address): Promise<Address> =>\n (await findActivityPda({ purchaser: wallet }))[0];\n\n/** `[\"identity\"]` under Gabox. The PDA the program signs its randomness request with. */\nexport const vrfIdentityAddress = async (): Promise<Address> => (await findIdentityPda())[0];\n\n/** `[\"identity\", gabox_program_id]` under the VRF program. MagicBlock signs the callback with it. */\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/** An associated token account under classic SPL Token. */\nexport const associatedTokenAddress = async (\n owner: Address,\n mint: Address,\n tokenProgram: Address = TOKEN_PROGRAM_ADDRESS,\n): Promise<Address> => await ata(owner, mint, tokenProgram);\n\n/** The prize vault: the pool PDA's own associated token account for the coin. */\nexport const vaultAddress = async (mint: Address): Promise<Address> =>\n await associatedTokenAddress(await poolAddress(mint), mint);\n","/**\n * Reading Raydium's accounts.\n *\n * Every decoder here is written from the field list in the two IDL snapshots under `idl/`. Nothing\n * is guessed: each struct is laid out in Borsh order with no padding between fields, so the offsets\n * follow from the field sizes alone. Each decoder checks the account's eight-byte discriminator\n * first, so a wrong account fails loudly instead of decoding as plausible rubbish.\n *\n * `test/raydium-decode.test.ts` builds one byte array per decoder by hand and reads it back.\n *\n * Only the fields Gabox needs are decoded. The trailing padding of each account is skipped, which\n * is also why a longer account than the one recorded here still decodes: Raydium only ever appends\n * into its own padding.\n *\n * Kit's codecs, never `Buffer`. This module is vendored into a Next.js app, and `Buffer` does not\n * exist in a browser.\n */\n\nimport {\n fixDecoderSize,\n getAddressDecoder,\n getBooleanDecoder,\n getBytesDecoder,\n getStructDecoder,\n getU8Decoder,\n getU16Decoder,\n getU64Decoder,\n getU128Decoder,\n type Address,\n type ReadonlyUint8Array,\n} from '@solana/kit';\n\nimport {\n CPMM_AMM_CONFIG_DISCRIMINATOR,\n CPMM_POOL_STATE_DISCRIMINATOR,\n LAUNCHLAB_GLOBAL_CONFIG_DISCRIMINATOR,\n LAUNCHLAB_PLATFORM_CONFIG_DISCRIMINATOR,\n LAUNCHLAB_POOL_STATE_DISCRIMINATOR,\n} from './abi';\n\nconst DISCRIMINATOR = 8;\n\nconst u8 = getU8Decoder();\nconst u16 = getU16Decoder();\nconst u64 = getU64Decoder();\nconst u128 = getU128Decoder();\nconst addressAt = getAddressDecoder();\nconst bool = getBooleanDecoder();\n\n/** Refuse an account that is too short or carries another type's discriminator. */\nfunction checked(data: Uint8Array, discriminator: ReadonlyUint8Array, what: string): Uint8Array {\n if (data.length < discriminator.length) {\n throw new Error(`not a ${what}: ${data.length} bytes is shorter than a discriminator`);\n }\n for (const [i, byte] of discriminator.entries()) {\n if (data[i] !== byte) throw new Error(`not a ${what}: the discriminator does not match`);\n }\n return data;\n}\n\n/** Refuse a truncated account before a decoder reads past its end. */\nfunction atLeast(data: Uint8Array, size: number, what: string): Uint8Array {\n if (data.length < size) {\n throw new Error(`not a ${what}: ${data.length} bytes, expected at least ${size}`);\n }\n return data;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Token accounts\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * The `amount` field of an SPL token account: bytes 64 to 72, little-endian.\n *\n * Both venues and every Gabox account use classic SPL Token, whose account is 165 bytes. The\n * Token-2022 layout shares those first 165 bytes, so this reader covers a Token-2022 account too.\n */\nexport function tokenAccountAmount(data: Uint8Array): bigint {\n if (data.length < 72) throw new Error('not a token account: fewer than 72 bytes');\n return u64.decode(data, 64);\n}\n\n/** The `mint` and `owner` of an SPL token account: bytes 0 to 32 and 32 to 64. */\nexport function tokenAccountOwnerAndMint(data: Uint8Array): { mint: Address; owner: Address } {\n if (data.length < 64) throw new Error('not a token account: fewer than 64 bytes');\n return { mint: addressAt.decode(data, 0), owner: addressAt.decode(data, 32) };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Mints and their metadata\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** The base SPL mint is 82 bytes. Token-2022 repeats those 82 and appends its extensions. */\nconst MINT_BASE_SIZE = 82;\n/** `decimals` sits after `mint_authority` (4 + 32) and `supply` (8). */\nconst MINT_DECIMALS_AT = 44;\n\n/**\n * The `decimals` of a mint. Both token programs share the first 82 bytes, so one reader covers a\n * classic SPL mint and a Token-2022 one.\n */\nexport function mintDecimals(data: Uint8Array): number {\n if (data.length < MINT_BASE_SIZE) {\n throw new Error(`not a mint: ${data.length} bytes, expected at least ${MINT_BASE_SIZE}`);\n }\n return u8.decode(data, MINT_DECIMALS_AT);\n}\n\n/** A Borsh string: a u32 little-endian length, then that many UTF-8 bytes. */\nfunction borshString(data: Uint8Array, at: number): { text: string; next: number } | null {\n if (at + 4 > data.length) return null;\n const length = new DataView(data.buffer, data.byteOffset, data.byteLength).getUint32(at, true);\n const end = at + 4 + length;\n if (end > data.length) return null;\n return { text: new TextDecoder().decode(data.subarray(at + 4, end)), next: end };\n}\n\n/** Metaplex pads its three strings with NUL bytes up to their maximum length. */\nconst trimmed = (text: string): string | null => {\n const clean = text.replace(/\\0+$/, '').trim();\n return clean.length > 0 ? clean : null;\n};\n\n/**\n * The `symbol` of a Metaplex token metadata account, or `null` when it carries none.\n *\n * Layout: a one-byte key, `update_authority` and `mint`, then the three Borsh strings `name`,\n * `symbol` and `uri`. Metaplex stores them at their maximum length, NUL padded.\n */\nexport function metaplexSymbol(data: Uint8Array): string | null {\n const name = borshString(data, 1 + 32 + 32);\n if (!name) return null;\n const symbol = borshString(data, name.next);\n return symbol ? trimmed(symbol.text) : null;\n}\n\n/** The Token-2022 extension type of `TokenMetadata`, from the SPL token metadata interface. */\nconst TOKEN_METADATA_EXTENSION = 19;\n/** Token-2022 writes one account-type byte after the 82-byte mint, then its TLV extensions. */\nconst EXTENSION_START = 165 + 1;\n\n/**\n * The `symbol` a Token-2022 mint stores in its own `TokenMetadata` extension, or `null`.\n *\n * The extensions are a TLV list: a u16 type, a u16 length, then the value. The metadata value is\n * `update_authority`, `mint`, then the Borsh strings `name`, `symbol` and `uri`.\n */\nexport function token2022Symbol(data: Uint8Array): string | null {\n let at = EXTENSION_START;\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n while (at + 4 <= data.length) {\n const type = view.getUint16(at, true);\n const length = view.getUint16(at + 2, true);\n const value = at + 4;\n if (value + length > data.length) return null;\n if (type === TOKEN_METADATA_EXTENSION) {\n const name = borshString(data.subarray(value, value + length), 32 + 32);\n if (!name) return null;\n const symbol = borshString(data.subarray(value, value + length), name.next);\n return symbol ? trimmed(symbol.text) : null;\n }\n at = value + length;\n }\n return null;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// LaunchLab\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** The curve pool of one coin, as far as pricing and routing need it. */\nexport type LaunchlabPoolState = {\n /** 0 while the curve still sells, 1 while Raydium migrates the coin, 2 once it has graduated. */\n status: number;\n baseDecimals: number;\n quoteDecimals: number;\n /** 1 means the coin graduates into a CPMM pool. Every Gabox launch pins this. */\n migrateType: number;\n supply: bigint;\n /** The part of the supply the curve sells. The curve cannot sell more than this. */\n totalBaseSell: bigint;\n /** The curve's virtual reserves. `virtualQuote / virtualBase` is the starting price. */\n virtualBase: bigint;\n virtualQuote: bigint;\n /** Coins the curve has already sold, and quote it has already raised. */\n realBase: bigint;\n realQuote: bigint;\n totalQuoteFundRaising: bigint;\n migrateFee: bigint;\n globalConfig: Address;\n platformConfig: Address;\n baseMint: Address;\n quoteMint: Address;\n baseVault: Address;\n quoteVault: Address;\n /** The coin creator. LaunchLab pays the creator share of every trade to this wallet's vault. */\n creator: Address;\n /** 0 means the CPMM creator fee is paid in the quote token only. Every Gabox launch pins it. */\n ammCreatorFeeOn: number;\n};\n\n/** Offsets follow the `PoolState` field list in `idl/raydium_launchpad.json`. */\nconst LAUNCHLAB_POOL_HEAD = getStructDecoder([\n ['epoch', u64],\n ['authBump', u8],\n ['status', u8],\n ['baseDecimals', u8],\n ['quoteDecimals', u8],\n ['migrateType', u8],\n ['supply', u64],\n ['totalBaseSell', u64],\n ['virtualBase', u64],\n ['virtualQuote', u64],\n ['realBase', u64],\n ['realQuote', u64],\n ['totalQuoteFundRaising', u64],\n ['quoteProtocolFee', u64],\n ['platformFee', u64],\n ['migrateFee', u64],\n // VestingSchedule: five u64s Gabox always launches as zero.\n ['vestingTotalLockedAmount', u64],\n ['vestingCliffPeriod', u64],\n ['vestingUnlockPeriod', u64],\n ['vestingStartTime', u64],\n ['vestingAllocatedShareAmount', u64],\n ['globalConfig', addressAt],\n ['platformConfig', addressAt],\n ['baseMint', addressAt],\n ['quoteMint', addressAt],\n ['baseVault', addressAt],\n ['quoteVault', addressAt],\n ['creator', addressAt],\n ['tokenProgramFlag', u8],\n ['ammCreatorFeeOn', u8],\n]);\n\n/** The bytes the decoder above reads, discriminator included. The account itself is longer. */\nexport const LAUNCHLAB_POOL_STATE_HEAD_SIZE = 367;\n\nexport function decodeLaunchlabPool(data: Uint8Array): LaunchlabPoolState {\n checked(data, LAUNCHLAB_POOL_STATE_DISCRIMINATOR, 'LaunchLab pool');\n atLeast(data, LAUNCHLAB_POOL_STATE_HEAD_SIZE, 'LaunchLab pool');\n const head = LAUNCHLAB_POOL_HEAD.decode(data, DISCRIMINATOR);\n return {\n status: head.status,\n baseDecimals: head.baseDecimals,\n quoteDecimals: head.quoteDecimals,\n migrateType: head.migrateType,\n supply: head.supply,\n totalBaseSell: head.totalBaseSell,\n virtualBase: head.virtualBase,\n virtualQuote: head.virtualQuote,\n realBase: head.realBase,\n realQuote: head.realQuote,\n totalQuoteFundRaising: head.totalQuoteFundRaising,\n migrateFee: head.migrateFee,\n globalConfig: head.globalConfig,\n platformConfig: head.platformConfig,\n baseMint: head.baseMint,\n quoteMint: head.quoteMint,\n baseVault: head.baseVault,\n quoteVault: head.quoteVault,\n creator: head.creator,\n ammCreatorFeeOn: head.ammCreatorFeeOn,\n };\n}\n\n/**\n * LaunchLab's settings for one quote asset.\n *\n * One of these exists for every quote Raydium enabled, and only Raydium's admin can create one. So\n * the account itself is what proves a quote is allowed: the program checks the same four things in\n * `venue/launch.rs` before it opens a pool.\n */\nexport type LaunchlabGlobalConfig = {\n /** 0 is the constant product curve, the only shape Gabox launches. */\n curveType: number;\n index: number;\n /** The quote LaunchLab keeps at graduation. It lowers the curve's own starting reserves. */\n migrateFee: bigint;\n /** Raydium's own share of every curve trade, out of 1,000,000. */\n tradeFeeRate: bigint;\n /** The smallest raise LaunchLab accepts for this quote, in its own base units. */\n minQuoteFundRaising: bigint;\n quoteMint: Address;\n};\n\nconst LAUNCHLAB_GLOBAL_CONFIG_HEAD = getStructDecoder([\n ['epoch', u64],\n ['curveType', u8],\n ['index', u16],\n ['migrateFee', u64],\n ['tradeFeeRate', u64],\n ['maxShareFeeRate', u64],\n ['minBaseSupply', u64],\n ['maxLockRate', u64],\n ['minBaseSellRate', u64],\n ['minBaseMigrateRate', u64],\n ['minQuoteFundRaising', u64],\n ['quoteMint', addressAt],\n]);\n\nexport const LAUNCHLAB_GLOBAL_CONFIG_HEAD_SIZE = 115;\n\nexport function decodeLaunchlabGlobalConfig(data: Uint8Array): LaunchlabGlobalConfig {\n checked(data, LAUNCHLAB_GLOBAL_CONFIG_DISCRIMINATOR, 'LaunchLab global config');\n atLeast(data, LAUNCHLAB_GLOBAL_CONFIG_HEAD_SIZE, 'LaunchLab global config');\n const head = LAUNCHLAB_GLOBAL_CONFIG_HEAD.decode(data, DISCRIMINATOR);\n return {\n curveType: head.curveType,\n index: head.index,\n migrateFee: head.migrateFee,\n tradeFeeRate: head.tradeFeeRate,\n minQuoteFundRaising: head.minQuoteFundRaising,\n quoteMint: head.quoteMint,\n };\n}\n\n/** The Gabox platform on LaunchLab. Its two rates are the platform and creator shares. */\nexport type LaunchlabPlatformConfig = {\n /** Receives the platform share of every curve trade. */\n platformFeeWallet: Address;\n /** The platform share of every curve trade, out of 1,000,000. 5,000 is 0.5%. */\n feeRate: bigint;\n /** The coin creator's share of every curve trade, out of 1,000,000. 5,000 is 0.5%. */\n creatorFeeRate: bigint;\n /** The CPMM fee tier a coin of this platform graduates into. */\n cpswapConfig: Address;\n /**\n * When this is a real wallet, it becomes the CPMM pool creator at graduation instead of the coin\n * creator. Gabox leaves it empty, so its coin creators keep the CPMM creator fee.\n */\n platformCpCreator: Address;\n};\n\n/**\n * The fixed-size head of `PlatformConfig`, before its `curve_params` vector. The three text fields\n * are fixed byte arrays, so this is the same length for every platform.\n */\nconst LAUNCHLAB_PLATFORM_CONFIG_HEAD = getStructDecoder([\n ['epoch', u64],\n ['platformFeeWallet', addressAt],\n ['platformNftWallet', addressAt],\n ['platformScale', u64],\n ['creatorScale', u64],\n ['burnScale', u64],\n ['feeRate', u64],\n]);\n\n/** `name` is 64 bytes, `web` and `img` are 256 each. They sit between the two rates. */\nconst PLATFORM_TEXT_BYTES = 64 + 256 + 256;\nconst PLATFORM_CPSWAP_CONFIG_OFFSET = DISCRIMINATOR + 8 + 32 + 32 + 8 + 8 + 8 + 8 + PLATFORM_TEXT_BYTES;\nconst PLATFORM_CREATOR_FEE_RATE_OFFSET = PLATFORM_CPSWAP_CONFIG_OFFSET + 32;\nconst PLATFORM_CP_CREATOR_OFFSET = PLATFORM_CREATOR_FEE_RATE_OFFSET + 8 + 32 + 32 + 8;\n\n/** Everything before `curve_params`, discriminator included. */\nexport const LAUNCHLAB_PLATFORM_CONFIG_HEAD_SIZE = PLATFORM_CP_CREATOR_OFFSET + 32 + 108;\n\nexport function decodeLaunchlabPlatformConfig(data: Uint8Array): LaunchlabPlatformConfig {\n checked(data, LAUNCHLAB_PLATFORM_CONFIG_DISCRIMINATOR, 'LaunchLab platform config');\n atLeast(data, LAUNCHLAB_PLATFORM_CONFIG_HEAD_SIZE, 'LaunchLab platform config');\n const head = LAUNCHLAB_PLATFORM_CONFIG_HEAD.decode(data, DISCRIMINATOR);\n return {\n platformFeeWallet: head.platformFeeWallet,\n feeRate: head.feeRate,\n creatorFeeRate: u64.decode(data, PLATFORM_CREATOR_FEE_RATE_OFFSET),\n cpswapConfig: addressAt.decode(data, PLATFORM_CPSWAP_CONFIG_OFFSET),\n platformCpCreator: addressAt.decode(data, PLATFORM_CP_CREATOR_OFFSET),\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// CPMM\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** The pool a graduated Gabox coin trades in. */\nexport type CpmmPoolState = {\n ammConfig: Address;\n /** LaunchLab sets this to the coin creator at migration. It earns the CPMM creator fee. */\n poolCreator: Address;\n token0Vault: Address;\n token1Vault: Address;\n /** The LP token. A graduated coin's LP is locked, and its fee NFT holder harvests the fees. */\n lpMint: Address;\n token0Mint: Address;\n token1Mint: Address;\n token0Program: Address;\n token1Program: Address;\n observationKey: Address;\n /** Bit flags. Bit 2 set (value 4) means swaps are switched off. */\n status: number;\n /** LP tokens in circulation. The pool keeps this equal to the LP mint's supply. */\n lpSupply: bigint;\n mint0Decimals: number;\n mint1Decimals: number;\n /** Fees the pool owes and a swap must not spend. Subtract them from the vault balances. */\n protocolFeesToken0: bigint;\n protocolFeesToken1: bigint;\n fundFeesToken0: bigint;\n fundFeesToken1: bigint;\n creatorFeesToken0: bigint;\n creatorFeesToken1: bigint;\n /** Unix seconds. Swaps fail before it. */\n openTime: bigint;\n /** 0 charges the creator fee on whichever token comes in, 1 only token 0, 2 only token 1. */\n creatorFeeOn: number;\n /** `false` switches the creator fee off entirely. */\n enableCreatorFee: boolean;\n};\n\nconst CPMM_POOL_HEAD = getStructDecoder([\n ['ammConfig', addressAt],\n ['poolCreator', addressAt],\n ['token0Vault', addressAt],\n ['token1Vault', addressAt],\n ['lpMint', addressAt],\n ['token0Mint', addressAt],\n ['token1Mint', addressAt],\n ['token0Program', addressAt],\n ['token1Program', addressAt],\n ['observationKey', addressAt],\n ['authBump', u8],\n ['status', u8],\n ['lpMintDecimals', u8],\n ['mint0Decimals', u8],\n ['mint1Decimals', u8],\n ['lpSupply', u64],\n ['protocolFeesToken0', u64],\n ['protocolFeesToken1', u64],\n ['fundFeesToken0', u64],\n ['fundFeesToken1', u64],\n ['openTime', u64],\n ['recentEpoch', u64],\n ['creatorFeeOn', u8],\n ['enableCreatorFee', bool],\n ['padding1', fixDecoderSize(getBytesDecoder(), 6)],\n ['creatorFeesToken0', u64],\n ['creatorFeesToken1', u64],\n]);\n\nexport const CPMM_POOL_STATE_HEAD_SIZE = 413;\n\n/**\n * The full byte length of a CPMM `PoolState`, trailing padding included. A `getProgramAccounts`\n * scan filters on it, so it has to be the whole account and not only the part decoded above.\n */\nexport const CPMM_POOL_STATE_SIZE = 637;\n\n/**\n * Byte offsets a `getProgramAccounts` scan matches on. They are the same offsets `venue/trade.rs`\n * reads the fields at, so a pool that passes the scan passes the program's own check.\n */\nexport const CPMM_POOL_OFFSETS = {\n ammConfig: 8,\n poolCreator: 40,\n token0Mint: 168,\n token1Mint: 200,\n enableCreatorFee: 390,\n} as const;\n\nexport function decodeCpmmPool(data: Uint8Array): CpmmPoolState {\n checked(data, CPMM_POOL_STATE_DISCRIMINATOR, 'CPMM pool');\n atLeast(data, CPMM_POOL_STATE_HEAD_SIZE, 'CPMM pool');\n const head = CPMM_POOL_HEAD.decode(data, DISCRIMINATOR);\n return {\n ammConfig: head.ammConfig,\n poolCreator: head.poolCreator,\n token0Vault: head.token0Vault,\n token1Vault: head.token1Vault,\n lpMint: head.lpMint,\n token0Mint: head.token0Mint,\n token1Mint: head.token1Mint,\n token0Program: head.token0Program,\n token1Program: head.token1Program,\n observationKey: head.observationKey,\n status: head.status,\n lpSupply: head.lpSupply,\n mint0Decimals: head.mint0Decimals,\n mint1Decimals: head.mint1Decimals,\n protocolFeesToken0: head.protocolFeesToken0,\n protocolFeesToken1: head.protocolFeesToken1,\n fundFeesToken0: head.fundFeesToken0,\n fundFeesToken1: head.fundFeesToken1,\n creatorFeesToken0: head.creatorFeesToken0,\n creatorFeesToken1: head.creatorFeesToken1,\n openTime: head.openTime,\n creatorFeeOn: head.creatorFeeOn,\n enableCreatorFee: head.enableCreatorFee,\n };\n}\n\n/** One CPMM fee tier. Every rate is out of 1,000,000. */\nexport type CpmmAmmConfig = {\n index: number;\n disableCreatePool: boolean;\n /** The pool's own fee on every swap. Devnet tier 5 is 5,000, which is 0.50%. */\n tradeFeeRate: bigint;\n /** Raydium's share of the trade fee, not an extra charge on the swap. */\n protocolFeeRate: bigint;\n fundFeeRate: bigint;\n /** The pool creator's fee on every swap. Devnet tier 5 is 4,000, which is 0.40%. */\n creatorFeeRate: bigint;\n};\n\nconst CPMM_AMM_CONFIG_HEAD = getStructDecoder([\n ['bump', u8],\n ['disableCreatePool', bool],\n ['index', u16],\n ['tradeFeeRate', u64],\n ['protocolFeeRate', u64],\n ['fundFeeRate', u64],\n ['createPoolFee', u64],\n ['protocolOwner', addressAt],\n ['fundOwner', addressAt],\n ['creatorFeeRate', u64],\n]);\n\nexport const CPMM_AMM_CONFIG_HEAD_SIZE = 116;\n\nexport function decodeCpmmAmmConfig(data: Uint8Array): CpmmAmmConfig {\n checked(data, CPMM_AMM_CONFIG_DISCRIMINATOR, 'CPMM amm config');\n atLeast(data, CPMM_AMM_CONFIG_HEAD_SIZE, 'CPMM amm config');\n const head = CPMM_AMM_CONFIG_HEAD.decode(data, DISCRIMINATOR);\n return {\n index: head.index,\n disableCreatePool: head.disableCreatePool,\n tradeFeeRate: head.tradeFeeRate,\n protocolFeeRate: head.protocolFeeRate,\n fundFeeRate: head.fundFeeRate,\n creatorFeeRate: head.creatorFeeRate,\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Liquidity lock\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * One locked CPMM position, as Raydium's lock program records it.\n *\n * LaunchLab locks a graduated pool's LP here and mints one fee NFT for it. Whoever holds the NFT\n * harvests the fees. Layout from `LockedCpLiquidityState` in the `pinocchio-raydium-locking-program`\n * crate, checked against a devnet record on 2026-09-19: six numbers, four addresses, then padding.\n */\nexport type LockedCpLiquidity = {\n /** LP tokens still locked. A harvest withdraws some of them and lowers this. */\n lockedLpAmount: bigint;\n /** LP tokens every past harvest withdrew, in total. */\n claimedLpAmount: bigint;\n unclaimedLpAmount: bigint;\n /** The LP supply at the last checkpoint: the lock itself, or the last harvest. */\n lastLp: bigint;\n /** The pool's `x * y` at that checkpoint, on the balances that belong to LPs. */\n lastK: bigint;\n recentEpoch: bigint;\n /** The CPMM pool the LP belongs to. */\n poolId: Address;\n /** The NFT whose holder may harvest. */\n feeNftMint: Address;\n lockedOwner: Address;\n lockedLpMint: Address;\n};\n\n/** `sha256(\"account:LockedCpLiquidityState\")[0..8]`. */\nexport const LOCKED_CP_LIQUIDITY_DISCRIMINATOR = new Uint8Array([25, 10, 238, 197, 207, 234, 73, 22]);\n\nconst LOCKED_CP_LIQUIDITY = getStructDecoder([\n ['lockedLpAmount', u64],\n ['claimedLpAmount', u64],\n ['unclaimedLpAmount', u64],\n ['lastLp', u64],\n ['lastK', u128],\n ['recentEpoch', u64],\n ['poolId', addressAt],\n ['feeNftMint', addressAt],\n ['lockedOwner', addressAt],\n ['lockedLpMint', addressAt],\n]);\n\n/** Six numbers and four addresses after the discriminator. The account itself is 256 bytes. */\nexport const LOCKED_CP_LIQUIDITY_HEAD_SIZE = DISCRIMINATOR + 8 * 5 + 16 + 32 * 4;\n\nexport function decodeLockedCpLiquidity(data: Uint8Array): LockedCpLiquidity {\n checked(data, LOCKED_CP_LIQUIDITY_DISCRIMINATOR, 'locked liquidity record');\n atLeast(data, LOCKED_CP_LIQUIDITY_HEAD_SIZE, 'locked liquidity record');\n return LOCKED_CP_LIQUIDITY.decode(data, DISCRIMINATOR);\n}\n","/** Account readers and bounded discovery scans. Old pool layouts are intentionally unsupported. */\nimport {\n fetchEncodedAccount, getBase58Decoder, getBase64Encoder,\n type Address, type Base58EncodedBytes, type MaybeEncodedAccount,\n} from '@solana/kit';\nimport { DRAW_DISCRIMINATOR, decodeDraw, getDrawSize, type Draw } from './generated/accounts/draw';\nimport { POOL_DISCRIMINATOR, decodePool, getPoolSize, type Pool } from './generated/accounts/pool';\nimport { WALLET_ACTIVITY_DISCRIMINATOR, decodeWalletActivity, getWalletActivitySize, type WalletActivity } from './generated/accounts/walletActivity';\nimport { GABOX_PROGRAM_ID } from './ids';\nimport { quote, type Tier } from './math';\nimport { activityAddress, poolAddress, vaultAddress } from './pdas';\nimport { tokenAccountAmount } from './raydium/adapter';\nimport type { GaboxClient, GaboxRpc } from './rpc';\n\nexport { decodeDraw, decodePool, decodeWalletActivity, DRAW_DISCRIMINATOR, POOL_DISCRIMINATOR, WALLET_ACTIVITY_DISCRIMINATOR };\nexport type { Draw, Pool, WalletActivity };\n\nconst DISCRIMINATOR = 8;\nconst PUBKEY = 32;\nexport const DRAW_POOL_OFFSET = DISCRIMINATOR;\nexport const DRAW_PURCHASER_OFFSET = DISCRIMINATOR + PUBKEY;\n/**\n * The `settled` byte: after pool, purchaser, nonce, bump, seq_start, count, two slots, attempts,\n * eight tiers, pack_tokens, free_snapshot and reserved. `test/surface.test.ts` pins it against the\n * generated encoder.\n */\nexport const DRAW_SETTLED_OFFSET = DISCRIMINATOR + PUBKEY * 2 + 8 + 1 + 8 + 1 + 8 + 8 + 1 + 8 * 8 + 8 + 8 + 8;\nexport const POOL_CREATOR_OFFSET = DISCRIMINATOR;\nexport const POOL_MINT_OFFSET = DISCRIMINATOR + PUBKEY;\nconst base58 = getBase58Decoder();\nconst base64 = getBase64Encoder();\n\ntype ProgramAccountFilter = { memcmp: { offset: bigint; bytes: Base58EncodedBytes; encoding: 'base58' } } | { dataSize: bigint };\nconst asBase58 = (bytes: Uint8Array): Base58EncodedBytes => base58.decode(bytes) as Base58EncodedBytes;\nconst memcmp = (offset: number, bytes: Base58EncodedBytes): ProgramAccountFilter => ({ memcmp: { offset: BigInt(offset), bytes, encoding: 'base58' } });\nconst encoded = (address: Address, data: Uint8Array) => ({ address, data, exists: true as const, executable: false, lamports: 0n as never, programAddress: GABOX_PROGRAM_ID, space: BigInt(data.length) });\n\nexport async function fetchPoolByMint(client: GaboxClient, mint: Address): Promise<Pool | null> {\n return await fetchPoolAt(client, await poolAddress(mint));\n}\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\nfunction decodeCurrentPool(account: MaybeEncodedAccount): Pool | null {\n if (!account.exists) return null;\n if (account.data.length !== getPoolSize()) {\n throw new Error(`pool ${account.address} is not a Gabox pool and is intentionally unsupported`);\n }\n return decodePool(account).data;\n}\n\nfunction decodeCurrentDraw(account: MaybeEncodedAccount): Draw | null {\n if (!account.exists) return null;\n if (account.data.length !== getDrawSize()) {\n throw new Error(`draw ${account.address} is not a Gabox draw and is intentionally unsupported`);\n }\n return decodeDraw(account).data;\n}\n\nexport async function fetchDraw(client: GaboxClient, address: Address): Promise<Draw | null> {\n const account = await fetchEncodedAccount(client.rpc, address, { commitment: 'confirmed' });\n return decodeCurrentDraw(account);\n}\n\nfunction decodeCurrentWalletActivity(account: MaybeEncodedAccount): WalletActivity | null {\n if (!account.exists) return null;\n if (account.data.length !== getWalletActivitySize()) {\n throw new Error(`activity account ${account.address} is not a Gabox WalletActivity and is intentionally unsupported`);\n }\n return decodeWalletActivity(account).data;\n}\n\n/**\n * A wallet's lifetime pack-buying activity, or `null` before it has bought its first pack.\n * `buy_packs` creates this account `init_if_needed`, so a fresh wallet has none yet.\n */\nexport async function fetchWalletActivity(client: GaboxClient, wallet: Address): Promise<WalletActivity | null> {\n const account = await fetchEncodedAccount(client.rpc, await activityAddress(wallet), { commitment: 'confirmed' });\n return decodeCurrentWalletActivity(account);\n}\n\nexport type PoolRecord = { address: Address; data: Pool };\nexport type DrawRecord = { address: Address; data: Draw };\n\nasync function scan<T>(rpc: GaboxRpc, filters: ProgramAccountFilter[], decode: (address: Address, data: Uint8Array) => T): Promise<T[]> {\n const accounts = await rpc.getProgramAccounts(GABOX_PROGRAM_ID, { encoding: 'base64', commitment: 'confirmed', filters }).send();\n return accounts.map(({ pubkey, account }) => decode(pubkey, new Uint8Array(base64.encode(account.data[0]))));\n}\n\nexport async function listPools(client: GaboxClient): Promise<PoolRecord[]> {\n return await scan(client.rpc, [memcmp(0, asBase58(POOL_DISCRIMINATOR as Uint8Array)), { dataSize: BigInt(getPoolSize()) }],\n (address, data) => ({ address, data: decodePool(encoded(address, data)).data }));\n}\n\nexport type DrawQuery = { pool?: Address; purchaser?: Address };\nexport async function listDraws(client: GaboxClient, query: DrawQuery = {}): Promise<DrawRecord[]> {\n const filters: ProgramAccountFilter[] = [memcmp(0, asBase58(DRAW_DISCRIMINATOR as Uint8Array)), { dataSize: BigInt(getDrawSize()) }];\n if (query.pool) filters.push(memcmp(DRAW_POOL_OFFSET, query.pool as unknown as Base58EncodedBytes));\n if (query.purchaser) filters.push(memcmp(DRAW_PURCHASER_OFFSET, query.purchaser as unknown as Base58EncodedBytes));\n return await scan(client.rpc, filters, (address, data) => ({ address, data: decodeDraw(encoded(address, data)).data }));\n}\nexport const listDrawsByPool = async (client: GaboxClient, pool: Address): Promise<DrawRecord[]> => await listDraws(client, { pool });\nexport const listDrawsByPurchaser = async (client: GaboxClient, purchaser: Address): Promise<DrawRecord[]> => await listDraws(client, { purchaser });\n\n/**\n * A purchaser's draws that settled without paying: the callback could not use the purchaser's coin\n * account, so the tokens wait in the vault as `owed` until `claimPrize` or `claimPrizeTo` pays\n * them. A pending draw is not in this list, and a paid one no longer exists.\n */\nexport async function fetchOwedDraws(client: GaboxClient, purchaser: Address): Promise<DrawRecord[]> {\n const filters: ProgramAccountFilter[] = [\n memcmp(0, asBase58(DRAW_DISCRIMINATOR as Uint8Array)),\n { dataSize: BigInt(getDrawSize()) },\n memcmp(DRAW_PURCHASER_OFFSET, purchaser as unknown as Base58EncodedBytes),\n memcmp(DRAW_SETTLED_OFFSET, asBase58(new Uint8Array([1]))),\n ];\n const rows = await scan(client.rpc, filters, (address, data) => ({ address, data: decodeDraw(encoded(address, data)).data }));\n return rows.filter((row) => row.data.settled && row.data.owed > 0n);\n}\n\nexport async function fetchVaultBalance(client: GaboxClient, mint: Address): Promise<bigint> {\n const vault = await vaultAddress(mint);\n const { value } = await client.rpc.getAccountInfo(vault, { encoding: 'base64', commitment: 'confirmed' }).send();\n return value ? tokenAccountAmount(new Uint8Array(base64.encode(value.data[0]))) : 0n;\n}\n\nexport type PoolInventory = { poolAddress: Address; pool: Pool; inventory: bigint; reserved: bigint; free: bigint };\nexport async function fetchPoolInventory(client: GaboxClient, mint: Address): Promise<PoolInventory | null> {\n // `reserved` and the vault amount form one invariant. Fetching them in separate RPC calls can\n // advertise free inventory that never existed at one slot while a buy or delivery is in flight.\n // Classic SPL Token owns every Gabox coin, so this is the sole supported vault PDA.\n const poolPda = await poolAddress(mint);\n const vaultPda = await vaultAddress(mint);\n const { value } = await client.rpc.getMultipleAccounts(\n [poolPda, vaultPda], { encoding: 'base64', commitment: 'confirmed' },\n ).send();\n const poolAccount = value[0];\n if (!poolAccount) return null;\n const pool = decodeCurrentPool(encoded(poolPda, new Uint8Array(base64.encode(poolAccount.data[0]))));\n if (!pool) return null;\n if (pool.vault !== vaultPda) {\n throw new Error(`pool ${poolPda} has an unexpected vault; it is not a supported Gabox pool`);\n }\n const vaultAccount = value[1];\n const inventory = vaultAccount\n ? tokenAccountAmount(new Uint8Array(base64.encode(vaultAccount.data[0])))\n : 0n;\n return { poolAddress: poolPda, pool, inventory, reserved: pool.reserved, free: inventory > pool.reserved ? inventory - pool.reserved : 0n };\n}\nexport const tiersOf = (pool: Pool): Tier[] => pool.tiers.map(({ multiplierBps, tickets }) => ({ multiplierBps, tickets }));\nexport const quotePool = (inventory: PoolInventory) => quote(inventory.pool.packTokens, 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 Raydium (which does its own CPIs into the token program and may create two fee vaults),\n * a `transfer_checked`, an account init, and a CPI into MagicBlock's VRF program that allocates a\n * request account. `createMachine` adds LaunchLab's `initialize_v2` to that, which mints the coin\n * and writes its Metaplex metadata. Neither fits in the default, and nothing on chain can raise its\n * own budget.\n *\n * # The numbers are measured\n *\n * Each figure below is about 1.3x the largest `computeUnitsConsumed` the devnet end-to-end test saw\n * over three runs on 2026-09-18, across both venues. That matters because the prioritisation fee is\n * `price x requested limit`: a request three times too large costs three times too much on every\n * pack. A caller may still override any of them.\n *\n * The three runs did not agree. A curve pack cost 164,717, then 167,723, then 181,225 units for the\n * same work, so the venue's own cost moves with state this SDK does not control. The 1.3x margin is\n * there to absorb that, and the largest of the three is always the basis.\n *\n * None of them covers a swap. When a builder puts a route in the same transaction, the route states\n * its own cost as `Route.computeUnits` and the builder adds it, capped at `MAX_COMPUTE_UNIT_LIMIT`.\n *\n * Re-measure after a change to a builder or to a Raydium program. `test/devnet.e2e.test.ts` prints\n * `CU <label>: <units> | <signature>` for every transaction it sends, which is where these came\n * from.\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 * LaunchLab `initialize_v2`, the WSOL wrap, pool initialization with a seed buy, and the WSOL\n * close, in one transaction. Measured at `266,488`, `258,988` and `267,988` over three devnet runs\n * against the slot-500297753 build.\n */\nexport const CREATE_MACHINE_COMPUTE_UNITS = 350_000;\n\n/**\n * A WSOL wrap, a venue buy, an escrow transfer, a draw init, a VRF request and the WSOL close.\n * Measured at `178,690`, `163,686` and `157,692` on the curve, and `113,891`, `110,922` and\n * `106,387` on CPMM. The curve buy is dearer because a coin's first trade also creates the platform\n * and creator fee vaults.\n *\n * One figure for every `count` from 1 to `MAX_BATCH_SIZE`: a purchase of five packs is still one\n * trade, one draw and one request. The per-pack work runs in the oracle's callback, on the oracle's\n * own budget. The devnet end-to-end test re-measures count 1 and 5.\n */\nexport const BUY_PACK_COMPUTE_UNITS = 235_000;\n\n/**\n * `claim_prize`: create the purchaser's ATA when it is missing, one transfer, close the draw. An\n * estimate until the devnet run measures it; a caller may override it.\n */\nexport const CLAIM_PRIZE_COMPUTE_UNITS = 80_000;\n\n/**\n * A WSOL wrap, a venue sale, and the WSOL close. Measured at `94,246`, `86,745` and `88,246` on the\n * curve, and `61,545`, `55,576` and `57,046` on CPMM.\n */\nexport const REDEEM_COMPUTE_UNITS = 125_000;\n\n/**\n * A creator fee claim: create the quote account, claim or collect, and close it when it is WSOL.\n * Measured at `31,319` every run for the LaunchLab claim and `40,959` for the CPMM collect. A claim\n * on a pool quoted in another token is cheaper, `17,635`, because nothing has to be unwrapped.\n */\nexport const CLAIM_COMPUTE_UNITS = 55_000;\n\n/**\n * A harvest of one locked CPMM position: `collect_cp_fees` on the lock program, which withdraws\n * LP through CPMM and pays both sides out.\n *\n * Measured at `102,221` on devnet on 2026-09-19 (tx `5s7xvy23…`), with both token accounts\n * created in the same transaction and the WSOL one closed again. `82,697` of that is the lock\n * program itself.\n */\nexport const HARVEST_COMPUTE_UNITS = 150_000;\n\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 * One account reader, shared by every module that decodes a Raydium account.\n *\n * Kit's codecs, not `Buffer`. This SDK is vendored into a Next.js app and `Buffer` is not defined\n * in the browser.\n */\n\nimport { getBase64Encoder, type Address } from '@solana/kit';\n\nimport type { GaboxRpc } from '../rpc';\n\nconst base64 = getBase64Encoder();\n\n/** An account that may not exist, with its raw bytes and its owning program. */\nexport type MaybeAccount = { data: Uint8Array; owner: Address } | null;\n\n/** Read several accounts in one call. A missing account comes back as `null`, not as an error. */\nexport async function readAccounts(rpc: GaboxRpc, addresses: Address[]): Promise<MaybeAccount[]> {\n const { value } = await rpc\n .getMultipleAccounts(addresses, { encoding: 'base64', commitment: 'confirmed' })\n .send();\n return value.map((account) => {\n if (!account) return null;\n const [encoded] = account.data;\n return { data: new Uint8Array(base64.encode(encoded)), owner: account.owner };\n });\n}\n\n/** Decode one base64 account payload the RPC returned inside another shape. */\nexport const decodeBase64 = (encoded: string): Uint8Array => new Uint8Array(base64.encode(encoded));\n","/**\n * The quote asset a machine is priced in.\n *\n * Gabox accepts any quote Raydium enabled on LaunchLab. There is no list of mints anywhere: Raydium\n * writes one `GlobalConfig` account per quote, only its admin can create one, and the program\n * proves the quote from that account's own data. So this module answers two questions from the\n * chain:\n *\n * 1. **Does the quote exist on LaunchLab?** `fetchQuoteConfig` derives\n * `[\"global_config\", quote_mint, u8 0, u16 big-endian 0]`, reads it and decodes it. `null`\n * means Raydium has no constant-product config for that mint, so no Gabox pool can use it.\n * 2. **What is the quote?** `fetchQuoteAsset` adds the mint's own token program, its decimals and\n * its symbol, which is what a price display and every account derivation need.\n *\n * The quote mint may be classic SPL Token or Token-2022. The base coin never is: LaunchLab mints it\n * with classic SPL Token, and the program pins the base slots to that program on both venues.\n */\n\nimport type { Address } from '@solana/kit';\n\nimport type { GaboxClient } from '../rpc';\nimport {\n decodeLaunchlabGlobalConfig,\n metaplexSymbol,\n mintDecimals,\n token2022Symbol,\n type LaunchlabGlobalConfig,\n} from './adapter';\nimport {\n CONSTANT_CURVE_TAG,\n TOKEN_2022_PROGRAM_ADDRESS,\n TOKEN_PROGRAM_ADDRESS,\n raydiumIds,\n type RaydiumIds,\n} from './ids';\nimport { launchlabGlobalConfig, metadataAddress } from './pdas';\nimport { readAccounts } from './read';\n\n/** LaunchLab's settings for one quote, and the address they were read from. */\nexport type QuoteConfig = LaunchlabGlobalConfig & {\n /** `[\"global_config\", quote_mint, u8 0, u16 big-endian 0]` under LaunchLab. */\n address: Address;\n};\n\n/** Everything a pool, a price and an account list need to know about a quote asset. */\nexport type QuoteAsset = {\n mint: Address;\n /** The LaunchLab global config `initialize_pool` proves the quote with. */\n config: Address;\n /** Classic SPL Token, or Token-2022. The user's quote ATA lives under it. */\n tokenProgram: Address;\n decimals: number;\n /** From Metaplex, or from the Token-2022 metadata extension. `null` when the mint has none. */\n symbol: string | null;\n /** Raydium's own share of every curve trade, out of 1,000,000. */\n tradeFeeRate: bigint;\n /** The quote LaunchLab keeps at graduation. The starting reserves depend on it. */\n migrateFee: bigint;\n /** The smallest `raise` LaunchLab accepts for this quote, in the quote's base units. */\n minQuoteFundRaising: bigint;\n};\n\n/**\n * LaunchLab's global config for one quote mint, or `null` when Raydium enabled no such quote.\n *\n * Index 0 is the usual config, and the constant-product curve is the only shape Gabox launches, so\n * those two are fixed here. The decoded `quoteMint` has to be the mint asked for: a config for a\n * different quote would price the wrong asset.\n */\nexport async function fetchQuoteConfig(\n client: GaboxClient,\n mint: Address,\n ids: RaydiumIds = raydiumIds(client.cluster),\n): Promise<QuoteConfig | null> {\n const address = await launchlabGlobalConfig(ids.launchlab, mint, CONSTANT_CURVE_TAG, 0);\n const [account] = await readAccounts(client.rpc, [address]);\n if (!account || account.owner !== ids.launchlab) return null;\n let config: LaunchlabGlobalConfig;\n try {\n config = decodeLaunchlabGlobalConfig(account.data);\n } catch {\n return null;\n }\n if (config.curveType !== CONSTANT_CURVE_TAG || config.quoteMint !== mint) return null;\n return { ...config, address };\n}\n\n/** Can a Gabox machine be quoted in this mint? One account read. */\nexport async function isQuoteSupported(client: GaboxClient, mint: Address): Promise<boolean> {\n return (await fetchQuoteConfig(client, mint)) !== null;\n}\n\n/**\n * The full quote asset: its LaunchLab config, its token program, its decimals and its symbol.\n *\n * Two round trips. The first reads the global config, because the config address is derived from\n * the mint. The second reads the mint and its Metaplex metadata account together.\n *\n * Throws when Raydium has no config for the mint, because no pool can be created or traded then.\n */\nexport async function fetchQuoteAsset(\n client: GaboxClient,\n mint: Address,\n ids: RaydiumIds = raydiumIds(client.cluster),\n): Promise<QuoteAsset> {\n const config = await fetchQuoteConfig(client, mint, ids);\n if (!config) {\n throw new Error(\n `Raydium has no LaunchLab global config for ${mint}, so it is not a quote asset Gabox can ` +\n 'use. Pick a quote Raydium enabled, such as wrapped SOL or USDC.',\n );\n }\n const display = await fetchQuoteDisplay(client, mint);\n return {\n mint,\n config: config.address,\n tokenProgram: display.tokenProgram,\n decimals: display.decimals,\n symbol: display.symbol,\n tradeFeeRate: config.tradeFeeRate,\n migrateFee: config.migrateFee,\n minQuoteFundRaising: config.minQuoteFundRaising,\n };\n}\n\n/** What a price display needs about a quote mint: its program, its decimals and its symbol. */\nexport type QuoteDisplay = {\n tokenProgram: Address;\n decimals: number;\n symbol: string | null;\n};\n\n/**\n * Read a quote mint and its Metaplex metadata in one call.\n *\n * A Token-2022 mint may carry its own `TokenMetadata` extension, and that one wins: it is the\n * issuer's own record. A classic SPL mint keeps its symbol in a Metaplex account, and a mint with\n * neither reports `null`.\n */\nexport async function fetchQuoteDisplay(\n client: GaboxClient,\n mint: Address,\n): Promise<QuoteDisplay> {\n const [mintAccount, metadata] = await readAccounts(client.rpc, [mint, await metadataAddress(mint)]);\n if (!mintAccount) throw new Error(`the quote mint ${mint} is not on chain`);\n const tokenProgram = mintAccount.owner;\n if (tokenProgram !== TOKEN_PROGRAM_ADDRESS && tokenProgram !== TOKEN_2022_PROGRAM_ADDRESS) {\n throw new Error(\n `the quote mint ${mint} is owned by ${tokenProgram}, which is neither classic SPL Token nor ` +\n 'Token-2022',\n );\n }\n const own = tokenProgram === TOKEN_2022_PROGRAM_ADDRESS ? token2022Symbol(mintAccount.data) : null;\n return {\n tokenProgram,\n decimals: mintDecimals(mintAccount.data),\n symbol: own ?? (metadata ? metaplexSymbol(metadata.data) : null),\n };\n}\n","/**\n * The ordered account list of every Raydium trade Gabox forwards.\n *\n * # Why these are built here\n *\n * `venue/trade.rs` accepts four trade instructions and no others: LaunchLab's `buy_exact_out` and\n * `sell_exact_in`, CPMM's `swap_base_output` and `swap_base_input`. It takes the venue's own\n * account list as `remaining_accounts` and walks it position by position. So the lists are\n * assembled here, from `abi.ts`, which codegen generated from the same Raydium IDLs the program's\n * `venue/abi.rs` came from.\n *\n * # How to read the output\n *\n * Each function returns `AccountMeta[]` in ABI order, with the role each slot's own ABI gives it.\n * That list goes into `initialize_pool`, `buy_pack` or `sell_tokens` as `remainingAccounts`,\n * unchanged. The program then requires every writable slot to be writable in the outer transaction,\n * requires the one signer slot to be the purchaser, and checks every address by name.\n *\n * # CPMM names its accounts by direction\n *\n * CPMM calls its four pairs `input_*` and `output_*`. A buy sends quote and receives the coin; a\n * sell is the other way round. So the two builders below fill the same four names with opposite\n * addresses, the token programs included. LaunchLab names its accounts by role instead, and uses\n * one list for both sides.\n *\n * # The token programs are inputs, not constants\n *\n * The base coin is always classic SPL Token. The quote may be Token-2022, so its program travels\n * with the pool: `pool.quoteTokenProgram` on the curve, and the two programs a migrated CPMM pool\n * records in its own data. `venue/trade.rs` checks both slots against the same values.\n */\n\nimport { AccountRole, type AccountMeta, type Address } from '@solana/kit';\n\nimport {\n CPMM_SWAP_BASE_INPUT,\n CPMM_SWAP_BASE_OUTPUT,\n LAUNCHLAB_BUY_EXACT_IN,\n LAUNCHLAB_BUY_EXACT_OUT,\n LAUNCHLAB_SELL_EXACT_IN,\n SYSTEM_PROGRAM_ADDRESS,\n TOKEN_PROGRAM_ADDRESS,\n type VenueInstructionAbi,\n} from './abi';\n\n/**\n * Turn `{name -> address}` into the ABI's ordered `AccountMeta[]`.\n *\n * The map is keyed by the IDL's own account names, so a missing entry names the slot it belongs to\n * rather than failing as an off-by-one further down. The role comes from the ABI table alone, never\n * from the caller, which is what keeps this list in step with `venue/abi.rs`.\n */\nexport function order(abi: VenueInstructionAbi, byName: Record<string, Address>): AccountMeta[] {\n return abi.accounts.map((spec) => {\n const address = byName[spec.name];\n if (address === undefined) {\n throw new Error(`${abi.name}: no address given for the \"${spec.name}\" account`);\n }\n const role = spec.signer\n ? spec.writable\n ? AccountRole.WRITABLE_SIGNER\n : AccountRole.READONLY_SIGNER\n : spec.writable\n ? AccountRole.WRITABLE\n : AccountRole.READONLY;\n return { address, role };\n });\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// LaunchLab\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Everything a LaunchLab trade list needs. Every address is derived, never read off the chain. */\nexport type LaunchlabTradeAccountsInput = {\n /** Raydium LaunchLab on this cluster. */\n launchlab: Address;\n /** `[\"vault_auth_seed\"]` under LaunchLab. */\n launchlabAuthority: Address;\n /** `[\"__event_authority\"]` under LaunchLab. */\n launchlabEventAuthority: Address;\n /** The global config of the quote asset. */\n globalConfig: Address;\n /** The Gabox platform config. */\n platformConfig: Address;\n /** `[\"pool\", mint, quote_mint]` under LaunchLab. */\n poolState: Address;\n mint: Address;\n quoteMint: Address;\n /** `[\"pool_vault\", pool_state, mint]` under LaunchLab. */\n baseVault: Address;\n /** `[\"pool_vault\", pool_state, quote_mint]` under LaunchLab. */\n quoteVault: Address;\n /** The trader. The one signing slot in the list. */\n user: Address;\n /** The trader's coin ATA. `buy_pack` passes the same address as its own `user_tokens`. */\n userBaseToken: Address;\n /** The trader's quote ATA, under the quote's own token program. Both venues settle here. */\n userQuoteToken: Address;\n /** The quote mint's token program: classic SPL Token, or Token-2022. */\n quoteTokenProgram: Address;\n /** `[platform_config, quote_mint]` under LaunchLab. */\n platformFeeVault: Address;\n /** `[creator, quote_mint]` under LaunchLab, where `creator` is the coin creator. */\n creatorFeeVault: Address;\n};\n\nfunction launchlabTradeAccounts(\n abi: VenueInstructionAbi,\n input: LaunchlabTradeAccountsInput,\n): AccountMeta[] {\n return order(abi, {\n payer: input.user,\n authority: input.launchlabAuthority,\n global_config: input.globalConfig,\n platform_config: input.platformConfig,\n pool_state: input.poolState,\n user_base_token: input.userBaseToken,\n user_quote_token: input.userQuoteToken,\n base_vault: input.baseVault,\n quote_vault: input.quoteVault,\n base_token_mint: input.mint,\n quote_token_mint: input.quoteMint,\n // The base coin is always classic SPL Token. Only the quote side varies.\n base_token_program: TOKEN_PROGRAM_ADDRESS,\n quote_token_program: input.quoteTokenProgram,\n event_authority: input.launchlabEventAuthority,\n program: input.launchlab,\n // The three LaunchLab reads from the remaining accounts. Without them it fails with error\n // 6018, `NotEnoughRemainingAccounts`.\n system_program: SYSTEM_PROGRAM_ADDRESS,\n platform_fee_vault: input.platformFeeVault,\n creator_fee_vault: input.creatorFeeVault,\n });\n}\n\n/** `buy_exact_out`: 18 accounts. The first argument is the coins wanted, the second the cost cap. */\nexport const launchlabBuyAccounts = (input: LaunchlabTradeAccountsInput): AccountMeta[] =>\n launchlabTradeAccounts(LAUNCHLAB_BUY_EXACT_OUT, input);\n\n/** `sell_exact_in`: the same 18 accounts. `venue/trade.rs` uses one table for both sides. */\nexport const launchlabSellAccounts = (input: LaunchlabTradeAccountsInput): AccountMeta[] =>\n launchlabTradeAccounts(LAUNCHLAB_SELL_EXACT_IN, input);\n\n/**\n * `buy_exact_in`: the same 18 accounts again. Gabox never forwards this instruction; a wallet sends\n * it on its own, to buy the curve out with a fixed spend.\n */\nexport const launchlabBuyExactInAccounts = (input: LaunchlabTradeAccountsInput): AccountMeta[] =>\n launchlabTradeAccounts(LAUNCHLAB_BUY_EXACT_IN, input);\n\n// ─────────────────────────────────────────────────────────────────────────────\n// CPMM\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Everything a CPMM trade list needs. */\nexport type CpmmTradeAccountsInput = {\n /** `[\"vault_and_lp_mint_auth_seed\"]` under CPMM. */\n cpmmAuthority: Address;\n /** The fee tier the pool belongs to. Gabox pins the one LaunchLab migrates into. */\n ammConfig: Address;\n /** The migrated pool. */\n poolState: Address;\n mint: Address;\n quoteMint: Address;\n /** `[\"pool_vault\", pool_state, mint]` under CPMM. */\n baseVault: Address;\n /** `[\"pool_vault\", pool_state, quote_mint]` under CPMM. */\n quoteVault: Address;\n /** `[\"observation\", pool_state]` under CPMM. */\n observationState: Address;\n /** The trader. The one signing slot, and read-only here: CPMM does not take its lamports. */\n user: Address;\n userBaseToken: Address;\n userQuoteToken: Address;\n /** The two token programs the pool records. Read them from the pool account, never derive them. */\n baseTokenProgram: Address;\n quoteTokenProgram: Address;\n};\n\n/** A buy sends the quote and receives the coin. A sell is the other way round. */\nfunction cpmmTradeAccounts(\n abi: VenueInstructionAbi,\n input: CpmmTradeAccountsInput,\n side: 'buy' | 'sell',\n): AccountMeta[] {\n const buying = side === 'buy';\n return order(abi, {\n payer: input.user,\n authority: input.cpmmAuthority,\n amm_config: input.ammConfig,\n pool_state: input.poolState,\n input_token_account: buying ? input.userQuoteToken : input.userBaseToken,\n output_token_account: buying ? input.userBaseToken : input.userQuoteToken,\n input_vault: buying ? input.quoteVault : input.baseVault,\n output_vault: buying ? input.baseVault : input.quoteVault,\n input_token_program: buying ? input.quoteTokenProgram : input.baseTokenProgram,\n output_token_program: buying ? input.baseTokenProgram : input.quoteTokenProgram,\n input_token_mint: buying ? input.quoteMint : input.mint,\n output_token_mint: buying ? input.mint : input.quoteMint,\n observation_state: input.observationState,\n });\n}\n\n/** `swap_base_output`: 13 accounts. Note the argument order is `(max_amount_in, amount_out)`. */\nexport const cpmmBuyAccounts = (input: CpmmTradeAccountsInput): AccountMeta[] =>\n cpmmTradeAccounts(CPMM_SWAP_BASE_OUTPUT, input, 'buy');\n\n/** `swap_base_input`: 13 accounts, with the four pairs swapped. */\nexport const cpmmSellAccounts = (input: CpmmTradeAccountsInput): AccountMeta[] =>\n cpmmTradeAccounts(CPMM_SWAP_BASE_INPUT, input, 'sell');\n","/**\n * Raydium's own price math, ported to bigint.\n *\n * Every function here is a line-by-line port of Raydium's TypeScript, which is itself the same math\n * their on-chain programs run. The point is that a buyer sees the exact number the venue will\n * charge, not an estimate: `buy_pack` passes the pack size as an exact-tokens-out amount, and the\n * program then requires the token delta to equal one pack.\n *\n * Sources, read on 2026-09-18:\n *\n * - `raydium/launchpad/curve/constantProductCurve.ts` and `curve.ts` (LaunchLab)\n * - `raydium/cpmm/curve/calculator.ts`, `constantProduct.ts` and `fee.ts` (CPMM)\n *\n * Raydium uses `BN`, which truncates toward zero on division. Every value here is a non-negative\n * bigint, where `/` truncates the same way, so a plain `/` is the faithful port of their `.div()`.\n * Where they round up they call a ceiling helper, and so does this file. Nothing is approximated\n * and no step is reordered: a division that happens before a subtraction there happens before it\n * here, because the two orders give different answers.\n *\n * Every rate is out of 1,000,000, not out of 10,000.\n */\n\nimport { RATE_DENOMINATOR } from './ids';\n\n/** `ceilDiv(a, b, denominator)` in Raydium's code: `ceil(a * b / denominator)`. */\nexport function ceilDivRate(amount: bigint, rate: bigint, denominator = RATE_DENOMINATOR): bigint {\n if (rate === 0n) return 0n;\n return ceilDiv(amount * rate, denominator);\n}\n\n/** `ceil(numerator / denominator)` for non-negative values. */\nexport function ceilDiv(numerator: bigint, denominator: bigint): bigint {\n if (denominator === 0n) throw new Error('divide by zero');\n return (numerator + denominator - 1n) / denominator;\n}\n\n/**\n * The amount before a fee was taken, given the amount after it: `ceil(post * 1e6 / (1e6 - rate))`.\n *\n * Raydium calls this `calculatePreFee` on the curve and `calculatePreFeeAmount` on CPMM. Both are\n * the same expression.\n */\nexport function preFeeAmount(postFeeAmount: bigint, rate: bigint): bigint {\n if (rate === 0n) return postFeeAmount;\n if (rate >= RATE_DENOMINATOR) throw new Error('a fee rate of 100% or more has no pre-fee amount');\n return ceilDiv(postFeeAmount * RATE_DENOMINATOR, RATE_DENOMINATOR - rate);\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// LaunchLab: the constant product curve\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** The four reserve numbers a curve price depends on. Read them off the pool account. */\nexport type CurveReserves = {\n virtualBase: bigint;\n virtualQuote: bigint;\n realBase: bigint;\n realQuote: bigint;\n /** The most the curve will ever sell. A buy larger than what is left is capped at it. */\n totalBaseSell: bigint;\n};\n\n/** The three fee rates a curve trade pays, each out of 1,000,000. */\nexport type CurveFeeRates = {\n /** `trade_fee_rate` on LaunchLab's global config: Raydium's own share. */\n tradeFeeRate: bigint;\n /** `fee_rate` on the platform config: the Gabox platform's share. */\n platformFeeRate: bigint;\n /** `creator_fee_rate` on the platform config: the coin creator's share. */\n creatorFeeRate: bigint;\n};\n\n/**\n * The whole fee a curve trade pays. Gabox never passes a share-fee receiver, so the fourth rate\n * Raydium supports is always zero and is left out here.\n */\nexport function totalCurveFeeRate(rates: CurveFeeRates): bigint {\n const total = rates.tradeFeeRate + rates.platformFeeRate + rates.creatorFeeRate;\n if (total > RATE_DENOMINATOR) throw new Error('the total curve fee rate exceeds 1,000,000');\n return total;\n}\n\n/** Coins the curve still has to sell. A buy cannot take more than this. */\nexport function remainingBase(pool: CurveReserves): bigint {\n return pool.totalBaseSell > pool.realBase ? pool.totalBaseSell - pool.realBase : 0n;\n}\n\n/** The two sides of the constant product, as the curve sees them right now. */\nconst quoteSide = (pool: CurveReserves): bigint => pool.virtualQuote + pool.realQuote;\nconst baseSide = (pool: CurveReserves): bigint => pool.virtualBase - pool.realBase;\n\n/**\n * Quote needed to buy exactly `tokens` coins on the curve, fees included.\n *\n * This is `Curve.buyExactOut` with no token transfer fee, which is always the case for Gabox: both\n * mints are classic SPL Token and carry no transfer-fee extension.\n *\n * Raydium caps the amount at what the curve has left to sell and still returns a price, so this\n * does the same. A caller that needs the whole `tokens` must check `remainingBase` first;\n * `resolveVenue` does.\n */\nexport function curveBuyExactOut(\n pool: CurveReserves,\n rates: CurveFeeRates,\n tokens: bigint,\n): bigint {\n if (tokens <= 0n) throw new Error('tokens must be positive');\n const remaining = remainingBase(pool);\n const amount = tokens > remaining ? remaining : tokens;\n if (amount === 0n) throw new Error('the curve has no coins left to sell');\n const quoteBeforeFees = curveQuoteInForBaseOut(pool, amount);\n return preFeeAmount(quoteBeforeFees, totalCurveFeeRate(rates));\n}\n\n/**\n * Coins `quote` buys on the curve right now, fees already taken off the spend.\n *\n * This is `Curve.buyExactIn`. It is what a raw `buy_exact_in` pays out, which the devnet end-to-end\n * test uses to push a curve to graduation.\n */\nexport function curveBuyExactIn(pool: CurveReserves, rates: CurveFeeRates, quote: bigint): bigint {\n if (quote <= 0n) throw new Error('quote must be positive');\n const fee = ceilDivRate(quote, totalCurveFeeRate(rates));\n const spend = quote - fee;\n if (spend <= 0n) throw new Error('the whole spend would go to fees');\n const tokens = curveBaseOutForQuoteIn(pool, spend);\n const remaining = remainingBase(pool);\n return tokens > remaining ? remaining : tokens;\n}\n\n/**\n * Quote a sale of exactly `tokens` coins returns, net of fees. This is `Curve.sellExactIn`.\n */\nexport function curveSellExactIn(pool: CurveReserves, rates: CurveFeeRates, tokens: bigint): bigint {\n if (tokens <= 0n) throw new Error('tokens must be positive');\n const gross = curveQuoteOutForBaseIn(pool, tokens);\n const fee = ceilDivRate(gross, totalCurveFeeRate(rates));\n return gross > fee ? gross - fee : 0n;\n}\n\n/** `getAmountIn` on the buy side: `ceil(quoteSide * out / (baseSide - out))`. */\nfunction curveQuoteInForBaseOut(pool: CurveReserves, tokens: bigint): bigint {\n const output = baseSide(pool);\n if (tokens >= output) throw new Error('the curve does not hold that many coins');\n return ceilDiv(quoteSide(pool) * tokens, output - tokens);\n}\n\n/** `getAmountOut` on the buy side: `floor(in * baseSide / (quoteSide + in))`. */\nfunction curveBaseOutForQuoteIn(pool: CurveReserves, quote: bigint): bigint {\n return (quote * baseSide(pool)) / (quoteSide(pool) + quote);\n}\n\n/** `getAmountOut` on the sell side: `floor(in * quoteSide / (baseSide + in))`. */\nfunction curveQuoteOutForBaseIn(pool: CurveReserves, tokens: bigint): bigint {\n return (tokens * quoteSide(pool)) / (baseSide(pool) + tokens);\n}\n\n/** What a launch pins, and what the starting reserves follow from. */\nexport type LaunchParams = {\n /** The whole supply the coin is minted with. */\n supply: bigint;\n /** The part of it the curve sells. */\n totalBaseSell: bigint;\n /** The quote the curve must raise before the coin graduates. */\n quoteRaise: bigint;\n /** Coins locked in a vesting schedule. Always zero for a Gabox launch. */\n totalLockedAmount?: bigint;\n /** The quote LaunchLab keeps at graduation, from its global config. */\n migrateFee?: bigint;\n};\n\n/**\n * The virtual reserves LaunchLab gives a coin that does not exist yet.\n *\n * This is `LaunchConstantProductCurve.getInitParam`. `createMachine` needs it because the seed buy\n * runs in the same transaction that creates the coin: there is no pool account to read yet, and the\n * reserves follow from the pinned launch shape alone.\n *\n * Checked against Raydium's own published numbers for the mainnet Gabox launch shape (supply\n * 1,000,000,000 coins, 793,100,000 sold on the curve, 85 SOL raised, no migrate fee):\n * `virtualBase` 1,073,025,605,596,382 and `virtualQuote` 30,000,852,951.\n */\nexport function initialCurve(params: LaunchParams): CurveReserves {\n const { supply, totalBaseSell, quoteRaise } = params;\n const locked = params.totalLockedAmount ?? 0n;\n const migrateFee = params.migrateFee ?? 0n;\n\n if (supply <= totalBaseSell) throw new Error('the supply must be larger than the curve sells');\n const migrateBase = supply - totalBaseSell - locked;\n if (migrateBase <= 0n) throw new Error('nothing would be left to seed the pool at graduation');\n const raiseLessMigrateFee = quoteRaise - migrateFee;\n if (raiseLessMigrateFee <= 0n) throw new Error('the migrate fee eats the whole raise');\n\n // Raydium divides where it divides. Moving either division changes the answer.\n const numerator = (raiseLessMigrateFee * totalBaseSell * totalBaseSell) / migrateBase;\n const denominator = (raiseLessMigrateFee * totalBaseSell) / migrateBase - quoteRaise;\n if (denominator <= 0n) throw new Error('these launch parameters have no valid starting price');\n\n return {\n virtualBase: numerator / denominator,\n virtualQuote: (quoteRaise * quoteRaise) / denominator,\n realBase: 0n,\n realQuote: 0n,\n totalBaseSell,\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// CPMM: the graduated pool\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** One side of a CPMM swap, after the pool's own unspendable fee balances are taken off. */\nexport type CpmmSwapSides = {\n /** Token going in: the quote on a buy, the coin on a sell. */\n inputReserve: bigint;\n /** Token coming out: the coin on a buy, the quote on a sell. */\n outputReserve: bigint;\n};\n\n/** The two CPMM rates, each out of 1,000,000, plus where the creator fee is charged. */\nexport type CpmmFeeRates = {\n /** `trade_fee_rate` on the `amm_config`. */\n tradeFeeRate: bigint;\n /** `creator_fee_rate` on the `amm_config`, or zero when the pool switched the fee off. */\n creatorFeeRate: bigint;\n /**\n * `true` when this side's creator fee comes off the input token, `false` when it comes off the\n * output. It follows from the pool's `creator_fee_on` and which token is going in.\n */\n creatorFeeOnInput: boolean;\n};\n\n/**\n * Quote a CPMM buy of exactly `tokens` coins costs, both fees included.\n *\n * This is `CurveCalculator.swapBaseOutput`, which is what `swap_base_output` charges.\n */\nexport function cpmmSwapBaseOutput(\n sides: CpmmSwapSides,\n rates: CpmmFeeRates,\n amountOut: bigint,\n): bigint {\n if (amountOut <= 0n) throw new Error('amountOut must be positive');\n const actualOut = rates.creatorFeeOnInput\n ? amountOut\n : preFeeAmount(amountOut, rates.creatorFeeRate);\n if (actualOut >= sides.outputReserve) {\n throw new Error('the pool does not hold that much of the output token');\n }\n const swapped = ceilDiv(sides.inputReserve * actualOut, sides.outputReserve - actualOut);\n const rate = rates.creatorFeeOnInput\n ? rates.tradeFeeRate + rates.creatorFeeRate\n : rates.tradeFeeRate;\n return preFeeAmount(swapped, rate);\n}\n\n/**\n * What a CPMM swap of exactly `amountIn` returns, net of both fees.\n *\n * This is `CurveCalculator.swapBaseInput`, which is what `swap_base_input` pays out.\n */\nexport function cpmmSwapBaseInput(\n sides: CpmmSwapSides,\n rates: CpmmFeeRates,\n amountIn: bigint,\n): bigint {\n if (amountIn <= 0n) throw new Error('amountIn must be positive');\n const tradeFee = ceilDivRate(amountIn, rates.tradeFeeRate);\n const creatorFeeIn = rates.creatorFeeOnInput ? ceilDivRate(amountIn, rates.creatorFeeRate) : 0n;\n const lessFees = amountIn - tradeFee - creatorFeeIn;\n if (lessFees <= 0n) throw new Error('the whole input would go to fees');\n const swapped = (lessFees * sides.outputReserve) / (sides.inputReserve + lessFees);\n if (rates.creatorFeeOnInput) return swapped;\n const creatorFeeOut = ceilDivRate(swapped, rates.creatorFeeRate);\n return swapped > creatorFeeOut ? swapped - creatorFeeOut : 0n;\n}\n","/**\n * Reading the venue: which one a coin trades on right now, what a pack costs there, and the account\n * list for the trade.\n *\n * `resolveVenue` reads every account the answer depends on, decodes them, and hands back a plain\n * object whose methods are pure. A caller that wants to re-price a different token count calls\n * `quoteBuy` again with no further reads.\n *\n * # The quote comes from the pool\n *\n * A machine is priced in one quote asset, fixed when the pool was created. The Gabox pool records\n * three things about it: `quoteMint`, `quoteConfig` (LaunchLab's global config, which is what\n * proves Raydium enabled the quote) and `quoteTokenProgram` (classic SPL Token or Token-2022).\n * Every function here takes that binding, or reads the Gabox pool to get it. Nothing assumes WSOL.\n *\n * # Choosing the venue\n *\n * The LaunchLab pool's `status` is the whole rule:\n *\n * - `0`: the curve is still selling, so trade LaunchLab.\n * - `1`: the raise is finished and Raydium's own bot is moving the coin into a CPMM pool. Nothing\n * trades. This throws, and the message says to retry in a moment. On devnet the move usually\n * finishes within a minute.\n * - `2`: the coin graduated, so trade its CPMM pool.\n *\n * A coin can graduate between the read and the send. A pack buy then fails and no draw is created,\n * which is the intended outcome: refresh and retry.\n *\n * # Finding the migrated CPMM pool\n *\n * The pool is normally at `[\"pool\", cpswap_config, token_0, token_1]` under CPMM, where\n * `cpswap_config` is the fee tier the Gabox platform config names. It is not always: when that\n * address is already taken, Raydium migrates into a random account instead. So this module tries\n * the derived address first and falls back to a filtered `getProgramAccounts` scan.\n *\n * Either way the pool has to prove itself from its own data, which is what `venue/trade.rs` checks\n * on chain as well: CPMM owns it, it carries the `PoolState` discriminator, its `pool_creator` is\n * the coin creator, its two mints are the sorted pair, and `enable_creator_fee` is true. That last\n * flag is the one that cannot be forged. A plain CPMM `initialize` always leaves it false; only a\n * creator Raydium has permissioned, such as LaunchLab's migration, can set it.\n */\n\nimport { type AccountMeta, type Address, type Base58EncodedBytes } from '@solana/kit';\n\nimport { fetchPoolByMint } from '../accounts';\nimport type { GaboxClient } from '../rpc';\nimport {\n CPMM_POOL_OFFSETS,\n CPMM_POOL_STATE_SIZE,\n decodeCpmmAmmConfig,\n decodeCpmmPool,\n decodeLaunchlabGlobalConfig,\n decodeLaunchlabPlatformConfig,\n decodeLaunchlabPool,\n tokenAccountAmount,\n type CpmmAmmConfig,\n type CpmmPoolState,\n type LaunchlabPoolState,\n} from './adapter';\nimport {\n cpmmBuyAccounts,\n cpmmSellAccounts,\n launchlabBuyAccounts,\n launchlabSellAccounts,\n type CpmmTradeAccountsInput,\n type LaunchlabTradeAccountsInput,\n} from './accounts';\nimport {\n cpmmSwapBaseInput,\n cpmmSwapBaseOutput,\n curveBuyExactOut,\n curveSellExactIn,\n initialCurve,\n remainingBase,\n type CpmmFeeRates,\n type CpmmSwapSides,\n type CurveFeeRates,\n type CurveReserves,\n} from './curve';\nimport {\n LAUNCHLAB_STATUS_FUND,\n LAUNCHLAB_STATUS_MIGRATE,\n LAUNCHLAB_STATUS_TRADE,\n LAUNCH_SUPPLY,\n LAUNCH_TOTAL_BASE_SELL,\n TOKEN_PROGRAM_ADDRESS,\n WSOL_MINT,\n raydiumIds,\n sortedMints,\n type RaydiumIds,\n} from './ids';\nimport {\n ata,\n cpmmPoolAddress,\n creatorFeeVaultAddress,\n launchlabPoolAddress,\n launchlabVaultAddress,\n platformFeeVaultAddress,\n} from './pdas';\nimport { decodeBase64, readAccounts } from './read';\n\nexport type VenueKind = 'launchlab' | 'cpmm';\n\n/**\n * The quote asset one pool is bound to, as the pool records it.\n *\n * `config` is LaunchLab's global config for the mint: the account that proves Raydium enabled the\n * quote, and the account both venues check the trade against. `tokenProgram` owns the mint, and the\n * user's quote ATA lives under it.\n */\nexport type QuoteBinding = {\n mint: Address;\n config: Address;\n tokenProgram: Address;\n};\n\n/** Everything `resolveVenue` learned, plus the pure functions that follow from it. */\nexport type ResolvedVenue = {\n kind: VenueKind;\n /** The program to pass as the `venue` account. */\n program: Address;\n mint: Address;\n quoteMint: Address;\n /** The token program the quote mint lives under: classic SPL Token, or Token-2022. */\n quoteTokenProgram: Address;\n /** The trader's quote ATA. Both venues settle here, and the program pins this address. */\n userQuoteToken: Address;\n /** The venue's own pool: the LaunchLab curve pool, or the migrated CPMM pool. */\n poolState: Address;\n /** The LaunchLab pool's `status`: 0 funding, 1 migrating, 2 graduated. */\n status: number;\n /** The coin creator. LaunchLab and CPMM both pay their creator fee to this wallet. */\n creator: Address;\n /** The CPMM fee tier the pool names. Equal to the LaunchLab program on the curve venue. */\n ammConfig: Address | null;\n /** Coins the curve still has to sell. `0n` once the coin has graduated. */\n remainingCurveBase: bigint;\n /** The ordered account list for an exact-coins-out buy, in `remainingAccounts` order. */\n buyAccounts: AccountMeta[];\n /** The ordered account list for a sale. */\n sellAccounts: AccountMeta[];\n /** Quote token an exact-coins-out buy of `tokens` costs right now, the venue's fees included. */\n quoteBuy(tokens: bigint): bigint;\n /** Quote token a sale of `tokens` returns right now, net of the venue's fees. */\n quoteSell(tokens: bigint): bigint;\n};\n\nexport type ResolveVenueOptions = {\n mint: Address;\n /** The wallet that will sign the trade. Its token accounts appear in the account list. */\n user: Address;\n /** Force a venue instead of reading the pool's `status`. A wrong choice fails on chain. */\n venue?: VenueKind;\n /** The pool's quote binding. Read from the Gabox pool when it is left out. */\n quote?: QuoteBinding;\n};\n\nexport { tokenAccountAmount };\n\n/** The quote binding a Gabox pool records. One account read. */\nexport async function fetchQuoteBinding(\n client: GaboxClient,\n mint: Address,\n): Promise<QuoteBinding> {\n const pool = await fetchPoolByMint(client, mint);\n if (!pool) {\n throw new Error(\n `no Gabox pool for mint ${mint}, so its quote asset is unknown. Pass \\`quote\\` to price a ` +\n 'coin that has no pool.',\n );\n }\n return { mint: pool.quoteMint, config: pool.quoteConfig, tokenProgram: pool.quoteTokenProgram };\n}\n\n/**\n * The user's quote associated token account, under the quote's own token program.\n *\n * Both venues settle in this account, never in native SOL. It must exist and hold enough before a\n * pack is bought, and sale proceeds land in it. For a WSOL-quoted pool every builder in `tx/` wraps\n * the SOL it needs into this account and closes it again in the same transaction.\n */\nexport async function quoteAccountFor(\n user: Address,\n quoteMint: Address,\n quoteTokenProgram: Address = TOKEN_PROGRAM_ADDRESS,\n): Promise<Address> {\n return await ata(user, quoteMint, quoteTokenProgram);\n}\n\n/** The user's WSOL associated token account. WSOL is always classic SPL Token. */\nexport async function wsolAccountFor(user: Address): Promise<Address> {\n return await ata(user, WSOL_MINT, TOKEN_PROGRAM_ADDRESS);\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// resolveVenue\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** What LaunchLab's global config and the Gabox platform config say about a curve trade. */\nexport type CurveSettings = {\n rates: CurveFeeRates;\n /** `migrate_fee` on the global config. The starting reserves depend on it. */\n migrateFee: bigint;\n /** `cpswap_config` on the platform config: the CPMM fee tier a Gabox coin graduates into. */\n cpswapConfig: Address;\n};\n\n/**\n * Read the quote's global config and the Gabox platform config, and take the four numbers a quote\n * needs out of them.\n *\n * `quoteConfig` is the LaunchLab global config of the pool's quote asset: `pool.quoteConfig`, or\n * the address `raydium.fetchQuoteConfig` derives for a coin that has no pool yet.\n */\nexport async function fetchCurveSettings(\n client: GaboxClient,\n quoteConfig: Address,\n ids: RaydiumIds = raydiumIds(client.cluster),\n): Promise<CurveSettings> {\n const [globalAccount, platformAccount] = await readAccounts(client.rpc, [\n quoteConfig,\n ids.gaboxPlatform,\n ]);\n if (!globalAccount) {\n throw new Error(`LaunchLab has no global config at ${quoteConfig}`);\n }\n if (!platformAccount) {\n throw new Error(`the Gabox platform config is missing at ${ids.gaboxPlatform}`);\n }\n return settingsFrom(globalAccount.data, platformAccount.data);\n}\n\nfunction settingsFrom(globalData: Uint8Array, platformData: Uint8Array): CurveSettings {\n const global = decodeLaunchlabGlobalConfig(globalData);\n const platform = decodeLaunchlabPlatformConfig(platformData);\n return {\n rates: {\n tradeFeeRate: global.tradeFeeRate,\n platformFeeRate: platform.feeRate,\n creatorFeeRate: platform.creatorFeeRate,\n },\n migrateFee: global.migrateFee,\n cpswapConfig: platform.cpswapConfig,\n };\n}\n\nexport async function resolveVenue(\n client: GaboxClient,\n options: ResolveVenueOptions,\n): Promise<ResolvedVenue> {\n const ids = raydiumIds(client.cluster);\n const { mint, user } = options;\n const quote = options.quote ?? (await fetchQuoteBinding(client, mint));\n\n const curvePool = await launchlabPoolAddress(ids.launchlab, mint, quote.mint);\n const [poolAccount, globalAccount, platformAccount] = await readAccounts(client.rpc, [\n curvePool,\n quote.config,\n ids.gaboxPlatform,\n ]);\n\n if (!poolAccount) {\n throw new Error(\n `no LaunchLab pool at ${curvePool}. The coin was not launched on LaunchLab with ` +\n `${quote.mint} as its quote, so it has no Gabox venue.`,\n );\n }\n if (!globalAccount) {\n throw new Error(`LaunchLab has no global config at ${quote.config}`);\n }\n if (!platformAccount) {\n throw new Error(`the Gabox platform config is missing at ${ids.gaboxPlatform}`);\n }\n\n const pool: LaunchlabPoolState = decodeLaunchlabPool(poolAccount.data);\n if (pool.baseMint !== mint || pool.quoteMint !== quote.mint) {\n throw new Error(`the LaunchLab pool at ${curvePool} is not the pool of ${mint}`);\n }\n const settings = settingsFrom(globalAccount.data, platformAccount.data);\n\n const kind: VenueKind =\n options.venue ?? (pool.status === LAUNCHLAB_STATUS_TRADE ? 'cpmm' : 'launchlab');\n\n if (options.venue === undefined && pool.status === LAUNCHLAB_STATUS_MIGRATE) {\n throw new Error(\n `${mint} is graduating: its LaunchLab curve is sold out and Raydium is moving it into a ` +\n 'CPMM pool. Retry in a moment; the move usually finishes within a minute.',\n );\n }\n\n if (kind === 'launchlab') {\n if (pool.status !== LAUNCHLAB_STATUS_FUND) {\n throw new Error(\n `${mint} no longer trades on its LaunchLab curve (status ${pool.status}). Use the CPMM ` +\n 'venue.',\n );\n }\n return await launchlabVenue(ids, pool, settings.rates, { mint, quote, user, poolState: curvePool });\n }\n\n return await cpmmVenue(client, ids, pool, settings.cpswapConfig, { mint, quote, user });\n}\n\nasync function launchlabVenue(\n ids: RaydiumIds,\n pool: LaunchlabPoolState,\n rates: CurveFeeRates,\n where: { mint: Address; quote: QuoteBinding; user: Address; poolState: Address },\n): Promise<ResolvedVenue> {\n const { mint, quote, user, poolState } = where;\n const userQuoteToken = await quoteAccountFor(user, quote.mint, quote.tokenProgram);\n const shared: LaunchlabTradeAccountsInput = {\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,\n userBaseToken: await ata(user, mint),\n userQuoteToken,\n quoteTokenProgram: quote.tokenProgram,\n platformFeeVault: await platformFeeVaultAddress(ids.launchlab, ids.gaboxPlatform, quote.mint),\n creatorFeeVault: await creatorFeeVaultAddress(ids.launchlab, pool.creator, quote.mint),\n };\n const reserves: CurveReserves = {\n virtualBase: pool.virtualBase,\n virtualQuote: pool.virtualQuote,\n realBase: pool.realBase,\n realQuote: pool.realQuote,\n totalBaseSell: pool.totalBaseSell,\n };\n const remaining = remainingBase(reserves);\n\n return {\n kind: 'launchlab',\n program: ids.launchlab,\n mint,\n quoteMint: quote.mint,\n quoteTokenProgram: quote.tokenProgram,\n userQuoteToken,\n poolState,\n status: pool.status,\n creator: pool.creator,\n ammConfig: null,\n remainingCurveBase: remaining,\n buyAccounts: launchlabBuyAccounts(shared),\n sellAccounts: launchlabSellAccounts(shared),\n quoteBuy: (tokens) => {\n if (tokens > remaining) {\n throw new Error(\n `the curve has ${remaining} base units left and cannot sell ${tokens}. Wait for the ` +\n 'coin to graduate, then buy on its CPMM pool.',\n );\n }\n return curveBuyExactOut(reserves, rates, tokens);\n },\n quoteSell: (tokens) => curveSellExactIn(reserves, rates, tokens),\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// The migrated CPMM pool\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** A CPMM pool that has proved, from its own data, that it is a coin's migrated pool. */\nexport type MigratedCpmmPool = { address: Address; pool: CpmmPoolState };\n\nexport type FindCpmmPoolOptions = {\n mint: Address;\n /** The coin creator, from the Gabox pool or the LaunchLab pool. */\n creator: Address;\n /** The fee tier the Gabox platform config names. Read it with `fetchCurveSettings`. */\n cpswapConfig: Address;\n /** The pool's quote mint. Defaults to WSOL, which is the default quote. */\n quoteMint?: Address;\n};\n\n/**\n * Every check the program makes on a CPMM pool account, in one place.\n *\n * `enable_creator_fee` is the one that identifies the migrated pool. Anyone can call CPMM's own\n * `initialize` and open a pool for the same pair with the same creator, but that pool always has\n * the flag false. Only a creator Raydium has permissioned can set it, and LaunchLab's migration is\n * one of those.\n */\nexport function cpmmPoolMatches(\n pool: CpmmPoolState,\n expect: { creator: Address; token0: Address; token1: Address },\n): boolean {\n return (\n pool.enableCreatorFee &&\n pool.poolCreator === expect.creator &&\n pool.token0Mint === expect.token0 &&\n pool.token1Mint === expect.token1\n );\n}\n\n/**\n * The CPMM pool LaunchLab migrated a coin into.\n *\n * Two steps, because the pool is not always at a derived address. Raydium migrates into\n * `[\"pool\", cpswap_config, token_0, token_1]` when that account is free, and into a random account\n * when it is not. So: try the derived address, and scan for the pool when it does not hold one.\n *\n * The scan filters on the account length and on the three fields at their fixed offsets, so the\n * RPC does the work and returns at most a handful of accounts. Every candidate still has to pass\n * `cpmmPoolMatches`, and more than one match is an error rather than a guess.\n */\nexport async function findCpmmPool(\n client: GaboxClient,\n options: FindCpmmPoolOptions,\n): Promise<MigratedCpmmPool> {\n const ids = raydiumIds(client.cluster);\n const { mint, creator, cpswapConfig } = options;\n const quoteMint = options.quoteMint ?? WSOL_MINT;\n const [token0, token1] = sortedMints(mint, quoteMint);\n const expect = { creator, token0, token1 };\n\n const derived = await cpmmPoolAddress(ids.cpmm, cpswapConfig, mint, quoteMint);\n const [account] = await readAccounts(client.rpc, [derived]);\n if (account && account.owner === ids.cpmm) {\n const pool = decodeCpmmPoolOrNull(account.data);\n if (pool && cpmmPoolMatches(pool, expect)) return { address: derived, pool };\n }\n\n const rows = await client.rpc\n .getProgramAccounts(ids.cpmm, {\n encoding: 'base64',\n commitment: 'confirmed',\n filters: [\n { dataSize: BigInt(CPMM_POOL_STATE_SIZE) },\n memcmp(CPMM_POOL_OFFSETS.poolCreator, creator),\n memcmp(CPMM_POOL_OFFSETS.token0Mint, token0),\n memcmp(CPMM_POOL_OFFSETS.token1Mint, token1),\n ],\n })\n .send();\n\n const matches: MigratedCpmmPool[] = [];\n for (const { pubkey, account: row } of rows) {\n const pool = decodeCpmmPoolOrNull(decodeBase64(row.data[0]));\n if (pool && cpmmPoolMatches(pool, expect)) matches.push({ address: pubkey, pool });\n }\n\n const [only] = matches;\n if (!only) {\n throw new Error(\n `no migrated CPMM pool for ${mint}. The derived address ${derived} holds no matching pool, ` +\n 'and no other CPMM pool has this coin, this creator and a creator fee enabled.',\n );\n }\n if (matches.length > 1) {\n throw new Error(\n `${matches.length} CPMM pools match ${mint}: ${matches.map((m) => m.address).join(', ')}. ` +\n 'Pass the one you mean rather than letting this choose.',\n );\n }\n return only;\n}\n\n/** A `getProgramAccounts` byte filter. The bytes of an address are its own base58 text. */\nfunction memcmp(offset: number, value: Address) {\n return {\n memcmp: {\n offset: BigInt(offset),\n bytes: value as unknown as Base58EncodedBytes,\n encoding: 'base58' as const,\n },\n };\n}\n\n/** Decode a candidate account, or give up quietly. A scan row that is not a pool is not an error. */\nfunction decodeCpmmPoolOrNull(data: Uint8Array): CpmmPoolState | null {\n try {\n return decodeCpmmPool(data);\n } catch {\n return null;\n }\n}\n\nasync function cpmmVenue(\n client: GaboxClient,\n ids: RaydiumIds,\n curve: LaunchlabPoolState,\n cpswapConfig: Address,\n where: { mint: Address; quote: QuoteBinding; user: Address },\n): Promise<ResolvedVenue> {\n const { mint, quote, user } = where;\n const { address: poolState, pool } = await findCpmmPool(client, {\n mint,\n quoteMint: quote.mint,\n creator: curve.creator,\n cpswapConfig,\n });\n\n // Every address below comes out of the pool account, exactly as `venue/trade.rs` reads them.\n // Nothing about a CPMM pool is derived: Raydium migrates into whatever address is free, and the\n // pool names its own fee tier, its own vaults, its own token programs and its own oracle.\n const baseIsToken0 = pool.token0Mint === mint;\n const baseVault = baseIsToken0 ? pool.token0Vault : pool.token1Vault;\n const quoteVault = baseIsToken0 ? pool.token1Vault : pool.token0Vault;\n const baseTokenProgram = baseIsToken0 ? pool.token0Program : pool.token1Program;\n const quoteTokenProgram = baseIsToken0 ? pool.token1Program : pool.token0Program;\n\n // The program refuses a pool whose own token programs disagree with the Gabox pool, so a\n // disagreement here is a pool this SDK must not build a trade for either.\n if (baseTokenProgram !== TOKEN_PROGRAM_ADDRESS || quoteTokenProgram !== quote.tokenProgram) {\n throw new Error(\n `the CPMM pool at ${poolState} records token programs ${baseTokenProgram} and ` +\n `${quoteTokenProgram}, which are not the ones this coin trades under`,\n );\n }\n\n const [configAccount, baseVaultAccount, quoteVaultAccount] = await readAccounts(client.rpc, [\n pool.ammConfig,\n baseVault,\n quoteVault,\n ]);\n if (!configAccount) {\n throw new Error(`the CPMM pool at ${poolState} names a fee tier that is not on chain`);\n }\n if (!baseVaultAccount || !quoteVaultAccount) {\n throw new Error(`the CPMM pool at ${poolState} has no reserve accounts`);\n }\n\n const config: CpmmAmmConfig = decodeCpmmAmmConfig(configAccount.data);\n // A swap may not spend what the pool already owes. Raydium subtracts the same three balances.\n const owedBase = baseIsToken0\n ? pool.protocolFeesToken0 + pool.fundFeesToken0 + pool.creatorFeesToken0\n : pool.protocolFeesToken1 + pool.fundFeesToken1 + pool.creatorFeesToken1;\n const owedQuote = baseIsToken0\n ? pool.protocolFeesToken1 + pool.fundFeesToken1 + pool.creatorFeesToken1\n : pool.protocolFeesToken0 + pool.fundFeesToken0 + pool.creatorFeesToken0;\n const baseReserve = tokenAccountAmount(baseVaultAccount.data) - owedBase;\n const quoteReserve = tokenAccountAmount(quoteVaultAccount.data) - owedQuote;\n if (baseReserve <= 0n || quoteReserve <= 0n) {\n throw new Error(`the CPMM pool at ${poolState} has no tradable reserves`);\n }\n\n const userQuoteToken = await quoteAccountFor(user, quote.mint, quoteTokenProgram);\n const shared: CpmmTradeAccountsInput = {\n cpmmAuthority: ids.cpmmAuthority,\n ammConfig: pool.ammConfig,\n poolState,\n mint,\n quoteMint: quote.mint,\n baseVault,\n quoteVault,\n observationState: pool.observationKey,\n user,\n userBaseToken: await ata(user, mint),\n userQuoteToken,\n baseTokenProgram,\n quoteTokenProgram,\n };\n\n const creatorFeeRate = pool.enableCreatorFee ? config.creatorFeeRate : 0n;\n const buySides: CpmmSwapSides = { inputReserve: quoteReserve, outputReserve: baseReserve };\n const sellSides: CpmmSwapSides = { inputReserve: baseReserve, outputReserve: quoteReserve };\n const buyRates: CpmmFeeRates = {\n tradeFeeRate: config.tradeFeeRate,\n creatorFeeRate,\n creatorFeeOnInput: creatorFeeOnInput(pool, quote.mint),\n };\n const sellRates: CpmmFeeRates = {\n tradeFeeRate: config.tradeFeeRate,\n creatorFeeRate,\n creatorFeeOnInput: creatorFeeOnInput(pool, mint),\n };\n\n return {\n kind: 'cpmm',\n program: ids.cpmm,\n mint,\n quoteMint: quote.mint,\n quoteTokenProgram,\n userQuoteToken,\n poolState,\n status: curve.status,\n creator: pool.poolCreator,\n ammConfig: pool.ammConfig,\n remainingCurveBase: 0n,\n buyAccounts: cpmmBuyAccounts(shared),\n sellAccounts: cpmmSellAccounts(shared),\n quoteBuy: (tokens) => cpmmSwapBaseOutput(buySides, buyRates, tokens),\n quoteSell: (tokens) => cpmmSwapBaseInput(sellSides, sellRates, tokens),\n };\n}\n\n/**\n * Does this side's creator fee come off the token going in?\n *\n * `creator_fee_on` is 0 when the fee follows the input token, 1 when it is always token 0, and 2\n * when it is always token 1. LaunchLab migrates a Gabox coin with `AmmCreatorFeeOn::QuoteToken`, so\n * the pool charges the creator fee in the quote token only: on the input of a buy, on the output of\n * a sale.\n */\nexport function creatorFeeOnInput(pool: CpmmPoolState, inputMint: Address): boolean {\n if (pool.creatorFeeOn === 0) return true;\n const inputIsToken0 = pool.token0Mint === inputMint;\n return pool.creatorFeeOn === 1 ? inputIsToken0 : !inputIsToken0;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Price-only reads\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Quote token an exact-coins-out buy of `tokens` costs right now, on whichever venue the coin\n * trades. Pass `pool.packTokens` for the pack price.\n *\n * Use `resolveVenue` when you also need the account list, which every transaction builder does.\n * This is for a price display.\n */\nexport async function curveQuote(\n client: GaboxClient,\n mint: Address,\n tokens: bigint,\n options: { user?: Address; venue?: VenueKind; quote?: QuoteBinding } = {},\n): Promise<bigint> {\n const venue = await resolveVenue(client, {\n mint,\n // No trade is built, so the account list is never used. Any address gives a valid one.\n user: options.user ?? mint,\n ...(options.venue ? { venue: options.venue } : {}),\n ...(options.quote ? { quote: options.quote } : {}),\n });\n return venue.quoteBuy(tokens);\n}\n\n/** Quote token a sale of `tokens` returns right now, net of the venue's fees. */\nexport async function sellQuote(\n client: GaboxClient,\n mint: Address,\n tokens: bigint,\n options: { user?: Address; venue?: VenueKind; quote?: QuoteBinding } = {},\n): Promise<bigint> {\n const venue = await resolveVenue(client, {\n mint,\n user: options.user ?? mint,\n ...(options.venue ? { venue: options.venue } : {}),\n ...(options.quote ? { quote: options.quote } : {}),\n });\n return venue.quoteSell(tokens);\n}\n\n/**\n * Quote token an exact-coins-out buy of `tokens` would cost on a curve that does not exist yet,\n * fees included.\n *\n * This is what the seed costs. `initialize_pool` buys it in the same transaction that creates the\n * coin, so the curve is a brand-new LaunchLab curve with the pinned Gabox launch shape at that\n * moment. Exact, unless Raydium changes a fee rate between this read and the send.\n */\nexport async function newCurveBuyCost(\n client: GaboxClient,\n tokens: bigint,\n launch: { quoteConfig: Address; raise: bigint },\n): Promise<bigint> {\n if (tokens <= 0n) return 0n;\n const ids = raydiumIds(client.cluster);\n const settings = await fetchCurveSettings(client, launch.quoteConfig, ids);\n return curveBuyExactOut(\n newCurveReserves(launch.raise, settings.migrateFee),\n settings.rates,\n tokens,\n );\n}\n\n/**\n * The starting reserves of a brand-new Gabox curve.\n *\n * `raise` is `total_quote_fund_raising`, in the quote's own base units. It is the one launch number\n * the client picks, so the reserves follow it.\n */\nexport function newCurveReserves(raise: bigint, migrateFee: bigint): CurveReserves {\n return initialCurve({\n supply: LAUNCH_SUPPLY,\n totalBaseSell: LAUNCH_TOTAL_BASE_SELL,\n quoteRaise: raise,\n migrateFee,\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","/**\n * LaunchLab's `initialize_v2`, built by hand.\n *\n * Put it **before** `initialize_pool` in the transaction. `venue/launch.rs` reads the Instructions\n * sysvar and looks for this instruction by discriminator, then checks all 18 of its accounts and\n * every one of its arguments. The order matters for a second reason too: the mint account has to\n * exist and deserialize before Anchor validates the Gabox accounts.\n *\n * # The launch shape is pinned\n *\n * A creator picks the name, the symbol and the metadata URI. Nothing else. Every other argument is\n * fixed, and the program refuses any other value:\n *\n * | Argument | Value |\n * | --- | --- |\n * | `decimals` | 6 (the coin; the quote keeps its own) |\n * | curve | `Constant` |\n * | `supply` | 1,000,000,000 coins |\n * | `total_base_sell` | 793,100,000 coins |\n * | `total_quote_fund_raising` | the caller's `raise`, pinned to 85 SOL on mainnet and 3 SOL on devnet for a WSOL pool |\n * | `migrate_type` | 1, which means graduate into a CPMM pool |\n * | `VestingParams` | all three fields 0 |\n * | `AmmCreatorFeeOn` | `QuoteToken` |\n *\n * The instruction data must end exactly after the last argument. Trailing bytes are refused.\n *\n * # The argument layout\n *\n * Borsh, in IDL order: `MintParams { decimals, name, symbol, uri }`, then the `CurveParams` enum\n * tag and its `ConstantCurve` fields, then `VestingParams`, then the `AmmCreatorFeeOn` enum tag.\n * An Anchor enum tag is one byte.\n */\n\nimport {\n addEncoderSizePrefix,\n getStructEncoder,\n getU8Encoder,\n getU32Encoder,\n getU64Encoder,\n getUtf8Encoder,\n type Address,\n type Instruction,\n type TransactionSigner,\n} from '@solana/kit';\n\nimport {\n LAUNCHLAB_INITIALIZE,\n LAUNCH_SUPPLY,\n LAUNCH_TOTAL_BASE_SELL,\n METAPLEX_PROGRAM_ADDRESS,\n RENT_SYSVAR_ADDRESS,\n SYSTEM_PROGRAM_ADDRESS,\n TOKEN_PROGRAM_ADDRESS,\n} from './abi';\nimport { order } from './accounts';\nimport {\n CONSTANT_CURVE_TAG,\n CREATOR_FEE_ON_QUOTE,\n LAUNCH_DECIMALS,\n METADATA_LIMITS,\n MIGRATE_TO_CPMM,\n type RaydiumIds,\n} from './ids';\nimport { launchlabPoolAddress, launchlabVaultAddress, metadataAddress } from './pdas';\n\nconst borshString = () => addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder());\n\nconst ARGS_ENCODER = getStructEncoder([\n // MintParams\n ['decimals', getU8Encoder()],\n ['name', borshString()],\n ['symbol', borshString()],\n ['uri', borshString()],\n // CurveParams::Constant(ConstantCurve { … })\n ['curveTag', getU8Encoder()],\n ['supply', getU64Encoder()],\n ['totalBaseSell', getU64Encoder()],\n ['totalQuoteFundRaising', getU64Encoder()],\n ['migrateType', getU8Encoder()],\n // VestingParams. Gabox coins have no vesting, so all three are zero.\n ['totalLockedAmount', getU64Encoder()],\n ['cliffPeriod', getU64Encoder()],\n ['unlockPeriod', getU64Encoder()],\n // AmmCreatorFeeOn\n ['ammFeeOn', getU8Encoder()],\n]);\n\nexport type LaunchInput = {\n /** The coin's mint. A fresh keypair, and it signs. */\n mint: TransactionSigner;\n /**\n * The wallet paying. LaunchLab takes it as both `payer` and `creator`, so this wallet receives\n * LaunchLab's creator fee and owns the CPMM creator fee after graduation. It must be the same\n * wallet that signs `initialize_pool`.\n */\n creator: TransactionSigner;\n name: string;\n symbol: string;\n /** The metadata URI. Metaplex stores it on the mint's metadata account. */\n uri: string;\n /** The quote asset the coin is priced in. */\n quoteMint: Address;\n /** LaunchLab's global config for that quote: `[\"global_config\", quote_mint, 0u8, 0u16]`. */\n quoteConfig: Address;\n /** The token program that owns the quote mint: classic SPL Token, or Token-2022. */\n quoteTokenProgram: Address;\n /** `total_quote_fund_raising`, in the quote's own base units. */\n raise: bigint;\n};\n\n/** Metaplex refuses a longer string, so refuse it here rather than on chain. */\nfunction bounded(value: string, limit: number, what: string): string {\n const bytes = new TextEncoder().encode(value).length;\n if (bytes === 0) throw new Error(`${what} must not be empty`);\n if (bytes > limit) {\n throw new Error(`${what} is ${bytes} UTF-8 bytes; Metaplex allows at most ${limit}`);\n }\n return value;\n}\n\n/**\n * Build `initialize_v2` for one cluster's LaunchLab. `ids` is `raydiumIds(client.cluster)`.\n *\n * Two slots sign: the mint keypair, which LaunchLab takes as a signer rather than deriving, and the\n * creator, who pays for everything.\n */\nexport async function getLaunchInstruction(\n input: LaunchInput,\n ids: RaydiumIds,\n): Promise<Instruction> {\n const { mint, creator } = input;\n const name = bounded(input.name, METADATA_LIMITS.name, 'name');\n const symbol = bounded(input.symbol, METADATA_LIMITS.symbol, 'symbol');\n const uri = bounded(input.uri, METADATA_LIMITS.uri, 'uri');\n\n const { quoteMint, quoteTokenProgram } = input;\n const poolState = await launchlabPoolAddress(ids.launchlab, mint.address, quoteMint);\n\n const metas = order(LAUNCHLAB_INITIALIZE, {\n payer: creator.address,\n creator: creator.address,\n global_config: input.quoteConfig,\n platform_config: ids.gaboxPlatform,\n authority: ids.launchlabAuthority,\n pool_state: poolState,\n base_mint: mint.address,\n quote_mint: quoteMint,\n base_vault: await launchlabVaultAddress(ids.launchlab, poolState, mint.address),\n quote_vault: await launchlabVaultAddress(ids.launchlab, poolState, quoteMint),\n metadata_account: await metadataAddress(mint.address),\n // The base coin is always classic SPL Token. Only the quote side varies.\n base_token_program: TOKEN_PROGRAM_ADDRESS,\n quote_token_program: quoteTokenProgram,\n metadata_program: METAPLEX_PROGRAM_ADDRESS,\n system_program: SYSTEM_PROGRAM_ADDRESS,\n rent_program: RENT_SYSVAR_ADDRESS,\n event_authority: ids.launchlabEventAuthority,\n program: ids.launchlab,\n });\n\n // `accounts.ts` set the roles from the ABI. This only attaches each signer to the slot that\n // already says signer, so a signer can never widen a slot's privileges.\n const signerFor = new Map<Address, TransactionSigner>([\n [mint.address, mint],\n [creator.address, creator],\n ]);\n const accounts = metas.map((meta) => {\n // Roles 2 and 3 are READONLY_SIGNER and WRITABLE_SIGNER.\n const signs = meta.role === 2 || meta.role === 3;\n const signer = signerFor.get(meta.address);\n return signs && signer ? { ...meta, signer } : meta;\n });\n\n const data = new Uint8Array([\n ...LAUNCHLAB_INITIALIZE.discriminator,\n ...ARGS_ENCODER.encode({\n decimals: LAUNCH_DECIMALS,\n name,\n symbol,\n uri,\n curveTag: CONSTANT_CURVE_TAG,\n supply: LAUNCH_SUPPLY,\n totalBaseSell: LAUNCH_TOTAL_BASE_SELL,\n totalQuoteFundRaising: input.raise,\n migrateType: MIGRATE_TO_CPMM,\n totalLockedAmount: 0n,\n cliffPeriod: 0n,\n unlockPeriod: 0n,\n ammFeeOn: CREATOR_FEE_ON_QUOTE,\n }),\n ]);\n\n return { programAddress: ids.launchlab, accounts, data } as Instruction;\n}\n","/**\n * Collecting the creator's share of trading.\n *\n * Gabox charges no fee at all. The creator's income is the share Raydium pays out of its own\n * revenue, and it sits in two different places depending on where the coin trades:\n *\n * - **On the curve.** LaunchLab pays 0.5% of every trade into `[creator, quote_mint]` under\n * LaunchLab. One vault per wallet **per quote asset**, not one per coin, so a single\n * `claim_creator_fee` sweeps every coin that creator launched against that quote. A creator\n * with a SOL machine and a USDC machine claims twice, once per quote.\n * - **After graduation.** The CPMM pool keeps the creator's fee inside the pool account, and\n * `collect_creator_fee` pays it out. That is per pool, so it takes one call per coin.\n *\n * Both instructions pay into the creator's associated token account for the quote mint, under that\n * mint's own token program. When the quote is WSOL, every builder here closes that account\n * afterwards, so the creator ends up with plain SOL. For any other quote the account is created if\n * missing and left alone: closing it would throw away a real balance.\n *\n * **Closing unwraps everything.** If the creator already held WSOL in that account before the\n * claim, closing turns that into SOL too. Nothing is lost, but the balance moves.\n */\n\nimport {\n getCloseAccountInstruction,\n getCreateAssociatedTokenIdempotentInstruction,\n} from '@solana-program/token';\nimport {\n AccountRole,\n type AccountMeta,\n type Address,\n type Instruction,\n type TransactionSigner,\n} from '@solana/kit';\n\nimport { CLAIM_COMPUTE_UNITS } from '../compute';\nimport type { GaboxClient } from '../rpc';\nimport { buildMessage, type BuildOptions, type GaboxTransactionMessage } from '../tx/message';\nimport {\n ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n CPMM_COLLECT_CREATOR_FEE,\n LAUNCHLAB_CLAIM_CREATOR_FEE,\n SYSTEM_PROGRAM_ADDRESS,\n TOKEN_PROGRAM_ADDRESS,\n} from './abi';\nimport { order } from './accounts';\nimport { tokenAccountAmount } from './adapter';\nimport { WSOL_MINT, raydiumIds, sortedMints, type RaydiumIds } from './ids';\nimport {\n ata,\n cpmmCreatorFeeShare,\n creatorFeeVaultAddress,\n creatorFeeVaultAuthority,\n launchlabGlobalConfig,\n} from './pdas';\nimport { fetchQuoteDisplay } from './quote';\nimport { readAccounts } from './read';\nimport { fetchCurveSettings, findCpmmPool, fetchQuoteBinding, type QuoteBinding } from './venue';\n\n/**\n * Create the creator's quote account, if it is missing, and close it again when it is WSOL.\n *\n * Raydium's own instructions create the account when they need to, but an idempotent create here\n * costs nothing and makes the flow the same whichever instruction runs. The close is what turns\n * WSOL into SOL, so it only belongs on a WSOL claim: closing a USDC account would throw the payout\n * away.\n */\nasync function wrapAround(\n creator: TransactionSigner,\n quote: { mint: Address; tokenProgram: Address },\n middle: Instruction[],\n): Promise<Instruction[]> {\n const account = await ata(creator.address, quote.mint, quote.tokenProgram);\n const create = getCreateAssociatedTokenIdempotentInstruction({\n payer: creator,\n ata: account,\n owner: creator.address,\n mint: quote.mint,\n tokenProgram: quote.tokenProgram,\n }) as Instruction;\n if (quote.mint !== WSOL_MINT) return [create, ...middle];\n return [\n create,\n ...middle,\n getCloseAccountInstruction({\n account,\n destination: creator.address,\n owner: creator,\n }) as Instruction,\n ];\n}\n\n/** Attach a signer to the one slot the ABI marks as signing. Roles never change here. */\nfunction withSigner(accounts: AccountMeta[], signer: TransactionSigner): AccountMeta[] {\n return accounts.map((meta) =>\n (meta.role === AccountRole.READONLY_SIGNER || meta.role === AccountRole.WRITABLE_SIGNER) &&\n meta.address === signer.address\n ? { ...meta, signer }\n : meta,\n );\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// LaunchLab\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * The instructions of a curve fee claim, for one quote asset: create the quote account, claim, and\n * close it again when the quote is WSOL.\n *\n * This sweeps **every** coin this wallet launched against that quote, because LaunchLab keeps one\n * vault per wallet per quote asset. There is no per-coin version, and a creator with machines in\n * two quote assets claims once per asset.\n */\nexport async function getClaimCreatorFeeInstructions(\n creator: TransactionSigner,\n ids: RaydiumIds,\n quote: { mint: Address; tokenProgram: Address },\n): Promise<Instruction[]> {\n const claim = {\n programAddress: ids.launchlab,\n accounts: withSigner(\n order(LAUNCHLAB_CLAIM_CREATOR_FEE, {\n creator: creator.address,\n fee_vault_authority: await creatorFeeVaultAuthority(ids.launchlab),\n creator_fee_vault: await creatorFeeVaultAddress(ids.launchlab, creator.address, quote.mint),\n recipient_token_account: await ata(creator.address, quote.mint, quote.tokenProgram),\n quote_mint: quote.mint,\n token_program: quote.tokenProgram,\n system_program: SYSTEM_PROGRAM_ADDRESS,\n associated_token_program: ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n }),\n creator,\n ),\n // `claim_creator_fee` takes no arguments.\n data: new Uint8Array(LAUNCHLAB_CLAIM_CREATOR_FEE.discriminator),\n } as Instruction;\n return await wrapAround(creator, quote, [claim]);\n}\n\nexport type ClaimCreatorFeeInput = {\n creator: TransactionSigner;\n /** The quote asset to claim. Defaults to wrapped SOL. One claim per quote asset. */\n quoteMint?: Address;\n} & Partial<BuildOptions>;\n\n/**\n * Claim the curve creator fee for one quote asset.\n *\n * A WSOL claim arrives as SOL, because the builder closes the WSOL account. Any other quote arrives\n * as that token, in the creator's own account.\n */\nexport async function claimCreatorFee(\n client: GaboxClient,\n input: ClaimCreatorFeeInput,\n): Promise<GaboxTransactionMessage> {\n const ids = raydiumIds(client.cluster);\n const quote = await quoteOf(client, input.quoteMint ?? WSOL_MINT);\n const instructions = await getClaimCreatorFeeInstructions(input.creator, ids, quote);\n return await buildMessage(client, input.creator, instructions, {\n addressLookupTables: input.addressLookupTables,\n computeUnitLimit: input.computeUnitLimit ?? CLAIM_COMPUTE_UNITS,\n ...(input.computeUnitPrice === undefined ? {} : { computeUnitPrice: input.computeUnitPrice }),\n });\n}\n\n/**\n * The token program a quote mint lives under. WSOL is always classic SPL Token, so that one needs\n * no read at all.\n */\nasync function quoteOf(\n client: GaboxClient,\n mint: Address,\n): Promise<{ mint: Address; tokenProgram: Address }> {\n if (mint === WSOL_MINT) return { mint, tokenProgram: TOKEN_PROGRAM_ADDRESS };\n return { mint, tokenProgram: (await fetchQuoteDisplay(client, mint)).tokenProgram };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// CPMM\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * The instructions of a graduated coin's fee collection: create the quote account, collect, and\n * close it again when the quote is WSOL.\n *\n * This is per coin. `collect_creator_fee` pays out both sides of the pair, so anything owed in the\n * coin itself lands in the creator's coin account and stays there.\n *\n * The coin's quote asset comes from its Gabox pool, so a caller never has to name it.\n */\nexport async function getCollectCreatorFeeInstructions(\n client: GaboxClient,\n input: { mint: Address; creator: TransactionSigner; quote?: QuoteBinding },\n ids: RaydiumIds = raydiumIds(client.cluster),\n): Promise<Instruction[]> {\n const { mint, creator } = input;\n const quote = input.quote ?? (await fetchQuoteBinding(client, mint));\n const settings = await fetchCurveSettings(client, quote.config, ids);\n const { address: poolState, pool } = await findCpmmPool(client, {\n mint,\n quoteMint: quote.mint,\n creator: creator.address,\n cpswapConfig: settings.cpswapConfig,\n });\n\n const collect = {\n programAddress: ids.cpmm,\n accounts: withSigner(\n order(CPMM_COLLECT_CREATOR_FEE, {\n creator: creator.address,\n authority: ids.cpmmAuthority,\n pool_state: poolState,\n // The fee tier the pool itself names, never a compiled-in address.\n amm_config: pool.ammConfig,\n // The pool names its own vaults; nothing here is derived.\n token_0_vault: pool.token0Vault,\n token_1_vault: pool.token1Vault,\n vault_0_mint: pool.token0Mint,\n vault_1_mint: pool.token1Mint,\n creator_token_0: await ata(creator.address, pool.token0Mint, pool.token0Program),\n creator_token_1: await ata(creator.address, pool.token1Mint, pool.token1Program),\n token_0_program: pool.token0Program,\n token_1_program: pool.token1Program,\n associated_token_program: ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n system_program: SYSTEM_PROGRAM_ADDRESS,\n // Keyed by the fee tier the pool names, so it follows the pool, not a compiled-in config.\n creator_fee_share: await cpmmCreatorFeeShare(ids.cpmm, creator.address, pool.ammConfig),\n }),\n creator,\n ),\n // `collect_creator_fee` takes no arguments.\n data: new Uint8Array(CPMM_COLLECT_CREATOR_FEE.discriminator),\n } as Instruction;\n return await wrapAround(creator, { mint: quote.mint, tokenProgram: quote.tokenProgram }, [\n collect,\n ]);\n}\n\nexport type CollectCreatorFeeInput = {\n mint: Address;\n creator: TransactionSigner;\n /** The coin's quote binding, when it is already at hand. Read from the Gabox pool otherwise. */\n quote?: QuoteBinding;\n} & Partial<BuildOptions>;\n\n/**\n * Collect one graduated coin's CPMM creator fee.\n *\n * A WSOL-quoted coin pays the quote side out as SOL, because the builder closes the WSOL account.\n * Any other quote arrives as that token.\n */\nexport async function collectCreatorFee(\n client: GaboxClient,\n input: CollectCreatorFeeInput,\n): Promise<GaboxTransactionMessage> {\n const instructions = await getCollectCreatorFeeInstructions(client, {\n mint: input.mint,\n creator: input.creator,\n ...(input.quote ? { quote: input.quote } : {}),\n });\n return await buildMessage(client, input.creator, instructions, {\n addressLookupTables: input.addressLookupTables,\n computeUnitLimit: input.computeUnitLimit ?? CLAIM_COMPUTE_UNITS,\n ...(input.computeUnitPrice === undefined ? {} : { computeUnitPrice: input.computeUnitPrice }),\n });\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Reads\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** What a creator can collect right now, for one quote asset. Every amount is in base units. */\nexport type CreatorFees = {\n /** The quote asset these three amounts are measured against. */\n quoteMint: Address;\n /**\n * Quote token waiting in the LaunchLab creator fee vault, across every coin this wallet launched\n * against that quote.\n */\n curveQuote: bigint;\n /**\n * Quote token the migrated CPMM pool of `mint` owes this creator. `0n` when the coin has not\n * graduated, and `0n` when no `mint` was passed.\n */\n cpmmQuote: bigint;\n /** Coins the same pool owes this creator. CPMM can charge the fee on either side. */\n cpmmTokens: bigint;\n};\n\n/**\n * Read both places a creator's fees can sit, for one quote asset.\n *\n * `quoteMint` defaults to wrapped SOL. LaunchLab keeps one vault per wallet per quote, so a creator\n * with machines in two quote assets reads this twice.\n *\n * `mint` is optional. Without it only the curve vault is read, which is the one number that covers\n * every coin of that quote at once. With it the coin's CPMM pool is read too, and a coin that has\n * not graduated reports zeros rather than failing.\n */\nexport async function fetchCreatorFees(\n client: GaboxClient,\n input: { creator: Address; mint?: Address; quoteMint?: Address },\n): Promise<CreatorFees> {\n const ids = raydiumIds(client.cluster);\n const quoteMint = input.quoteMint ?? WSOL_MINT;\n const vault = await creatorFeeVaultAddress(ids.launchlab, input.creator, quoteMint);\n const [vaultAccount] = await readAccounts(client.rpc, [vault]);\n const curveQuote = vaultAccount ? tokenAccountAmount(vaultAccount.data) : 0n;\n\n if (!input.mint) return { quoteMint, curveQuote, cpmmQuote: 0n, cpmmTokens: 0n };\n\n const quoteConfig = await launchlabGlobalConfig(ids.launchlab, quoteMint);\n const settings = await fetchCurveSettings(client, quoteConfig, ids);\n try {\n const { pool } = await findCpmmPool(client, {\n mint: input.mint,\n quoteMint,\n creator: input.creator,\n cpswapConfig: settings.cpswapConfig,\n });\n const [token0] = sortedMints(input.mint, quoteMint);\n const baseIsToken0 = token0 === input.mint;\n return {\n quoteMint,\n curveQuote,\n cpmmQuote: baseIsToken0 ? pool.creatorFeesToken1 : pool.creatorFeesToken0,\n cpmmTokens: baseIsToken0 ? pool.creatorFeesToken0 : pool.creatorFeesToken1,\n };\n } catch {\n // The coin has not graduated, so no CPMM pool owes anything yet.\n return { quoteMint, curveQuote, cpmmQuote: 0n, cpmmTokens: 0n };\n }\n}\n","/**\n * Collecting the platform's share of trading.\n *\n * Gabox charges no fee of its own. The platform's income is the share Raydium pays out of its own\n * revenue, and it sits in two different places depending on where a coin trades:\n *\n * - **On the curve.** LaunchLab pays 0.5% of every trade into `[platform_config, quote_mint]`\n * under LaunchLab. One vault per quote asset for the whole platform, not one per coin, so a\n * single `claim_platform_fee_from_vault` sweeps every coin on that quote. Only the wallet the\n * platform config names as `platform_fee_wallet` can sign it.\n * - **After graduation.** LaunchLab moves the whole pool into a CPMM pool and locks 100% of the\n * LP under Raydium's lock program. The lock mints one fee NFT to the platform NFT wallet. The\n * LP earns the pool's trade fee, and `collect_cp_fees` on the lock program pays the NFT holder\n * that growth. One position per graduated coin, so it takes one call per coin.\n *\n * Both flows pay into the signer's associated token account. When a side is WSOL, the builders\n * close that account afterwards, so the wallet ends up with plain SOL. Any other token is created if\n * missing and left alone, because closing it would throw away a real balance.\n *\n * **Closing unwraps everything.** If the wallet already held WSOL in that account, closing turns it\n * into SOL too. Nothing is lost, but the balance moves.\n */\n\nimport {\n getCloseAccountInstruction,\n getCreateAssociatedTokenIdempotentInstruction,\n} from '@solana-program/token';\nimport {\n AccountRole,\n getU64Encoder,\n type AccountMeta,\n type Address,\n type Instruction,\n type TransactionSigner,\n} from '@solana/kit';\n\nimport { CLAIM_COMPUTE_UNITS, HARVEST_COMPUTE_UNITS } from '../compute';\nimport type { GaboxClient } from '../rpc';\nimport { buildMessage, type BuildOptions, type GaboxTransactionMessage } from '../tx/message';\nimport {\n ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n LAUNCHLAB_CLAIM_PLATFORM_FEE_FROM_VAULT,\n SYSTEM_PROGRAM_ADDRESS,\n TOKEN_2022_PROGRAM_ADDRESS,\n TOKEN_PROGRAM_ADDRESS,\n type VenueInstructionAbi,\n} from './abi';\nimport { order } from './accounts';\nimport {\n decodeCpmmPool,\n decodeLockedCpLiquidity,\n tokenAccountAmount,\n type CpmmPoolState,\n type LockedCpLiquidity,\n} from './adapter';\nimport { MEMO_PROGRAM_ADDRESS, WSOL_MINT, raydiumIds, type RaydiumIds } from './ids';\nimport {\n ata,\n lockedLiquidityAddress,\n platformFeeVaultAddress,\n platformFeeVaultAuthority,\n} from './pdas';\nimport { fetchQuoteDisplay } from './quote';\nimport { readAccounts } from './read';\n\nconst u64 = getU64Encoder();\n\n/**\n * Create the signer's token account for one mint, if it is missing, and close it again when the\n * mint is WSOL. The close is what turns WSOL into SOL, so it only belongs on a WSOL side.\n */\nasync function wrapAround(\n signer: TransactionSigner,\n sides: { mint: Address; tokenProgram: Address }[],\n middle: Instruction[],\n): Promise<Instruction[]> {\n const before: Instruction[] = [];\n const after: Instruction[] = [];\n for (const side of sides) {\n const account = await ata(signer.address, side.mint, side.tokenProgram);\n before.push(\n getCreateAssociatedTokenIdempotentInstruction({\n payer: signer,\n ata: account,\n owner: signer.address,\n mint: side.mint,\n tokenProgram: side.tokenProgram,\n }) as Instruction,\n );\n if (side.mint === WSOL_MINT) {\n after.push(\n getCloseAccountInstruction({\n account,\n destination: signer.address,\n owner: signer,\n }) as Instruction,\n );\n }\n }\n return [...before, ...middle, ...after];\n}\n\n/** Attach a signer to the one slot the ABI marks as signing. Roles never change here. */\nfunction withSigner(accounts: AccountMeta[], signer: TransactionSigner): AccountMeta[] {\n return accounts.map((meta) =>\n (meta.role === AccountRole.READONLY_SIGNER || meta.role === AccountRole.WRITABLE_SIGNER) &&\n meta.address === signer.address\n ? { ...meta, signer }\n : meta,\n );\n}\n\n/**\n * The token program a quote mint lives under. WSOL is always classic SPL Token, so that one needs\n * no read at all.\n */\nasync function quoteOf(\n client: GaboxClient,\n mint: Address,\n): Promise<{ mint: Address; tokenProgram: Address }> {\n if (mint === WSOL_MINT) return { mint, tokenProgram: TOKEN_PROGRAM_ADDRESS };\n return { mint, tokenProgram: (await fetchQuoteDisplay(client, mint)).tokenProgram };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// LaunchLab\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * The instructions of a platform fee claim, for one quote asset: create the quote account, claim,\n * and close it again when the quote is WSOL.\n *\n * This sweeps **every** coin launched against that quote, because LaunchLab keeps one platform\n * vault per quote asset. `feeWallet` must be the wallet the platform config names, or LaunchLab\n * refuses the claim.\n */\nexport async function getClaimPlatformFeeInstructions(\n feeWallet: TransactionSigner,\n ids: RaydiumIds,\n quote: { mint: Address; tokenProgram: Address },\n): Promise<Instruction[]> {\n const claim = {\n programAddress: ids.launchlab,\n accounts: withSigner(\n order(LAUNCHLAB_CLAIM_PLATFORM_FEE_FROM_VAULT, {\n platform_fee_wallet: feeWallet.address,\n fee_vault_authority: await platformFeeVaultAuthority(ids.launchlab),\n platform_config: ids.gaboxPlatform,\n platform_fee_vault: await platformFeeVaultAddress(\n ids.launchlab,\n ids.gaboxPlatform,\n quote.mint,\n ),\n recipient_token_account: await ata(feeWallet.address, quote.mint, quote.tokenProgram),\n quote_mint: quote.mint,\n token_program: quote.tokenProgram,\n system_program: SYSTEM_PROGRAM_ADDRESS,\n associated_token_program: ASSOCIATED_TOKEN_PROGRAM_ADDRESS,\n }),\n feeWallet,\n ),\n // `claim_platform_fee_from_vault` takes no arguments.\n data: new Uint8Array(LAUNCHLAB_CLAIM_PLATFORM_FEE_FROM_VAULT.discriminator),\n } as Instruction;\n return await wrapAround(feeWallet, [quote], [claim]);\n}\n\nexport type ClaimPlatformFeeInput = {\n /** The platform fee wallet. It signs, and it receives the payout. */\n feeWallet: TransactionSigner;\n /** The quote asset to claim. Defaults to wrapped SOL. One claim per quote asset. */\n quoteMint?: Address;\n} & Partial<BuildOptions>;\n\n/**\n * Claim the curve platform fee for one quote asset.\n *\n * A WSOL claim arrives as SOL, because the builder closes the WSOL account. Any other quote arrives\n * as that token, in the fee wallet's own account.\n */\nexport async function claimPlatformFee(\n client: GaboxClient,\n input: ClaimPlatformFeeInput,\n): Promise<GaboxTransactionMessage> {\n const ids = raydiumIds(client.cluster);\n const quote = await quoteOf(client, input.quoteMint ?? WSOL_MINT);\n const instructions = await getClaimPlatformFeeInstructions(input.feeWallet, ids, quote);\n return await buildMessage(client, input.feeWallet, instructions, {\n addressLookupTables: input.addressLookupTables,\n computeUnitLimit: input.computeUnitLimit ?? CLAIM_COMPUTE_UNITS,\n ...(input.computeUnitPrice === undefined ? {} : { computeUnitPrice: input.computeUnitPrice }),\n });\n}\n\n/**\n * What the platform can claim from the curve right now, for one quote asset, in base units.\n *\n * `quoteMint` defaults to wrapped SOL. One vault per quote asset, so a platform with coins on two\n * quotes reads this twice. A vault that does not exist yet reads as zero.\n */\nexport async function fetchPlatformFees(\n client: GaboxClient,\n input: { quoteMint?: Address } = {},\n): Promise<{ quoteMint: Address; curveQuote: bigint }> {\n const ids = raydiumIds(client.cluster);\n const quoteMint = input.quoteMint ?? WSOL_MINT;\n const vault = await platformFeeVaultAddress(ids.launchlab, ids.gaboxPlatform, quoteMint);\n const [account] = await readAccounts(client.rpc, [vault]);\n return { quoteMint, curveQuote: account ? tokenAccountAmount(account.data) : 0n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Locked liquidity\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * `collect_cp_fees` on the lock program. There is no public IDL for it. The account list and the\n * discriminator come from Raydium's own SDK and from the `pinocchio-raydium-locking-program`\n * client crate, and the devnet harvest in `test/devnet.e2e.test.ts` runs it.\n */\nexport const LOCK_COLLECT_CP_FEES: VenueInstructionAbi = {\n name: 'collect_cp_fees',\n discriminator: new Uint8Array([8, 30, 51, 199, 209, 184, 247, 133]),\n accounts: [\n { name: 'authority', writable: false, signer: false },\n { name: 'fee_nft_owner', writable: false, signer: true },\n { name: 'fee_nft_account', writable: false, signer: false },\n { name: 'locked_liquidity', writable: true, signer: false },\n { name: 'cpmm_program', writable: false, signer: false },\n { name: 'cp_authority', writable: false, signer: false },\n { name: 'pool_state', writable: true, signer: false },\n { name: 'lp_mint', writable: true, signer: false },\n { name: 'recipient_token_0_account', writable: true, signer: false },\n { name: 'recipient_token_1_account', writable: true, signer: false },\n { name: 'token_0_vault', writable: true, signer: false },\n { name: 'token_1_vault', writable: true, signer: false },\n { name: 'vault_0_mint', writable: false, signer: false },\n { name: 'vault_1_mint', writable: false, signer: false },\n { name: 'locked_lp_vault', writable: true, signer: false },\n { name: 'token_program', writable: false, signer: false },\n { name: 'token_program_2022', writable: false, signer: false },\n { name: 'memo_program', writable: false, signer: false },\n ],\n};\n\n/** One locked CPMM position a wallet holds the fee NFT of, with what it can harvest right now. */\nexport type LockedPosition = {\n /** The fee NFT. Holding it is the right to harvest. */\n feeNftMint: Address;\n /** The lock program's record for this position. */\n record: Address;\n lock: LockedCpLiquidity;\n /** The CPMM pool the LP belongs to. */\n poolAddress: Address;\n pool: CpmmPoolState;\n /** The pool's balances that belong to LPs: each vault less the fees the pool still owes. */\n vault0: bigint;\n vault1: bigint;\n /** LP tokens the position may withdraw now. Zero until the pool trades. */\n claimableLp: bigint;\n /** What those LP tokens are worth in the pool's two tokens, rounded down. */\n claimableToken0: bigint;\n claimableToken1: bigint;\n};\n\n/** Integer square root, rounded down. */\nfunction isqrt(value: bigint): bigint {\n if (value < 0n) throw new Error('isqrt of a negative number');\n if (value < 2n) return value;\n let x = BigInt(Math.floor(Math.sqrt(Number(value))));\n // Newton's method from the floating-point guess, then settle on the exact floor.\n for (;;) {\n const y = (x + value / x) >> 1n;\n if (y >= x) break;\n x = y;\n }\n while (x * x > value) x -= 1n;\n while ((x + 1n) * (x + 1n) <= value) x += 1n;\n return x;\n}\n\n/**\n * The LP tokens a locked position may withdraw as fees.\n *\n * Every swap leaves its fee in the vaults, so one LP token buys a little more of the pool after\n * each trade than before it. The record keeps the pool's `x * y` and LP supply from its last\n * checkpoint. The LP tokens that still hold exactly the checkpoint's liquidity are\n * `locked * sqrt(last_k) / last_lp * supply / sqrt(k)`; everything above that is fee growth.\n *\n * The division rounds the kept part up, so the answer never claims a unit the pool does not owe.\n */\nexport function lockedFeeLp(\n lock: Pick<LockedCpLiquidity, 'lockedLpAmount' | 'lastLp' | 'lastK'>,\n pool: { vault0: bigint; vault1: bigint; lpSupply: bigint },\n): bigint {\n if (lock.lockedLpAmount === 0n || lock.lastLp === 0n || pool.lpSupply === 0n) return 0n;\n const rootNow = isqrt(pool.vault0 * pool.vault1);\n if (rootNow === 0n) return 0n;\n const numerator = lock.lockedLpAmount * isqrt(lock.lastK) * pool.lpSupply;\n const denominator = lock.lastLp * rootNow;\n const keep = (numerator + denominator - 1n) / denominator;\n return keep >= lock.lockedLpAmount ? 0n : lock.lockedLpAmount - keep;\n}\n\n/**\n * Every locked CPMM position `owner` holds a fee NFT for, with what each one can harvest.\n *\n * Three reads: the wallet's token accounts, then the lock record behind every NFT-shaped one, then\n * the pool and the two vaults of every record found. A token account of one unit and zero decimals\n * is not always a lock NFT, so the record decides: no record, not a position.\n */\nexport async function fetchLockedPositions(\n client: GaboxClient,\n owner: Address,\n ids: RaydiumIds = raydiumIds(client.cluster),\n): Promise<LockedPosition[]> {\n const { value: accounts } = await client.rpc\n .getTokenAccountsByOwner(\n owner,\n { programId: TOKEN_PROGRAM_ADDRESS },\n { encoding: 'jsonParsed', commitment: 'confirmed' },\n )\n .send();\n const nftMints: Address[] = [];\n for (const { account } of accounts) {\n const info = account.data.parsed.info;\n if (info.tokenAmount.decimals === 0 && info.tokenAmount.amount === '1') {\n nftMints.push(info.mint);\n }\n }\n if (nftMints.length === 0) return [];\n\n const records = await Promise.all(\n nftMints.map((mint) => lockedLiquidityAddress(ids.lock, mint)),\n );\n const found: { feeNftMint: Address; record: Address; lock: LockedCpLiquidity }[] = [];\n for (const [index, account] of (await readAccounts(client.rpc, records)).entries()) {\n if (!account || account.owner !== ids.lock) continue;\n const lock = decodeLockedCpLiquidity(account.data);\n if (lock.feeNftMint !== nftMints[index]) continue;\n found.push({ feeNftMint: nftMints[index] as Address, record: records[index] as Address, lock });\n }\n if (found.length === 0) return [];\n\n const pools = await readAccounts(\n client.rpc,\n found.map((entry) => entry.lock.poolId),\n );\n const decoded = pools.map((account) =>\n account && account.owner === ids.cpmm ? decodeCpmmPool(account.data) : null,\n );\n const vaults = await readAccounts(\n client.rpc,\n decoded.flatMap((pool) => (pool ? [pool.token0Vault, pool.token1Vault] : [])),\n );\n\n const positions: LockedPosition[] = [];\n let cursor = 0;\n for (const [index, entry] of found.entries()) {\n const pool = decoded[index];\n if (!pool) continue;\n const raw0 = vaults[cursor];\n const raw1 = vaults[cursor + 1];\n cursor += 2;\n if (!raw0 || !raw1 || pool.lpMint !== entry.lock.lockedLpMint) continue;\n const vault0 =\n tokenAccountAmount(raw0.data) -\n pool.protocolFeesToken0 -\n pool.fundFeesToken0 -\n pool.creatorFeesToken0;\n const vault1 =\n tokenAccountAmount(raw1.data) -\n pool.protocolFeesToken1 -\n pool.fundFeesToken1 -\n pool.creatorFeesToken1;\n const claimableLp = lockedFeeLp(entry.lock, { vault0, vault1, lpSupply: pool.lpSupply });\n positions.push({\n ...entry,\n poolAddress: entry.lock.poolId,\n pool,\n vault0,\n vault1,\n claimableLp,\n claimableToken0: pool.lpSupply === 0n ? 0n : (claimableLp * vault0) / pool.lpSupply,\n claimableToken1: pool.lpSupply === 0n ? 0n : (claimableLp * vault1) / pool.lpSupply,\n });\n }\n return positions;\n}\n\n/**\n * The instructions of one harvest: create the two token accounts, collect, and close the WSOL one\n * when a side is WSOL.\n *\n * `feeLp` defaults to everything the position can withdraw now. The lock program refuses more than\n * that, so a caller that passes its own number keeps it at or below `position.claimableLp`.\n */\nexport async function getHarvestLockedFeesInstructions(\n owner: TransactionSigner,\n ids: RaydiumIds,\n position: LockedPosition,\n feeLp: bigint = position.claimableLp,\n): Promise<Instruction[]> {\n if (feeLp <= 0n) throw new Error('nothing to harvest: the position has earned no fee LP yet');\n const { pool } = position;\n const collect = {\n programAddress: ids.lock,\n accounts: withSigner(\n order(LOCK_COLLECT_CP_FEES, {\n authority: ids.lockAuthority,\n fee_nft_owner: owner.address,\n fee_nft_account: await ata(owner.address, position.feeNftMint, TOKEN_PROGRAM_ADDRESS),\n locked_liquidity: position.record,\n cpmm_program: ids.cpmm,\n cp_authority: ids.cpmmAuthority,\n pool_state: position.poolAddress,\n lp_mint: pool.lpMint,\n recipient_token_0_account: await ata(owner.address, pool.token0Mint, pool.token0Program),\n recipient_token_1_account: await ata(owner.address, pool.token1Mint, pool.token1Program),\n token_0_vault: pool.token0Vault,\n token_1_vault: pool.token1Vault,\n vault_0_mint: pool.token0Mint,\n vault_1_mint: pool.token1Mint,\n // The lock authority's associated account for the LP mint, always under classic SPL Token.\n locked_lp_vault: await ata(ids.lockAuthority, pool.lpMint, TOKEN_PROGRAM_ADDRESS),\n token_program: TOKEN_PROGRAM_ADDRESS,\n token_program_2022: TOKEN_2022_PROGRAM_ADDRESS,\n memo_program: MEMO_PROGRAM_ADDRESS,\n }),\n owner,\n ),\n data: new Uint8Array([...LOCK_COLLECT_CP_FEES.discriminator, ...u64.encode(feeLp)]),\n } as Instruction;\n return await wrapAround(\n owner,\n [\n { mint: pool.token0Mint, tokenProgram: pool.token0Program },\n { mint: pool.token1Mint, tokenProgram: pool.token1Program },\n ],\n [collect],\n );\n}\n\nexport type HarvestLockedFeesInput = {\n /** The wallet holding the fee NFT. It signs, and it receives both tokens. */\n owner: TransactionSigner;\n /** The position, as `fetchLockedPositions` returned it. */\n position: LockedPosition;\n /** LP tokens to withdraw. Defaults to everything harvestable now. */\n feeLp?: bigint;\n} & Partial<BuildOptions>;\n\n/**\n * Harvest one locked position's fees.\n *\n * A pool with WSOL on one side pays that side out as SOL, because the builder closes the WSOL\n * account. The other side arrives as that token, in the owner's own account.\n */\nexport async function harvestLockedFees(\n client: GaboxClient,\n input: HarvestLockedFeesInput,\n): Promise<GaboxTransactionMessage> {\n const ids = raydiumIds(client.cluster);\n const instructions = await getHarvestLockedFeesInstructions(\n input.owner,\n ids,\n input.position,\n input.feeLp,\n );\n return await buildMessage(client, input.owner, instructions, {\n addressLookupTables: input.addressLookupTables,\n computeUnitLimit: input.computeUnitLimit ?? HARVEST_COMPUTE_UNITS,\n ...(input.computeUnitPrice === undefined ? {} : { computeUnitPrice: input.computeUnitPrice }),\n });\n}\n","/**\n * A venue trade a wallet sends on its own, outside any Gabox instruction.\n *\n * Pack buys and token sales go through `buy_pack` and `sell_tokens`: they take the venue's account\n * list as `remainingAccounts` and the Gabox program does the call. This file is for the one trade\n * Gabox never makes, a plain `buy_exact_in` on the curve. Anyone may trade a Gabox coin directly,\n * and the devnet end-to-end test uses this to buy the rest of the curve and force graduation.\n *\n * The account list and the discriminator both come from `abi.ts`, which codegen took from\n * Raydium's IDL. Nothing here retypes either.\n */\n\nimport {\n getU64Encoder,\n type AccountMeta,\n type Address,\n type Instruction,\n type TransactionSigner,\n} from '@solana/kit';\n\nimport { LAUNCHLAB_BUY_EXACT_IN, TOKEN_PROGRAM_ADDRESS } from './abi';\nimport { launchlabBuyExactInAccounts } from './accounts';\nimport { SHARE_FEE_RATE, WSOL_MINT, raydiumIds, type RaydiumIds } from './ids';\nimport {\n ata,\n creatorFeeVaultAddress,\n launchlabGlobalConfig,\n launchlabPoolAddress,\n launchlabVaultAddress,\n platformFeeVaultAddress,\n} from './pdas';\nimport type { GaboxClient } from '../rpc';\n\nconst u64 = getU64Encoder();\n\nexport type CurveBuyExactInInput = {\n mint: Address;\n /** The coin creator, so the creator fee vault can be derived. Read it off the pool. */\n creator: Address;\n /** The wallet spending. It signs, and its quote ATA must already hold `quoteIn`. */\n user: TransactionSigner;\n /** Quote token to spend, fees included. */\n quoteIn: bigint;\n /** The floor on the coins received. Use `curveBuyExactIn` from `curve.ts` to compute it. */\n minTokensOut: bigint;\n /** The pool's quote mint. Defaults to wrapped SOL. */\n quoteMint?: Address;\n /** The quote mint's token program. Defaults to classic SPL Token, which is what WSOL uses. */\n quoteTokenProgram?: Address;\n};\n\n/**\n * `buy_exact_in` on the curve: spend exactly `quoteIn` of the quote token and take whatever coins\n * it buys.\n *\n * LaunchLab caps the trade at what the curve has left to sell, so a spend larger than the rest of\n * the raise still succeeds and graduates the coin. Fund the user's quote ATA first. On a WSOL pool\n * that means wrapping the SOL and closing the account afterwards, the same way the Gabox builders\n * do.\n */\nexport async function getCurveBuyExactInInstruction(\n client: GaboxClient,\n input: CurveBuyExactInInput,\n ids: RaydiumIds = raydiumIds(client.cluster),\n): Promise<Instruction> {\n if (input.quoteIn <= 0n) throw new Error('quoteIn must be positive');\n if (input.minTokensOut < 0n) throw new Error('minTokensOut must not be negative');\n\n const quoteMint = input.quoteMint ?? WSOL_MINT;\n const quoteTokenProgram = input.quoteTokenProgram ?? TOKEN_PROGRAM_ADDRESS;\n const poolState = await launchlabPoolAddress(ids.launchlab, input.mint, quoteMint);\n const accounts = launchlabBuyExactInAccounts({\n launchlab: ids.launchlab,\n launchlabAuthority: ids.launchlabAuthority,\n launchlabEventAuthority: ids.launchlabEventAuthority,\n globalConfig: await launchlabGlobalConfig(ids.launchlab, quoteMint),\n platformConfig: ids.gaboxPlatform,\n poolState,\n mint: input.mint,\n quoteMint,\n baseVault: await launchlabVaultAddress(ids.launchlab, poolState, input.mint),\n quoteVault: await launchlabVaultAddress(ids.launchlab, poolState, quoteMint),\n user: input.user.address,\n userBaseToken: await ata(input.user.address, input.mint),\n userQuoteToken: await ata(input.user.address, quoteMint, quoteTokenProgram),\n quoteTokenProgram,\n platformFeeVault: await platformFeeVaultAddress(ids.launchlab, ids.gaboxPlatform, quoteMint),\n creatorFeeVault: await creatorFeeVaultAddress(ids.launchlab, input.creator, quoteMint),\n });\n\n return {\n programAddress: ids.launchlab,\n accounts: attachSigner(accounts, input.user),\n data: new Uint8Array([\n ...LAUNCHLAB_BUY_EXACT_IN.discriminator,\n ...u64.encode(input.quoteIn),\n ...u64.encode(input.minTokensOut),\n // Gabox never passes a share-fee receiver, so this rate is always zero.\n ...u64.encode(SHARE_FEE_RATE),\n ]),\n } as Instruction;\n}\n\n/** Give the signer to the slot the ABI already marks as signing. Roles never change here. */\nfunction attachSigner(accounts: readonly AccountMeta[], signer: TransactionSigner): AccountMeta[] {\n let matched = false;\n const withSigner = accounts.map((meta) => {\n // Roles 2 and 3 are READONLY_SIGNER and WRITABLE_SIGNER.\n const signs = meta.role === 2 || meta.role === 3;\n if (!signs || meta.address !== signer.address) return meta;\n matched = true;\n return { ...meta, signer };\n });\n if (!matched) {\n throw new Error(\n `${signer.address} is not the signing account of this trade. Build the account list with ` +\n 'the same wallet you are going to sign with.',\n );\n }\n return withSigner as AccountMeta[];\n}\n","/**\n * Everything about the two venues.\n *\n * `abi.ts` is generated: it carries the Raydium addresses of both clusters and the account table of\n * every Raydium instruction this SDK builds. `ids.ts` names those tables per cluster and holds the\n * pinned launch shape. `pdas.ts` derives every Raydium address. `adapter.ts` decodes Raydium's\n * accounts and `read.ts` fetches them. `curve.ts` is the price math, ported from Raydium's own\n * code. `quote.ts` answers which quote assets exist and what they are. `accounts.ts` builds the\n * ordered trade account lists. `venue.ts` reads the chain and decides which venue a coin trades on.\n * `launch.ts` builds LaunchLab's `initialize_v2`. `claim.ts` collects the creator's fees and\n * `platform.ts` the platform's. `trade.ts` builds the one venue trade Gabox never makes itself.\n */\n\nexport * from './abi';\nexport * from './accounts';\nexport * from './adapter';\nexport * from './claim';\nexport * from './curve';\nexport * from './ids';\nexport * from './launch';\nexport * from './pdas';\nexport * from './platform';\nexport * from './quote';\nexport * from './read';\nexport * from './trade';\nexport * from './venue';\n"],"mappings":";;;;;AAgEA,MAAa,sBAAyC;CACpD,WAAW;CACX,oBAAoB;CACpB,yBAAyB;CACzB,eAAe;CACf,MAAM;CACN,eAAe;CACf,kBAAkB;AACpB;AAEA,MAAa,qBAAwC;CACnD,WAAW;CACX,oBAAoB;CACpB,yBAAyB;CACzB,eAAe;CACf,MAAM;CACN,eAAe;CACf,kBAAkB;AACpB;;;;;AAMA,MAAa,YAAY;;AAEzB,MAAa,2BAA2B;;;;;AAKxC,MAAa,iBAAiB;;AAG9B,MAAa,gBAAgB;;AAE7B,MAAa,yBAAyB;;AAGtC,MAAa,wBAAwB;;;;;AAKrC,MAAa,6BAA6B;AAC1C,MAAa,mCAAmC;AAChD,MAAa,yBAAyB;;AAEtC,MAAa,sBAAsB;;;;;;;;;AAUnC,MAAa,qCAAqC,IAAI,WAAW;CAAC;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;AAAE,CAAC;AACxG,MAAa,wCAAwC,IAAI,WAAW;CAAC;CAAK;CAAG;CAAK;CAAK;CAAK;CAAK;CAAK;AAAG,CAAC;AAC1G,MAAa,0CAA0C,IAAI,WAAW;CAAC;CAAK;CAAI;CAAK;CAAG;CAAK;CAAI;CAAK;AAAG,CAAC;AAC1G,MAAa,gCAAgC,IAAI,WAAW;CAAC;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;AAAE,CAAC;AACnG,MAAa,gCAAgC,IAAI,WAAW;CAAC;CAAK;CAAK;CAAI;CAAK;CAAK;CAAK;CAAI;AAAG,CAAC;;;;AAIlG,MAAa,uBAA4C;CACvD,MAAM;CACN,eAAe,IAAI,WAAW;EAAC;EAAI;EAAK;EAAK;EAAI;EAAK;EAAI;EAAI;CAAE,CAAC;CACjE,UAAU;EAC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