* fix(trading): sell the exact raw token count the buy received
The buy read the raw token count off its transaction, kept it as a float, and
the sell rebuilt it with int(amount * 10**6), which for some counts comes out
one raw unit short and leaves dust in the token account. The raw count now
travels on TradeResult and Position to the seller, and an exact-in buy converts
its configured spend through its decimal text.
* fix(trading): keep the exact token count when the spend cannot be read
* fix(trading): price an exact-in buy from its spend when the spend can't be read
A graduated curve takes no trades. Curve managers now report it and refuse a
price, and the trader prices and sells through the platform's post-graduation
market: the canonical PumpSwap pool for pump.fun, the Raydium CPMM pool for
LaunchLab. Both pools are derived from the mint.
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
buy_v2 takes an exact token count and caps the quote cost. The trader passed
the slippage-reduced floor meant for exact-in programs as that count, so every
pump.fun buy received token_amount * (1 - slippage). Slippage now goes on the
cost ceiling only.
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
letsbonk.fun and StonkFun now share one LaunchLab implementation that prices
from real reserves, trades any quote mint, spends exactly the buy amount, and
accounts for the curve fee and Token-2022 transfer fees. Cleanup harvests
withheld fees before closing an account.
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* 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>
* fix(monitoring): skip token creates whose transaction reverted
logsSubscribe delivers the logs a transaction emitted before it reverted,
so a CreateEvent decoded from one describes a mint that was never created.
The buy then fails at the ATA-create instruction with IncorrectProgramId,
which reads as a token-program fault rather than a detection one.
The blocks listener already guarded on meta.err; geyser excludes failed
transactions server-side. Shreds is pre-execution and has no meta.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(platforms): build the buy from the migrated bonding-curve creator
A coin with creator-fee sharing has its BondingCurve.creator overwritten
with the sharing-config PDA in the same transaction that creates it, while
CreateEvent.creator still reports the submitting wallet. buy_v2 derives
creator_vault from the curve's value, so a buy built from the event passed
the wrong vault and reverted with ConstraintSeeds.
The migration announces what it wrote in the same log set the CreateEvent
came from, so reading it there costs no RPC call and extreme_fast_mode
keeps its zero-RPC path. Covers the logs, blocks and geyser listeners,
which share the parser; shreds sees no logs and is unchanged.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(platforms): honour only pump.fun's own create and creator events
Program data lines name no program, so any program sharing the
transaction could emit a matching discriminator. A forged CreateEvent
makes the bot buy a mint that was never created; a forged creator
rewrite picks the account the buy derives its vault from and reverts it.
Attribute each log line to the invocation that emitted it and ignore
the rest, falling back to the old behaviour only for a reconstructed
log list that carries no frames.
The ordinary-create check compared the parser against its own output;
it now decodes CreateEvent.creator from the logs independently.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* chore(monitoring,platforms,tools): retire the pumpportal listener
Remove the third-party feed from the bot, the cookbook and the listener
race. It sampled rather than covered the chain, and was the one listener
that could never set state_from_event, so every buy paid the pre-buy
curve read.
Rescope the two buy-path verifiers that used it as a stand-in for a
TokenInfo without state_from_event.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* style(trading): rewrap a docstring paragraph
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
The logs create gate tested the marker as a substring. Anchor writes
`Instruction: <Name>` for every program, so it also accepted
CreateTokenAccount, CreatePool and the rest from whichever programs shared the
transaction. The CreateEvent check downstream rejected them, but a
CreateTokenAccount veto had been added to suppress them and, being a
whole-transaction test, it also dropped genuine creates whose transaction
opened a token account. Matching the marker lines whole retires the veto.
compare_listeners' PumpPortal lane ignored the payload's `pool` field, so
letsbonk creates raced as pump.fun coins against lanes that subscribe to the
pump.fun program alone. The lane now reports `pool: "pump"` only.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
shreds is one of the bot's listeners but was missing from the comparison. It
subscribes on the mint-authority PDA rather than the program id, walks top-level
instructions only, and resolves lookup-table accounts off the update itself,
since a pre-execution stream carries no meta.
The window is now a --duration flag (default 60s) rather than a module constant.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(trading): balance task_done against get in the token queue processor
`_process_token_queue` called `task_done()` from a `finally` that also runs
when `queue.get()` itself is cancelled, at which point no item was taken, so
the call was unbalanced and raised:
ValueError: task_done() called too many times
Cancelling that task is how `start()` shuts yolo mode down, and the
cancellation almost always lands while parked on `get()`. `start()` catches
only `CancelledError` around the await, so the ValueError reached the outer
handler and every clean yolo-mode shutdown was logged as `Trading stopped due
to error` with a traceback. Nothing was lost, since `_cleanup_resources()`
still ran, but the log said a good run had failed.
Track whether an item was taken and call `task_done()` only then. The
stale-token `continue` path did take one and still calls it, or `join()` would
never return.
Closes#210
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(monitoring): stop logging a normal WebSocket close as a ping error
Every WebSocket listener runs a `_ping_loop` that caught `CancelledError` and
then fell through to a broad `except Exception: logger.exception("Ping error")`.
When the connection closes normally, `websocket.ping()` raises
`ConnectionClosedOK` or `ConnectionClosedError` — neither is a `CancelledError`,
so both landed in the broad handler and printed a traceback at ERROR:
ERROR:monitoring.universal_logs_listener:Ping error
websockets.exceptions.ConnectionClosedError: sent 1000 (OK); no close frame received
Close code 1000 is a normal closure. Nothing was wrong, but a completed run
reported a failure to anyone reading the logs or alerting on ERROR.
Catch `ConnectionClosed` before the broad handler and exit the loop at debug.
The broad handler stays for anything genuinely unexpected.
#206 had narrowed the race by cancelling the ping task in a `finally` on the
read loop, but the ping can still fire between the connection closing and the
cancellation landing, and a server-initiated close always reached the loop this
way. The pumpportal listener has the same loop and is fixed here too.
Closes#203
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(cookbook,tools): reject payloads that are not the migration event
`parse_migrate_instruction` skipped the first 8 bytes as a discriminator but
never checked them, so every `Program data:` line in a migration transaction
was decoded against the migration schema whatever event it actually was. The
schema needs 301 bytes; any payload at least that long came back as a fully
populated dict of meaningless values rather than as a failure — a
`baseMintDecimals` of 176 where the field can only legitimately be 0-9. Shorter
payloads happened to fail inside `struct.unpack`, which is why the underrun was
never the visible symptom.
The event is the wrapper program's `CreatePoolEvent`, not the
`CompletePumpAmmMigrationEvent` in `idl/pump_fun_idl.json` — confirmed against
mainnet, where every payload the program emits carries discriminator
`b1310cd2a076a774`, which is `sha256("event:CreatePoolEvent")[:8]`. Assert it
before reading any field. The field layout itself was already correct.
Both copies of the decoder are fixed. In the cookbook script, `parsed_data` was
also reassigned on every `Program data:` line, so a later non-matching line
would wipe a good parse now that the guard returns None; keep the first match.
Closes#198
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* refactor(cookbook): declare BondingCurveState fields instead of __dict__.update
The class assigned its parsed fields through `self.__dict__.update(...)`. The
fields were correct at runtime, but nothing declared them, so type checkers and
editors could not see them: reading `state.virtual_token_reserves` in any
consumer produced an "attribute is unknown" warning, with no autocomplete and
no go-to-definition for any reserve field.
Declare the fields and assign them from the parse result. Where several struct
versions share the leading fields, pick the struct in the branch and assign
once after it, so the optional trailing fields resolve through one `.get` each
rather than through a pre-set default that a later update may or may not
overwrite. This also drops construct's `_io` from the instance dict.
No behaviour change: parsed state for a live curve is identical field for field
before and after, across all three classes. `src/` is unaffected — its curve
manager works on plain dicts and never used this class.
Closes#204
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* fix(trading): finish shutdown cleanup through the cancellation that triggered it
`start()` reclaims account rent from a `finally` that awaited
`_cleanup_resources`. Shutdown reaches that coroutine as a cancellation, and
cleanup awaits once per account — a settle wait, then an RPC read — so the first
of those re-raised `CancelledError` and every account after it kept its rent.
The run then ended without even logging that it shut down, so nothing in the log
said cleanup had been cut short.
Seen on a live run interrupted during the settle wait: it stopped after two of
its accounts. Three other runs interrupted a moment earlier finished cleanly, so
this is a race rather than a certainty.
Run cleanup as its own task and wait through the cancellation with
`asyncio.wait`, which neither cancels the task on timeout nor re-raises what it
failed with. Bounded by `_CLEANUP_SHUTDOWN_BUDGET` so a stuck RPC cannot hold
the process open; rent left behind is recoverable, so the warning names
`tools/cleanup_accounts.py` rather than retrying here.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Prices, exit targets and PnL printed "SOL" for every coin. They now use the
quote mint's symbol, promoted to `core.pubkeys.quote_symbol`, and `get_pnl`
returns `unrealized_pnl_quote`.
Also deletes seven uncalled methods that converted with `LAMPORTS_PER_SOL` or
a hardcoded base unit, and adds a verifier to stop them returning. It covers
`core/`, `trading/` and `platforms/pumpfun/`; letsbonk still scales prices by
a SOL literal, and the verifier records which sites and why it stops there.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Only the buy path's quote gate kept a guessed power of ten off the chain.
`quote_decimals` now raises, `cached_quote_units` returns None for the curve
decoder, and `resolve_quote_token_program` no longer short-circuits before
reading decimals. The buy validates its price after the gate.
verify_quote_decimals_resolved gains four checks and now covers src/.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
QuoteControl admits mints from 4 to 12 decimals, so the default was wrong
for most quote assets and silently so. Parsers return raw quote reserves;
callers scale off the mint account.
Same class elsewhere: pumpswap refuses non-SOL-quoted pools instead of
capping in the wrong unit, letsbonk exact_out/exact_in scale by
base_decimals, wallet_trades decodes through to quote_mint (fixing an
ix_name offset that left later fields three bytes short), balances read at
confirmed, cleanup_accounts takes a required mint.
Verified on mainnet with real funds; wallet left holding SOL only.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>