Files
pumpfun-bonkfun-bot_github/cookbook/pumpfun/trade/pumpfun_sell_token.py
T
75d9087d05 feat(cookbook): launch any coin create_v2 supports, as a v0 or a v1 transaction (#234)
* 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>
2026-09-28 08:48:31 +02:00

349 lines
13 KiB
Python

"""Sell your whole position in a pump.fun coin, using sell_v2.
WARNING: this submits a real transaction and spends real funds.
Usage:
uv run cookbook/pumpfun/trade/pumpfun_sell_token.py <MINT>
The mirror of `pumpfun_buy_token.py`. It reads how many tokens you hold, reads the curve
for a price, and sells the lot with a slippage floor underneath.
One thing to know before you run it:
- **The floor is yours to set.** `min_sol_output` is computed here from the price
and the slippage, and the program enforces only that number. Passing a floor
derived from a stale price is how a sell goes through at a price you did not intend.
"""
import argparse
import asyncio
import os
import sys
from pathlib import Path
# solana_transaction_status.py lives in cookbook/solana/; pumpfun_instructions.py sits beside this file.
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "solana"))
import base58
import pumpfun_instructions as pump
import solana_transaction_status as tx_status
from dotenv import load_dotenv
from solana.rpc.async_api import AsyncClient
from solana.rpc.commitment import Confirmed
from solana.rpc.core import TxOptsModel
from solders.account import Account
from solders.compute_budget import set_compute_unit_price
from solders.keypair import Keypair
from solders.message import MessageV0
from solders.pubkey import Pubkey
from solders.transaction import VersionedTransaction
from spl.token.instructions import (
create_idempotent_associated_token_account,
get_associated_token_address,
)
# Here and later all the discriminators are precalculated. See cookbook/solana/anchor_calculate_discriminator.py
EXPECTED_DISCRIMINATOR = pump.BONDING_CURVE_DISCRIMINATOR
TOKEN_DECIMALS = 6
# Default for the command line below, not a fixed setting.
DEFAULT_SLIPPAGE = 0.25
# Global constants
PUMP_PROGRAM = Pubkey.from_string("6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P")
PUMP_GLOBAL = Pubkey.from_string("4wTV1YmiEkRvAtNtsSGPtUrqRYQMe5SKy2uB4Jjaxnjf")
PUMP_EVENT_AUTHORITY = Pubkey.from_string(
"Ce6TQqeHC9p8KetsN6JsjHK7UTZk7nasjjnr7XxXp9F1"
)
PUMP_FEE = Pubkey.from_string("CebN5WGQ4jvEPvsVU4EoHEpgzq1VV7AbicfhtW4xC9iM")
PUMP_FEE_PROGRAM = Pubkey.from_string("pfeeUxB6jkeY1Hxd7CsFCAjcbHA9rWtchMGdZ6VojVZ")
SYSTEM_PROGRAM = Pubkey.from_string("11111111111111111111111111111111")
SYSTEM_TOKEN_PROGRAM = Pubkey.from_string("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA")
TOKEN_2022_PROGRAM = Pubkey.from_string("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb")
SYSTEM_ASSOCIATED_TOKEN_ACCOUNT_PROGRAM = Pubkey.from_string(
"ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"
)
SYSTEM_RENT = Pubkey.from_string("SysvarRent111111111111111111111111111111111")
SOL = Pubkey.from_string("So11111111111111111111111111111111111111112")
LAMPORTS_PER_SOL = 1_000_000_000
UNIT_PRICE = 10_000_000
UNIT_BUDGET = 100_000
load_dotenv()
RPC_ENDPOINT = os.environ.get("SOLANA_NODE_RPC_ENDPOINT")
BondingCurveState = pump.BondingCurveState
async def get_pump_curve_state(
conn: AsyncClient, curve_address: Pubkey
) -> BondingCurveState:
response = await conn.get_account_info(curve_address, encoding="base64")
if not response.value or not response.value.data:
raise ValueError("Invalid curve state: No data")
data = response.value.data
if data[:8] != EXPECTED_DISCRIMINATOR:
raise ValueError("Invalid curve state discriminator")
return pump.BondingCurveState(data)
def get_bonding_curve_address(mint: Pubkey) -> tuple[Pubkey, int]:
return Pubkey.find_program_address([b"bonding-curve", bytes(mint)], PUMP_PROGRAM)
def find_associated_bonding_curve(
mint: Pubkey, bonding_curve: Pubkey, token_program_id: Pubkey
) -> Pubkey:
derived_address, _ = Pubkey.find_program_address(
[
bytes(bonding_curve),
bytes(token_program_id),
bytes(mint),
],
SYSTEM_ASSOCIATED_TOKEN_ACCOUNT_PROGRAM,
)
return derived_address
def find_creator_vault(creator: Pubkey) -> Pubkey:
derived_address, _ = Pubkey.find_program_address(
[b"creator-vault", bytes(creator)],
PUMP_PROGRAM,
)
return derived_address
def calculate_pump_curve_price(curve_state: pump.BondingCurveState) -> float:
"""Price of one whole token in whole units of the curve's quote asset.
Args:
curve_state: Parsed curve state
Returns:
Price in the quote asset
Raises:
ValueError: If reserves are empty
"""
price = curve_state.price_per_token()
if price <= 0:
raise ValueError("Invalid reserve state")
return price
async def get_token_balance(conn: AsyncClient, associated_token_account: Pubkey):
response = await conn.get_token_account_balance(associated_token_account)
if response.value:
return int(response.value.amount)
return 0
async def _get_mint_account_info(client: AsyncClient, address: Pubkey) -> Account:
"""Fetch an account, unwrapping AsyncClient's `.value` envelope.
Adapter for `pump.resolve_quote_token_program`, which expects a
getter returning the account object (with an `.owner` attribute)
directly rather than solana-py's RPC response wrapper.
Args:
client: Solana RPC client
address: Account to fetch
Raises:
ValueError: If the account does not exist
"""
response = await client.get_account_info(address)
if response.value is None:
raise ValueError(f"Could not fetch account info for {address}")
return response.value
async def get_token_program_id(client: AsyncClient, mint_address: Pubkey) -> Pubkey:
"""Determines if a mint uses TokenProgram or Token2022Program."""
mint_info = await client.get_account_info(mint_address)
if not mint_info.value:
raise ValueError(f"Could not fetch mint info for {mint_address}")
owner = mint_info.value.owner
if owner == SYSTEM_TOKEN_PROGRAM:
return SYSTEM_TOKEN_PROGRAM
elif owner == TOKEN_2022_PROGRAM:
return TOKEN_2022_PROGRAM
else:
raise ValueError(
f"Mint account {mint_address} is owned by an unknown program: {owner}"
)
async def sell_token(
mint: Pubkey,
bonding_curve: Pubkey,
associated_bonding_curve: Pubkey,
creator_vault: Pubkey,
token_program_id: Pubkey,
slippage: float = 0.25,
max_retries=5,
):
private_key = base58.b58decode(os.environ.get("SOLANA_PRIVATE_KEY"))
payer = Keypair.from_bytes(private_key)
async with AsyncClient(RPC_ENDPOINT) as client:
associated_token_account = get_associated_token_address(
payer.pubkey(), mint, token_program_id
)
token_balance = await get_token_balance(client, associated_token_account)
token_balance_decimal = token_balance / 10**TOKEN_DECIMALS
print(f"Token balance: {token_balance_decimal}")
if token_balance == 0:
print("No tokens to sell.")
return
# Fetch bonding curve state to calculate price and determine fee recipient
curve_state = await get_pump_curve_state(client, bonding_curve)
quote_mint = pump.normalize_quote_mint(getattr(curve_state, "quote_mint", None))
# Resolve the quote mint before pricing: one read gives both the token
# program -- Token-2022 for every tokenized equity pump.fun admits -- and
# the decimals the price and slippage floor are in. Pricing first floors
# the sell against a number off by a power of ten.
quote_token_program_id = await pump.resolve_quote_token_program(
quote_mint, lambda pk: _get_mint_account_info(client, pk)
)
quote_unit = pump.quote_units(quote_mint)
# Named for the quote asset, not for SOL: the curve prices in whatever
# it is paired with, and calling a USDC price "SOL" is how a misread
# number gets past a reader who is checking.
token_price_quote = calculate_pump_curve_price(curve_state)
print(f"Price per Token: {token_price_quote:.20f} per quote unit")
# Minimum payout, in the curve's quote asset raw units.
amount = token_balance
expected_output = float(token_balance_decimal) * float(token_price_quote)
min_quote_output = max(1, int(expected_output * (1 - slippage) * quote_unit))
print(f"Selling {token_balance_decimal} tokens")
print(f"Quote asset: {quote_mint}")
print(
f"Minimum output: {min_quote_output / quote_unit:.10f} ({min_quote_output} raw)"
)
# sell_v2 takes the same 26 mandatory accounts for every coin — no
# cashback/mayhem branching on the account list any more.
sell_ix = pump.build_sell_v2_instruction(
base_mint=mint,
creator=curve_state.creator,
user=payer.pubkey(),
token_amount_raw=amount,
min_quote_output_raw=min_quote_output,
quote_mint=quote_mint,
base_token_program=token_program_id,
is_mayhem_mode=curve_state.is_mayhem_mode,
quote_token_program_id=quote_token_program_id,
)
instructions = [set_compute_unit_price(1_000)]
# Non-SOL proceeds land in the seller's quote ATA, which must exist.
if not pump.is_sol_paired(quote_mint):
instructions.append(
create_idempotent_associated_token_account(
payer.pubkey(),
payer.pubkey(),
quote_mint,
token_program_id=quote_token_program_id,
)
)
instructions.append(sell_ix)
recent_blockhash = await client.get_latest_blockhash()
# The blockhash is fixed for every attempt, so the transaction is built
# once: each retry resubmits identical bytes.
transaction = VersionedTransaction(
MessageV0.try_compile(
payer.pubkey(), instructions, [], recent_blockhash.value.blockhash
),
[payer],
)
opts = TxOptsModel(skip_preflight=True, preflight_commitment=Confirmed)
# Continue with the sell transaction
for attempt in range(max_retries):
try:
tx = await client.send_transaction(transaction, opts=opts)
tx_hash = tx.value
print(f"Transaction sent: https://explorer.solana.com/tx/{tx_hash}")
await tx_status.confirm_and_assert(client, tx_hash)
print("Transaction confirmed")
return # Success, exit the function
except tx_status.TransactionRevertedError as e:
# The signature is already on chain and reverted. The
# transaction above is fixed, so a retry would resubmit
# identical bytes and revert identically — stop instead of
# burning attempts.
print(f"Transaction reverted on-chain, not retrying: {e}")
return
except Exception as e:
print(f"Attempt {attempt + 1} failed: {e!s}")
if attempt < max_retries - 1:
wait_time = 2**attempt # Exponential backoff
print(f"Retrying in {wait_time} seconds...")
await asyncio.sleep(wait_time)
else:
print("Max retries reached. Unable to complete the transaction.")
async def run(mint: Pubkey, slippage: float) -> None:
"""Sell the whole position in one coin.
Args:
mint: The coin to sell
slippage: Slippage tolerance
"""
async with AsyncClient(RPC_ENDPOINT) as client:
token_program_id = await get_token_program_id(client, mint)
bonding_curve, _ = get_bonding_curve_address(mint)
associated_bonding_curve = find_associated_bonding_curve(
mint, bonding_curve, token_program_id
)
async with AsyncClient(RPC_ENDPOINT) as client:
curve_state = await get_pump_curve_state(client, bonding_curve)
creator_vault = find_creator_vault(curve_state.creator)
print(f"Bonding curve address: {bonding_curve}")
print(f"Selling tokens with {slippage * 100:.1f}% slippage tolerance...")
await sell_token(
mint,
bonding_curve,
associated_bonding_curve,
creator_vault,
token_program_id,
slippage,
)
def main() -> None:
"""Parse the command line and run the sell."""
parser = argparse.ArgumentParser(description="Sell a whole pump.fun position")
parser.add_argument("mint", help="The coin's mint address")
parser.add_argument(
"--slippage",
type=float,
default=DEFAULT_SLIPPAGE,
help=f"Slippage tolerance (default {DEFAULT_SLIPPAGE})",
)
args = parser.parse_args()
asyncio.run(run(Pubkey.from_string(args.mint), args.slippage))
if __name__ == "__main__":
main()