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>
557 lines
21 KiB
Python
557 lines
21 KiB
Python
"""Cross-check the hardcoded buy_v2/sell_v2 account layouts against the IDL.
|
|
|
|
The v2 instructions take 27 and 26 mandatory accounts in a fixed order. Getting
|
|
one position or writability flag wrong produces an on-chain failure that is
|
|
awkward to debug, so this script diffs the layouts in
|
|
`platforms.pumpfun.instruction_builder` against `idl/pump_fun_idl.json` and also
|
|
recomputes every PDA/ATA the address provider derives, comparing each against
|
|
the seeds declared in the IDL.
|
|
|
|
Runs entirely offline — no RPC, no keys, no transactions.
|
|
|
|
Usage:
|
|
uv run tests/regression/verify_v2_account_layout.py
|
|
"""
|
|
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
PROJECT_ROOT = Path(__file__).resolve().parents[2]
|
|
sys.path.insert(0, str(PROJECT_ROOT / "cookbook" / "pumpfun" / "trade"))
|
|
sys.path.insert(0, str(PROJECT_ROOT / "src"))
|
|
|
|
from solders.pubkey import Pubkey # noqa: E402
|
|
from spl.token.instructions import get_associated_token_address # noqa: E402
|
|
|
|
from core.pubkeys import USDC_MINT, WSOL_MINT, SystemAddresses # noqa: E402
|
|
from interfaces.core import Platform, TokenInfo # noqa: E402
|
|
from platforms.pumpfun.address_provider import ( # noqa: E402
|
|
PumpFunAddresses,
|
|
PumpFunAddressProvider,
|
|
)
|
|
from platforms.pumpfun.instruction_builder import ( # noqa: E402
|
|
_BUY_V2_ACCOUNTS,
|
|
_SELL_V2_ACCOUNTS,
|
|
)
|
|
|
|
IDL_PATH = PROJECT_ROOT / "idl" / "pump_fun_idl.json"
|
|
|
|
|
|
def load_idl_accounts(name: str) -> list[dict]:
|
|
"""Get the IDL account list for an instruction.
|
|
|
|
Args:
|
|
name: Instruction name
|
|
|
|
Returns:
|
|
List of IDL account definitions
|
|
"""
|
|
idl = json.loads(IDL_PATH.read_text())
|
|
for instruction in idl["instructions"]:
|
|
if instruction["name"] == name:
|
|
return instruction["accounts"]
|
|
raise KeyError(f"Instruction {name} not present in {IDL_PATH}")
|
|
|
|
|
|
def check_layout(name: str, layout: list[tuple[str, bool]]) -> list[str]:
|
|
"""Compare a hardcoded layout against the IDL's account list.
|
|
|
|
Args:
|
|
name: Instruction name
|
|
layout: Ordered (account name, is_writable) pairs from our builder
|
|
|
|
Returns:
|
|
List of human-readable problems (empty if the layout matches)
|
|
"""
|
|
idl_accounts = load_idl_accounts(name)
|
|
problems = []
|
|
|
|
if len(layout) != len(idl_accounts):
|
|
problems.append(
|
|
f"{name}: account count {len(layout)} != IDL {len(idl_accounts)}"
|
|
)
|
|
|
|
for index, (idl_account, ours) in enumerate(zip(idl_accounts, layout), start=1):
|
|
our_name, our_writable = ours
|
|
if idl_account["name"] != our_name:
|
|
problems.append(
|
|
f"{name}[{index}]: name {our_name!r} != IDL {idl_account['name']!r}"
|
|
)
|
|
idl_writable = bool(idl_account.get("writable"))
|
|
if idl_writable != our_writable:
|
|
problems.append(
|
|
f"{name}[{index}] {our_name}: writable={our_writable} "
|
|
f"!= IDL writable={idl_writable}"
|
|
)
|
|
if idl_account.get("signer") and our_name != "user":
|
|
problems.append(
|
|
f"{name}[{index}] {our_name}: IDL marks this a signer but only "
|
|
f"`user` is expected to sign"
|
|
)
|
|
|
|
return problems
|
|
|
|
|
|
def build_token_info(quote_mint: Pubkey, *, mayhem: bool) -> TokenInfo:
|
|
"""Construct a TokenInfo for a synthetic coin.
|
|
|
|
Args:
|
|
quote_mint: Quote mint to pair the coin against
|
|
mayhem: Whether the coin is in mayhem mode
|
|
|
|
Returns:
|
|
TokenInfo suitable for driving the address provider
|
|
"""
|
|
provider = PumpFunAddressProvider()
|
|
# Fixed, arbitrary mint/creator so results are reproducible.
|
|
mint = Pubkey.from_string("CU7nUQaJ4beyYjC3xAUrh5RiSjw14fhU6oWTwRBse8gj")
|
|
creator = Pubkey.from_string("5wyFsNExysbXf2hTtcn8Tqd3urs9Nv85Zx1zNdAfTMmX")
|
|
bonding_curve = provider.derive_pool_address(mint)
|
|
|
|
return TokenInfo(
|
|
name="layout-check",
|
|
symbol="CHK",
|
|
uri="",
|
|
mint=mint,
|
|
platform=Platform.PUMP_FUN,
|
|
bonding_curve=bonding_curve,
|
|
associated_bonding_curve=provider.derive_associated_bonding_curve(
|
|
mint, bonding_curve, SystemAddresses.TOKEN_2022_PROGRAM
|
|
),
|
|
creator=creator,
|
|
creator_vault=provider.derive_creator_vault(creator),
|
|
token_program_id=SystemAddresses.TOKEN_2022_PROGRAM,
|
|
is_mayhem_mode=mayhem,
|
|
quote_mint=quote_mint,
|
|
)
|
|
|
|
|
|
def check_derivations(quote_mint: Pubkey, *, mayhem: bool) -> list[str]:
|
|
"""Independently recompute every derived v2 account and compare.
|
|
|
|
Args:
|
|
quote_mint: Quote mint to pair the coin against
|
|
mayhem: Whether the coin is in mayhem mode
|
|
|
|
Returns:
|
|
List of mismatches (empty if all derivations agree)
|
|
"""
|
|
provider = PumpFunAddressProvider()
|
|
token_info = build_token_info(quote_mint, mayhem=mayhem)
|
|
user = Pubkey.from_string("Ba99j1dYxidfQZvuNGMaXGxJsUeWXu6VNW8damkrdLVd")
|
|
accounts = provider.get_buy_v2_instruction_accounts(token_info, user)
|
|
|
|
pump = PumpFunAddresses.PROGRAM
|
|
fee_program = PumpFunAddresses.FEE_PROGRAM
|
|
quote_program = SystemAddresses.TOKEN_PROGRAM
|
|
base_program = SystemAddresses.TOKEN_2022_PROGRAM
|
|
mint = token_info.mint
|
|
bonding_curve = token_info.bonding_curve
|
|
creator_vault = token_info.creator_vault
|
|
uva, _ = Pubkey.find_program_address(
|
|
[b"user_volume_accumulator", bytes(user)], pump
|
|
)
|
|
|
|
expected = {
|
|
"bonding_curve": Pubkey.find_program_address(
|
|
[b"bonding-curve", bytes(mint)], pump
|
|
)[0],
|
|
"creator_vault": Pubkey.find_program_address(
|
|
[b"creator-vault", bytes(token_info.creator)], pump
|
|
)[0],
|
|
"sharing_config": Pubkey.find_program_address(
|
|
[b"sharing-config", bytes(mint)], fee_program
|
|
)[0],
|
|
"global_volume_accumulator": Pubkey.find_program_address(
|
|
[b"global_volume_accumulator"], pump
|
|
)[0],
|
|
"user_volume_accumulator": uva,
|
|
"fee_config": Pubkey.find_program_address(
|
|
[b"fee_config", bytes(pump)], fee_program
|
|
)[0],
|
|
"event_authority": Pubkey.find_program_address([b"__event_authority"], pump)[0],
|
|
"associated_base_bonding_curve": get_associated_token_address(
|
|
bonding_curve, mint, base_program
|
|
),
|
|
"associated_quote_bonding_curve": get_associated_token_address(
|
|
bonding_curve, quote_mint, quote_program
|
|
),
|
|
"associated_base_user": get_associated_token_address(user, mint, base_program),
|
|
"associated_quote_user": get_associated_token_address(
|
|
user, quote_mint, quote_program
|
|
),
|
|
"associated_creator_vault": get_associated_token_address(
|
|
creator_vault, quote_mint, quote_program
|
|
),
|
|
"associated_quote_fee_recipient": get_associated_token_address(
|
|
accounts["fee_recipient"], quote_mint, quote_program
|
|
),
|
|
"associated_quote_buyback_fee_recipient": get_associated_token_address(
|
|
accounts["buyback_fee_recipient"], quote_mint, quote_program
|
|
),
|
|
"associated_user_volume_accumulator": get_associated_token_address(
|
|
uva, quote_mint, quote_program
|
|
),
|
|
"quote_mint": quote_mint,
|
|
"base_mint": mint,
|
|
"user": user,
|
|
"program": pump,
|
|
"fee_program": fee_program,
|
|
"system_program": SystemAddresses.SYSTEM_PROGRAM,
|
|
"associated_token_program": SystemAddresses.ASSOCIATED_TOKEN_PROGRAM,
|
|
"base_token_program": base_program,
|
|
"quote_token_program": quote_program,
|
|
"global": PumpFunAddresses.GLOBAL,
|
|
}
|
|
|
|
problems = [
|
|
f"{key}: provider={accounts[key]} != expected={value}"
|
|
for key, value in expected.items()
|
|
if accounts[key] != value
|
|
]
|
|
|
|
# The fee recipient must come from the right documented set.
|
|
recipient_set = (
|
|
PumpFunAddresses.RESERVED_FEE_RECIPIENTS
|
|
if mayhem
|
|
else PumpFunAddresses.NORMAL_FEE_RECIPIENTS
|
|
)
|
|
if accounts["fee_recipient"] not in recipient_set:
|
|
problems.append(
|
|
f"fee_recipient {accounts['fee_recipient']} not in "
|
|
f"{'reserved' if mayhem else 'normal'} fee recipient set"
|
|
)
|
|
if accounts["buyback_fee_recipient"] not in PumpFunAddresses.BUYBACK_FEE_RECIPIENTS:
|
|
problems.append(
|
|
f"buyback_fee_recipient {accounts['buyback_fee_recipient']} not in "
|
|
f"buyback fee recipient set"
|
|
)
|
|
|
|
# Every account must be distinct except where the program expects reuse.
|
|
if len(set(accounts.values())) != len(accounts):
|
|
duplicates = [
|
|
key
|
|
for key, value in accounts.items()
|
|
if list(accounts.values()).count(value) > 1
|
|
]
|
|
problems.append(f"duplicate account addresses for: {sorted(duplicates)}")
|
|
|
|
return problems
|
|
|
|
|
|
def check_instruction_encoding() -> list[str]:
|
|
"""Build real v2 instructions and assert their shape and data encoding.
|
|
|
|
Covers the USDC path, which cannot be exercised on-chain until a
|
|
USDC-paired coin exists.
|
|
|
|
Returns:
|
|
List of problems (empty if the instructions are well-formed)
|
|
"""
|
|
import asyncio
|
|
import struct
|
|
|
|
from interfaces.core import Platform as _Platform # noqa: F401
|
|
from platforms.pumpfun.instruction_builder import PumpFunInstructionBuilder
|
|
from utils.idl_manager import get_idl_manager
|
|
|
|
provider = PumpFunAddressProvider()
|
|
builder = PumpFunInstructionBuilder(get_idl_manager().get_parser(Platform.PUMP_FUN))
|
|
user = Pubkey.from_string("Ba99j1dYxidfQZvuNGMaXGxJsUeWXu6VNW8damkrdLVd")
|
|
problems = []
|
|
|
|
for quote_mint, label, expect_quote_ata in (
|
|
(WSOL_MINT, "SOL-paired", False),
|
|
(USDC_MINT, "USDC-paired", True),
|
|
):
|
|
token_info = build_token_info(quote_mint, mayhem=False)
|
|
|
|
buy = asyncio.run(
|
|
builder.build_buy_v2_instruction(
|
|
token_info, user, 1_500_000, 20_000_000, provider
|
|
)
|
|
)
|
|
sell = asyncio.run(
|
|
builder.build_sell_v2_instruction(
|
|
token_info, user, 20_000_000, 900_000, provider
|
|
)
|
|
)
|
|
|
|
# Instruction counts: base ATA always, quote ATA only for non-SOL.
|
|
expected_buy_ix = 3 if expect_quote_ata else 2
|
|
if len(buy) != expected_buy_ix:
|
|
problems.append(
|
|
f"{label}: buy produced {len(buy)} instructions, "
|
|
f"expected {expected_buy_ix}"
|
|
)
|
|
expected_sell_ix = 2 if expect_quote_ata else 1
|
|
if len(sell) != expected_sell_ix:
|
|
problems.append(
|
|
f"{label}: sell produced {len(sell)} instructions, "
|
|
f"expected {expected_sell_ix}"
|
|
)
|
|
|
|
if len(buy[-1].accounts) != 27:
|
|
problems.append(
|
|
f"{label}: buy_v2 has {len(buy[-1].accounts)} accounts != 27"
|
|
)
|
|
if len(sell[-1].accounts) != 26:
|
|
problems.append(
|
|
f"{label}: sell_v2 has {len(sell[-1].accounts)} accounts != 26"
|
|
)
|
|
|
|
# buy_v2 data: 8-byte discriminator + amount (tokens) + max_sol_cost.
|
|
# No trailing track_volume OptionBool, unlike the legacy buy.
|
|
buy_data = bytes(buy[-1].data)
|
|
if len(buy_data) != 24:
|
|
problems.append(
|
|
f"{label}: buy_v2 data is {len(buy_data)} bytes, expected 24 "
|
|
f"(discriminator + 2 u64, no track_volume)"
|
|
)
|
|
else:
|
|
amount, max_cost = struct.unpack("<QQ", buy_data[8:])
|
|
if amount != 20_000_000 or max_cost != 1_500_000:
|
|
problems.append(
|
|
f"{label}: buy_v2 args decoded as amount={amount}, "
|
|
f"max_sol_cost={max_cost}; expected 20000000 and 1500000"
|
|
)
|
|
|
|
sell_data = bytes(sell[-1].data)
|
|
if len(sell_data) != 24:
|
|
problems.append(
|
|
f"{label}: sell_v2 data is {len(sell_data)} bytes, expected 24"
|
|
)
|
|
else:
|
|
amount, min_out = struct.unpack("<QQ", sell_data[8:])
|
|
if amount != 20_000_000 or min_out != 900_000:
|
|
problems.append(
|
|
f"{label}: sell_v2 args decoded as amount={amount}, "
|
|
f"min_sol_output={min_out}; expected 20000000 and 900000"
|
|
)
|
|
|
|
# Exactly one signer, and it must be the user.
|
|
signers = [meta.pubkey for meta in buy[-1].accounts if meta.is_signer]
|
|
if signers != [user]:
|
|
problems.append(f"{label}: buy_v2 signers {signers} != [{user}]")
|
|
|
|
return problems
|
|
|
|
|
|
def check_quote_config() -> list[str]:
|
|
"""Assert quote-amount config resolution and alias handling.
|
|
|
|
Returns:
|
|
List of problems (empty if config resolution behaves correctly)
|
|
"""
|
|
from core.pubkeys import resolve_quote_amounts, resolve_quote_mint
|
|
from trading.universal_trader import _resolve_quote_config
|
|
|
|
problems = []
|
|
|
|
if resolve_quote_mint("usdc") != USDC_MINT:
|
|
problems.append("alias 'usdc' did not resolve to the USDC mint")
|
|
if resolve_quote_mint("sol") != WSOL_MINT:
|
|
problems.append("alias 'sol' did not resolve to wrapped SOL")
|
|
if resolve_quote_mint(str(USDC_MINT)) != USDC_MINT:
|
|
problems.append("raw USDC mint string did not resolve")
|
|
|
|
try:
|
|
resolve_quote_amounts({"usdc": 0})
|
|
problems.append("resolve_quote_amounts accepted a zero amount")
|
|
except ValueError:
|
|
pass
|
|
|
|
try:
|
|
resolve_quote_mint("not-a-mint")
|
|
problems.append("resolve_quote_mint accepted an invalid mint")
|
|
except ValueError:
|
|
pass
|
|
|
|
# SOL always present from buy_amount; USDC only when configured.
|
|
amounts, allowed = _resolve_quote_config(0.0001, None, None)
|
|
if amounts.get(WSOL_MINT) != 0.0001:
|
|
problems.append("SOL amount did not fall back to buy_amount")
|
|
if USDC_MINT in amounts:
|
|
problems.append("USDC present in amounts without being configured")
|
|
if allowed is not None:
|
|
problems.append("allowed_quote_mints should be None when unset")
|
|
|
|
amounts, allowed = _resolve_quote_config(0.0001, {"usdc": 5.0}, ["sol", "usdc"])
|
|
if amounts.get(USDC_MINT) != 5.0:
|
|
problems.append("configured USDC amount not resolved")
|
|
if allowed != {WSOL_MINT, USDC_MINT}:
|
|
problems.append(f"allowed_quote_mints resolved to {allowed}")
|
|
|
|
return problems
|
|
|
|
|
|
def check_examples_toolkit() -> list[str]:
|
|
"""Check cookbook/pumpfun/trade/pumpfun_instructions_v2.py agrees with the IDL and with src/.
|
|
|
|
The examples carry their own standalone copy of the v2 layout so they stay
|
|
readable without importing src/. That copy is exactly the kind of thing that
|
|
silently drifts, so diff it against both sources of truth.
|
|
|
|
Returns:
|
|
List of problems (empty if the toolkit agrees)
|
|
"""
|
|
import pumpfun_instructions_v2 as pump_v2
|
|
|
|
from platforms.pumpfun.address_provider import PumpFunAddresses
|
|
|
|
problems = []
|
|
user = Pubkey.from_string("Ba99j1dYxidfQZvuNGMaXGxJsUeWXu6VNW8damkrdLVd")
|
|
mint = Pubkey.from_string("CU7nUQaJ4beyYjC3xAUrh5RiSjw14fhU6oWTwRBse8gj")
|
|
creator = Pubkey.from_string("5wyFsNExysbXf2hTtcn8Tqd3urs9Nv85Zx1zNdAfTMmX")
|
|
|
|
# Fee recipient sets must match src/ exactly.
|
|
for label, theirs, ours in (
|
|
(
|
|
"normal",
|
|
pump_v2.NORMAL_FEE_RECIPIENTS,
|
|
PumpFunAddresses.NORMAL_FEE_RECIPIENTS,
|
|
),
|
|
(
|
|
"reserved",
|
|
pump_v2.RESERVED_FEE_RECIPIENTS,
|
|
PumpFunAddresses.RESERVED_FEE_RECIPIENTS,
|
|
),
|
|
(
|
|
"buyback",
|
|
pump_v2.BUYBACK_FEE_RECIPIENTS,
|
|
PumpFunAddresses.BUYBACK_FEE_RECIPIENTS,
|
|
),
|
|
):
|
|
if theirs != ours:
|
|
problems.append(f"pump_v2 {label} fee recipients differ from src/")
|
|
|
|
# Discriminators must match the IDL.
|
|
idl = json.loads(IDL_PATH.read_text())
|
|
by_name = {i["name"]: i for i in idl["instructions"]}
|
|
for name, disc in (
|
|
("buy_v2", pump_v2.BUY_V2_DISCRIMINATOR),
|
|
("sell_v2", pump_v2.SELL_V2_DISCRIMINATOR),
|
|
):
|
|
expected = bytes(by_name[name]["discriminator"])
|
|
if disc != expected:
|
|
problems.append(
|
|
f"pump_v2 {name} discriminator {list(disc)} != IDL {list(expected)}"
|
|
)
|
|
|
|
# Account lists must match the IDL in order and writability, for both
|
|
# quote assets and both mayhem states.
|
|
for quote_mint, label in (
|
|
(pump_v2.WSOL_MINT, "SOL"),
|
|
(pump_v2.USDC_MINT, "USDC"),
|
|
):
|
|
for mayhem in (False, True):
|
|
for name, builder in (
|
|
("buy_v2", pump_v2.build_buy_v2_instruction),
|
|
("sell_v2", pump_v2.build_sell_v2_instruction),
|
|
):
|
|
kwargs = {
|
|
"base_mint": mint,
|
|
"creator": creator,
|
|
"user": user,
|
|
"quote_mint": quote_mint,
|
|
"is_mayhem_mode": mayhem,
|
|
}
|
|
if name == "buy_v2":
|
|
instruction = builder(
|
|
token_amount_raw=1, max_quote_cost_raw=2, **kwargs
|
|
)
|
|
else:
|
|
instruction = builder(
|
|
token_amount_raw=1, min_quote_output_raw=2, **kwargs
|
|
)
|
|
|
|
idl_accounts = by_name[name]["accounts"]
|
|
if len(instruction.accounts) != len(idl_accounts):
|
|
problems.append(
|
|
f"pump_v2 {name} ({label}, mayhem={mayhem}): "
|
|
f"{len(instruction.accounts)} accounts != IDL "
|
|
f"{len(idl_accounts)}"
|
|
)
|
|
continue
|
|
for index, (meta, idl_account) in enumerate(
|
|
zip(instruction.accounts, idl_accounts), start=1
|
|
):
|
|
if meta.is_writable != bool(idl_account.get("writable")):
|
|
problems.append(
|
|
f"pump_v2 {name}[{index}] {idl_account['name']} "
|
|
f"({label}, mayhem={mayhem}): writable "
|
|
f"{meta.is_writable} != IDL "
|
|
f"{bool(idl_account.get('writable'))}"
|
|
)
|
|
|
|
# Cross-check every address against the src/ provider, which the
|
|
# checks above already validated.
|
|
provider = PumpFunAddressProvider()
|
|
token_info = build_token_info(quote_mint, mayhem=mayhem)
|
|
resolved = (
|
|
provider.get_buy_v2_instruction_accounts(token_info, user)
|
|
if name == "buy_v2"
|
|
else provider.get_sell_v2_instruction_accounts(token_info, user)
|
|
)
|
|
layout = _BUY_V2_ACCOUNTS if name == "buy_v2" else _SELL_V2_ACCOUNTS
|
|
for (account_name, _), meta in zip(layout, instruction.accounts):
|
|
# Fee recipients are picked at random from a set, so compare
|
|
# membership rather than identity.
|
|
if "fee_recipient" in account_name:
|
|
continue
|
|
if resolved[account_name] != meta.pubkey:
|
|
problems.append(
|
|
f"pump_v2 {name} {account_name} ({label}, "
|
|
f"mayhem={mayhem}): {meta.pubkey} != src/ "
|
|
f"{resolved[account_name]}"
|
|
)
|
|
|
|
return problems
|
|
|
|
|
|
def main() -> int:
|
|
"""Run all layout and derivation checks.
|
|
|
|
Returns:
|
|
Process exit code (0 on success)
|
|
"""
|
|
all_problems = []
|
|
|
|
for name, layout in (("buy_v2", _BUY_V2_ACCOUNTS), ("sell_v2", _SELL_V2_ACCOUNTS)):
|
|
problems = check_layout(name, layout)
|
|
status = "OK" if not problems else f"{len(problems)} PROBLEM(S)"
|
|
print(f"{name}: {len(layout)} accounts vs IDL -> {status}")
|
|
all_problems.extend(problems)
|
|
|
|
for quote_mint, label in ((WSOL_MINT, "SOL-paired"), (USDC_MINT, "USDC-paired")):
|
|
for mayhem in (False, True):
|
|
problems = check_derivations(quote_mint, mayhem=mayhem)
|
|
tag = f"{label}, mayhem={mayhem}"
|
|
status = "OK" if not problems else f"{len(problems)} PROBLEM(S)"
|
|
print(f"derivations ({tag}) -> {status}")
|
|
all_problems.extend(problems)
|
|
|
|
for name, check in (
|
|
("instruction encoding", check_instruction_encoding),
|
|
("quote config resolution", check_quote_config),
|
|
("cookbook pump_v2 toolkit", check_examples_toolkit),
|
|
):
|
|
problems = check()
|
|
status = "OK" if not problems else f"{len(problems)} PROBLEM(S)"
|
|
print(f"{name} -> {status}")
|
|
all_problems.extend(problems)
|
|
|
|
if all_problems:
|
|
print("\nProblems found:")
|
|
for problem in all_problems:
|
|
print(f" - {problem}")
|
|
return 1
|
|
|
|
print("\nAll v2 account layouts and derivations match the IDL.")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|