Files
pumpfun-bonkfun-bot_github/tests/regression/verify_quote_decimals_resolved.py
T
75d9087d05 feat(cookbook): launch any coin create_v2 supports, as a v0 or a v1 transaction (#234)
* feat(cookbook): cover every create_v2 coin parameter in the launch scripts

Both create scripts now build create_v2 through pumpfun_instructions_v2
instead of each carrying their own copy of the discriminators, PDAs and
account list.

- A holder-reward coin's curve creator is derived rather than assumed, so
  the opening buy finds the matching creator vault instead of reverting.
- create_v2's three trailing arguments are settable independently. None
  omits an argument, a value sends it, so all four wire forms are
  reachable and an explicit default is distinct from an omission.
- create_v2 carries all four remaining accounts, quote_control included.
  Without them the program ignores creator_fee_bps.
- --creator, --creator-fee-bps and --quote-mint added. A creator fee on a
  SOL-paired coin warns, because the program stores zero for it; the
  create-and-buy script refuses one outright before sending anything.
- The opening buy is sized from Global's reserves and fee rates.
- Mayhem mode is off by default.

Removes the fee-recipient lookup whose result was discarded and the buy
wrapper whose parameters were unused.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(regression): verify the launch path's create_v2 arguments

Eight offline checks: the substituted creator on a holder-reward coin,
every committed create_v2 fixture round-tripping through the trailing
argument encoder, all four wire forms being reachable, --creator reaching
the wire, the opening buy following Global rather than constants, the
Global decoder stopping cleanly on a short buffer, and the four quote
accounts being present with the ATA under the quote mint's own program.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs: correct create_v2's remaining accounts and the creator-fee rule

create_v2 takes four remaining accounts, not three; the fourth is the
QuoteControl PDA. Omitting them is accepted and yields a SOL-paired coin,
which is also how a creator fee goes missing: the program applies
creator_fee_bps only to a coin priced in something other than SOL, and
otherwise stores zero without an error.

Also records that solders documents TransactionConfig.priority_fee as
micro-lamports while SIMD-0385 defines the field as total lamports.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(cookbook): price a new coin in an asset other than SOL

--quote-mint on both create scripts, checked against both registries that
admit a quote asset. QuoteControl carries most of them with a per-mint
opening reserve; Global.whitelisted_quote_mints carries USDC, which
QuoteControl does not list, so consulting either alone refuses a mint the
program accepts. A mint neither admits is refused rather than priced from
a default, since the opening reserve spans orders of magnitude.

The quote mint's token program and decimals are resolved from chain, and
--amount is denominated in the quote asset rather than in SOL. A paused
mint is refused before anything is sent, and a scaled-UI mint says so,
because amounts here are raw units.

A creator fee now works, since pump.fun applies one only to a coin priced
in something other than SOL. On a SOL-paired coin it is refused instead of
being accepted and stored as zero.

The create-and-buy script requires the wallet to already hold the quote
asset; it does not acquire one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(cookbook): launch a coin in one v1 transaction

Create, extend, the buyer's token account and the buy now travel under a
single signature, so nobody can buy between the create and the opening
buy. They were split because the two together are 1479 bytes against the
1232 a v0 transaction is held to; SIMD-0296 raised the limit to 4096 for
v1 and the combined message uses about a third of it.

v1 has no address lookup tables -- the larger limit exists so the whole
account list goes inline -- and it carries the compute budget in the
message header, so the script sends no ComputeBudget instructions. The
priority fee is now one total in lamports rather than micro-lamports per
compute unit; the constant is converted, not renamed.

The two-transaction path is removed rather than kept behind a flag.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(cookbook): state the loaded-accounts data size limit on the v1 launch

A v1 message carries this limit in its header, and left unset it is zero
rather than the network default, so the runtime rejects the transaction
for exceeding it. The launch skips preflight, so the rejection never
reached the caller: send returned a signature that never landed.

Measured against a forked mainnet, the launch is rejected at 128 KiB and
lands at 256 KiB. The limit is set to 1 MiB, which leaves room for a quote
mint whose accounts are larger, and the verifier fails if it is dropped or
set at or below the measured failing size.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(cookbook): offer the launch as a v0 or a v1 transaction

The Solana transaction version changes what a launch can be, so it is the
script that changes rather than a flag on one of them.

_txv1 sends create and buy under a single signature, so the coin is bought
by the transaction that creates it. _txv0 sends them as two transactions,
because together they do not fit what a v0 transaction can carry, and
anyone watching the create can buy in the gap. Use it when the endpoint
will not take a v1 send.

The coin is identical either way: quote asset, creator fee, holder rewards
and mayhem mode all behave the same.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(cookbook): drop the instruction version from script names

The cookbook ships one form of each pump.fun action, so `_v2` in a
basename distinguished nothing — and it read as a Solana transaction
version, which is a different thing and now appears in the same names.
`pumpfun_buy_token_exact_sol_in.py` already went without it.

Every trade script loses the suffix, the shared module becomes
`pumpfun_instructions.py`, and the retired path is named for what it is
rather than for the instruction set it uses. The instruction each script
builds is named in its docstring, where it cannot be mistaken for a
transaction version. `txv0`/`txv1` is now the only version marker in any
filename, and it is the one the reader chooses between.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(cookbook): refuse mayhem mode paired with a non-SOL quote asset

The program rejects the pairing with MayhemModeQuoteMintNotAllowed (6071),
so a mayhem coin is always SOL-paired — and therefore can never carry a
creator fee, which needs a non-SOL quote. Both create scripts now refuse
the combination before sending, rather than letting it land as a reverted
transaction that has already cost fees.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(cookbook): size the v1 loaded-accounts limit for what mainnet loads

The limit counts the executable data of every program a transaction
touches, not just the accounts it names, and the pump program's own code
is the bulk of it. The previous figure was set against a local fork, which
does not charge for executables; on mainnet the launch was rejected with
MaxLoadedAccountsDataSizeExceeded.

Set to the network default a v0 transaction gets when nothing narrows it,
which is the behaviour being reproduced. The verifier now holds the
mainnet figure as its floor.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(cookbook): a creator fee needs a QuoteControl quote mint, not just a non-SOL one

Measured on mainnet: the fee is applied on a coin priced in a mint
QuoteControl admits, whether that mint is SPL Token or Token-2022, and is
not applied on wrapped SOL or on USDC — which the older Global whitelist
carries and QuoteControl does not. The deciding property is registry
membership, so the previous check let a USDC-priced coin through and the
program stored zero without an error.

Also stops the sell script calling a price "SOL" when the curve is priced
in something else.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(cookbook): offer the create-only script as a v0 or a v1 transaction

Same split as the create-and-buy pair, for the same reason: the Solana
transaction version is the reader's choice, so it is the script that
changes rather than a flag. _txv1 carries the compute budget in the
message header and sends no ComputeBudget instructions; _txv0 sends them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(cookbook): refuse a paused quote mint on the create-and-buy path too

The check only ran in the create-only scripts, so a launch that also buys
could reach the chain with a quote mint whose transfers are paused. On the
two-transaction path that leaves a created coin nobody bought, after the
create has already cost rent.

Also corrects the v1 script's run docstring, which still described two
transactions and a spend denominated in SOL.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(cookbook): say --amount is in whole quote units, not raw ones

The scaled-UI notice told the reader the opposite of what the scripts do:
--amount is multiplied by the mint's decimals, so it is a whole-token
figure. A reader who followed the notice would have overspent by a factor
of the decimals.

Reworded so the multiplier is described as what it is — a display scale a
wallet applies — rather than as something the amount has to account for.
The create-only scripts carried the same wording without even taking an
amount.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-28 08:48:31 +02:00

352 lines
14 KiB
Python

"""Verify no trade path prices a coin before resolving its quote mint.
pump.fun's quote assets are not just SOL and USDC. The `QuoteControl` registry
(PDA `["quote-control"]`) admits mints anywhere from 4 to 12 decimals — 8 for
Backed's xStocks, 6 for Backpack Securities — and coins paired with them trade
live.
`quote_units()` used to default to 9 decimals for an unresolved mint. Every
cookbook trade script called it *before* `resolve_quote_token_program()` warmed
the decimals cache, so every one of those coins was sized against the wrong
power of ten:
xStock (8 decimals) -> cap and size 10x too large
Backpack (6 decimals) -> cap and size 1000x too large
The error does not cancel. `price_per_token()` divides the quote reserves by the
same wrong unit, so the price comes out low by the same factor, the token amount
comes out high by it, and the inflated cap authorises the overspend instead of
catching it.
The bot carried the same default long after the cookbook stopped: `quote_units_per_token`
returned 9 for an unresolved mint, and only the buy path's quote gate kept a
mispriced trade off the chain. Checks E through G cover `src/` so the guarantee
lives in the function rather than in two call sites.
Offline machine checks, no network and no funds moved:
A. `quote_units()` raises for a mint whose decimals are unknown, rather than
assuming 9, and returns the right value once resolved.
B. `resolve_quote_token_program()` caches decimals off the same account read
it makes for the token program, so resolving costs no extra RPC call.
C. Every cookbook script that calls `quote_units` or `price_per_token` calls
`resolve_quote_token_program` first, checked per function body.
D. Nothing in `cookbook/` or `src/` falls back to a literal decimal count for
a quote mint. The table name is matched on containing DECIMAL, not ending
in it: the bot's default sat on `_QUOTE_DECIMALS_CACHE`, which an
endswith test walks straight past.
E. `quote_units_per_token()` raises for an unresolved mint, and
`cached_quote_units()` answers None instead, for decoders that must not
fail on a coin nobody trades.
F. `QUOTE_TOKEN_PROGRAMS` and `QUOTE_DECIMALS` carry the same mints. A mint in
the first alone short-circuits resolution before its decimals are read.
G. The buy path resolves its spend amount before it sizes with a quote unit.
The sell path deliberately does not: it liquidates a position already held,
against a mint inherited from the buy, and gating it on a configured buy
amount would strand that position whenever a config changed.
Usage:
uv run tests/regression/verify_quote_decimals_resolved.py
"""
import ast
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"))
import pumpfun_instructions as pump # noqa: E402
from solders.pubkey import Pubkey # noqa: E402
from core import pubkeys as core_pubkeys # noqa: E402
COOKBOOK = PROJECT_ROOT / "cookbook"
SRC = PROJECT_ROOT / "src"
# A real Token-2022 tokenized equity: Apple xStock, 8 decimals, admitted through
# QuoteControl rather than Global's whitelist.
AAPLX = Pubkey.from_string("XsbEhLAtcf6HdfpFZ5xEMdqW8nfAvcsP5bdudRLJzJp")
AAPLX_DECIMALS = 8
class _FakeMintAccount:
"""The two fields `resolve_quote_token_program` reads off a mint account."""
def __init__(self, owner: Pubkey, decimals: int) -> None:
"""Build a mint account whose data carries `decimals` at offset 44.
Args:
owner: Token program that owns the mint
decimals: Decimal count to place at the mint layout's fixed offset
"""
self.owner = owner
data = bytearray(82)
data[44] = decimals
self.data = bytes(data)
def check_unresolved_mint_raises() -> None:
"""An unknown quote mint must fail loudly, never default to 9 decimals."""
assert AAPLX not in pump.QUOTE_DECIMALS, "fixture mint must start unknown"
try:
pump.quote_units(AAPLX)
except ValueError as exc:
assert "resolve_quote_token_program" in str(exc), (
f"the error must say how to fix it, got: {exc}"
)
else:
raise AssertionError(
"quote_units() returned a value for an unresolved mint; a wrong "
"power of ten here oversizes the trade instead of capping it"
)
# The pre-seeded pair still answers without a lookup.
assert pump.quote_units(pump.WSOL_MINT) == 10**9
assert pump.quote_units(pump.USDC_MINT) == 10**6
async def check_resolution_caches_decimals() -> None:
"""Resolving the token program must cache decimals from the same read."""
reads = []
async def get_account(address: Pubkey) -> _FakeMintAccount:
reads.append(address)
return _FakeMintAccount(pump.TOKEN_2022_PROGRAM, AAPLX_DECIMALS)
program = await pump.resolve_quote_token_program(AAPLX, get_account)
assert program == pump.TOKEN_2022_PROGRAM, program
assert pump.quote_units(AAPLX) == 10**AAPLX_DECIMALS, (
"decimals were not cached by the token-program resolution"
)
assert len(reads) == 1, f"expected one account read, made {len(reads)}"
# Second call must be free.
await pump.resolve_quote_token_program(AAPLX, get_account)
assert len(reads) == 1, "a resolved mint was fetched again"
def _called_names(node: ast.AST) -> list[tuple[str, int]]:
"""Every call made inside one function body, as (name, line).
Args:
node: The function definition to walk
Returns:
Called attribute/function names paired with their line numbers
"""
out = []
for sub in ast.walk(node):
if not isinstance(sub, ast.Call):
continue
fn = sub.func
name = fn.attr if isinstance(fn, ast.Attribute) else getattr(fn, "id", None)
if name:
out.append((name, sub.lineno))
return out
def check_scripts_resolve_before_pricing() -> None:
"""No cookbook script may size or price a trade before resolving.
Checked per function body, not per file: a module-level helper that wraps
`price_per_token()` is defined above the trade path that calls it, so plain
source order reads as a violation when the runtime order is fine.
"""
offenders = []
for path in sorted(COOKBOOK.rglob("*.py")):
source = path.read_text()
# Only scripts that share the helper module's cache are in scope here.
# Scripts carrying their own arithmetic are covered by
# check_no_assumed_quote_decimals instead.
if "pumpfun_instructions" not in source:
continue
tree = ast.parse(source)
for node in ast.walk(tree):
if not isinstance(node, ast.AsyncFunctionDef | ast.FunctionDef):
continue
calls = _called_names(node)
sizing = [
ln for name, ln in calls if name in {"quote_units", "price_per_token"}
]
resolving = [
ln for name, ln in calls if name == "resolve_quote_token_program"
]
if not sizing:
continue
where = f"{path.relative_to(PROJECT_ROOT)}:{node.name}"
if not resolving:
# Fine only if this function never sizes a trade itself, i.e. it
# is a pure helper whose caller resolves. Those take the curve
# state as an argument rather than fetching it.
if any(name == "quote_units" for name, _ in calls):
offenders.append(f"{where}: sizes without resolving")
elif min(sizing) < min(resolving):
offenders.append(
f"{where}: prices at line {min(sizing)}, "
f"resolves at line {min(resolving)}"
)
assert not offenders, "trade paths price before resolving:\n " + "\n ".join(
offenders
)
def check_no_assumed_quote_decimals() -> None:
"""No script or bot module may fall back to a literal decimal count.
`QuoteControl` admits mints from 4 to 12 decimals, so the literal is wrong
for most quote assets and silently so. A two-argument `.get` on a decimals
table is the defect whatever the default is; read the mint instead.
The table name is matched on containing DECIMAL rather than ending in it.
The bot's own default was `_QUOTE_DECIMALS_CACHE.get(quote_mint, 9)`, which
an endswith test reports as clean.
"""
_GET_WITH_DEFAULT_ARGC = 2 # dict.get(key, default)
offenders = []
trees = [*sorted(COOKBOOK.rglob("*.py")), *sorted(SRC.rglob("*.py"))]
for path in trees:
if "generated" in path.parts:
continue
for node in ast.walk(ast.parse(path.read_text())):
if (
not isinstance(node, ast.Call)
or len(node.args) != _GET_WITH_DEFAULT_ARGC
):
continue
func = node.func
if not isinstance(func, ast.Attribute) or func.attr != "get":
continue
table = func.value
if not isinstance(table, ast.Name) or "DECIMAL" not in table.id.upper():
continue
offenders.append(
f"{path.relative_to(PROJECT_ROOT)}:{node.lineno}: "
f"{table.id}.get(..., <default>)"
)
assert not offenders, (
"quote decimals assumed rather than resolved:\n " + "\n ".join(offenders)
)
def check_core_unit_helper_raises() -> None:
"""The bot's own unit helper must refuse an unresolved mint too.
The buy path's quote gate keeps an unconfigured mint off the chain, but that
is a property of two call sites rather than of the helper. A helper that
answers 9 for anything it has not heard of is one refactor away from
mispricing a trade.
"""
unknown = Pubkey.from_string("XsbEhLAtcf6HdfpFZ5xEMdqW8nfAvcsP5bdudRLJzJp")
assert unknown not in core_pubkeys.QUOTE_DECIMALS, "fixture mint must be unknown"
try:
core_pubkeys.quote_units_per_token(unknown)
except ValueError as exc:
assert "resolve_quote_token_program" in str(exc), (
f"the error must say how to fix it, got: {exc}"
)
else:
raise AssertionError(
"quote_units_per_token() answered for an unresolved mint; a wrong "
"power of ten oversizes the trade instead of capping it"
)
# The non-raising variant exists for decoders, and must not guess either.
assert core_pubkeys.cached_quote_units(unknown) is None
assert core_pubkeys.cached_quote_units(core_pubkeys.WSOL_MINT) == 10**9
assert core_pubkeys.quote_units_per_token(core_pubkeys.USDC_MINT) == 10**6
def check_seed_tables_agree() -> None:
"""Every pre-seeded quote mint must carry both facts.
`resolve_quote_token_program` returns early once a mint's token program is
known. A mint seeded into QUOTE_TOKEN_PROGRAMS but not QUOTE_DECIMALS would
take that early return and never have its decimals read -- at startup, right
behind a log line saying it resolved.
"""
programs = set(core_pubkeys.QUOTE_TOKEN_PROGRAMS)
decimals = set(core_pubkeys.QUOTE_DECIMALS)
assert programs == decimals, (
"pre-seeded quote mints disagree:\n"
f" token program only: {sorted(str(m) for m in programs - decimals)}\n"
f" decimals only: {sorted(str(m) for m in decimals - programs)}"
)
def check_buy_resolves_amount_before_sizing() -> None:
"""The buy must clear its quote gate before it scales anything.
Scoped to the buyer by name. The seller sizes without the gate on purpose:
it liquidates a position already held, against a mint inherited from the
buy, so gating it on a configured buy amount would strand that position
whenever a config changed between the two.
"""
source = (SRC / "trading" / "platform_aware.py").read_text()
tree = ast.parse(source)
buyer = next(
(
node
for node in ast.walk(tree)
if isinstance(node, ast.ClassDef) and node.name == "PlatformAwareBuyer"
),
None,
)
assert buyer is not None, "PlatformAwareBuyer not found; update this check"
execute = next(
(
node
for node in buyer.body
if isinstance(node, ast.AsyncFunctionDef | ast.FunctionDef)
and node.name == "execute"
),
None,
)
assert execute is not None, "PlatformAwareBuyer.execute not found"
calls = _called_names(execute)
sizing = [ln for name, ln in calls if name == "quote_units_per_token"]
gating = [ln for name, ln in calls if name == "_resolve_quote_amount"]
assert sizing, "the buy no longer sizes with a quote unit; update this check"
assert gating, "the buy no longer resolves a quote amount; update this check"
assert min(gating) < min(sizing), (
f"the buy sizes at line {min(sizing)} but resolves its quote amount at "
f"line {min(gating)}; an unconfigured quote asset must be refused first"
)
async def main() -> None:
"""Run every check and report."""
print("=" * 72)
print("Verifying quote-mint decimals are resolved before pricing")
print("=" * 72)
checks = [
("an unresolved quote mint raises", check_unresolved_mint_raises),
("resolution caches decimals in one read", check_resolution_caches_decimals),
("every script resolves before pricing", check_scripts_resolve_before_pricing),
("no script assumes a quote mint's decimals", check_no_assumed_quote_decimals),
("the bot's unit helper raises too", check_core_unit_helper_raises),
("pre-seeded quote tables agree", check_seed_tables_agree),
("the buy gates before it sizes", check_buy_resolves_amount_before_sizing),
]
for label, fn in checks:
result = fn()
if result is not None:
await result
print(f"{label} -> OK")
print("\nALL CHECKS PASSED")
if __name__ == "__main__":
import asyncio
asyncio.run(main())