mirror of
https://github.com/chainstacklabs/pumpfun-bonkfun-bot.git
synced 2026-11-02 06:16:10 +00:00
* refactor(tests): move the regression verifiers into tests/regression verify_*.py are not standalone examples: each imports src/, stubs the RPC client, and asserts one previously fixed bug stays fixed. Their checks are unchanged; PROJECT_ROOT, the usage lines and the bonk fixture lookup are adjusted for the new depth. run_all.py runs the set and reports failures. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * chore(tools): move the dev harness and listener benchmarks into tools/ simulate_*, live_*, both compare_* scripts and the account cleanup import src/ and several spend real funds — they exercise the bot rather than teach anything. compare_listeners.py reaches the repo root one level higher than before; nothing else changes. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * refactor(cookbook): reorganise learning-examples into cookbook/ The directory is a reference collection — one runnable script per action — but nothing said so: no index, scripts grouped by the transport they happened to use, fixtures loose at the root. Now grouped by platform, then by what you are doing: pumpfun/{listen,read,trade,graduation,decode}, pumpswap, letsbonk, legacy. Fixtures sit beside the script that reads them, manual_sell.py becomes sell_token.py, and the legacy create example moves to legacy/ and says why. pump_v2.py and tx_status.py stay at the cookbook root as the only two shared helpers; subdirectories add that root to sys.path before importing them. cookbook/README.md indexes every script and marks the ones that spend funds. Also fixes create_v2's account list: the five mayhem accounts are mandatory whatever is_mayhem_mode says, so mint_and_buy_v2.py could never have worked with mayhem off. 11 accounts fails AnchorError 3005 (AccountNotEnoughKeys) on sol_vault, 16 succeeds with the argument either way — simulateTransaction against mainnet. Seven scripts gain a module docstring they were missing. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * feat(cookbook): add buy, create, balance and status examples buy_token.py <MINT> buy_v2 against one coin; --dry-run simulates create_token.py create_v2 on its own get_balances.py SOL and tokens across both token programs check_tx_status.py <SIG> success, reverted, or not visible yet Buying previously meant manual_buy.py, which waits for the next coin created anywhere before it trades — there was no way to buy a coin you already know. Creating one meant bundling a buy with it, and the transaction-status helper was a library with no entry point. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * refactor(cookbook): move pump_v2 next to the scripts that use it pump_v2.py holds the buy_v2/sell_v2 account layouts, and only the pump.fun trade scripts import it — it sat at the cookbook root because tx_status.py does, not because anything outside pumpfun/trade/ needed it. The five callers now pick it up as a plain sibling; legacy/ and the layout verifier reach into that directory. tx_status.py stays at the root, where all four platforms use it. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * refactor(cookbook): name every script protocol_verb_noun_variant manual_buy.py did not just buy — it waited for the next coin created anywhere, then bought, so the verb was wrong. Protocol was encoded three different ways: directory, suffix, or not at all. And three scripts sat under pumpfun/ that have nothing to do with pump.fun. Filenames are now <protocol>_<verb>_<noun>[_<variant>].py, so a basename says which chain, what it does and which instruction version without opening it: manual_buy.py -> pumpfun_snipe_token_blocksubscribe.py manual_buy_geyser.py -> pumpfun_snipe_token_geyser.py buy_token.py -> pumpfun_buy_token_v2.py mint_and_buy_v2.py -> pumpfun_create_and_buy_token_v2.py manual_buy_pumpswap.py -> pumpswap_buy_token.py manual_buy_exact_in.py -> letsbonk_buy_token_exact_in.py legacy/mint_and_buy.py -> legacy/pumpfun_create_and_buy_token_v1.py The sniper was named for logsSubscribe in an earlier draft; it sends blockSubscribe, and the name now says so. Balances, transaction status and the Anchor discriminator calculator are not pump.fun-specific and move to a new cookbook/solana/. The two non-runnable helpers take no verb — pump_v2.py becomes pumpfun_instructions_v2.py beside its callers, tx_status.py becomes solana_transaction_status.py in solana/. Both are imported under a short alias so the 106 call sites stay readable. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(cookbook): resolve a coin's quote mint before pricing it quote_units() defaulted to 9 decimals for an unresolved mint, and every trade script called it before resolve_quote_token_program() warmed the decimals cache. pump.fun's QuoteControl registry admits mints at 6, 8 and 9 decimals — 79 of the 170 admitted are tokenized equities, 8 decimals for xStocks and 6 for Backpack Securities — so those coins were sized against the wrong power of ten. The error compounds rather than cancels: price_per_token() divides by the same wrong unit, so the price reads low by the factor, the token amount comes out high by it, and the inflated cap authorises the overspend instead of catching it. 10x on an xStock pair, 1000x on a Backpack one. This is not hypothetical. A 75s sample of live curve updates on 2026-09-22 caught 8 stock-paired curves out of 124 — IONQ across 5 of them, plus QUBT, PLTRx and COPX. quote_units() now raises for an unresolved mint instead of guessing, the four trade paths resolve before they price, and pumpfun_read_price.py reads decimals from chain rather than from a two-entry table. The geyser sniper never resolved at all: it also passed SPL Token as the quote token program, which fails the account constraints for any Token-2022 quote, and created no quote ATA. verify_quote_decimals_resolved.py checks the fail-closed contract, that resolution costs no extra RPC call, and that no function prices before it resolves — confirmed to fail when the ordering is put back. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR * feat(cookbook): read the quote-mint registry and Token-2022 mint state Two reads that were unreachable without knowing an undocumented PDA seed. pumpfun_read_quote_mints.py decodes QuoteControl (PDA ["quote-control"]), the second quote-mint registry added in the 2026-09-15 upgrade. Reading only Global.whitelisted_quote_mints under-reports: a coin can be paired with a mint Global has never heard of. 170 admitted today, 79 of them tokenized equities, each with the initial virtual quote reserves that set a new curve's opening price. --stocks narrows to the equities, identified by the Token-2022 extension set create_v2 requires of them rather than by a name lookup. solana_read_token2022_mint.py reads the extensions that change what a balance means: scaled UI amount, pausable, permanent delegate, transfer hook, default account state. It exists mainly for one trap — the RPC returns both `multiplier` and `newMultiplier` with an effective timestamp, and once that timestamp passes the field named `multiplier` is the stale one. On AAPLx it passed on 2026-08-08, so the obvious field has been wrong for six weeks. This compares against the clock and says which is in force. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR * feat(cookbook): add the exact-quote-in buy buy_exact_quote_in_v2 was uncovered. It is the mirror of buy_v2 — buy_v2 fixes the tokens received and caps the spend, this fixes the spend and floors the tokens — and it takes the same 27 accounts in the same order, so it reuses build_v2_accounts and differs only in discriminator and arguments. Worth having because pinning the spend is the natural direction once a coin is priced in something other than SOL: "spend exactly one AAPLx" is something you can mean, where a token count is a number derived from a price that moved while you derived it. Verified by simulateTransaction against a live COPX-paired coin: the program executes the full buy and stops at TransferChecked with insufficient funds, which is as far as a wallet holding none of the quote asset can go. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR * feat(cookbook): add the exact-SOL-in buy buy_exact_sol_in was uncovered. SOL only — it pre-dates non-SOL quote assets and carries no quote accounts, so the script checks the curve and points at the exact-quote version for anything else rather than failing obscurely. Its account list is the reason to have it. The IDL lists 16; the program needs 18, the extras being the bonding-curve-v2 PDA and a buyback fee recipient. Determined by simulation rather than assumed: 16 accounts fails AnchorError 6062 (BuybackFeeRecipientMissing), 18 simulates clean at 96k CU. The v2 instructions are complete in the IDL and this family is not, which is worth a newcomer knowing before they trust the file. The docstring carries the IDL's own fee arithmetic, since fees come out of the amount you name rather than on top of it, and the printed estimate ignores that split while min_tokens_out is what the program enforces. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR * feat(cookbook): add the creator-fee and cashback payouts Two payout paths that had no script. Both take no arguments and, per the IDL, no signer — the funds can only reach the wallet they already belong to, so either can be run for anyone, which --creator and --user expose. collect_creator_fee_v2 sweeps a creator vault. The vault is per creator and per quote asset, so a creator whose coins are priced in several assets collects each separately; --quote picks which. claim_cashback_v2 pays out an accrued cashback balance. create_v2 has rejected new cashback coins since 2026-09-15 (error 6082), but coins minted before that keep accruing and stay claimable, which is why the cashback handling elsewhere in this repo is not dead code. Both verified by simulateTransaction against mainnet: 10 accounts each, 8 data bytes, no error. Also repairs two cookbook README rows that the earlier rename mangled — pumpswap_buy_token.py had been rewritten to pumpswap_pumpfun_buy_token_v2.py because its name contains the string that rename matched on. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR * refactor(cookbook): take every script's input on the command line A reference collection only works if you can run a script against your own coin without editing it. Several carried the coin as a module-level constant instead: TOKEN_MINT = Pubkey.from_string(sys.argv[1] if len(sys.argv) > 1 else "...") which reads as optional but raises at import, so running the script the way its own usage line described it died on ValueError: Invalid Base58 string before printing anything. Nine scripts did this. Four more took their amount and slippage from environment variables that no usage line mentioned. Every script now builds an ArgumentParser in main(): required values are positionals, tunables are --options, and the literals live in DEFAULT_* constants that supply the defaults. --help works on all 32 that take input; the seven listeners take none and are exempt. The decode scripts keep defaulting to the fixture beside them, so they still run bare. Behaviour is unchanged. create_and_buy's mayhem flag defaulted to on, so it takes --mayhem/--no-mayhem via BooleanOptionalAction rather than a store_true that would have silently flipped it off. Two fixes found while threading the values through: the wallet listener read a global `wallet` from four functions that no longer had one, and find_pool raised IndexError on a coin that has not graduated instead of saying so. verify_cookbook_arguments.py enforces the shape — no module-level sys.argv, no placeholder values, argparse wherever there is input, and every default a usable value. Confirmed to fail when the old pattern is put back. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR * fix(docs): replace three dead links and check the rest The Anchor discriminator citation in anchor_calculate_discriminator.py pointed at book.anchor-lang.com/anchor_bts/discriminator.html, which Anchor removed when it restructured its docs. Two links in the README had also moved: docs.chainstack.com/quickstart/ and docs.chainstack.com/docs/trader-nodes. book.anchor-lang.com/anchor_bts/discriminator.html -> www.anchor-lang.com/docs/basics/idl (has a Discriminators section) docs.chainstack.com/quickstart/ -> docs.chainstack.com/reference/blockchain-apis docs.chainstack.com/docs/trader-nodes -> docs.chainstack.com/docs/solana-trader-nodes All 28 real URLs in the repo now return 200, checked by fetching each one. verify_documentation_links.py keeps them honest: offline it asserts every URL is https and that none of the four dead endpoints has come back, and --live fetches each and fails on 4xx/5xx. It skips the unroutable hosts the offline verifiers point stub clients at, and example.com, which RFC 2606 reserves for exactly the placeholder metadata URI a test coin is created with. The discriminator script also still asked you to edit a constant, which the argument rule had just outlawed, so it takes the name on the command line and prints the u64, the byte list and the hex. Cross-checks against the constants in pumpfun_instructions_v2.py: global:buy_v2 gives [184, 23, 238, 97, 103, 197, 211, 61], which is BUY_V2_DISCRIMINATOR. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR * fix(cookbook,tools): detect coins via logs so v1 transactions are not skipped Solana transaction v1 has been live since 2026-09-15 and solders cannot deserialize one until 0.29. Three scripts detected coins by deserializing the transaction envelope, so each went blind to v1: cookbook/pumpfun/listen/pumpfun_listen_tokens_blocksubscribe.py 30,080 "skipping a v1 transaction" lines in 150s tools/compare_listeners.py 601 "Failed to process transaction: io error: unexpected end of file" in 100s, which its own comment read as a transport difference cookbook/pumpfun/trade/pumpfun_snipe_token_blocksubscribe.py skipped v1 silently, so a coin created in one was never sniped All three now route on meta.logMessages, which the RPC has already decoded and which reads the same for every version. The blocks example keeps the envelope decode as a genuine fallback for providers that return blocks without logs; the sniper derives the associated bonding curve from the mint and curve instead of reading the instruction's account list, verified against pumpfun_derive_curve_addresses.py on a live coin. Measured live after the change: the blocks example decoded 88 v0, 6 v1 and 4 legacy creates with zero skips and zero errors, and compare_listeners' block lane now appears alongside logs and geyser for the same coins. Upgrading solders was tried first and reverted. 0.29 does decode v1 — 0.26, 0.27.1 and 0.28 all raise "io error: unexpected end of file" on the committed fixture — but it requires solana>=0.40, which moved TxOpts, MemcmpOpts and TokenAccountOpts out of solana.rpc.types. 22 files import them and 16 of 19 verifiers failed on the import alone, so that is a migration of its own. verify_transaction_v1.py gains a check that no cookbook or tools listener detects by opening the envelope. It found the sniper, which this had missed. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR * fix(cookbook): label the transaction version and restore the lost fields The blocks listener printed "Found CreateEvent in a 0 transaction", which reads as a count rather than what it is — Solana's transaction version. It now prints v0, v1 or legacy. Routing detection through the CreateEvent also dropped two fields the instruction path used to fill, so every detection showed "Token Standard: N/A" and no Associated BC. Both come from the event's token_program: the standard is that program, and the associated bonding curve is an ordinary ATA of the curve under it. Verified against pumpfun_derive_curve_addresses.py on a live coin — curve E94izXvHd7dd... derives to He94dArnuprt..., matching what the listener now prints. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
920 lines
34 KiB
Python
920 lines
34 KiB
Python
"""Self-contained pump.fun v2 trade helpers for the learning examples.
|
|
|
|
The bonding-curve program's `buy_v2` / `sell_v2` instructions take 27 and 26
|
|
mandatory accounts in a fixed order, identical for every coin — SOL-paired or
|
|
USDC-paired, mayhem or not, cashback or not. Encoding that once here keeps the
|
|
example scripts from each carrying their own copy of the list, which is how they
|
|
drift out of sync with the program.
|
|
|
|
Deliberately standalone: it imports nothing from `src/`, so the examples stay
|
|
readable on their own. `tests/regression/verify_v2_account_layout.py` checks the
|
|
layout below against `idl/pump_fun_idl.json`.
|
|
|
|
Docs: BUY.md, SELL.md and COIN_CREATION.md under docs/instructions in
|
|
github.com/pump-fun/pump-public-docs
|
|
"""
|
|
|
|
import secrets
|
|
import struct
|
|
from collections.abc import Awaitable, Callable
|
|
from typing import Any
|
|
|
|
from construct import Flag, Int64ul, Struct
|
|
from solders.instruction import AccountMeta, Instruction
|
|
from solders.pubkey import Pubkey
|
|
|
|
# Programs and well-known accounts
|
|
PUMP_PROGRAM = Pubkey.from_string("6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P")
|
|
PUMP_GLOBAL = Pubkey.from_string("4wTV1YmiEkRvAtNtsSGPtUrqRYQMe5SKy2uB4Jjaxnjf")
|
|
PUMP_EVENT_AUTHORITY = Pubkey.from_string(
|
|
"Ce6TQqeHC9p8KetsN6JsjHK7UTZk7nasjjnr7XxXp9F1"
|
|
)
|
|
PUMP_FEE_PROGRAM = Pubkey.from_string("pfeeUxB6jkeY1Hxd7CsFCAjcbHA9rWtchMGdZ6VojVZ")
|
|
SYSTEM_PROGRAM = Pubkey.from_string("11111111111111111111111111111111")
|
|
TOKEN_PROGRAM = Pubkey.from_string("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA")
|
|
TOKEN_2022_PROGRAM = Pubkey.from_string("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb")
|
|
ASSOCIATED_TOKEN_PROGRAM = Pubkey.from_string(
|
|
"ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"
|
|
)
|
|
|
|
# Quote mints. bonding_curve.quote_mint is Pubkey::default() for SOL-paired
|
|
# coins, but the v2 instructions expect wrapped SOL to be passed explicitly.
|
|
DEFAULT_PUBKEY = Pubkey.from_string("11111111111111111111111111111111")
|
|
WSOL_MINT = Pubkey.from_string("So11111111111111111111111111111111111111112")
|
|
USDC_MINT = Pubkey.from_string("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v")
|
|
QUOTE_DECIMALS = {WSOL_MINT: 9, USDC_MINT: 6}
|
|
|
|
# Token program that owns each quote mint below. WSOL and USDC are legacy
|
|
# SPL Token, but a pump.fun upgrade verified 2026-09-15 lets create_v2 pair a
|
|
# coin with a Token-2022 quote mint (error 6064 now accepts "SPL Token or
|
|
# Token-2022"), so this two-entry map is not exhaustive -- see
|
|
# resolve_quote_token_program below for mints outside it.
|
|
QUOTE_TOKEN_PROGRAMS = {WSOL_MINT: TOKEN_PROGRAM, USDC_MINT: TOKEN_PROGRAM}
|
|
|
|
TOKEN_DECIMALS = 6
|
|
LAMPORTS_PER_SOL = 1_000_000_000
|
|
|
|
# Account discriminator for the BondingCurve account.
|
|
BONDING_CURVE_DISCRIMINATOR = struct.pack("<Q", 6966180631402821399)
|
|
|
|
# Instruction discriminators (first 8 bytes of sha256("global:<name>")).
|
|
BUY_V2_DISCRIMINATOR = bytes([184, 23, 238, 97, 103, 197, 211, 61])
|
|
SELL_V2_DISCRIMINATOR = bytes([93, 246, 130, 60, 231, 233, 64, 178])
|
|
# buy_exact_quote_in_v2 takes the same 27 accounts as buy_v2, in the same
|
|
# order — only the discriminator and the two arguments differ.
|
|
BUY_EXACT_QUOTE_IN_V2_DISCRIMINATOR = bytes([194, 171, 28, 70, 104, 77, 91, 47])
|
|
# buy_exact_sol_in is SOL-only and pre-dates the v2 account list. The IDL
|
|
# under-reports it at 16 accounts; on chain it needs 18 (see the builder).
|
|
BUY_EXACT_SOL_IN_DISCRIMINATOR = bytes([56, 252, 116, 8, 158, 223, 205, 95])
|
|
# Both payouts are permissionless: the IDL marks no account a signer, because
|
|
# the funds can only move to the wallet they already belong to.
|
|
COLLECT_CREATOR_FEE_V2_DISCRIMINATOR = bytes([207, 17, 138, 242, 4, 34, 19, 56])
|
|
CLAIM_CASHBACK_V2_DISCRIMINATOR = bytes([122, 243, 204, 65, 94, 116, 29, 55])
|
|
|
|
# Fee recipients: 8 normal (non-mayhem coins), 8 reserved (mayhem coins),
|
|
# 8 buyback (every coin). See FEE_RECIPIENTS.md in the pump-fun public docs.
|
|
NORMAL_FEE_RECIPIENTS = [
|
|
Pubkey.from_string("62qc2CNXwrYqQScmEdiZFFAnJR262PxWEuNQtxfafNgV"),
|
|
Pubkey.from_string("7VtfL8fvgNfhz17qKRMjzQEXgbdpnHHHQRh54R9jP2RJ"),
|
|
Pubkey.from_string("7hTckgnGnLQR6sdH7YkqFTAA7VwTfYFaZ6EhEsU3saCX"),
|
|
Pubkey.from_string("9rPYyANsfQZw3DnDmKE3YCQF5E8oD89UXoHn9JFEhJUz"),
|
|
Pubkey.from_string("AVmoTthdrX6tKt4nDjco2D775W2YK3sDhxPcMmzUAmTY"),
|
|
Pubkey.from_string("CebN5WGQ4jvEPvsVU4EoHEpgzq1VV7AbicfhtW4xC9iM"),
|
|
Pubkey.from_string("FWsW1xNtWscwNmKv6wVsU1iTzRN6wmmk3MjxRP5tT7hz"),
|
|
Pubkey.from_string("G5UZAVbAf46s7cKWoyKu8kYTip9DGTpbLZ2qa9Aq69dP"),
|
|
]
|
|
RESERVED_FEE_RECIPIENTS = [
|
|
Pubkey.from_string("GesfTA3X2arioaHp8bbKdjG9vJtskViWACZoYvxp4twS"),
|
|
Pubkey.from_string("4budycTjhs9fD6xw62VBducVTNgMgJJ5BgtKq7mAZwn6"),
|
|
Pubkey.from_string("8SBKzEQU4nLSzcwF4a74F2iaUDQyTfjGndn6qUWBnrpR"),
|
|
Pubkey.from_string("4UQeTP1T39KZ9Sfxzo3WR5skgsaP6NZa87BAkuazLEKH"),
|
|
Pubkey.from_string("8sNeir4QsLsJdYpc9RZacohhK1Y5FLU3nC5LXgYB4aa6"),
|
|
Pubkey.from_string("Fh9HmeLNUMVCvejxCtCL2DbYaRyBFVJ5xrWkLnMH6fdk"),
|
|
Pubkey.from_string("463MEnMeGyJekNZFQSTUABBEbLnvMTALbT6ZmsxAbAdq"),
|
|
Pubkey.from_string("6AUH3WEHucYZyC61hqpqYUWVto5qA5hjHuNQ32GNnNxA"),
|
|
]
|
|
BUYBACK_FEE_RECIPIENTS = [
|
|
Pubkey.from_string("5YxQFdt3Tr9zJLvkFccqXVUwhdTWJQc1fFg2YPbxvxeD"),
|
|
Pubkey.from_string("9M4giFFMxmFGXtc3feFzRai56WbBqehoSeRE5GK7gf7"),
|
|
Pubkey.from_string("GXPFM2caqTtQYC2cJ5yJRi9VDkpsYZXzYdwYpGnLmtDL"),
|
|
Pubkey.from_string("3BpXnfJaUTiwXnJNe7Ej1rcbzqTTQUvLShZaWazebsVR"),
|
|
Pubkey.from_string("5cjcW9wExnJJiqgLjq7DEG75Pm6JBgE1hNv4B2vHXUW6"),
|
|
Pubkey.from_string("EHAAiTxcdDwQ3U4bU6YcMsQGaekdzLS3B5SmYo46kJtL"),
|
|
Pubkey.from_string("5eHhjP8JaYkz83CWwvGU2uMUXefd3AazWGx4gpcuEEYD"),
|
|
Pubkey.from_string("A7hAgCzFw14fejgCp387JUJRMNyz4j89JKnhtKU8piqW"),
|
|
]
|
|
|
|
|
|
def normalize_quote_mint(quote_mint: Pubkey | None) -> Pubkey:
|
|
"""Map a curve's raw quote_mint onto the mint to pass to the instruction.
|
|
|
|
Args:
|
|
quote_mint: Raw value read from the bonding curve, or None
|
|
|
|
Returns:
|
|
Wrapped SOL for SOL-paired coins, otherwise the mint unchanged
|
|
"""
|
|
if quote_mint is None or quote_mint == DEFAULT_PUBKEY:
|
|
return WSOL_MINT
|
|
return quote_mint
|
|
|
|
|
|
def is_sol_paired(quote_mint: Pubkey | None) -> bool:
|
|
"""Whether a coin settles in native SOL.
|
|
|
|
Args:
|
|
quote_mint: Raw or normalized quote mint
|
|
|
|
Returns:
|
|
True if the coin is SOL-paired
|
|
"""
|
|
return normalize_quote_mint(quote_mint) == WSOL_MINT
|
|
|
|
|
|
# Byte offset of the `decimals` field in a Mint account's raw data. SPL Token
|
|
# and Token-2022 mints share the same base layout -- COption<Pubkey>
|
|
# mint_authority (4-byte tag + 32-byte pubkey = 36 bytes), u64 supply
|
|
# (8 bytes), then u8 decimals at byte 44. Token-2022 extensions are appended
|
|
# *after* this base 82-byte struct, never rearranging it. Verified 2026-09-15
|
|
# by reading byte 44 off-chain for WSOL (9), USDC (6) and a live Token-2022
|
|
# quote mint (6, in a 690-byte account carrying extensions) -- all three
|
|
# matched their known decimals. Mirrors core/pubkeys.py's constant, kept as a
|
|
# separate copy because this module deliberately imports nothing from src/.
|
|
_MINT_DECIMALS_OFFSET = 44
|
|
|
|
|
|
def _parse_mint_decimals(data: bytes) -> int:
|
|
"""Read the `decimals` field out of a raw Mint account's byte layout.
|
|
|
|
Args:
|
|
data: Raw account data, e.g. `.data` on an `AsyncClient.get_account_info`
|
|
response's `.value`
|
|
|
|
Returns:
|
|
The mint's decimal count
|
|
|
|
Raises:
|
|
ValueError: If the data is too short to be a Mint account
|
|
"""
|
|
if len(data) <= _MINT_DECIMALS_OFFSET:
|
|
raise ValueError(
|
|
f"Account data is only {len(data)} bytes, too short to be a "
|
|
f"Mint account (decimals lives at byte {_MINT_DECIMALS_OFFSET})"
|
|
)
|
|
return data[_MINT_DECIMALS_OFFSET]
|
|
|
|
|
|
# Process-lifetime cache of quote mint -> decimals, pre-seeded so WSOL/USDC
|
|
# never cost an RPC call. Mirrors core/pubkeys.py's cache, kept as a separate
|
|
# copy because this module deliberately imports nothing from src/. Warmed by
|
|
# `resolve_quote_token_program` off the same mint-account fetch it already
|
|
# makes to resolve the token program, so this costs zero extra RPC calls.
|
|
_QUOTE_DECIMALS_CACHE = dict(QUOTE_DECIMALS)
|
|
|
|
|
|
def quote_units(quote_mint: Pubkey) -> int:
|
|
"""Raw units per whole unit of a quote mint, from the warm cache.
|
|
|
|
Pre-seeded with WSOL (9) and USDC (6). Every other quote mint must be
|
|
resolved by `resolve_quote_token_program` first, which caches its decimals
|
|
off the same account read it already makes.
|
|
|
|
This raises rather than guessing, on purpose. pump.fun's `QuoteControl`
|
|
registry admits mints at 6, 8 and 9 decimals -- tokenized equities are 8
|
|
(xStocks) or 6 (Backpack Securities) -- so a default of 9 silently
|
|
overstates a slippage cap by 10x or 1000x, and overstates it in the same
|
|
direction as the price error it causes, so the two compound instead of
|
|
cancelling. A loud failure is the only safe answer.
|
|
|
|
Args:
|
|
quote_mint: Quote mint address
|
|
|
|
Returns:
|
|
10 ** decimals for the quote mint (1e9 for SOL, 1e6 for USDC)
|
|
|
|
Raises:
|
|
ValueError: If the mint's decimals have not been resolved yet
|
|
"""
|
|
decimals = _QUOTE_DECIMALS_CACHE.get(quote_mint)
|
|
if decimals is None:
|
|
raise ValueError(
|
|
f"Decimals for quote mint {quote_mint} are unknown. Call "
|
|
f"resolve_quote_token_program() for it before pricing or sizing a "
|
|
f"trade -- guessing here misprices the trade by a power of ten."
|
|
)
|
|
return 10**decimals
|
|
|
|
|
|
def quote_token_program(quote_mint: Pubkey) -> Pubkey:
|
|
"""Token program owning a quote mint, defaulting to SPL Token.
|
|
|
|
Args:
|
|
quote_mint: Quote mint address
|
|
|
|
Returns:
|
|
Token program id for quote_mint if known, else SPL Token
|
|
"""
|
|
return QUOTE_TOKEN_PROGRAMS.get(quote_mint, TOKEN_PROGRAM)
|
|
|
|
|
|
# Process-lifetime cache of quote mint -> owning token program, pre-seeded so
|
|
# WSOL/USDC never cost an RPC call. Mirrors core/pubkeys.py's cache, kept as
|
|
# a separate copy because this module deliberately imports nothing from src/.
|
|
_QUOTE_TOKEN_PROGRAM_CACHE = dict(QUOTE_TOKEN_PROGRAMS)
|
|
|
|
|
|
async def resolve_quote_token_program(
|
|
quote_mint: Pubkey,
|
|
get_account_info: Callable[[Pubkey], Awaitable[Any]],
|
|
) -> Pubkey:
|
|
"""Resolve and cache the token program *and* decimals for a quote mint.
|
|
|
|
Returns instantly, with no RPC call, for a mint already known or
|
|
resolved by an earlier call in this process. Otherwise fetches the mint
|
|
account once -- a mint account's owner *is* the token program that
|
|
created it, and its raw data carries `decimals` at a fixed byte offset
|
|
shared by SPL Token and Token-2022 (see `_parse_mint_decimals`) -- and
|
|
caches both results. `build_v2_accounts` and its callers stay
|
|
synchronous; call this first and pass the result as
|
|
`quote_token_program_id` when trading a mint outside QUOTE_TOKEN_PROGRAMS.
|
|
|
|
Args:
|
|
quote_mint: Quote mint address to resolve
|
|
get_account_info: Async getter returning an account object with
|
|
`.owner` (Pubkey) and `.data` (bytes) attributes, e.g.
|
|
`AsyncClient.get_account_info` (unwrap `.value` from the RPC
|
|
response first)
|
|
|
|
Returns:
|
|
Token program id that owns the quote mint
|
|
|
|
Raises:
|
|
ValueError: If the mint's owner is neither SPL Token nor Token-2022,
|
|
or its account data is too short to carry a decimals field
|
|
"""
|
|
cached = _QUOTE_TOKEN_PROGRAM_CACHE.get(quote_mint)
|
|
if cached is not None:
|
|
return cached
|
|
|
|
account = await get_account_info(quote_mint)
|
|
owner = account.owner
|
|
if owner not in (TOKEN_PROGRAM, TOKEN_2022_PROGRAM):
|
|
raise ValueError(
|
|
f"Quote mint {quote_mint} is owned by {owner}, expected "
|
|
f"{TOKEN_PROGRAM} (SPL Token) or {TOKEN_2022_PROGRAM} (Token-2022)"
|
|
)
|
|
decimals = _parse_mint_decimals(bytes(account.data))
|
|
_QUOTE_TOKEN_PROGRAM_CACHE[quote_mint] = owner
|
|
_QUOTE_DECIMALS_CACHE[quote_mint] = decimals
|
|
return owner
|
|
|
|
|
|
def find_bonding_curve(mint: Pubkey) -> Pubkey:
|
|
"""Derive the bonding curve PDA.
|
|
|
|
Args:
|
|
mint: Base token mint
|
|
|
|
Returns:
|
|
Bonding curve address
|
|
"""
|
|
return Pubkey.find_program_address([b"bonding-curve", bytes(mint)], PUMP_PROGRAM)[0]
|
|
|
|
|
|
def find_creator_vault(creator: Pubkey) -> Pubkey:
|
|
"""Derive the creator vault PDA.
|
|
|
|
Args:
|
|
creator: Coin creator
|
|
|
|
Returns:
|
|
Creator vault address
|
|
"""
|
|
return Pubkey.find_program_address(
|
|
[b"creator-vault", bytes(creator)], PUMP_PROGRAM
|
|
)[0]
|
|
|
|
|
|
def find_global_volume_accumulator() -> Pubkey:
|
|
"""Derive the global volume accumulator PDA.
|
|
|
|
Returns:
|
|
Global volume accumulator address
|
|
"""
|
|
return Pubkey.find_program_address([b"global_volume_accumulator"], PUMP_PROGRAM)[0]
|
|
|
|
|
|
def find_user_volume_accumulator(user: Pubkey) -> Pubkey:
|
|
"""Derive a user's volume accumulator PDA.
|
|
|
|
Args:
|
|
user: User wallet
|
|
|
|
Returns:
|
|
User volume accumulator address
|
|
"""
|
|
return Pubkey.find_program_address(
|
|
[b"user_volume_accumulator", bytes(user)], PUMP_PROGRAM
|
|
)[0]
|
|
|
|
|
|
def find_fee_config() -> Pubkey:
|
|
"""Derive the fee config PDA (under the pump fees program).
|
|
|
|
Returns:
|
|
Fee config address
|
|
"""
|
|
return Pubkey.find_program_address(
|
|
[b"fee_config", bytes(PUMP_PROGRAM)], PUMP_FEE_PROGRAM
|
|
)[0]
|
|
|
|
|
|
def find_sharing_config(base_mint: Pubkey) -> Pubkey:
|
|
"""Derive the creator-fee sharing config PDA (under the pump fees program).
|
|
|
|
Mandatory on buy_v2/sell_v2.
|
|
|
|
Args:
|
|
base_mint: Base token mint
|
|
|
|
Returns:
|
|
Sharing config address
|
|
"""
|
|
return Pubkey.find_program_address(
|
|
[b"sharing-config", bytes(base_mint)], PUMP_FEE_PROGRAM
|
|
)[0]
|
|
|
|
|
|
def find_associated_token_account(
|
|
owner: Pubkey, mint: Pubkey, token_program: Pubkey
|
|
) -> Pubkey:
|
|
"""Derive an associated token account address.
|
|
|
|
Args:
|
|
owner: ATA owner (may be a PDA)
|
|
mint: Token mint
|
|
token_program: Token program owning the mint
|
|
|
|
Returns:
|
|
Associated token account address
|
|
"""
|
|
return Pubkey.find_program_address(
|
|
[bytes(owner), bytes(token_program), bytes(mint)],
|
|
ASSOCIATED_TOKEN_PROGRAM,
|
|
)[0]
|
|
|
|
|
|
def pick_fee_recipient(*, is_mayhem_mode: bool) -> Pubkey:
|
|
"""Pick a fee_recipient from the set the program expects for this coin.
|
|
|
|
Args:
|
|
is_mayhem_mode: Whether the coin is in mayhem mode
|
|
|
|
Returns:
|
|
A fee recipient address
|
|
"""
|
|
pool = RESERVED_FEE_RECIPIENTS if is_mayhem_mode else NORMAL_FEE_RECIPIENTS
|
|
return secrets.choice(pool)
|
|
|
|
|
|
def pick_buyback_fee_recipient() -> Pubkey:
|
|
"""Pick a buyback fee recipient, required on every v2 trade.
|
|
|
|
Returns:
|
|
A buyback fee recipient address
|
|
"""
|
|
return secrets.choice(BUYBACK_FEE_RECIPIENTS)
|
|
|
|
|
|
class BondingCurveState:
|
|
"""Parsed pump.fun BondingCurve account.
|
|
|
|
The account is 125 bytes as created; an extend_account instruction (not
|
|
always in a separate transaction from create_v2 — see
|
|
cookbook/pumpfun/trade/pumpfun_create_and_buy_token_v2.py) can grow it to 151, 256, or any
|
|
other length the program allows. The struct below covers the leading
|
|
fields, which are at the same offsets regardless of total length. The
|
|
SOL-named reserve fields were renamed to quote fields when non-SOL quote
|
|
assets landed; the old names are kept as aliases.
|
|
"""
|
|
|
|
_STRUCT = Struct(
|
|
"virtual_token_reserves" / Int64ul,
|
|
"virtual_quote_reserves" / Int64ul,
|
|
"real_token_reserves" / Int64ul,
|
|
"real_quote_reserves" / Int64ul,
|
|
"token_total_supply" / Int64ul,
|
|
"complete" / Flag,
|
|
)
|
|
# Byte offsets from the start of the account, discriminator included.
|
|
_CREATOR_OFFSET = 49
|
|
_MAYHEM_OFFSET = 81
|
|
_CASHBACK_OFFSET = 82
|
|
_QUOTE_MINT_OFFSET = 83
|
|
|
|
def __init__(self, data: bytes) -> None:
|
|
"""Parse bonding curve account data.
|
|
|
|
Args:
|
|
data: Raw account data including the 8-byte discriminator
|
|
|
|
Raises:
|
|
ValueError: If the discriminator is wrong or the data is truncated
|
|
"""
|
|
if len(data) < 8:
|
|
raise ValueError("Data too short to contain discriminator")
|
|
if data[:8] != BONDING_CURVE_DISCRIMINATOR:
|
|
raise ValueError("Invalid curve state discriminator")
|
|
|
|
self.__dict__.update(self._STRUCT.parse(data[8:]))
|
|
|
|
# Aliases for the pre-rename field names.
|
|
self.virtual_sol_reserves = self.virtual_quote_reserves
|
|
self.real_sol_reserves = self.real_quote_reserves
|
|
|
|
self.creator = self._read_pubkey(data, self._CREATOR_OFFSET)
|
|
self.is_mayhem_mode = self._read_flag(data, self._MAYHEM_OFFSET)
|
|
self.is_cashback_coin = self._read_flag(data, self._CASHBACK_OFFSET)
|
|
raw_quote_mint = self._read_pubkey(data, self._QUOTE_MINT_OFFSET)
|
|
self.quote_mint = normalize_quote_mint(raw_quote_mint)
|
|
self.is_sol_paired = is_sol_paired(raw_quote_mint)
|
|
|
|
@staticmethod
|
|
def _read_pubkey(data: bytes, offset: int) -> Pubkey | None:
|
|
"""Read a 32-byte pubkey if the data extends that far.
|
|
|
|
Args:
|
|
data: Raw account data
|
|
offset: Byte offset
|
|
|
|
Returns:
|
|
Pubkey, or None if the field is absent
|
|
"""
|
|
if len(data) < offset + 32:
|
|
return None
|
|
return Pubkey.from_bytes(data[offset : offset + 32])
|
|
|
|
@staticmethod
|
|
def _read_flag(data: bytes, offset: int) -> bool:
|
|
"""Read a single-byte bool if the data extends that far.
|
|
|
|
Args:
|
|
data: Raw account data
|
|
offset: Byte offset
|
|
|
|
Returns:
|
|
Flag value, or False if the field is absent
|
|
"""
|
|
return bool(data[offset]) if len(data) > offset else False
|
|
|
|
def price_per_token(self) -> float:
|
|
"""Current price in whole quote units per whole token.
|
|
|
|
Returns:
|
|
Price, or 0.0 if reserves are empty
|
|
"""
|
|
if not self.virtual_token_reserves or not self.virtual_quote_reserves:
|
|
return 0.0
|
|
return (self.virtual_quote_reserves / quote_units(self.quote_mint)) / (
|
|
self.virtual_token_reserves / 10**TOKEN_DECIMALS
|
|
)
|
|
|
|
|
|
def build_v2_accounts(
|
|
*,
|
|
base_mint: Pubkey,
|
|
creator: Pubkey,
|
|
user: Pubkey,
|
|
quote_mint: Pubkey,
|
|
base_token_program: Pubkey,
|
|
is_mayhem_mode: bool,
|
|
include_global_volume_accumulator: bool,
|
|
quote_token_program_id: Pubkey | None = None,
|
|
) -> list[AccountMeta]:
|
|
"""Build the ordered account list shared by buy_v2 and sell_v2.
|
|
|
|
Args:
|
|
base_mint: Coin being traded
|
|
creator: Coin creator, from bonding_curve.creator
|
|
user: Signer / trader
|
|
quote_mint: Normalized quote mint (wrapped SOL for SOL-paired coins)
|
|
base_token_program: Token program owning base_mint
|
|
is_mayhem_mode: Selects which fee recipient set to draw from
|
|
include_global_volume_accumulator: True for buy_v2, False for sell_v2
|
|
quote_token_program_id: Token program owning quote_mint. Omit to use
|
|
`quote_token_program`'s SPL Token default; pass the result of
|
|
`resolve_quote_token_program` for a mint outside that default,
|
|
e.g. a Token-2022-paired coin.
|
|
|
|
Returns:
|
|
Ordered AccountMeta list (27 entries for buy_v2, 26 for sell_v2)
|
|
"""
|
|
quote_program = quote_token_program_id or quote_token_program(quote_mint)
|
|
bonding_curve = find_bonding_curve(base_mint)
|
|
creator_vault = find_creator_vault(creator)
|
|
user_volume_accumulator = find_user_volume_accumulator(user)
|
|
fee_recipient = pick_fee_recipient(is_mayhem_mode=is_mayhem_mode)
|
|
buyback_fee_recipient = pick_buyback_fee_recipient()
|
|
|
|
def ata(owner: Pubkey, mint: Pubkey, program: Pubkey) -> Pubkey:
|
|
return find_associated_token_account(owner, mint, program)
|
|
|
|
accounts = [
|
|
(PUMP_GLOBAL, False),
|
|
(base_mint, False),
|
|
(quote_mint, False),
|
|
(base_token_program, False),
|
|
(quote_program, False),
|
|
(ASSOCIATED_TOKEN_PROGRAM, False),
|
|
(fee_recipient, True),
|
|
(ata(fee_recipient, quote_mint, quote_program), True),
|
|
(buyback_fee_recipient, True),
|
|
(ata(buyback_fee_recipient, quote_mint, quote_program), True),
|
|
(bonding_curve, True),
|
|
(ata(bonding_curve, base_mint, base_token_program), True),
|
|
(ata(bonding_curve, quote_mint, quote_program), True),
|
|
(user, True),
|
|
(ata(user, base_mint, base_token_program), True),
|
|
(ata(user, quote_mint, quote_program), True),
|
|
(creator_vault, True),
|
|
(ata(creator_vault, quote_mint, quote_program), True),
|
|
(find_sharing_config(base_mint), False),
|
|
]
|
|
if include_global_volume_accumulator:
|
|
accounts.append((find_global_volume_accumulator(), False))
|
|
accounts += [
|
|
(user_volume_accumulator, True),
|
|
(ata(user_volume_accumulator, quote_mint, quote_program), True),
|
|
(find_fee_config(), False),
|
|
(PUMP_FEE_PROGRAM, False),
|
|
(SYSTEM_PROGRAM, False),
|
|
(PUMP_EVENT_AUTHORITY, False),
|
|
(PUMP_PROGRAM, False),
|
|
]
|
|
|
|
return [
|
|
AccountMeta(pubkey=pubkey, is_signer=pubkey == user, is_writable=writable)
|
|
for pubkey, writable in accounts
|
|
]
|
|
|
|
|
|
def build_buy_v2_instruction(
|
|
*,
|
|
base_mint: Pubkey,
|
|
creator: Pubkey,
|
|
user: Pubkey,
|
|
token_amount_raw: int,
|
|
max_quote_cost_raw: int,
|
|
quote_mint: Pubkey = WSOL_MINT,
|
|
base_token_program: Pubkey = TOKEN_2022_PROGRAM,
|
|
is_mayhem_mode: bool = False,
|
|
quote_token_program_id: Pubkey | None = None,
|
|
) -> Instruction:
|
|
"""Build a buy_v2 instruction.
|
|
|
|
Args:
|
|
base_mint: Coin to buy
|
|
creator: Coin creator, from bonding_curve.creator
|
|
user: Buyer / signer
|
|
token_amount_raw: Base tokens to buy, in raw units
|
|
max_quote_cost_raw: Spend cap in the quote mint's raw units
|
|
quote_mint: Normalized quote mint
|
|
base_token_program: Token program owning base_mint
|
|
is_mayhem_mode: Whether the coin is in mayhem mode
|
|
quote_token_program_id: Token program owning quote_mint; see
|
|
`build_v2_accounts`
|
|
|
|
Returns:
|
|
The buy_v2 instruction
|
|
"""
|
|
return Instruction(
|
|
program_id=PUMP_PROGRAM,
|
|
data=BUY_V2_DISCRIMINATOR
|
|
+ struct.pack("<Q", token_amount_raw)
|
|
+ struct.pack("<Q", max_quote_cost_raw),
|
|
accounts=build_v2_accounts(
|
|
base_mint=base_mint,
|
|
creator=creator,
|
|
user=user,
|
|
quote_mint=quote_mint,
|
|
base_token_program=base_token_program,
|
|
is_mayhem_mode=is_mayhem_mode,
|
|
include_global_volume_accumulator=True,
|
|
quote_token_program_id=quote_token_program_id,
|
|
),
|
|
)
|
|
|
|
|
|
def build_buy_exact_quote_in_v2_instruction(
|
|
*,
|
|
base_mint: Pubkey,
|
|
creator: Pubkey,
|
|
user: Pubkey,
|
|
spendable_quote_in_raw: int,
|
|
min_tokens_out_raw: int,
|
|
quote_mint: Pubkey = WSOL_MINT,
|
|
base_token_program: Pubkey = TOKEN_2022_PROGRAM,
|
|
is_mayhem_mode: bool = False,
|
|
quote_token_program_id: Pubkey | None = None,
|
|
) -> Instruction:
|
|
"""Build a buy_exact_quote_in_v2 instruction.
|
|
|
|
The mirror of `buy_v2`. `buy_v2` fixes how many tokens you receive and caps
|
|
what you spend; this fixes what you spend and floors what you receive. The
|
|
second form is the natural one when the quote asset is the thing you hold a
|
|
budget of — a stablecoin, or a tokenized equity.
|
|
|
|
Fees come out of `spendable_quote_in_raw`, so the whole amount leaves the
|
|
wallet and the tokens arrive against what is left.
|
|
|
|
Args:
|
|
base_mint: Coin to buy
|
|
creator: Coin creator, from bonding_curve.creator
|
|
user: Buyer / signer
|
|
spendable_quote_in_raw: Exact amount to spend, in the quote mint's raw
|
|
units, fees included
|
|
min_tokens_out_raw: Floor on base tokens received, in raw units. This is
|
|
the slippage protection; the caller owns it.
|
|
quote_mint: Normalized quote mint
|
|
base_token_program: Token program owning base_mint
|
|
is_mayhem_mode: Whether the coin is in mayhem mode
|
|
quote_token_program_id: Token program owning quote_mint; see
|
|
`build_v2_accounts`
|
|
|
|
Returns:
|
|
The buy_exact_quote_in_v2 instruction
|
|
"""
|
|
return Instruction(
|
|
program_id=PUMP_PROGRAM,
|
|
data=BUY_EXACT_QUOTE_IN_V2_DISCRIMINATOR
|
|
+ struct.pack("<Q", spendable_quote_in_raw)
|
|
+ struct.pack("<Q", min_tokens_out_raw),
|
|
accounts=build_v2_accounts(
|
|
base_mint=base_mint,
|
|
creator=creator,
|
|
user=user,
|
|
quote_mint=quote_mint,
|
|
base_token_program=base_token_program,
|
|
is_mayhem_mode=is_mayhem_mode,
|
|
include_global_volume_accumulator=True,
|
|
quote_token_program_id=quote_token_program_id,
|
|
),
|
|
)
|
|
|
|
|
|
def build_buy_exact_sol_in_instruction(
|
|
*,
|
|
mint: Pubkey,
|
|
creator: Pubkey,
|
|
user: Pubkey,
|
|
spendable_sol_in_lamports: int,
|
|
min_tokens_out_raw: int,
|
|
base_token_program: Pubkey = TOKEN_2022_PROGRAM,
|
|
is_mayhem_mode: bool = False,
|
|
track_volume: bool = True,
|
|
) -> Instruction:
|
|
"""Build a buy_exact_sol_in instruction.
|
|
|
|
SOL only. This one pre-dates non-SOL quote assets and has no quote accounts
|
|
at all, so it cannot trade a coin paired with USDC, another coin or a
|
|
tokenized equity — use `build_buy_exact_quote_in_v2_instruction` for those.
|
|
|
|
**The IDL lists 16 accounts and the program requires 18.** The two it omits
|
|
are the `bonding-curve-v2` PDA and a buyback fee recipient, both writable,
|
|
both appended after `fee_program`. Sending the IDL's 16 fails with
|
|
AnchorError 6062 (BuybackFeeRecipientMissing), which names the missing
|
|
account but not where it goes. Verified by simulateTransaction on mainnet,
|
|
2026-09-22: 16 accounts fails 6062, 18 succeeds.
|
|
|
|
Args:
|
|
mint: Coin to buy
|
|
creator: Coin creator, from bonding_curve.creator
|
|
user: Buyer / signer
|
|
spendable_sol_in_lamports: Exact lamports to spend, fees included
|
|
min_tokens_out_raw: Floor on base tokens received, in raw units
|
|
base_token_program: Token program owning the mint
|
|
is_mayhem_mode: Whether the coin is in mayhem mode, which selects the
|
|
reserved fee recipient set instead of the normal one
|
|
track_volume: Whether to credit the user's volume accumulator
|
|
|
|
Returns:
|
|
The buy_exact_sol_in instruction
|
|
"""
|
|
bonding_curve = find_bonding_curve(mint)
|
|
accounts = [
|
|
AccountMeta(pubkey=PUMP_GLOBAL, is_signer=False, is_writable=False),
|
|
AccountMeta(
|
|
pubkey=pick_fee_recipient(is_mayhem_mode=is_mayhem_mode),
|
|
is_signer=False,
|
|
is_writable=True,
|
|
),
|
|
AccountMeta(pubkey=mint, is_signer=False, is_writable=False),
|
|
AccountMeta(pubkey=bonding_curve, is_signer=False, is_writable=True),
|
|
AccountMeta(
|
|
pubkey=find_associated_token_account(
|
|
bonding_curve, mint, base_token_program
|
|
),
|
|
is_signer=False,
|
|
is_writable=True,
|
|
),
|
|
AccountMeta(
|
|
pubkey=find_associated_token_account(user, mint, base_token_program),
|
|
is_signer=False,
|
|
is_writable=True,
|
|
),
|
|
AccountMeta(pubkey=user, is_signer=True, is_writable=True),
|
|
AccountMeta(pubkey=SYSTEM_PROGRAM, is_signer=False, is_writable=False),
|
|
AccountMeta(pubkey=base_token_program, is_signer=False, is_writable=False),
|
|
AccountMeta(
|
|
pubkey=find_creator_vault(creator), is_signer=False, is_writable=True
|
|
),
|
|
AccountMeta(pubkey=PUMP_EVENT_AUTHORITY, is_signer=False, is_writable=False),
|
|
AccountMeta(pubkey=PUMP_PROGRAM, is_signer=False, is_writable=False),
|
|
AccountMeta(
|
|
pubkey=find_global_volume_accumulator(), is_signer=False, is_writable=True
|
|
),
|
|
AccountMeta(
|
|
pubkey=find_user_volume_accumulator(user), is_signer=False, is_writable=True
|
|
),
|
|
AccountMeta(pubkey=find_fee_config(), is_signer=False, is_writable=False),
|
|
AccountMeta(pubkey=PUMP_FEE_PROGRAM, is_signer=False, is_writable=False),
|
|
# The two the IDL omits.
|
|
AccountMeta(
|
|
pubkey=Pubkey.find_program_address(
|
|
[b"bonding-curve-v2", bytes(mint)], PUMP_PROGRAM
|
|
)[0],
|
|
is_signer=False,
|
|
is_writable=True,
|
|
),
|
|
AccountMeta(
|
|
pubkey=pick_buyback_fee_recipient(), is_signer=False, is_writable=True
|
|
),
|
|
]
|
|
return Instruction(
|
|
program_id=PUMP_PROGRAM,
|
|
data=BUY_EXACT_SOL_IN_DISCRIMINATOR
|
|
+ struct.pack("<Q", spendable_sol_in_lamports)
|
|
+ struct.pack("<Q", min_tokens_out_raw)
|
|
# OptionBool is a single-field Anchor struct with no presence tag, so
|
|
# it serializes as its bare inner bool.
|
|
+ struct.pack("<?", track_volume),
|
|
accounts=accounts,
|
|
)
|
|
|
|
|
|
def build_collect_creator_fee_v2_instruction(
|
|
*,
|
|
creator: Pubkey,
|
|
quote_mint: Pubkey = WSOL_MINT,
|
|
quote_token_program_id: Pubkey | None = None,
|
|
) -> Instruction:
|
|
"""Build a collect_creator_fee_v2 instruction.
|
|
|
|
Sweeps whatever has accrued in the creator's vault for one quote asset into
|
|
the creator's own token account. Takes no arguments and no signer — the
|
|
money can only go to the wallet it already belongs to, so anyone may run it.
|
|
|
|
A creator vault is per (creator, quote asset), so a creator whose coins are
|
|
priced in several assets collects each one separately.
|
|
|
|
Args:
|
|
creator: The coin creator whose vault to sweep
|
|
quote_mint: Quote asset to collect, normalized
|
|
quote_token_program_id: Token program owning quote_mint; resolved from
|
|
the cache when omitted
|
|
|
|
Returns:
|
|
The collect_creator_fee_v2 instruction
|
|
"""
|
|
program = quote_token_program_id or quote_token_program(quote_mint)
|
|
vault = find_creator_vault(creator)
|
|
accounts = [
|
|
AccountMeta(pubkey=creator, is_signer=False, is_writable=True),
|
|
AccountMeta(
|
|
pubkey=find_associated_token_account(creator, quote_mint, program),
|
|
is_signer=False,
|
|
is_writable=True,
|
|
),
|
|
AccountMeta(pubkey=vault, is_signer=False, is_writable=True),
|
|
AccountMeta(
|
|
pubkey=find_associated_token_account(vault, quote_mint, program),
|
|
is_signer=False,
|
|
is_writable=True,
|
|
),
|
|
AccountMeta(pubkey=quote_mint, is_signer=False, is_writable=False),
|
|
AccountMeta(pubkey=program, is_signer=False, is_writable=False),
|
|
AccountMeta(
|
|
pubkey=ASSOCIATED_TOKEN_PROGRAM, is_signer=False, is_writable=False
|
|
),
|
|
AccountMeta(pubkey=SYSTEM_PROGRAM, is_signer=False, is_writable=False),
|
|
AccountMeta(pubkey=PUMP_EVENT_AUTHORITY, is_signer=False, is_writable=False),
|
|
AccountMeta(pubkey=PUMP_PROGRAM, is_signer=False, is_writable=False),
|
|
]
|
|
return Instruction(
|
|
program_id=PUMP_PROGRAM,
|
|
data=COLLECT_CREATOR_FEE_V2_DISCRIMINATOR,
|
|
accounts=accounts,
|
|
)
|
|
|
|
|
|
def build_claim_cashback_v2_instruction(
|
|
*,
|
|
user: Pubkey,
|
|
quote_mint: Pubkey = WSOL_MINT,
|
|
quote_token_program_id: Pubkey | None = None,
|
|
) -> Instruction:
|
|
"""Build a claim_cashback_v2 instruction.
|
|
|
|
Pays out the cashback accrued on the user's volume accumulator. `create_v2`
|
|
has refused to mint new cashback coins since 2026-09-15 (error 6082,
|
|
CashbackDeprecated), but coins created before that keep accruing and stay
|
|
claimable, so this path is still live.
|
|
|
|
Args:
|
|
user: Wallet whose cashback to pay out
|
|
quote_mint: Quote asset the cashback accrued in, normalized
|
|
quote_token_program_id: Token program owning quote_mint; resolved from
|
|
the cache when omitted
|
|
|
|
Returns:
|
|
The claim_cashback_v2 instruction
|
|
"""
|
|
program = quote_token_program_id or quote_token_program(quote_mint)
|
|
accumulator = find_user_volume_accumulator(user)
|
|
accounts = [
|
|
AccountMeta(pubkey=user, is_signer=False, is_writable=True),
|
|
AccountMeta(pubkey=accumulator, is_signer=False, is_writable=True),
|
|
AccountMeta(pubkey=quote_mint, is_signer=False, is_writable=False),
|
|
AccountMeta(pubkey=program, is_signer=False, is_writable=False),
|
|
AccountMeta(
|
|
pubkey=ASSOCIATED_TOKEN_PROGRAM, is_signer=False, is_writable=False
|
|
),
|
|
AccountMeta(
|
|
pubkey=find_associated_token_account(accumulator, quote_mint, program),
|
|
is_signer=False,
|
|
is_writable=True,
|
|
),
|
|
# Any token account of quote_mint owned by the user works here; the
|
|
# associated one is the obvious choice.
|
|
AccountMeta(
|
|
pubkey=find_associated_token_account(user, quote_mint, program),
|
|
is_signer=False,
|
|
is_writable=True,
|
|
),
|
|
AccountMeta(pubkey=SYSTEM_PROGRAM, is_signer=False, is_writable=False),
|
|
AccountMeta(pubkey=PUMP_EVENT_AUTHORITY, is_signer=False, is_writable=False),
|
|
AccountMeta(pubkey=PUMP_PROGRAM, is_signer=False, is_writable=False),
|
|
]
|
|
return Instruction(
|
|
program_id=PUMP_PROGRAM,
|
|
data=CLAIM_CASHBACK_V2_DISCRIMINATOR,
|
|
accounts=accounts,
|
|
)
|
|
|
|
|
|
def build_sell_v2_instruction(
|
|
*,
|
|
base_mint: Pubkey,
|
|
creator: Pubkey,
|
|
user: Pubkey,
|
|
token_amount_raw: int,
|
|
min_quote_output_raw: int,
|
|
quote_mint: Pubkey = WSOL_MINT,
|
|
base_token_program: Pubkey = TOKEN_2022_PROGRAM,
|
|
is_mayhem_mode: bool = False,
|
|
quote_token_program_id: Pubkey | None = None,
|
|
) -> Instruction:
|
|
"""Build a sell_v2 instruction.
|
|
|
|
Args:
|
|
base_mint: Coin to sell
|
|
creator: Coin creator, from bonding_curve.creator
|
|
user: Seller / signer
|
|
token_amount_raw: Base tokens to sell, in raw units
|
|
min_quote_output_raw: Minimum acceptable payout in raw quote units
|
|
quote_mint: Normalized quote mint
|
|
base_token_program: Token program owning base_mint
|
|
is_mayhem_mode: Whether the coin is in mayhem mode
|
|
quote_token_program_id: Token program owning quote_mint; see
|
|
`build_v2_accounts`
|
|
|
|
Returns:
|
|
The sell_v2 instruction
|
|
"""
|
|
return Instruction(
|
|
program_id=PUMP_PROGRAM,
|
|
data=SELL_V2_DISCRIMINATOR
|
|
+ struct.pack("<Q", token_amount_raw)
|
|
+ struct.pack("<Q", min_quote_output_raw),
|
|
accounts=build_v2_accounts(
|
|
base_mint=base_mint,
|
|
creator=creator,
|
|
user=user,
|
|
quote_mint=quote_mint,
|
|
base_token_program=base_token_program,
|
|
is_mayhem_mode=is_mayhem_mode,
|
|
include_global_volume_accumulator=False,
|
|
quote_token_program_id=quote_token_program_id,
|
|
),
|
|
)
|