978946f8ed fix(trading,monitoring,cookbook): keep clean shutdowns clean, guard the migration decoder (#228)
* 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>
2026-09-25 14:28:43 +02:00
2025-04-30 13:38:32 +02:00
2025-01-07 08:26:19 +07:00

Labs

Chainstack is the leading suite of services connecting developers with Web3 infrastructure

• Homepage • Supported protocols • Chainstack blog • Blockchain API reference •
• Start for free •

A Solana trading bot for pump.fun and letsbonk.fun. It watches for token creation, buys, and exits on a strategy you configure. cookbook/ holds one standalone script per action, useful on their own even if you never run the bot.

For the full walkthrough, see Solana: Creating a trading and sniping pump.fun bot. It lags behind the code, so treat this README as the source of truth for setup and configuration.

Also by Chainstack — if you prefer a terminal interface or want to give an AI agent trading capabilities:

  • pumpfun-cli — CLI for trading, launching, and managing tokens on pump.fun; buy, sell, wallet management, and smart routing between the bonding curve and PumpSwap AMM.
  • pumpclaw — agent skill that equips AI assistants (OpenClaw, Claude Code, Cursor, Codex) with the ability to operate pumpfun-cli.

🚨 SCAM ALERT: The Issues section is regularly targeted by scam bots that try to redirect you to an external site and drain your funds. A GitHub Action tags the common patterns, which is not 100% accurate. Deleted comments in issues are scam bots after your private keys — genuine outside devs are welcome and appreciated.

⚠️ NOT FOR PRODUCTION: This code is for learning purposes only. We assume no responsibility for the code or its usage. Modify it for your needs and learn from it — the examples, issues, and PRs contain valuable insights.


Getting started

1. Prerequisites

Install uv, a fast Python package manager. The project needs Python 3.11+; uv uses an existing install if it's new enough, otherwise it fetches one for you.

2. Clone and install

git clone https://github.com/chainstacklabs/pumpfun-bonkfun-bot.git
cd pumpfun-bonkfun-bot

uv sync                        # create .venv and install dependencies
source .venv/bin/activate      # Unix/macOS — Windows: .venv\Scripts\activate
uv pip install -e .            # install the bot as an editable package

3. Set your credentials

cp .env.example .env

Fill in .env:

Variable Purpose
SOLANA_NODE_RPC_ENDPOINT HTTPS RPC endpoint
SOLANA_NODE_WSS_ENDPOINT WebSocket endpoint (for logs / blocks listeners)
SOLANA_PRIVATE_KEY Base58 private key of the trading wallet
GEYSER_ENDPOINT, GEYSER_API_TOKEN, GEYSER_AUTH_TYPE For the geyser and shreds listeners (same endpoint, different RPC)

Public RPC nodes will not work for this workload — see throughput below.

4. Configure a bot

Each YAML file in bots/ is one bot instance. They ship with commented defaults; start from the one matching the listener you want:

File Listener Ships with
bot-sniper-1-geyser.yaml geyser — fastest, needs a Geyser endpoint pump_fun
bot-sniper-2-logs.yaml logs — logsSubscribe, supported everywhere pump_fun
bot-sniper-3-blocks.yaml blocks — blockSubscribe, not supported by every provider pump_fun
bot-sniper-4-pp.yaml pumpportal — third-party aggregator, misses some coins lets_bonk
bot-sniper-5-shreds.yaml shreds — pre-execution, ahead of geyser, cannot see router-created coins pump_fun

Set platform: "pump_fun" or platform: "lets_bonk". pump.fun supports all five listeners; letsbonk.fun supports blocks, geyser, and pumpportal but not logs or shreds. The bot validates the pairing at startup and refuses to run an invalid one.

pumpportal is a third-party feed and only reports what it indexes — it does not push coins whose creation landed in a Solana transaction v1, so it sees a sample rather than everything. geyser, logs and blocks read the chain directly and are unaffected.

Set enabled: false to keep a config around without running it. Every bot with enabled: true starts when you run the bot.

5. Run

pump_bot                   # as an installed package
uv run src/bot_runner.py   # or directly

Logs land in logs/{bot_name}_{timestamp}.log.

Configuration reference

The YAML files are commented inline. The sections that matter most:

  • trade — buy_amount (in SOL), slippage, exit_strategy (time_based, tp_sl, manual), and extreme_fast_mode.
  • priority_fees — fixed or dynamic. Dynamic costs an extra RPC call, which slows the buy.
  • filters — listener_type, max_token_age, name/creator matching, marry_mode (buy only, never sell), yolo_mode (trade continuously).
  • retries — attempts and the wait windows around creation, buy, and the next token.
  • cleanup — when to close leftover token accounts: disabled, on_fail, after_sell, post_session.
  • node.max_rps — cap requests per second to match your provider's plan.

Extreme fast mode

With extreme_fast_mode: true the bot buys a fixed token amount (extreme_fast_token_amount) instead of reading the curve price first. You give up knowing what you paid per token; you get the buy submitted sooner.

How much sooner depends on the listener. With geyser, logs or blocks the bot makes no RPC call at all between detecting the token and submitting the buy. pumpportal does one account read first, because its payload is missing fields the buy needs.

Two knobs:

  • curve_refresh_budget (seconds, default 2.0) — how long that read may take before the bot gives up and skips the token. Raise it to buy more coins on a slow endpoint, lower it to skip faster.
  • trust_create_event (default true) — set false to make every listener do the read, giving up the zero-RPC path.

Non-SOL quote assets

pump.fun supports quote assets other than SOL, USDC first. Amounts are in that mint's own whole units, so usdc: 1.0 is one USDC and is not comparable to buy_amount:

trade:
  buy_amount: 0.0001    # SOL-paired coins
  quote_amounts:
    usdc: 1.0           # USDC-paired coins

filters:
  allowed_quote_mints: ["sol", "usdc"]   # omit to allow any configured quote

Keys accept the aliases sol / wsol / usdc or a raw base58 mint. A coin whose quote mint has no configured amount is skipped rather than bought with a wrongly-scaled amount, so a config that lists nothing here trades SOL-paired coins only. Buying a USDC-paired coin needs USDC in the wallet plus a little SOL for fees and ATA rent.

Cookbook

cookbook/ is one script per thing you might want to do. Each runs on its own with uv run <path>, reads .env directly, and needs no bot config. cookbook/README.md is the index; the shape is:

Directory What is in it
cookbook/pumpfun/listen/ One script per detection method — logs, blocks, geyser, pumpportal — plus wallet watching
cookbook/pumpfun/read/ Price, curve state, graduation progress, address derivation
cookbook/pumpfun/trade/ Buy, sell, create, and the two sniping variants
cookbook/pumpfun/graduation/ Coins approaching graduation, and migrations to PumpSwap
cookbook/pumpfun/decode/ Account data and transactions, against committed fixtures
cookbook/solana/ Chain-level basics: balances, transaction status, Anchor discriminators
cookbook/pumpswap/ Pool discovery and manual buy/sell on the AMM
cookbook/letsbonk/ Exact-in / exact-out buys and sells on letsbonk.fun
cookbook/legacy/ Instructions pump.fun has moved on from

The quickest way in:

uv run cookbook/solana/solana_read_balances.py               # what you hold
uv run cookbook/pumpfun/read/pumpfun_read_price.py <CURVE>   # what it costs
uv run cookbook/pumpfun/trade/pumpfun_buy_token_v2.py <MINT> --dry-run

A filename tells you the chain, the action and the instruction version before you open it. Scripts that spend real funds say so on the first line of their docstring. The decode scripts run with no arguments, against the fixtures beside them.

Related docs: Listening to pump.fun migrations · Sniping with only logsSubscribe

Regression checks

tests/regression/ holds one offline script per fixed bug, each naming the bug in its docstring. They move no funds. Run them after any change to src/, and after a pump.fun program upgrade:

uv run tests/regression/run_all.py                      # the whole set
uv run tests/regression/verify_v2_account_layout.py     # account layouts, PDAs, encoding
uv run tests/regression/verify_curve_account_sizes.py   # 125/151/256-byte curves all decode
uv run tests/regression/verify_tx_status_checks.py      # every path reads meta.err

Development tools

tools/ holds the scripts used to exercise the bot rather than teach it. They import src/ and several of them spend real funds — read the module docstring first.

uv run tools/simulate_v2_trades.py <MINT>    # mainnet simulation, no funds moved
uv run tools/simulate_bot_buy_path.py        # the bot's buy path against a fresh coin, no funds moved
uv run tools/compare_listeners.py            # race all four listeners against each other
uv run tools/compare_migration_listeners.py  # race the two migration detection methods
uv run tools/cleanup_accounts.py [MINT]      # close leftover token accounts — submits transactions
uv run tools/live_v2_round_trip.py --yes     # real buy_v2 + sell_v2 — SPENDS REAL FUNDS
uv run tools/live_listener_matrix.py --yes   # real round trip per listener — SPENDS REAL FUNDS

Throughput and rate limits

Every node provider has its own limits — method availability, requests per second, plan-specific caps. Consult your provider's docs before running the bot, and don't expect public RPC nodes to hold up. For Chainstack, see the throughput guidelines.

getProgramAccounts over the whole pump.fun program is no longer served by anyone: it owns more than 10 million accounts, so providers reject the request or time out whatever filters you pass. Use a filtered subscription instead — cookbook/pumpfun/graduation/pumpfun_watch_graduating_programsubscribe.py shows the pattern.

The bot rate-limits itself with a token bucket: node.max_rps (25 by default) smooths the request rate while allowing short bursts, and 429s are retried with exponential backoff.

For faster execution, Chainstack offers Solana Trader nodes for transaction propagation and the Yellowstone gRPC Geyser plugin for streaming updates.

IDLs

The IDLs under idl/ are vendored from pump-fun/pump-public-docs — currently upstream commit 8109141. To refresh, copy pump.json, pump_amm.json, and pump_fees.json into pump_fun_idl.json, pump_swap_idl.json, and pump_fees.json, and note the upstream commit in your commit message. Don't hand-edit them.

The buy_v2 / sell_v2 account lists are complete in the IDL. The legacy buy / sell lists are not — the IDL omits PDAs the on-chain program requires, so cross-check anything outside v2 against a recent successful on-chain transaction.

docs/pumpfun-protocol.md documents the protocol gotchas in detail — account layouts, quote-mint handling, fee recipients, and what the IDL gets wrong.

Contributing

Maintainers are listed in MAINTAINERS.md. Open an Issue for feedback or bugs.

Lint and format the files you changed (uv sync installs ruff for you):

uv run ruff check --fix path/to/changed.py
uv run ruff format path/to/changed.py

Running ruff check over the whole repo reports a large backlog of pre-existing errors — that's a known baseline, so scope it to your own files.

Then test your change with a cookbook script rather than by running a bot with real funds.

Languages
Python 100%