Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,12 @@ lists; these are the ones this CLI depends on.
transaction (`close_if_emptied`), on every venue. Token-2022 won't close an
account holding withheld transfer fees, so they are harvested to the mint
first. An account whose close authority is another wallet, or a frozen one,
stays open. `wallet close-atas` closes empty accounts the same way and lists
the ones it can't close in `skipped`, since one failed close reverts the batch.
stays open. `wallet close-atas` closes empty accounts the same way, 20 per
transaction, and lists the ones it can't close in `skipped`, since one failed
close reverts its batch.
- Never ask the user to run a command again to finish a job: a command that
needs several transactions sends them all (`close-atas`, the sweeps in
`collect-creator-fee`), confirming any whose effect a later one depends on.
- `create_v2` rejects cashback (6082). A creator fee only applies on a coin
priced in a `QuoteControl` mint, and mayhem coins must be SOL-priced; launch
refuses both before sending.
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ Amounts are in the coin's quote asset. Most pump.fun coins are priced in SOL, bu

A LaunchLab coin priced in anything but SOL is found with `getProgramAccounts`, so it needs an RPC that serves it.

`collect-creator-fee` first sweeps the creator fees still waiting on your coins' curves and pools into your vaults, the largest eight per run; run it again if it says more coins hold fees. It finds them with `getProgramAccounts`; without that method it collects only what the vaults already hold.
`collect-creator-fee` first sweeps the creator fees still waiting on your coins' curves and pools into your vaults: the largest eight in the collect transaction, any others in transactions of eight sent and confirmed before it. It finds them with `getProgramAccounts`; without that method it collects only what the vaults already hold.

### Transfer fees

Expand All @@ -170,7 +170,7 @@ Some LaunchLab coins (StonkFun reward coins, for example) are Token-2022 mints w

A sell that empties the coin's token account (`all`, or exactly the balance) closes the account in the same transaction and returns its rent: `token_account_closed` and `rent_recovered_sol` in the output. Withheld transfer fees in a Token-2022 account go to the mint first, since the account can't close while it holds them. A partial sell, a sell the curve can only partly pay for, or an account whose close authority is another wallet leaves the account open.

`wallet close-atas` closes up to 20 empty token accounts per run the same way, reports the rent they held in `recovered_sol`, and lists any it can't close (frozen, or another wallet's close authority) in `skipped`.
`wallet close-atas` closes every empty token account the same way, 20 per transaction (`signatures` lists them all), reports the rent they held in `recovered_sol`, and lists any it can't close (frozen, or another wallet's close authority) in `skipped`. `wallet drain` waits for those closes to land before it sends the SOL, so the rent goes with it.

### Amounts in JSON output

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "pumpfun-cli"
version = "0.3.6"
version = "0.3.7"
description = "CLI for pump.fun and Raydium LaunchLab on Solana — trade, launch, and browse tokens"
readme = "README.md"
license = {text = "Apache-2.0"}
Expand Down
2 changes: 1 addition & 1 deletion src/pumpfun_cli/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
"""pumpfun-cli — CLI for pump.fun on Solana."""

__version__ = "0.3.6"
__version__ = "0.3.7"
4 changes: 0 additions & 4 deletions src/pumpfun_cli/commands/trade.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,10 +353,6 @@ def collect_creator_fee(
symbol = result["quote_symbol"]
typer.echo(f"Pump.fun fees: {result['pump_recovered']:.6f} {symbol}")
typer.echo(f"PumpSwap fees: {result['pumpswap_recovered']:.6f} {symbol}")
if result.get("coins_still_waiting"):
typer.echo(
f"{result['coins_still_waiting']} more coins hold fees; run it again to collect them."
)
if result.get("sweep_warning"):
typer.echo(f"Warning: {result['sweep_warning']}")
typer.echo(f"TX: {result['explorer']}")
7 changes: 6 additions & 1 deletion src/pumpfun_cli/commands/wallet.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,10 @@ def wallet_close_atas(
f"Closed {result['closed']} empty account(s),"
f" recovered {sol_text(result['recovered_sol_raw'])} SOL"
)
typer.echo(f"TX: {result['explorer']}")
for sig in result["signatures"]:
typer.echo(f"TX: https://solscan.io/tx/{sig}")
if result.get("incomplete"):
typer.echo(f"Stopped early: {result['incomplete']}")
_echo_skipped(result.get("skipped", []))


Expand Down Expand Up @@ -377,6 +380,8 @@ def wallet_drain(
)
else:
typer.echo("No empty ATAs to close.")
if result.get("ata_incomplete"):
typer.echo(f"Stopped early: {result['ata_incomplete']}")
_echo_skipped(result.get("ata_skipped", []))

if result.get("sol_error"):
Expand Down
131 changes: 92 additions & 39 deletions src/pumpfun_cli/core/trade.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,11 @@
find_ata,
find_user_volume_accumulator,
)
from pumpfun_cli.protocol.client import RpcClient, TransactionFailedError
from pumpfun_cli.protocol.client import (
RpcClient,
TransactionFailedError,
TransactionNotSentError,
)
from pumpfun_cli.protocol.contracts import (
ATA_RENT_LAMPORTS,
LAMPORTS_PER_SOL,
Expand Down Expand Up @@ -593,6 +597,74 @@ async def migrate_token(
SWEEP_COMPUTE_UNITS = 40_000


def _sweep_instruction(w, creator: Pubkey, quote_mint: Pubkey, quote_program: Pubkey):
"""Move one coin's waiting creator fee into the creator's vault."""
if isinstance(w, WaitingCurve):
return build_sweep_creator_fee_instruction(
payer=creator,
mint=w.mint,
creator=creator,
quote_mint=quote_mint,
quote_token_program=quote_program,
)
return build_pumpswap_sweep_creator_fee_instruction(
payer=creator, pool_address=w.address, pool=w.pool, quote_token_program=quote_program
)


async def _sweep_ahead(
client: RpcClient,
keypair,
waiting: list,
quote_mint: Pubkey,
quote_program: Pubkey,
priority_fee: int | None,
) -> tuple[list, str | None]:
"""Sweep `waiting` in transactions of `MAX_SWEEPS`, each confirmed so its fees
are in the vaults before the collect. Returns what was swept, and why it
stopped early if it did."""
creator = keypair.pubkey()
swept = []
for i in range(0, len(waiting), MAX_SWEEPS):
chunk = waiting[i : i + MAX_SWEEPS]
try:
await client.send_tx(
[_sweep_instruction(w, creator, quote_mint, quote_program) for w in chunk],
[keypair],
confirm=True,
priority_fee=priority_fee if priority_fee is not None else DEFAULT_PRIORITY_FEE,
compute_units=SWEEP_COMPUTE_UNITS * len(chunk),
)
except (TransactionFailedError, TransactionNotSentError) as exc:
left = len(waiting) - len(swept)
return swept, f"{left} coin(s) not swept, their fees still wait on them: {exc}"
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
except RuntimeError as exc:
return (
swept,
f"A sweep's outcome is unknown ({exc}); collected what reached the vaults.",
)
swept += chunk
return swept, None


async def _vault_balances(
client: RpcClient, creator: Pubkey, quote_mint: Pubkey, quote_program: Pubkey
) -> tuple[int, int]:
"""Collectable fees in the creator's pump.fun and PumpSwap vaults, as of "confirmed".

A SOL pump.fun vault holds lamports itself and keeps its rent-exempt
minimum; any other quote sits in the vault's ATA.
"""
vault = derive_creator_vault(creator)
if is_sol(quote_mint):
rent_floor = await client.get_minimum_balance_for_rent_exemption(0)
pump = max(0, await client.get_balance(vault, commitment="confirmed") - rent_floor)
else:
pump = (await client.get_token_account(find_ata(vault, quote_mint, quote_program))).amount
amm_ata = find_ata(derive_amm_creator_vault(creator), quote_mint, quote_program)
return pump, (await client.get_token_account(amm_ata)).amount


async def collect_creator_fees(
rpc_url: str,
keystore_path: str,
Expand All @@ -606,7 +678,9 @@ async def collect_creator_fees(

Vaults are per creator and per quote asset, so fees earned in USDC are
collected with a separate run. Fees still waiting on the creator's curves
and pools are swept into the vaults first, the largest `MAX_SWEEPS` per run.
and pools are swept into the vaults first: the largest `MAX_SWEEPS` in the
collect transaction, any others in sweep-only transactions of `MAX_SWEEPS`
sent and confirmed before it.
"""
keypair = decrypt_keypair(Path(keystore_path), password)
creator = keypair.pubkey()
Expand All @@ -616,20 +690,8 @@ async def collect_creator_fees(
_, quote_decimals = await get_mint_info(client, quote_mint)
instructions = []

# pump.fun: a SOL vault holds lamports itself, and keeps its rent-exempt
# minimum; any other quote sits in the vault's ATA.
vault = derive_creator_vault(creator)
if is_sol(quote_mint):
rent_floor = await client.get_minimum_balance_for_rent_exemption(0)
pump_balance = max(0, await client.get_balance(vault) - rent_floor)
else:
pump_balance = await client.get_token_account_balance(
find_ata(vault, quote_mint, quote_program)
)

amm_vault = derive_amm_creator_vault(creator)
pumpswap_balance = await client.get_token_account_balance(
find_ata(amm_vault, quote_mint, quote_program)
pump_balance, pumpswap_balance = await _vault_balances(
client, creator, quote_mint, quote_program
)

search_failed = False
Expand All @@ -641,9 +703,18 @@ async def collect_creator_fees(
waiting_curves, waiting_pools = [], []
search_failed = True
waiting = sorted([*waiting_curves, *waiting_pools], key=lambda w: w.amount, reverse=True)
sweeps, still_waiting = waiting[:MAX_SWEEPS], len(waiting) - MAX_SWEEPS
sweeps, extra = waiting[:MAX_SWEEPS], waiting[MAX_SWEEPS:]
swept_first, sweep_failure = await _sweep_ahead(
client, keypair, extra, quote_mint, quote_program, priority_fee
)
if extra:
# Whatever the extra sweeps reported, what landed is in the vaults now.
pump_balance, pumpswap_balance = await _vault_balances(
client, creator, quote_mint, quote_program
)
pump_balance += sum(w.amount for w in sweeps if isinstance(w, WaitingCurve))
pumpswap_balance += sum(w.amount for w in sweeps if isinstance(w, WaitingPool))
swept = [*sweeps, *swept_first]

if pump_balance <= 0 and pumpswap_balance <= 0:
if search_failed:
Expand All @@ -661,6 +732,8 @@ async def collect_creator_fees(
sweep_warning = (
f"{_SEARCH_FAILED}; collected what the vaults hold." if search_failed else None
)
if sweep_failure:
sweep_warning = sweep_failure

if pumpswap_balance > 0 or not is_sol(quote_mint):
# Both payouts land in the creator's token account for the quote asset.
Expand All @@ -669,26 +742,7 @@ async def collect_creator_fees(
creator, creator, quote_mint, quote_program
)
)
for w in sweeps:
if isinstance(w, WaitingCurve):
instructions.append(
build_sweep_creator_fee_instruction(
payer=creator,
mint=w.mint,
creator=creator,
quote_mint=quote_mint,
quote_token_program=quote_program,
)
)
else:
instructions.append(
build_pumpswap_sweep_creator_fee_instruction(
payer=creator,
pool_address=w.address,
pool=w.pool,
quote_token_program=quote_program,
)
)
instructions += [_sweep_instruction(w, creator, quote_mint, quote_program) for w in sweeps]
if pump_balance > 0:
instructions.append(
build_collect_creator_fee_v2_instruction(
Expand Down Expand Up @@ -726,8 +780,7 @@ async def collect_creator_fees(
# between are collected too.
pump_recovered=pump_balance / 10**quote_decimals,
pumpswap_recovered=pumpswap_balance / 10**quote_decimals,
coins_swept=len(sweeps),
**({"coins_still_waiting": still_waiting} if still_waiting > 0 else {}),
coins_swept=len(swept),
**({"sweep_warning": sweep_warning} if sweep_warning else {}),
)
finally:
Expand Down
77 changes: 46 additions & 31 deletions src/pumpfun_cli/core/wallet.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,11 +317,13 @@ async def close_empty_atas(
priority_fee: int | None = None,
compute_units: int | None = None,
) -> dict:
"""Close the wallet's empty token accounts, up to 20 per run, and recover their rent.
"""Close all of the wallet's empty token accounts and recover their rent.

Withheld Token-2022 transfer fees go to the mint first. An account the
wallet can't close (frozen, or with another close authority) is left and
listed in `skipped`, since one failed close would revert the batch.
One transaction per 20 accounts. Withheld Token-2022 transfer fees go to
the mint first. An account the wallet can't close (frozen, or with another
close authority) is left and listed in `skipped`, since one failed close
would revert its batch. If a batch fails after others landed, the result
reports what closed and the failure in `incomplete`.
"""
from pumpfun_cli.protocol.client import RpcClient
from pumpfun_cli.protocol.contracts import TOKEN_2022_PROGRAM, TOKEN_PROGRAM
Expand All @@ -348,35 +350,46 @@ async def close_empty_atas(
}
if skipped:
result["skipped"] = skipped
batch = closable[:_CLOSE_BATCH]
if not batch:
signatures, recovered = [], 0
for i in range(0, len(closable), _CLOSE_BATCH):
batch = closable[i : i + _CLOSE_BATCH]
instructions = []
for account, mint, program, holding in batch:
instructions += build_close_emptied_account_instructions(
user=pubkey,
mint=mint,
account=account,
token_program=program,
withheld=holding.withheld,
)
try:
sig = await client.send_tx(
instructions,
[keypair],
confirm=confirm,
priority_fee=priority_fee if priority_fee is not None else 200_000,
compute_units=compute_units
if compute_units is not None
else _CLOSE_COMPUTE_UNITS * len(batch),
)
except RuntimeError as exc:
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if not signatures:
raise
result["incomplete"] = (
f"{len(closable) - result['closed']} account(s) not closed: {exc}"
)
break
signatures.append(sig)
recovered += sum(holding.lamports for *_, holding in batch)
result["closed"] += len(batch)
if not signatures:
return result

instructions = []
for account, mint, program, holding in batch:
instructions += build_close_emptied_account_instructions(
user=pubkey,
mint=mint,
account=account,
token_program=program,
withheld=holding.withheld,
)
sig = await client.send_tx(
instructions,
[keypair],
confirm=confirm,
priority_fee=priority_fee if priority_fee is not None else 200_000,
compute_units=compute_units
if compute_units is not None
else _CLOSE_COMPUTE_UNITS * len(batch),
)
recovered = sum(holding.lamports for *_, holding in batch)
result.update(
{
"closed": len(batch),
**amount_fields("recovered_sol", recovered, SOL_DECIMALS),
"signature": sig,
"explorer": f"https://solscan.io/tx/{sig}",
"signature": signatures[0],
"signatures": signatures,
"explorer": f"https://solscan.io/tx/{signatures[0]}",
}
)
if confirm:
Expand Down Expand Up @@ -410,13 +423,14 @@ async def drain_wallet(
token_result = await list_token_accounts(rpc_url, wallet_pubkey, show_empty=False)
non_empty_tokens = token_result["token_accounts"]

# Step 2 — Close empty ATAs
# Step 2 — Close empty ATAs. Always confirmed: the rent has to be back in
# the wallet before step 3 reads the balance it sends.
try:
ata_result = await close_empty_atas(
rpc_url,
keystore_path,
password,
confirm=confirm,
confirm=True,
priority_fee=priority_fee,
compute_units=compute_units,
)
Expand Down Expand Up @@ -450,6 +464,7 @@ async def drain_wallet(
"ata_signature": ata_result.get("signature"),
"ata_error": ata_result.get("ata_error"),
"ata_skipped": ata_result.get("skipped", []),
**({"ata_incomplete": ata_result["incomplete"]} if "incomplete" in ata_result else {}),
"sol_transferred": sol_result.get("sol_amount", 0),
"sol_transferred_raw": sol_result.get("sol_amount_raw", 0),
"sol_signature": sol_result.get("signature"),
Expand Down
Loading
Loading