Files
pumpfun-bonkfun-bot_github/learning-examples/decode_from_getaccountinfo.py
T
Anton Sauchyk a33f4fd035 fix(learning-examples): repair crashing listeners and decoders, prune obsolete paths, unify naming (#181)
Audited every script in learning-examples/ against mainnet.

Broken — found by running them, all invisible offline:

- listen_geyser.py crashed with IndexError after ~11 coins: it never resolved
  v0 address-lookup-table accounts, which geyser reports in
  meta.loaded_writable_addresses / loaded_readonly_addresses. Resolving them
  removes the crash and brings detections level with the WebSocket listeners,
  35 coins each per 150 s.
- compare_listeners.py logged 13,090,862 error lines / 888 MB in 150 s and never
  printed its own 30-second report: the inner recv() loop caught ConnectionClosed
  in a broad handler that only logged, so every following recv() raised at once
  and the outer reconnect handler was unreachable. Now 12 KB and exit 0. Same
  shape fixed in compare_migration_listeners.py, listen_blocksubscribe.py and
  extract_blocksubscribe_transactions.py; the last two also gained the reconnect
  loop their siblings already had.
- decode_from_gettransaction.py matched instructions on account count instead of
  discriminator, reporting a real 19-account create_v2 as claim_cashback with
  every account under the wrong name. It also walked only top-level
  instructions, and in 40 consecutive pump.fun transactions there was 1
  top-level pump instruction against 8 inner ones.
- decode_from_blocksubscribe.py crashed on every real create_v2: on chain the
  trailing args are variable length, 0001 in one tx and 00 in another, so
  is_cashback_enabled can be absent entirely.
- poll_bonding_curve_progress.py polled a hardcoded dead mint and took no argv.

Obsolete:

- Delete listen_blocksubscribe_old_raydium.py. Seven minutes on mainnet produced
  0 initialize2 events while the wrapper listener caught 3 real migrations.
- Delete the duplicate geyser stubs and protos under listen-new-tokens/. The
  protos were byte-identical to src/geyser/proto and the stubs had drifted; both
  geyser examples now import src.geyser.generated.
- Recapture all four fixtures. The old ones were from Aug 2024 and included a
  49-byte pre-creator bonding curve.

Behind the protocol:

- fetch_price.py, get_bonding_curve_status.py, poll_bonding_curve_progress.py
  and decode_from_getaccountinfo.py never read quote_mint and scaled by a
  hardcoded 1e9. Against a live USDC-paired curve the price was off by 1000x.
- get_pumpswap_pools.py stopped parsing at coin_creator and missed the i128
  virtual_quote_reserves. Live pools carry 17.5845 SOL of them, which
  under-prices by 3.5-23.9% when ignored.

Duplication and naming:

- Merge manual_buy_cu_optimized.py into manual_buy.py --cu-optimized. The
  deleted file's docstring said 512 KB while its code used 16 MB; simulation
  confirms 512 KB and 4 MB both fail MaxLoadedAccountsDataSizeExceeded on
  Token-2022 mints, so 16 MB is the correct value.
- Merge listen_logsubscribe_abc.py into listen_logsubscribe.py. Its ATA
  derivation hardcoded the legacy token program, so every Associated BC it
  printed for a Token2022 coin was an address that does not exist on chain.
  Fixed on merge and cross-checked 59/59 against on-chain accounts.
- Remove 19 dead symbols. BREAKING_FEE_RECIPIENTS is still live in the PumpSwap
  scripts and stays there.
- Normalize naming: kebab-case directories, RPC method names as one lowercase
  token, scripts verb-first. Rules documented in CLAUDE.md.

get_graduating_tokens.py is knowingly left broken: getProgramAccounts over the
whole pump program is now rejected by providers and it needs a
getProgramAccountsV2 rewrite, which belongs in its own PR.

Verified: both offline gates pass, all 41 examples parse, every read-only script
exercised on mainnet against SOL- and USDC-paired coins, no new ruff findings
(427 -> 413). No script that spends real funds was run.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-29 15:26:26 +02:00

148 lines
5.4 KiB
Python

import base64
import json
import struct
import sys
from construct import Bytes, Flag, Int64ul, Struct
from solders.pubkey import Pubkey
TOKEN_DECIMALS = 6
EXPECTED_DISCRIMINATOR = struct.pack("<Q", 6966180631402821399)
# Quote assets. A curve's `quote_mint` is all zeros when the coin is SOL-paired, and
# the quote-side reserves are always raw units of that mint: 1e9 for SOL, 1e6 for USDC.
DEFAULT_QUOTE_MINT = Pubkey.from_bytes(bytes(32))
WSOL_MINT = Pubkey.from_string("So11111111111111111111111111111111111111112")
USDC_MINT = Pubkey.from_string("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v")
QUOTE_DECIMALS = {WSOL_MINT: 9, USDC_MINT: 6}
QUOTE_SYMBOLS = {WSOL_MINT: "SOL", USDC_MINT: "USDC"}
class BondingCurveState:
_STRUCT = Struct(
"virtual_token_reserves" / Int64ul,
"virtual_sol_reserves" / Int64ul,
"real_token_reserves" / Int64ul,
"real_sol_reserves" / Int64ul,
"token_total_supply" / Int64ul,
"complete" / Flag,
"creator" / Bytes(32), # Added new creator field - 32 bytes for Pubkey
"is_mayhem_mode" / Flag, # Added mayhem mode flag - 1 byte
)
def __init__(self, data: bytes) -> None:
"""Parse bonding curve data - supports all versions."""
if data[:8] != EXPECTED_DISCRIMINATOR:
raise ValueError("Invalid curve state discriminator")
# Required fields (always present)
offset = 8
self.virtual_token_reserves = int.from_bytes(
data[offset : offset + 8], "little"
)
offset += 8
self.virtual_sol_reserves = int.from_bytes(data[offset : offset + 8], "little")
offset += 8
self.real_token_reserves = int.from_bytes(data[offset : offset + 8], "little")
offset += 8
self.real_sol_reserves = int.from_bytes(data[offset : offset + 8], "little")
offset += 8
self.token_total_supply = int.from_bytes(data[offset : offset + 8], "little")
offset += 8
self.complete = bool(data[offset])
offset += 1
# Optional fields (may not be present in older versions)
if len(data) >= offset + 32:
self.creator = Pubkey.from_bytes(data[offset : offset + 32])
offset += 32
if len(data) > offset:
self.is_mayhem_mode = bool(data[offset])
offset += 1
else:
self.is_mayhem_mode = None
if len(data) > offset:
self.is_cashback_coin = bool(data[offset])
offset += 1
else:
self.is_cashback_coin = None
if len(data) >= offset + 32:
self.quote_mint = Pubkey.from_bytes(data[offset : offset + 32])
else:
self.quote_mint = DEFAULT_QUOTE_MINT
else:
self.creator = None
self.is_mayhem_mode = None
self.is_cashback_coin = None
self.quote_mint = DEFAULT_QUOTE_MINT
@property
def effective_quote_mint(self) -> Pubkey:
"""The quote mint to price against, resolving all-zeros to wrapped SOL."""
return WSOL_MINT if self.quote_mint == DEFAULT_QUOTE_MINT else self.quote_mint
@property
def quote_symbol(self) -> str:
"""Display symbol of the quote asset."""
mint = self.effective_quote_mint
return QUOTE_SYMBOLS.get(mint, str(mint))
@property
def quote_units(self) -> int:
"""Raw units per whole token of the quote asset."""
return 10 ** QUOTE_DECIMALS.get(self.effective_quote_mint, 9)
def calculate_bonding_curve_price(curve_state: BondingCurveState) -> float:
if curve_state.virtual_token_reserves <= 0 or curve_state.virtual_sol_reserves <= 0:
raise ValueError("Invalid reserve state")
return (curve_state.virtual_sol_reserves / curve_state.quote_units) / (
curve_state.virtual_token_reserves / 10**TOKEN_DECIMALS
)
def decode_bonding_curve_data(raw_data: str) -> BondingCurveState:
decoded_data = base64.b64decode(raw_data)
if decoded_data[:8] != EXPECTED_DISCRIMINATOR:
raise ValueError("Invalid curve state discriminator")
return BondingCurveState(decoded_data)
# Load the JSON data: pass a getAccountInfo response as argv[1], or use the fixture
curve_file = (
sys.argv[1]
if len(sys.argv) > 1
else "learning-examples/raw_bonding_curve_from_getaccountinfo.json"
)
with open(curve_file) as file:
json_data = json.load(file)
# Extract the base64 encoded data
encoded_data = json_data["result"]["value"]["data"][0]
# Decode the data
bonding_curve_state = decode_bonding_curve_data(encoded_data)
# Calculate and print the token price
token_price = calculate_bonding_curve_price(bonding_curve_state)
symbol = bonding_curve_state.quote_symbol
print("Bonding Curve State:")
print(f" Virtual Token Reserves: {bonding_curve_state.virtual_token_reserves}")
print(
f" Virtual Quote Reserves: {bonding_curve_state.virtual_sol_reserves} raw {symbol}"
)
print(f" Real Token Reserves: {bonding_curve_state.real_token_reserves}")
print(f" Real Quote Reserves: {bonding_curve_state.real_sol_reserves} raw {symbol}")
print(f" Token Total Supply: {bonding_curve_state.token_total_supply}")
print(f" Complete: {bonding_curve_state.complete}")
print(f" Mayhem Mode: {bonding_curve_state.is_mayhem_mode}")
print(f" Cashback Coin: {bonding_curve_state.is_cashback_coin}")
print(f" Quote Mint: {bonding_curve_state.effective_quote_mint}")
print(f"\nToken Price: {token_price:.10f} {symbol}")