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
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,8 @@ 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.
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.
- `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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,8 @@ 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`.

### Amounts in JSON output

An exact amount comes twice: in whole units for reading (`tokens_sold`) and as the integer in raw units (`tokens_sold_raw`). Use the `_raw` field for anything that has to add up; the float can drop a unit. An amount known only as an estimate has no `_raw` twin: `quote_received`, the `collect-creator-fee` totals, and `tokens_received` unless the buy ran with `--confirm`, in which case it is read from the confirmed transaction. If that transaction cannot be read back, a confirmed buy also reports the estimate without `tokens_received_raw`, so check for the field. Dry-run fields (`expected_tokens_raw`, `expected_quote_raw`, `min_*_out_raw`) are exact integers of the quote the transaction would be built from, not executed amounts.
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.5"
version = "0.3.6"
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.5"
__version__ = "0.3.6"
4 changes: 2 additions & 2 deletions src/pumpfun_cli/commands/trade.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from pumpfun_cli.core.trade import (
collect_creator_fees as collect_creator_fees_core,
)
from pumpfun_cli.output import error, render
from pumpfun_cli.output import error, render, sol_text


def _route(curve, amm, launchlab, cpmm, force_amm: bool, mint: str, call) -> dict:
Expand Down Expand Up @@ -255,7 +255,7 @@ def sell(
)
if result.get("token_account_closed"):
typer.echo(
f"Closed the emptied token account: {result['rent_recovered_sol']:.6f} SOL"
f"Closed the emptied token account: {sol_text(result['rent_recovered_sol_raw'])} SOL"
" rent back."
)
typer.echo(f"TX: {result['explorer']}")
Expand Down
19 changes: 15 additions & 4 deletions src/pumpfun_cli/commands/wallet.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
transfer_token,
)
from pumpfun_cli.group import JsonAwareGroup
from pumpfun_cli.output import error, render, render_table
from pumpfun_cli.output import error, render, render_table, sol_text

app = typer.Typer(help="Manage wallet keys.", invoke_without_command=True, cls=JsonAwareGroup)

Expand Down Expand Up @@ -302,16 +302,26 @@ def wallet_close_atas(

try:
result = asyncio.run(close_empty_atas(rpc, path, password, confirm=confirm, **overrides))
except ValueError as exc:
except (ValueError, RuntimeError) as exc:
error(str(exc))
if not render(result, ctx.obj and ctx.obj.json_mode):
if result["closed"] == 0:
typer.echo("No empty token accounts to close.")
else:
typer.echo(
f"Closed {result['closed']} empty account(s), recovered ~{result['recovered_sol']} SOL"
f"Closed {result['closed']} empty account(s),"
f" recovered {sol_text(result['recovered_sol_raw'])} SOL"
)
typer.echo(f"TX: {result['explorer']}")
_echo_skipped(result.get("skipped", []))


def _echo_skipped(skipped: list[dict]) -> None:
if skipped:
typer.echo(
f"Left {len(skipped)} empty account(s) this wallet can't close"
" (frozen, or another wallet holds the close authority)."
)


@app.command("drain")
Expand Down Expand Up @@ -363,10 +373,11 @@ def wallet_drain(
elif result["atas_closed"] > 0:
typer.echo(
f"Closed {result['atas_closed']} empty ATA(s),"
f" recovered ~{result['ata_rent_recovered_sol']} SOL"
f" recovered {sol_text(result['ata_rent_recovered_sol_raw'])} SOL"
)
else:
typer.echo("No empty ATAs to close.")
_echo_skipped(result.get("ata_skipped", []))

if result.get("sol_error"):
typer.echo(f"SOL transfer skipped: {result['sol_error']}")
Expand Down
4 changes: 2 additions & 2 deletions src/pumpfun_cli/core/amounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from solders.pubkey import Pubkey

from pumpfun_cli.protocol.client import RpcClient
from pumpfun_cli.protocol.contracts import LAMPORTS_PER_SOL
from pumpfun_cli.protocol.contracts import SOL_DECIMALS
from pumpfun_cli.protocol.token_account import (
TokenHolding,
build_close_emptied_account_instructions,
Expand Down Expand Up @@ -111,5 +111,5 @@ def close_if_emptied(
)
return ixs, {
"token_account_closed": True,
"rent_recovered_sol": holding.lamports / LAMPORTS_PER_SOL,
**amount_fields("rent_recovered_sol", holding.lamports, SOL_DECIMALS),
}
86 changes: 54 additions & 32 deletions src/pumpfun_cli/core/wallet.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
from pathlib import Path

from solders.keypair import Keypair
from solders.pubkey import Pubkey

from pumpfun_cli.core.amounts import amount_fields, to_raw
from pumpfun_cli.core.validate import invalid_pubkey_error, parse_pubkey
Expand Down Expand Up @@ -304,6 +303,12 @@ async def transfer_token(
await client.close()


# Closes per transaction, and compute units for each: a close, or a harvest of
# withheld transfer fees and a close.
_CLOSE_BATCH = 20
_CLOSE_COMPUTE_UNITS = 5_000


async def close_empty_atas(
rpc_url: str,
keystore_path: str,
Expand All @@ -312,53 +317,68 @@ async def close_empty_atas(
priority_fee: int | None = None,
compute_units: int | None = None,
) -> dict:
from solders.instruction import AccountMeta, Instruction
"""Close the wallet's empty token accounts, up to 20 per run, 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.
"""
from pumpfun_cli.protocol.client import RpcClient
from pumpfun_cli.protocol.contracts import TOKEN_2022_PROGRAM, TOKEN_PROGRAM
from pumpfun_cli.protocol.token_account import build_close_emptied_account_instructions

keypair = decrypt_keypair(Path(keystore_path), password)
pubkey = keypair.pubkey()
client = RpcClient(rpc_url)
try:
all_accounts = await client.get_token_accounts_by_owner(pubkey, TOKEN_PROGRAM)
all_accounts += await client.get_token_accounts_by_owner(pubkey, TOKEN_2022_PROGRAM)
empty = [a for a in all_accounts if a["amount"] == 0]
if not empty:
return {"closed": 0, "recovered_sol": 0.0, "signature": None}
closable, skipped = [], []
for program in (TOKEN_PROGRAM, TOKEN_2022_PROGRAM):
for account, mint, holding in await client.get_token_holdings(pubkey, program):
if holding.amount:
continue
if holding.closable_by(pubkey):
closable.append((account, mint, program, holding))
else:
reason = "frozen" if holding.frozen else "close_authority"
skipped.append({"address": str(account), "mint": str(mint), "reason": reason})
result = {
"closed": 0,
**amount_fields("recovered_sol", 0, SOL_DECIMALS),
"signature": None,
}
if skipped:
result["skipped"] = skipped
batch = closable[:_CLOSE_BATCH]
if not batch:
return result

# Batch up to 20 close instructions per tx
instructions = []
for acc in empty[:20]:
token_prog = Pubkey.from_string(acc["program"])
ata = Pubkey.from_string(acc["address"])
# SPL Token CloseAccount instruction (index 9)
ix = Instruction(
program_id=token_prog,
accounts=[
AccountMeta(pubkey=ata, is_signer=False, is_writable=True),
AccountMeta(pubkey=pubkey, is_signer=False, is_writable=True),
AccountMeta(pubkey=pubkey, is_signer=True, is_writable=False),
],
data=bytes([9]),
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,
)
instructions.append(ix)

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 100_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}",
}
)
# Each ATA holds ~0.00203928 SOL rent
recovered = len(instructions) * 0.00203928
result = {
"closed": len(instructions),
"recovered_sol": round(recovered, 6),
"signature": sig,
"explorer": f"https://solscan.io/tx/{sig}",
}
if confirm:
result["confirmed"] = True
return result
Expand Down Expand Up @@ -403,7 +423,7 @@ async def drain_wallet(
except Exception as e:
ata_result = {
"closed": 0,
"recovered_sol": 0.0,
**amount_fields("recovered_sol", 0, SOL_DECIMALS),
"signature": None,
"ata_error": str(e),
}
Expand All @@ -426,8 +446,10 @@ async def drain_wallet(
"non_empty_token_accounts": non_empty_tokens,
"atas_closed": ata_result["closed"],
"ata_rent_recovered_sol": ata_result["recovered_sol"],
"ata_rent_recovered_sol_raw": ata_result.get("recovered_sol_raw", 0),
"ata_signature": ata_result.get("signature"),
"ata_error": ata_result.get("ata_error"),
"ata_skipped": ata_result.get("skipped", []),
"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
5 changes: 5 additions & 0 deletions src/pumpfun_cli/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,8 @@ def error(message: str, hint: str | None = None, exit_code: int = 1) -> NoReturn
if hint:
_console.print(f" {hint}")
raise SystemExit(exit_code)


def sol_text(lamports: int) -> str:
"""Lamports as an exact SOL amount, all nine decimals."""
return f"{lamports // 10**9}.{lamports % 10**9:09d}"
26 changes: 26 additions & 0 deletions src/pumpfun_cli/protocol/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,32 @@ async def get_token_account(self, token_account: Pubkey) -> TokenHolding:
return TokenHolding()
return parse_token_account(bytes(resp.value.data), resp.value.lamports)

async def get_token_holdings(
self, owner: Pubkey, token_program: Pubkey
) -> list[tuple[Pubkey, Pubkey, TokenHolding]]:
"""(account, mint, holding) for every `token_program` account `owner` owns,
as of "confirmed".

Raises:
RuntimeError: The RPC didn't answer; an empty list would read as "none".
"""
failure = None
try:
resp = await self.rpc.get_token_accounts_by_owner(
owner, TokenAccountOpts(program_id=token_program), commitment="confirmed"
)
except Exception as exc: # noqa: BLE001 - its text can carry the RPC URL
failure = type(exc).__name__
if failure:
# Raised outside the handler so the original, URL and all, isn't chained.
raise RuntimeError(f"Couldn't list the wallet's token accounts ({failure}).")
rows = []
for item in resp.value:
data = bytes(item.account.data)
holding = parse_token_account(data, item.account.lamports)
rows.append((item.pubkey, Pubkey.from_bytes(data[:32]), holding))
return rows

async def get_token_accounts_by_owner(
self,
owner: Pubkey,
Expand Down
42 changes: 41 additions & 1 deletion tests/test_commands/test_human_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,12 @@ def test_a_sale_that_closes_the_account_says_so(wallet):
"tokens_sold": 6.0,
"token_account_closed": True,
"rent_recovered_sol": 0.00207408,
"rent_recovered_sol_raw": 2_074_080,
"explorer": "x",
}
sold = runner.invoke(app, ["--rpc", "http://rpc", "sell", MINT, "all"])
assert sold.exit_code == 0
assert "Closed the emptied token account: 0.002074 SOL rent back." in sold.output
assert "Closed the emptied token account: 0.002074080 SOL rent back." in sold.output


def test_dry_runs(wallet):
Expand Down Expand Up @@ -401,3 +402,42 @@ def test_info_for_a_launchlab_coin(wallet, graduated):
assert shown.exit_code == 0, shown.output
assert "StonkFun (Raydium LaunchLab)" in shown.output
assert "Transfer fee: 100 bps" in shown.output


def test_close_atas_reports_exact_rent_and_what_it_left(wallet):
with (
_human("wallet"),
patch("pumpfun_cli.commands.wallet.close_empty_atas", new_callable=AsyncMock) as close,
):
close.return_value = {
"closed": 2,
"recovered_sol": 0.00355312,
"recovered_sol_raw": 3_553_120,
"signature": "s",
"explorer": "x",
"skipped": [{"address": "a", "mint": "m", "reason": "frozen"}],
}
out = runner.invoke(app, ["--rpc", "http://rpc", "wallet", "close-atas"])
assert out.exit_code == 0
assert "Closed 2 empty account(s), recovered 0.003553120 SOL" in out.output
assert "Left 1 empty account(s) this wallet can't close" in out.output


def test_close_atas_reports_a_failed_listing_instead_of_nothing_to_close(wallet):
with patch(
"pumpfun_cli.commands.wallet.close_empty_atas",
new_callable=AsyncMock,
side_effect=RuntimeError("Couldn't list the wallet's token accounts (ReadTimeout)."),
):
out = runner.invoke(app, ["--rpc", "http://rpc", "wallet", "close-atas"])
assert out.exit_code == 1
assert "Couldn't list the wallet's token accounts" in out.output
assert "No empty token accounts" not in out.output


def test_sol_text_is_exact():
from pumpfun_cli.output import sol_text

assert sol_text(3_002_280) == "0.003002280"
assert sol_text(12_000_000_001) == "12.000000001"
assert sol_text(0) == "0.000000000"
1 change: 1 addition & 0 deletions tests/test_commands/test_wallet_cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,7 @@ def test_wallet_drain_happy_path(tmp_path):
"non_empty_token_accounts": [],
"atas_closed": 2,
"ata_rent_recovered_sol": 0.004,
"ata_rent_recovered_sol_raw": 4_000_000,
"ata_signature": "atasig",
"ata_error": None,
"sol_transferred": 0.99,
Expand Down
Loading
Loading