Files
pumpfun-bonkfun-bot_github/tools/cleanup_accounts.py
T
ebbfa9f124 chore(deps): upgrade to solders 0.29 / solana 0.40 and bring the rest of the dependencies current (#217)
* chore(deps): upgrade solders to 0.29 and solana to 0.40 in cookbook and tools

solana 0.40 moves TxOpts (now TxOptsModel), MemcmpOpts and TokenAccountOpts
from solana.rpc.types to solana.rpc.core, and spl.token's *Params dataclasses
to spl.token.models as pydantic models — validated and keyword-only. Three
call sites only failed against mainnet: MemcmpOpts.bytes now takes a base58
str, SyncNativeParams was built positionally, and confirm_transaction was
passed a bare "confirmed".

Also moves every cookbook and tools send path off the legacy Transaction onto
VersionedTransaction + MessageV0, and teaches the getTransaction decoder the
json and base64 encodings alongside jsonParsed — the base64 v1 fixture needs
solders 0.29 to deserialize at all.

src/ is untouched and still on the old imports; the offline suite is 3/19
until that lands.

Verified on mainnet: a 0.003 SOL buy_v2/sell_v2 round trip confirmed and the
wallet returned to SOL only, all six listeners and every read-only script run
live, five trade paths simulated with error=None.

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

* chore(deps): move the bot onto solders 0.29 and solana 0.40

Same three API moves as the cookbook commit, now in src: TxOpts is
TxOptsModel in solana.rpc.core, and spl.token's BurnParams/CloseAccountParams
come from spl.token.models. build_and_send_transaction builds a
VersionedTransaction from MessageV0 with no lookup tables, so the bot no
longer sends a legacy transaction anywhere.

verify_transaction_v1 proved the log route by stripping the logs and expecting
nothing back, which only held while solders could not read a v1 envelope. On
0.29 it can, so the check is inverted: make the envelope unreadable, keep the
logs, and the create must still arrive. A second check pins the envelope
fallback, so a decode regression is reported rather than silently absorbed by
the log route.

Offline: 19/19. Live on mainnet, funds returned:
- tools/simulate_bot_buy_path: zero-RPC buy path, err=None, 107,015 CU
- tools/simulate_v2_trades: buy_v2 95,573 CU, buy+sell 174,190 — both inside
  the existing 180k/120k limits, so no retune
- tools/live_v2_round_trip: buy_v2 + sell_v2 both landed
- tools/live_listener_matrix: all four listeners detected; logs and pumpportal
  ran full round trips; geyser and blocks both drew a coin on an unconfigured
  quote mint and correctly refused to size a buy. Every ATA closed.

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

* chore(deps): bring the rest of the dependencies to current

Every remaining dependency is now at its latest release, with the floors
raised to the versions actually tested rather than the oldest that resolves:

  grpcio        1.73.1 -> 1.84.0    grpcio-tools 1.73.1 -> 1.84.0
  protobuf      6.33.5 -> 7.36.2    uvloop       0.21.0 -> 0.22.1
  pyyaml        6.0.2  -> 6.0.3     python-dotenv 1.2.2 -> 1.2.3
  construct     2.10.70 (floor)     websockets   17.1 (floor)
  ruff          0.12.4 -> 0.16.8

aiohttp and base58 were already current. winloop is left at its old floor:
it is Windows-only and cannot be installed, let alone tested, here.

protobuf 7 arrives with grpcio-tools 1.84 and is the only major. The
committed geyser stubs are gencode 6.31.1 and still pass
ValidateProtobufRuntimeVersion against it; they are not regenerated, because
the committed files import each other absolutely and protoc does not emit
that, so the output would need rewriting. Noted in CLAUDE.md with the
verification date.

ruff 0.16 needs no config change. The repo-wide baseline moves 1680 -> 1713
because the rules moved, not the code; CLAUDE.md carries the new figure so it
is not misread as a regression.

Verified per dependency, not just in aggregate: all four bot configs load
under the new pyyaml/dotenv; the logs, blocks and pumpportal listeners run
under the uvloop policy bot_runner installs; both geyser paths (token
listener and the account-filtered graduation watcher) run under grpcio 1.84 /
protobuf 7. Offline 19/19, including verify_listener_cancellation for
websockets. One more live buy_v2/sell_v2 round trip on the final set, both
landed, ATA closed.

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

* fix(utils): redact RPC credentials from every log record

The provider endpoints carry their API key in the URL and the HTTP clients log
a full request URL at INFO, so anything that raises the root logger to INFO
prints the key. tools/cleanup_accounts.py did, four times, in a terminal.

It was already silencing httpx and httpcore by name. That stopped working the
moment solana-py 0.40 switched to httpx2: the rename took the guard with it
and nothing said so. Naming the clients is now a convenience on top of the
real control — install_secret_redaction masks the value itself, at log-record
creation, whichever logger emits it.

It redacts the *rendered* message rather than record.msg plus the string
arguments. The first version of this did the latter and still leaked: httpx2
passes its URL as a URL object, so the type check skipped the only argument
carrying the key. Confirmed by forcing httpx2 back to INFO and watching the
key print anyway. The host is kept, so a log line still says which provider
answered.

Installed from get_logger, from both logging.basicConfig sites, and from
setup_file_logging before it attaches the handler — logs/ outlives a terminal.

verify_no_rpc_credentials_logged covers all of it, including the non-str
argument. Checked against the defeated version first: it fails there and
passes here. Suite is 20/20.

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

* docs(agents): make a real bot run the verification, not the simulations

The ground rule said never to run a bot with real funds, which points at the
tools/ harnesses instead. Those call the buyer, seller and listeners directly:
they skip bot_runner, config loading, the trader loop, the exit strategy and
cleanup, so passing there says nothing about the paths only a full run reaches.
Verification is a real run, with explicit approval for that session, covering
every mode the change touches and ending with the wallet holding SOL only.

Also records why a run can look clean when nothing happened: pump_bot runs every
bots/*.yaml, three of the four committed configs ship enabled: false, and with
all of them disabled it prints nothing and exits 0. The log file is the tell.

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

* docs(utils): keep the redaction comment provider-neutral

The parameter list is what matters, not which provider uses which spelling.

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

---------

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

166 lines
6.3 KiB
Python

import asyncio
import logging
import os
import sys
from dotenv import load_dotenv
from solders.pubkey import Pubkey
from spl.token.instructions import burn, close_account
from spl.token.models import BurnParams, CloseAccountParams
from core.client import SolanaClient
from core.pubkeys import SystemAddresses
from core.wallet import Wallet
from utils.logger import get_logger, install_secret_redaction
load_dotenv()
# get_logger attaches no handler — the bot installs one at startup, but a
# standalone example has to do it itself or every line below goes nowhere. This
# script ran completely silently, success or failure, without it.
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
# The HTTP clients log each request at INFO and the RPC endpoint carries an API
# key, so raising the root logger to INFO is what leaks it. Naming the clients
# here is not enough — solana-py 0.40 renamed httpx to httpx2 and this script
# went on printing the key for four runs. install_secret_redaction masks the
# value itself, whichever logger emits it.
install_secret_redaction()
logger = get_logger(__name__)
RPC_ENDPOINT = os.getenv("SOLANA_NODE_RPC_ENDPOINT")
PRIVATE_KEY = os.getenv("SOLANA_PRIVATE_KEY")
# Update this address to MINT address of a token you want to close
# Mint of the token account to close: pass as argv[1], or hardcode here.
MINT_ADDRESS = Pubkey.from_string(
sys.argv[1] if len(sys.argv) > 1 else "9WHpYbqG6LJvfCYfMjvGbyo1wHXgroCrixPb33s2pump"
)
# The mint's token program is read from the mint account itself (see
# resolve_token_program). Guessing it derives the wrong ATA address, and the
# script then reports "already closed" for an account that was never looked at.
async def resolve_token_program(client: SolanaClient, mint: Pubkey) -> Pubkey:
"""Return the token program that owns this mint.
A mint account is owned by whichever token program created it, so the mint
itself is the authoritative source. Every pump.fun coin is Token-2022 while
letsbonk coins and USDC are legacy SPL, and the ATA address differs between
them — deriving with the wrong one silently points at an address that does
not exist.
Args:
client: Solana RPC client
mint: Mint address
Returns:
TOKEN_PROGRAM or TOKEN_2022_PROGRAM
Raises:
ValueError: If the mint is missing or owned by something else
"""
info = await client.get_account_info(mint)
owner = info.owner
if owner not in (SystemAddresses.TOKEN_PROGRAM, SystemAddresses.TOKEN_2022_PROGRAM):
raise ValueError(f"Mint {mint} is not owned by a token program (owner {owner})")
return owner
async def close_account_if_exists(
client: SolanaClient,
wallet: Wallet,
account: Pubkey,
mint: Pubkey,
token_program: Pubkey,
):
"""Safely close a token account if it exists and reclaim rent."""
try:
try:
await client.get_account_info(account)
except ValueError:
logger.info(f"Account does not exist or already closed: {account}")
return
# WARNING: This will permanently burn all tokens in the account before closing it
# Closing account is impossible if balance is positive
# Burn + close are combined into a single transaction to avoid race conditions
instructions = []
balance = await client.get_token_account_balance(account)
if balance > 0 and mint == SystemAddresses.WSOL_MINT:
# Wrapped SOL cannot be burned — the token program rejects it with
# NativeNotSupported (error 10) and the whole transaction reverts, so
# the account can never be closed. Closing a WSOL account already
# returns both the wrapped lamports and the rent to the owner, so
# there is nothing to burn first. Matches AccountCleanupManager.
logger.info(
f"Unwrapping {balance} lamports of wrapped SOL from {account} "
f"by closing it (burn skipped)"
)
elif balance > 0:
logger.info(f"Burning {balance} tokens from account {account}...")
burn_ix = burn(
BurnParams(
account=account,
mint=mint,
owner=wallet.pubkey,
amount=balance,
program_id=token_program,
)
)
instructions.append(burn_ix)
# Account exists, attempt to close it
logger.info(f"Closing account: {account}")
close_params = CloseAccountParams(
account=account,
dest=wallet.pubkey,
owner=wallet.pubkey,
program_id=token_program,
)
instructions.append(close_account(close_params))
tx_sig = await client.build_and_send_transaction(
instructions,
wallet.keypair,
skip_preflight=True,
)
# confirm_transaction returns False when the transaction landed but
# reverted — reporting success on that would hide a failed cleanup.
# The label reflects what was actually built: wrapped SOL is unwrapped by
# the close, never burned, so it must not claim a burn.
if balance > 0 and mint == SystemAddresses.WSOL_MINT:
action = "Unwrapped and closed"
elif balance > 0:
action = "Burned and closed"
else:
action = "Closed"
if await client.confirm_transaction(tx_sig):
logger.info(f"{action} successfully: {account}")
else:
logger.error(f"Failed to {action.lower()} account {account}: {tx_sig}")
except Exception as e:
logger.error(f"Error while processing account {account}: {e}")
async def main():
try:
client = SolanaClient(RPC_ENDPOINT)
wallet = Wallet(PRIVATE_KEY)
token_program = await resolve_token_program(client, MINT_ADDRESS)
logger.info(f"Mint {MINT_ADDRESS} uses token program {token_program}")
# Get user's ATA for the token
ata = wallet.get_associated_token_address(MINT_ADDRESS, token_program)
await close_account_if_exists(client, wallet, ata, MINT_ADDRESS, token_program)
except Exception as e:
logger.error(f"Unexpected error: {e}")
finally:
await client.close()
if __name__ == "__main__":
asyncio.run(main())