Files
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

246 lines
8.7 KiB
Python

"""This module provides functionality to:
1. Find market addresses by base mint
2. Fetch and parse market data (including pool addresses) from Pump AMM program accounts
Usage:
uv run cookbook/pumpswap/pumpswap_find_pool.py <MINT>
"""
import argparse
import asyncio
import os
import struct
import base58
from dotenv import load_dotenv
from solana.rpc.async_api import AsyncClient
from solana.rpc.core import MemcmpOpts
from solders.pubkey import Pubkey
load_dotenv()
RPC_ENDPOINT = os.environ.get("SOLANA_NODE_RPC_ENDPOINT")
PUMP_AMM_PROGRAM_ID = Pubkey.from_string("pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA")
# coin_creator sits after discriminator(8) + pool_bump(1) + index(2) + six
# pubkeys(192) + lp_supply(8). It is set only on a pool the coin graduated into
# and left at the default on every other pool, so it is what tells the canonical
# pool from a copy anyone can open against the same mint.
POOL_COIN_CREATOR_OFFSET = 211
DEFAULT_COIN_CREATOR = Pubkey.default()
def read_pool_coin_creator(data: bytes) -> Pubkey:
"""Read a pool account's coin_creator.
Args:
data: Raw pool account data, discriminator included
Returns:
The pubkey, or the default one if the account is too short to hold it
"""
end = POOL_COIN_CREATOR_OFFSET + 32
if len(data) < end:
return DEFAULT_COIN_CREATOR
return Pubkey.from_bytes(data[POOL_COIN_CREATOR_OFFSET:end])
async def get_pools_by_base_mint(
base_mint_address: Pubkey, amm_program_id: Pubkey
) -> tuple[list[Pubkey], list[Pubkey]]:
"""Find every pool holding this base mint, split by whether it is canonical.
Anyone can open a pool against any mint, and getProgramAccounts returns them
in no defined order, so the first match is an arbitrary pool rather than the
coin's own.
Args:
base_mint_address: The coin's mint
amm_program_id: PUMP AMM program address
Returns:
Canonical pools and the rest, each in the order the RPC returned them
"""
async with AsyncClient(RPC_ENDPOINT, timeout=120) as client:
# Define the offset for base_mint field
offset = 43
# Create the filter to match the base_mint. MemcmpOpts takes the bytes
# base58-encoded, which is what a Pubkey's str already is.
filters = [MemcmpOpts(offset=offset, bytes=str(base_mint_address))]
# Retrieve the accounts that match the filter
response = await client.get_program_accounts(
amm_program_id, # AMM program ID
encoding="base64",
filters=filters,
)
canonical, others = [], []
for account in response.value:
target = (
canonical
if read_pool_coin_creator(bytes(account.account.data))
!= DEFAULT_COIN_CREATOR
else others
)
target.append(account.pubkey)
return canonical, others
# Same offset in SPL Token and Token-2022: extensions are appended after it.
_MINT_DECIMALS_OFFSET = 44
async def read_mint_decimals(mint: Pubkey) -> int:
"""Read a mint's decimals from chain.
pump-amm pools do not all quote in SOL, so only the pool's own quote mint
says what power of ten its reserves are in.
Raises:
ValueError: If the mint is missing or too short to be a mint
"""
async with AsyncClient(RPC_ENDPOINT, timeout=120) as client:
response = await client.get_account_info(mint, encoding="base64")
if response.value is None:
raise ValueError(f"Mint {mint} does not exist on chain")
data = bytes(response.value.data)
if len(data) <= _MINT_DECIMALS_OFFSET:
raise ValueError(f"Account {mint} is too short to be a mint")
return data[_MINT_DECIMALS_OFFSET]
async def get_market_data(market_address: Pubkey):
async with AsyncClient(RPC_ENDPOINT, timeout=120) as client:
response = await client.get_account_info(market_address, encoding="base64")
data = response.value.data
parsed_data = {}
offset = 8
# Fields end at 261; live pool accounts are 301 bytes with trailing padding.
# virtual_quote_reserves is an i128, not a u64 — reading only 8 bytes happens
# to work while the high half is zero, and silently breaks when it isn't.
fields = [
("pool_bump", "u8"),
("index", "u16"),
("creator", "pubkey"),
("base_mint", "pubkey"),
("quote_mint", "pubkey"),
("lp_mint", "pubkey"),
("pool_base_token_account", "pubkey"),
("pool_quote_token_account", "pubkey"),
("lp_supply", "u64"),
("coin_creator", "pubkey"),
("is_mayhem_mode", "bool"),
("is_cashback_coin", "bool"),
("virtual_quote_reserves", "i128"),
]
for field_name, field_type in fields:
if field_type == "pubkey":
value = data[offset : offset + 32]
parsed_data[field_name] = base58.b58encode(value).decode("utf-8")
offset += 32
elif field_type in {"u64", "i64"}:
value = (
struct.unpack("<Q", data[offset : offset + 8])[0]
if field_type == "u64"
else struct.unpack("<q", data[offset : offset + 8])[0]
)
parsed_data[field_name] = value
offset += 8
elif field_type == "i128":
if len(data) < offset + 16:
parsed_data[field_name] = 0
continue
parsed_data[field_name] = int.from_bytes(
data[offset : offset + 16], "little", signed=True
)
offset += 16
elif field_type == "u16":
value = struct.unpack("<H", data[offset : offset + 2])[0]
parsed_data[field_name] = value
offset += 2
elif field_type == "u8":
value = data[offset]
parsed_data[field_name] = value
offset += 1
elif field_type == "bool":
parsed_data[field_name] = (
bool(data[offset]) if len(data) > offset else False
)
offset += 1
return parsed_data
async def show_pool(token_mint: Pubkey) -> None:
"""Find and print one coin's PumpSwap pool.
Args:
token_mint: The coin whose pool to look up
"""
canonical, others = await get_pools_by_base_mint(token_mint, PUMP_AMM_PROGRAM_ID)
if not canonical and not others:
print(
f"No PumpSwap pool for {token_mint}.\n"
"It has not graduated off its bonding curve yet — trade it with\n"
"cookbook/pumpfun/trade/pumpfun_buy_token.py instead."
)
return
if not canonical:
print(
f"No canonical pool for {token_mint}. The {len(others)} pool(s) below "
"carry its base mint but none was created by graduation:"
)
for pool in others:
print(f" {pool}")
return
market_address = canonical[0]
print(market_address)
market_data = await get_market_data(market_address)
for key, value in market_data.items():
print(f" {key}: {value}")
if len(canonical) > 1:
print(f"\nWARNING: {len(canonical)} canonical pools carry this base mint:")
for pool in canonical[1:]:
print(f" {pool}")
if others:
print(
f"\n{len(others)} further pool(s) carry this base mint and are not "
"canonical. Trading one means passing --pool to the buy/sell scripts:"
)
for pool in others:
print(f" {pool}")
# Quote against effective reserves. Upstream's release note says
# virtual_quote_reserves is 0 on all pools; that is out of date — pools carry
# 17.5845 SOL of virtual reserves, so quoting off the raw vault balance
# under-prices by anywhere from a few percent to over 20%.
virtual = market_data.get("virtual_quote_reserves", 0)
if virtual:
quote_mint = Pubkey.from_string(market_data["quote_mint"])
quote_decimals = await read_mint_decimals(quote_mint)
print(
f"\nNote: this pool carries {virtual / 10**quote_decimals:.9f} "
f"of virtual quote reserves ({quote_mint}, {quote_decimals} decimals). "
"Add them to pool_quote_token_account.amount before quoting."
)
def main() -> None:
"""Parse the command line and print the pool."""
parser = argparse.ArgumentParser(description="Find a coin's PumpSwap pool")
parser.add_argument("mint", help="The coin's mint address")
args = parser.parse_args()
asyncio.run(show_pool(Pubkey.from_string(args.mint)))
if __name__ == "__main__":
main()