mirror of
https://github.com/chainstacklabs/pumpfun-bonkfun-bot.git
synced 2026-08-01 17:57:43 +00:00
a33f4fd035
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>
393 lines
14 KiB
Python
393 lines
14 KiB
Python
import asyncio
|
|
import os
|
|
import struct
|
|
from typing import Final
|
|
|
|
import base58
|
|
import pump_v2
|
|
import tx_status
|
|
from dotenv import load_dotenv
|
|
from solana.rpc.async_api import AsyncClient
|
|
from solana.rpc.commitment import Confirmed
|
|
from solana.rpc.types import TxOpts
|
|
from solders.compute_budget import set_compute_unit_limit, set_compute_unit_price
|
|
from solders.instruction import AccountMeta, Instruction
|
|
from solders.keypair import Keypair
|
|
from solders.message import Message
|
|
from solders.pubkey import Pubkey
|
|
from solders.transaction import Transaction
|
|
from spl.token.instructions import (
|
|
create_idempotent_associated_token_account,
|
|
get_associated_token_address,
|
|
)
|
|
|
|
# Configuration for the token to be created
|
|
TOKEN_NAME = "Test Token"
|
|
TOKEN_SYMBOL = "TEST"
|
|
TOKEN_URI = "https://example.com/token.json"
|
|
BUY_AMOUNT_SOL = 0.001 # Amount of SOL to spend on buying
|
|
MAX_SLIPPAGE = 0.3 # 30% slippage
|
|
PRIORITY_FEE_MICROLAMPORTS = 37_037 # Priority fee in microlamports
|
|
COMPUTE_UNIT_LIMIT = 250_000 # Compute unit limit for the transaction
|
|
|
|
load_dotenv()
|
|
|
|
# Global constants from existing codebase
|
|
PUMP_PROGRAM: Final[Pubkey] = Pubkey.from_string(
|
|
"6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P"
|
|
)
|
|
PUMP_GLOBAL: Final[Pubkey] = Pubkey.from_string(
|
|
"4wTV1YmiEkRvAtNtsSGPtUrqRYQMe5SKy2uB4Jjaxnjf"
|
|
)
|
|
PUMP_EVENT_AUTHORITY: Final[Pubkey] = Pubkey.from_string(
|
|
"Ce6TQqeHC9p8KetsN6JsjHK7UTZk7nasjjnr7XxXp9F1"
|
|
)
|
|
PUMP_FEE: Final[Pubkey] = Pubkey.from_string(
|
|
"CebN5WGQ4jvEPvsVU4EoHEpgzq1VV7AbicfhtW4xC9iM"
|
|
)
|
|
PUMP_FEE_PROGRAM: Final[Pubkey] = Pubkey.from_string(
|
|
"pfeeUxB6jkeY1Hxd7CsFCAjcbHA9rWtchMGdZ6VojVZ"
|
|
)
|
|
|
|
PUMP_MINT_AUTHORITY: Final[Pubkey] = Pubkey.from_string(
|
|
"TSLvdd1pWpHVjahSpsvCXUbgwsL3JAcvokwaKt1eokM"
|
|
)
|
|
|
|
SYSTEM_PROGRAM: Final[Pubkey] = Pubkey.from_string("11111111111111111111111111111111")
|
|
SYSTEM_TOKEN_PROGRAM: Final[Pubkey] = Pubkey.from_string(
|
|
"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
|
|
)
|
|
SYSTEM_ASSOCIATED_TOKEN_ACCOUNT_PROGRAM: Final[Pubkey] = Pubkey.from_string(
|
|
"ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"
|
|
)
|
|
SYSTEM_RENT: Final[Pubkey] = Pubkey.from_string(
|
|
"SysvarRent111111111111111111111111111111111"
|
|
)
|
|
METAPLEX_TOKEN_METADATA: Final[Pubkey] = Pubkey.from_string(
|
|
"metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s"
|
|
)
|
|
|
|
LAMPORTS_PER_SOL: Final[int] = 1_000_000_000
|
|
TOKEN_DECIMALS: Final[int] = 6
|
|
|
|
# Discriminators
|
|
CREATE_DISCRIMINATOR: Final[bytes] = struct.pack("<Q", 8576854823835016728)
|
|
EXTEND_ACCOUNT_DISCRIMINATOR: Final[bytes] = bytes(
|
|
[234, 102, 194, 203, 150, 72, 62, 229]
|
|
)
|
|
|
|
# From environment
|
|
RPC_ENDPOINT = os.environ.get("SOLANA_NODE_RPC_ENDPOINT")
|
|
PRIVATE_KEY = os.environ.get("SOLANA_PRIVATE_KEY")
|
|
|
|
|
|
def find_bonding_curve_address(mint: Pubkey) -> tuple[Pubkey, int]:
|
|
"""Find the bonding curve PDA for a mint."""
|
|
return Pubkey.find_program_address([b"bonding-curve", bytes(mint)], PUMP_PROGRAM)
|
|
|
|
|
|
def find_associated_bonding_curve(mint: Pubkey, bonding_curve: Pubkey) -> Pubkey:
|
|
"""Find the associated bonding curve token account."""
|
|
derived_address, _ = Pubkey.find_program_address(
|
|
[
|
|
bytes(bonding_curve),
|
|
bytes(SYSTEM_TOKEN_PROGRAM),
|
|
bytes(mint),
|
|
],
|
|
SYSTEM_ASSOCIATED_TOKEN_ACCOUNT_PROGRAM,
|
|
)
|
|
return derived_address
|
|
|
|
|
|
def find_metadata_address(mint: Pubkey) -> Pubkey:
|
|
"""Find the metadata PDA for a mint."""
|
|
derived_address, _ = Pubkey.find_program_address(
|
|
[
|
|
b"metadata",
|
|
bytes(METAPLEX_TOKEN_METADATA),
|
|
bytes(mint),
|
|
],
|
|
METAPLEX_TOKEN_METADATA,
|
|
)
|
|
return derived_address
|
|
|
|
|
|
def find_creator_vault(creator: Pubkey) -> Pubkey:
|
|
"""Find the creator vault PDA."""
|
|
derived_address, _ = Pubkey.find_program_address(
|
|
[b"creator-vault", bytes(creator)],
|
|
PUMP_PROGRAM,
|
|
)
|
|
return derived_address
|
|
|
|
|
|
def create_pump_create_instruction(
|
|
mint: Pubkey,
|
|
mint_authority: Pubkey,
|
|
bonding_curve: Pubkey,
|
|
associated_bonding_curve: Pubkey,
|
|
global_state: Pubkey,
|
|
metadata: Pubkey,
|
|
user: Pubkey,
|
|
creator: Pubkey,
|
|
name: str,
|
|
symbol: str,
|
|
uri: str,
|
|
) -> Instruction:
|
|
"""Create the pump.fun create instruction."""
|
|
accounts = [
|
|
AccountMeta(pubkey=mint, is_signer=True, is_writable=True),
|
|
AccountMeta(pubkey=mint_authority, is_signer=False, is_writable=False),
|
|
AccountMeta(pubkey=bonding_curve, is_signer=False, is_writable=True),
|
|
AccountMeta(pubkey=associated_bonding_curve, is_signer=False, is_writable=True),
|
|
AccountMeta(pubkey=global_state, is_signer=False, is_writable=False),
|
|
AccountMeta(pubkey=METAPLEX_TOKEN_METADATA, is_signer=False, is_writable=False),
|
|
AccountMeta(pubkey=metadata, is_signer=False, is_writable=True),
|
|
AccountMeta(pubkey=user, is_signer=True, is_writable=True),
|
|
AccountMeta(pubkey=SYSTEM_PROGRAM, is_signer=False, is_writable=False),
|
|
AccountMeta(pubkey=SYSTEM_TOKEN_PROGRAM, is_signer=False, is_writable=False),
|
|
AccountMeta(
|
|
pubkey=SYSTEM_ASSOCIATED_TOKEN_ACCOUNT_PROGRAM,
|
|
is_signer=False,
|
|
is_writable=False,
|
|
),
|
|
AccountMeta(pubkey=SYSTEM_RENT, is_signer=False, is_writable=False),
|
|
AccountMeta(pubkey=PUMP_EVENT_AUTHORITY, is_signer=False, is_writable=False),
|
|
AccountMeta(pubkey=PUMP_PROGRAM, is_signer=False, is_writable=False),
|
|
]
|
|
|
|
# Encode string as length-prefixed
|
|
def encode_string(s: str) -> bytes:
|
|
encoded = s.encode("utf-8")
|
|
return struct.pack("<I", len(encoded)) + encoded
|
|
|
|
def encode_pubkey(pubkey: Pubkey) -> bytes:
|
|
return bytes(pubkey)
|
|
|
|
data = (
|
|
CREATE_DISCRIMINATOR
|
|
+ encode_string(name)
|
|
+ encode_string(symbol)
|
|
+ encode_string(uri)
|
|
+ encode_pubkey(creator)
|
|
)
|
|
|
|
return Instruction(PUMP_PROGRAM, data, accounts)
|
|
|
|
|
|
def create_extend_account_instruction(
|
|
bonding_curve: Pubkey,
|
|
user: Pubkey,
|
|
) -> Instruction:
|
|
"""Create the extend_account instruction to expand bonding curve account size."""
|
|
accounts = [
|
|
AccountMeta(pubkey=bonding_curve, is_signer=False, is_writable=True),
|
|
AccountMeta(pubkey=user, is_signer=True, is_writable=True),
|
|
AccountMeta(pubkey=SYSTEM_PROGRAM, is_signer=False, is_writable=False),
|
|
AccountMeta(pubkey=PUMP_EVENT_AUTHORITY, is_signer=False, is_writable=False),
|
|
AccountMeta(pubkey=PUMP_PROGRAM, is_signer=False, is_writable=False),
|
|
]
|
|
|
|
# No arguments for extend_account instruction
|
|
data = EXTEND_ACCOUNT_DISCRIMINATOR
|
|
|
|
return Instruction(PUMP_PROGRAM, data, accounts)
|
|
|
|
|
|
def create_buy_instruction(
|
|
global_state: Pubkey,
|
|
fee_recipient: Pubkey,
|
|
mint: Pubkey,
|
|
bonding_curve: Pubkey,
|
|
associated_bonding_curve: Pubkey,
|
|
associated_user: Pubkey,
|
|
user: Pubkey,
|
|
creator_vault: Pubkey,
|
|
token_amount: int,
|
|
max_sol_cost: int,
|
|
track_volume: bool = True,
|
|
is_mayhem_mode: bool = False,
|
|
) -> Instruction:
|
|
"""Create the buy instruction (buy_v2).
|
|
|
|
The signature is unchanged for callers, but this builds `buy_v2` with its 27
|
|
mandatory accounts. Several parameters are accepted only for backwards
|
|
compatibility and are derived or dropped internally: buy_v2 takes no
|
|
track_volume argument, and pump_v2 selects the fee recipient from the
|
|
documented set. This script mints the coin with `creator = payer`, so the
|
|
buyer is also the creator.
|
|
|
|
Args:
|
|
global_state: Unused; pump_v2 uses the canonical global PDA
|
|
fee_recipient: Unused; pump_v2 selects from the documented set
|
|
mint: Base token mint just created
|
|
bonding_curve: Unused; derived from the mint
|
|
associated_bonding_curve: Unused; derived
|
|
associated_user: Unused; derived
|
|
user: Buyer, and the coin's creator in this script
|
|
creator_vault: Unused; derived from the creator
|
|
token_amount: Base tokens to buy, raw units
|
|
max_sol_cost: Spend cap in lamports
|
|
track_volume: Ignored; volume tracking is unconditional under buy_v2
|
|
is_mayhem_mode: Mayhem coins must use a *reserved* fee recipient; passing
|
|
this wrong makes the program reject the buy with NotAuthorized (6000)
|
|
|
|
Returns:
|
|
The buy_v2 instruction
|
|
"""
|
|
return pump_v2.build_buy_v2_instruction(
|
|
base_mint=mint,
|
|
creator=user,
|
|
user=user,
|
|
token_amount_raw=token_amount,
|
|
max_quote_cost_raw=max_sol_cost,
|
|
quote_mint=pump_v2.WSOL_MINT,
|
|
is_mayhem_mode=is_mayhem_mode,
|
|
base_token_program=SYSTEM_TOKEN_PROGRAM,
|
|
)
|
|
|
|
|
|
async def main():
|
|
"""Create and buy pump.fun token in a single transaction."""
|
|
private_key_bytes = base58.b58decode(PRIVATE_KEY)
|
|
payer = Keypair.from_bytes(private_key_bytes)
|
|
mint_keypair = Keypair()
|
|
|
|
print("Creating token with:")
|
|
print(f" Name: {TOKEN_NAME}")
|
|
print(f" Symbol: {TOKEN_SYMBOL}")
|
|
print(f" Mint: {mint_keypair.pubkey()}")
|
|
print(f" Creator: {payer.pubkey()}")
|
|
|
|
# Derive PDAs
|
|
bonding_curve, _ = find_bonding_curve_address(mint_keypair.pubkey())
|
|
associated_bonding_curve = find_associated_bonding_curve(
|
|
mint_keypair.pubkey(), bonding_curve
|
|
)
|
|
metadata = find_metadata_address(mint_keypair.pubkey())
|
|
user_ata = get_associated_token_address(payer.pubkey(), mint_keypair.pubkey())
|
|
creator_vault = find_creator_vault(payer.pubkey())
|
|
|
|
print("\nDerived addresses:")
|
|
print(f" Bonding curve: {bonding_curve}")
|
|
print(f" Associated bonding curve: {associated_bonding_curve}")
|
|
print(f" Metadata: {metadata}")
|
|
print(f" User ATA: {user_ata}")
|
|
print(f" Creator vault: {creator_vault}")
|
|
|
|
# Calculate buy parameters
|
|
# For pump.fun, we need to calculate expected tokens based on initial curve state
|
|
# Initial virtual reserves (from pump.fun constants)
|
|
initial_virtual_token_reserves = 1_073_000_000 * 10**TOKEN_DECIMALS
|
|
initial_virtual_sol_reserves = 30 * LAMPORTS_PER_SOL
|
|
|
|
initial_price = initial_virtual_sol_reserves / initial_virtual_token_reserves
|
|
|
|
buy_amount_lamports = int(BUY_AMOUNT_SOL * LAMPORTS_PER_SOL)
|
|
expected_tokens = int(
|
|
(buy_amount_lamports * 0.99) / initial_price
|
|
) # 1% buffer for fees
|
|
max_sol_cost = int(buy_amount_lamports * (1 + MAX_SLIPPAGE))
|
|
|
|
print("\nBuy parameters:")
|
|
print(f" Buy amount: {BUY_AMOUNT_SOL} SOL")
|
|
print(f" Expected tokens: {expected_tokens / 10**TOKEN_DECIMALS:.6f}")
|
|
print(f" Max SOL cost: {max_sol_cost / LAMPORTS_PER_SOL:.6f} SOL")
|
|
|
|
instructions = [
|
|
# Priority fee instructions
|
|
set_compute_unit_limit(COMPUTE_UNIT_LIMIT),
|
|
set_compute_unit_price(PRIORITY_FEE_MICROLAMPORTS),
|
|
# Create token with pump.fun (this will handle mint account, metadata, etc.)
|
|
create_pump_create_instruction(
|
|
mint=mint_keypair.pubkey(),
|
|
mint_authority=PUMP_MINT_AUTHORITY,
|
|
bonding_curve=bonding_curve,
|
|
associated_bonding_curve=associated_bonding_curve,
|
|
global_state=PUMP_GLOBAL,
|
|
metadata=metadata,
|
|
user=payer.pubkey(),
|
|
creator=payer.pubkey(),
|
|
name=TOKEN_NAME,
|
|
symbol=TOKEN_SYMBOL,
|
|
uri=TOKEN_URI,
|
|
),
|
|
# Extend bonding curve account (required for frontend visibility)
|
|
create_extend_account_instruction(
|
|
bonding_curve=bonding_curve,
|
|
user=payer.pubkey(),
|
|
),
|
|
]
|
|
|
|
# buy_v2's 27 accounts push a combined create+buy message past Solana's
|
|
# 1232-byte packet limit (measured 1972 bytes for the v2 pair), so the buy
|
|
# goes in a second transaction. The legacy 18-account buy used to fit;
|
|
# recovering atomicity would need an address lookup table.
|
|
buy_instructions = [
|
|
create_idempotent_associated_token_account(
|
|
payer.pubkey(),
|
|
payer.pubkey(),
|
|
mint_keypair.pubkey(),
|
|
SYSTEM_TOKEN_PROGRAM,
|
|
),
|
|
create_buy_instruction(
|
|
global_state=PUMP_GLOBAL,
|
|
fee_recipient=PUMP_FEE,
|
|
mint=mint_keypair.pubkey(),
|
|
bonding_curve=bonding_curve,
|
|
associated_bonding_curve=associated_bonding_curve,
|
|
associated_user=user_ata,
|
|
user=payer.pubkey(),
|
|
creator_vault=creator_vault,
|
|
token_amount=expected_tokens,
|
|
max_sol_cost=max_sol_cost,
|
|
track_volume=True,
|
|
),
|
|
]
|
|
|
|
# Send transaction
|
|
async with AsyncClient(RPC_ENDPOINT) as client:
|
|
recent_blockhash = await client.get_latest_blockhash()
|
|
message = Message(instructions, payer.pubkey())
|
|
transaction = Transaction(
|
|
[payer, mint_keypair], message, recent_blockhash.value.blockhash
|
|
)
|
|
|
|
print("\nSending create transaction...")
|
|
opts = TxOpts(skip_preflight=True, preflight_commitment=Confirmed)
|
|
|
|
try:
|
|
response = await client.send_transaction(transaction, opts)
|
|
tx_hash = response.value
|
|
|
|
print(f"Create sent: https://solscan.io/tx/{tx_hash}")
|
|
|
|
print("Waiting for confirmation...")
|
|
await client.confirm_transaction(tx_hash, commitment="confirmed")
|
|
await tx_status.assert_transaction_succeeded(client, tx_hash)
|
|
print("Create confirmed!")
|
|
|
|
buy_blockhash = await client.get_latest_blockhash()
|
|
buy_tx = Transaction(
|
|
[payer],
|
|
Message(buy_instructions, payer.pubkey()),
|
|
buy_blockhash.value.blockhash,
|
|
)
|
|
print("\nSending buy transaction (buy_v2)...")
|
|
buy_response = await client.send_transaction(buy_tx, opts)
|
|
buy_hash = buy_response.value
|
|
print(f"Buy sent: https://solscan.io/tx/{buy_hash}")
|
|
await client.confirm_transaction(buy_hash, commitment="confirmed")
|
|
await tx_status.assert_transaction_succeeded(client, buy_hash)
|
|
print("Buy confirmed!")
|
|
|
|
return tx_hash
|
|
|
|
except Exception as e:
|
|
print(f"Transaction failed: {e}")
|
|
raise
|
|
|
|
|
|
if __name__ == "__main__":
|
|
asyncio.run(main())
|