From 32e2f9f58f0d4ddc48530406ffd7d543b4e02f3c Mon Sep 17 00:00:00 2001 From: Anton Sauchyk Date: Mon, 23 Nov 2026 19:05:19 +0100 Subject: [PATCH 1/3] fix(close-atas): harvest withheld fees, skip unclosable accounts, report exact rent (0.3.6) An empty Token-2022 account still holding withheld transfer fees made the whole close-atas batch revert. Those fees now go to the mint first, accounts the wallet can't close are left out and listed in `skipped`, and the rent reported is what the closed accounts held. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 3 +- README.md | 2 + pyproject.toml | 2 +- src/pumpfun_cli/__init__.py | 2 +- src/pumpfun_cli/commands/wallet.py | 15 ++- src/pumpfun_cli/core/wallet.py | 81 +++++++++------- src/pumpfun_cli/protocol/client.py | 18 ++++ tests/test_commands/test_human_output.py | 18 ++++ tests/test_core/test_close_atas.py | 107 ++++++++++++++++++++++ tests/test_core/test_wallet.py | 9 +- tests/test_protocol/test_token_account.py | 12 +++ uv.lock | 2 +- 12 files changed, 232 insertions(+), 39 deletions(-) create mode 100644 tests/test_core/test_close_atas.py diff --git a/AGENTS.md b/AGENTS.md index 82ff09f..14304ae 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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. diff --git a/README.md b/README.md index fecc037..0351c06 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/pyproject.toml b/pyproject.toml index 46a9306..c95eb44 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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"} diff --git a/src/pumpfun_cli/__init__.py b/src/pumpfun_cli/__init__.py index d88497b..2013f91 100644 --- a/src/pumpfun_cli/__init__.py +++ b/src/pumpfun_cli/__init__.py @@ -1,3 +1,3 @@ """pumpfun-cli — CLI for pump.fun on Solana.""" -__version__ = "0.3.5" +__version__ = "0.3.6" diff --git a/src/pumpfun_cli/commands/wallet.py b/src/pumpfun_cli/commands/wallet.py index 280157a..95d4275 100644 --- a/src/pumpfun_cli/commands/wallet.py +++ b/src/pumpfun_cli/commands/wallet.py @@ -309,9 +309,19 @@ def wallet_close_atas( 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 {result['recovered_sol']:.6f} 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") @@ -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 {result['ata_rent_recovered_sol']:.6f} 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']}") diff --git a/src/pumpfun_cli/core/wallet.py b/src/pumpfun_cli/core/wallet.py index 3fbfe48..a7cfa32 100644 --- a/src/pumpfun_cli/core/wallet.py +++ b/src/pumpfun_cli/core/wallet.py @@ -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 @@ -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, @@ -312,53 +317,64 @@ 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.contracts import LAMPORTS_PER_SOL, 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, "recovered_sol": 0.0, "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), + "recovered_sol": recovered / LAMPORTS_PER_SOL, + "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 @@ -428,6 +444,7 @@ async def drain_wallet( "ata_rent_recovered_sol": ata_result["recovered_sol"], "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"), diff --git a/src/pumpfun_cli/protocol/client.py b/src/pumpfun_cli/protocol/client.py index ffda795..25b6774 100644 --- a/src/pumpfun_cli/protocol/client.py +++ b/src/pumpfun_cli/protocol/client.py @@ -145,6 +145,24 @@ 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"; empty if the RPC can't answer.""" + try: + resp = await self.rpc.get_token_accounts_by_owner( + owner, TokenAccountOpts(program_id=token_program), commitment="confirmed" + ) + except Exception: + return [] + 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, diff --git a/tests/test_commands/test_human_output.py b/tests/test_commands/test_human_output.py index 1ee98d3..2fc9e21 100644 --- a/tests/test_commands/test_human_output.py +++ b/tests/test_commands/test_human_output.py @@ -401,3 +401,21 @@ 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, + "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.003553 SOL" in out.output + assert "Left 1 empty account(s) this wallet can't close" in out.output diff --git a/tests/test_core/test_close_atas.py b/tests/test_core/test_close_atas.py new file mode 100644 index 0000000..0612741 --- /dev/null +++ b/tests/test_core/test_close_atas.py @@ -0,0 +1,107 @@ +"""Closing the wallet's empty token accounts (`wallet close-atas`).""" + +from unittest.mock import AsyncMock, MagicMock, patch + +from solders.keypair import Keypair +from solders.pubkey import Pubkey + +from pumpfun_cli.core.wallet import close_empty_atas +from pumpfun_cli.crypto import encrypt_keypair +from pumpfun_cli.protocol.contracts import TOKEN_2022_PROGRAM, TOKEN_PROGRAM +from pumpfun_cli.protocol.token_account import TokenHolding +from tests.test_core.helpers import assert_closes, assert_harvests, closed_accounts + + +def _wallet(tmp_path) -> tuple[str, Pubkey]: + keypair = Keypair() + encrypt_keypair(keypair, "testpass", tmp_path / "wallet.enc") + return str(tmp_path / "wallet.enc"), keypair.pubkey() + + +def _client(accounts: list[tuple[Pubkey, TokenHolding]]) -> MagicMock: + """A client holding `accounts` as (token program, holding), each at a fresh address.""" + rows = [(Pubkey.new_unique(), Pubkey.new_unique(), program, h) for program, h in accounts] + client = MagicMock() + client.rows = rows + + async def holdings(owner, program): + return [(a, m, h) for a, m, p, h in rows if p == program] + + async def parsed(owner, program, commitment=None): + return [ + {"address": str(a), "mint": str(m), "amount": h.amount, "program": str(p)} + for a, m, p, h in rows + if p == program + ] + + client.get_token_holdings = holdings + client.get_token_accounts_by_owner = parsed + client.send_tx = AsyncMock(return_value="sig") + client.close = AsyncMock() + return client + + +async def _run(tmp_path, accounts, **kwargs): + keyfile, user = _wallet(tmp_path) + holdings = [(p, TokenHolding(**{"closer": user, **h})) for p, h in accounts] + client = _client(holdings) + with patch("pumpfun_cli.protocol.client.RpcClient", return_value=client): + result = await close_empty_atas("http://rpc", keyfile, "testpass", **kwargs) + return result, client, user + + +async def test_withheld_fees_are_harvested_and_rent_is_what_the_accounts_held(tmp_path): + result, client, user = await _run( + tmp_path, + [ + (TOKEN_PROGRAM, {"lamports": 2_039_280}), + (TOKEN_2022_PROGRAM, {"lamports": 1_513_840, "withheld": 42}), + (TOKEN_2022_PROGRAM, {"amount": 5, "lamports": 1_513_840}), + ], + ) + (spl, _, spl_prog, _), (t22, t22_mint, _, _), _ = client.rows + close_spl, harvest, close_t22 = client.send_tx.call_args.args[0] + assert_closes(close_spl, spl, user, spl_prog) + assert_harvests(harvest, t22_mint, t22) + assert_closes(close_t22, t22, user, TOKEN_2022_PROGRAM) + assert result["closed"] == 2 + assert result["recovered_sol"] == (2_039_280 + 1_513_840) / 10**9 + assert "skipped" not in result + + +async def test_accounts_the_wallet_cant_close_are_left_out_of_the_batch(tmp_path): + other = Pubkey.new_unique() + result, client, user = await _run( + tmp_path, + [ + (TOKEN_PROGRAM, {"lamports": 2_039_280}), + (TOKEN_2022_PROGRAM, {"lamports": 1, "frozen": True}), + (TOKEN_2022_PROGRAM, {"lamports": 1, "closer": other}), + ], + ) + ok, frozen, foreign = (row[0] for row in client.rows) + assert closed_accounts(client.send_tx.call_args.args[0]) == [ok] + assert result["closed"] == 1 + assert result["skipped"] == [ + {"address": str(frozen), "mint": str(client.rows[1][1]), "reason": "frozen"}, + {"address": str(foreign), "mint": str(client.rows[2][1]), "reason": "close_authority"}, + ] + + +async def test_nothing_closable_sends_nothing(tmp_path): + result, client, _ = await _run(tmp_path, [(TOKEN_2022_PROGRAM, {"frozen": True})]) + client.send_tx.assert_not_called() + assert result["closed"] == 0 and result["signature"] is None + assert result["skipped"][0]["reason"] == "frozen" + + +async def test_a_run_closes_twenty_with_compute_for_each(tmp_path): + result, client, _ = await _run(tmp_path, [(TOKEN_PROGRAM, {"lamports": 1})] * 25) + assert result["closed"] == 20 + assert len(client.send_tx.call_args.args[0]) == 20 + assert client.send_tx.call_args.kwargs["compute_units"] == 100_000 + + +async def test_compute_units_override(tmp_path): + _, client, _ = await _run(tmp_path, [(TOKEN_PROGRAM, {})], compute_units=55_000) + assert client.send_tx.call_args.kwargs["compute_units"] == 55_000 diff --git a/tests/test_core/test_wallet.py b/tests/test_core/test_wallet.py index cbaf85b..c0f14c5 100644 --- a/tests/test_core/test_wallet.py +++ b/tests/test_core/test_wallet.py @@ -535,7 +535,12 @@ async def test_drain_wallet_happy_path(tmp_path): patch( "pumpfun_cli.core.wallet.close_empty_atas", new_callable=AsyncMock, - return_value={"closed": 3, "recovered_sol": 0.006118, "signature": "atasig"}, + return_value={ + "closed": 3, + "recovered_sol": 0.006118, + "signature": "atasig", + "skipped": [{"address": "a", "mint": "m", "reason": "frozen"}], + }, ), patch( "pumpfun_cli.core.wallet.transfer_all_sol", @@ -555,6 +560,7 @@ async def test_drain_wallet_happy_path(tmp_path): assert result["atas_closed"] == 3 assert result["sol_transferred"] == 0.99 assert result["ata_signature"] == "atasig" + assert result["ata_skipped"] == [{"address": "a", "mint": "m", "reason": "frozen"}] assert result["sol_signature"] == "solsig" assert result["non_empty_token_accounts"] == [] assert result.get("ata_error") is None @@ -626,6 +632,7 @@ async def test_drain_wallet_no_empty_atas(tmp_path): ) assert result["atas_closed"] == 0 + assert result["ata_skipped"] == [] assert result["sol_transferred"] == 1.0 assert result["sol_signature"] == "solsig2" diff --git a/tests/test_protocol/test_token_account.py b/tests/test_protocol/test_token_account.py index 3638f07..158719e 100644 --- a/tests/test_protocol/test_token_account.py +++ b/tests/test_protocol/test_token_account.py @@ -109,3 +109,15 @@ async def test_client_reads_a_missing_account_as_empty(): client = RpcClient("http://rpc") client.rpc.get_account_info = AsyncMock(return_value=SimpleNamespace(value=None)) assert await client.get_token_account(ACCOUNT) == TokenHolding() + + +async def test_client_lists_the_owners_accounts_with_their_holdings(): + client = RpcClient("http://rpc") + item = SimpleNamespace( + pubkey=ACCOUNT, + account=SimpleNamespace(data=_account(0, [(2, struct.pack(" Date: Mon, 23 Nov 2026 20:40:06 +0100 Subject: [PATCH 2/3] fix: report recovered rent in exact lamports too recovered_sol, ata_rent_recovered_sol and a sell's rent_recovered_sol were floats only; each now has its _raw twin in lamports, like other exact amounts. Co-Authored-By: Claude Opus 5.5 --- src/pumpfun_cli/core/amounts.py | 4 ++-- src/pumpfun_cli/core/wallet.py | 13 +++++++++---- tests/test_core/test_close_atas.py | 1 + tests/test_core/test_trade.py | 1 + tests/test_core/test_wallet.py | 2 ++ 5 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/pumpfun_cli/core/amounts.py b/src/pumpfun_cli/core/amounts.py index b1fc429..9de168d 100644 --- a/src/pumpfun_cli/core/amounts.py +++ b/src/pumpfun_cli/core/amounts.py @@ -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, @@ -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), } diff --git a/src/pumpfun_cli/core/wallet.py b/src/pumpfun_cli/core/wallet.py index a7cfa32..5bc1ce1 100644 --- a/src/pumpfun_cli/core/wallet.py +++ b/src/pumpfun_cli/core/wallet.py @@ -324,7 +324,7 @@ async def close_empty_atas( listed in `skipped`, since one failed close would revert the batch. """ from pumpfun_cli.protocol.client import RpcClient - from pumpfun_cli.protocol.contracts import LAMPORTS_PER_SOL, TOKEN_2022_PROGRAM, TOKEN_PROGRAM + 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) @@ -341,7 +341,11 @@ async def close_empty_atas( else: reason = "frozen" if holding.frozen else "close_authority" skipped.append({"address": str(account), "mint": str(mint), "reason": reason}) - result = {"closed": 0, "recovered_sol": 0.0, "signature": None} + result = { + "closed": 0, + **amount_fields("recovered_sol", 0, SOL_DECIMALS), + "signature": None, + } if skipped: result["skipped"] = skipped batch = closable[:_CLOSE_BATCH] @@ -370,7 +374,7 @@ async def close_empty_atas( result.update( { "closed": len(batch), - "recovered_sol": recovered / LAMPORTS_PER_SOL, + **amount_fields("recovered_sol", recovered, SOL_DECIMALS), "signature": sig, "explorer": f"https://solscan.io/tx/{sig}", } @@ -419,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), } @@ -442,6 +446,7 @@ 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", []), diff --git a/tests/test_core/test_close_atas.py b/tests/test_core/test_close_atas.py index 0612741..9478c5a 100644 --- a/tests/test_core/test_close_atas.py +++ b/tests/test_core/test_close_atas.py @@ -66,6 +66,7 @@ async def test_withheld_fees_are_harvested_and_rent_is_what_the_accounts_held(tm assert_closes(close_t22, t22, user, TOKEN_2022_PROGRAM) assert result["closed"] == 2 assert result["recovered_sol"] == (2_039_280 + 1_513_840) / 10**9 + assert result["recovered_sol_raw"] == 2_039_280 + 1_513_840 assert "skipped" not in result diff --git a/tests/test_core/test_trade.py b/tests/test_core/test_trade.py index 9bbb11a..6ef3d85 100644 --- a/tests/test_core/test_trade.py +++ b/tests/test_core/test_trade.py @@ -234,6 +234,7 @@ async def test_sell_all(tmp_keystore): assert_closes(close, find_ata(user, COIN, TOKEN_2022_PROGRAM), user, TOKEN_2022_PROGRAM) assert result["token_account_closed"] is True assert result["rent_recovered_sol"] == TOKEN_ACCOUNT_LAMPORTS / 10**9 + assert result["rent_recovered_sol_raw"] == TOKEN_ACCOUNT_LAMPORTS async def test_selling_exactly_the_balance_closes_the_account(tmp_keystore): diff --git a/tests/test_core/test_wallet.py b/tests/test_core/test_wallet.py index c0f14c5..d028fc7 100644 --- a/tests/test_core/test_wallet.py +++ b/tests/test_core/test_wallet.py @@ -538,6 +538,7 @@ async def test_drain_wallet_happy_path(tmp_path): return_value={ "closed": 3, "recovered_sol": 0.006118, + "recovered_sol_raw": 6_118_000, "signature": "atasig", "skipped": [{"address": "a", "mint": "m", "reason": "frozen"}], }, @@ -560,6 +561,7 @@ async def test_drain_wallet_happy_path(tmp_path): assert result["atas_closed"] == 3 assert result["sol_transferred"] == 0.99 assert result["ata_signature"] == "atasig" + assert result["ata_rent_recovered_sol_raw"] == 6_118_000 assert result["ata_skipped"] == [{"address": "a", "mint": "m", "reason": "frozen"}] assert result["sol_signature"] == "solsig" assert result["non_empty_token_accounts"] == [] From c8445d663a6c50d58d9e6b96cf244b56e47ecebd Mon Sep 17 00:00:00 2001 From: Anton Sauchyk Date: Mon, 23 Nov 2026 21:07:33 +0100 Subject: [PATCH 3/3] fix: report a failed token-account listing, show recovered rent exactly An unanswered listing made close-atas report nothing to close; it is now an error, and drain records it in ata_error. Rent is printed from the lamport count with all nine decimals. Co-Authored-By: Claude Opus 5.5 --- src/pumpfun_cli/commands/trade.py | 4 ++-- src/pumpfun_cli/commands/wallet.py | 8 +++---- src/pumpfun_cli/output.py | 5 +++++ src/pumpfun_cli/protocol/client.py | 14 +++++++++--- tests/test_commands/test_human_output.py | 26 +++++++++++++++++++++-- tests/test_commands/test_wallet_cmd.py | 1 + tests/test_protocol/test_token_account.py | 14 ++++++++++++ 7 files changed, 61 insertions(+), 11 deletions(-) diff --git a/src/pumpfun_cli/commands/trade.py b/src/pumpfun_cli/commands/trade.py index 7e3ca65..484ea65 100644 --- a/src/pumpfun_cli/commands/trade.py +++ b/src/pumpfun_cli/commands/trade.py @@ -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: @@ -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']}") diff --git a/src/pumpfun_cli/commands/wallet.py b/src/pumpfun_cli/commands/wallet.py index 95d4275..66ab1a6 100644 --- a/src/pumpfun_cli/commands/wallet.py +++ b/src/pumpfun_cli/commands/wallet.py @@ -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) @@ -302,7 +302,7 @@ 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: @@ -310,7 +310,7 @@ def wallet_close_atas( else: typer.echo( f"Closed {result['closed']} empty account(s)," - f" recovered {result['recovered_sol']:.6f} SOL" + f" recovered {sol_text(result['recovered_sol_raw'])} SOL" ) typer.echo(f"TX: {result['explorer']}") _echo_skipped(result.get("skipped", [])) @@ -373,7 +373,7 @@ 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']:.6f} SOL" + f" recovered {sol_text(result['ata_rent_recovered_sol_raw'])} SOL" ) else: typer.echo("No empty ATAs to close.") diff --git a/src/pumpfun_cli/output.py b/src/pumpfun_cli/output.py index 0292a68..aba0ee8 100644 --- a/src/pumpfun_cli/output.py +++ b/src/pumpfun_cli/output.py @@ -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}" diff --git a/src/pumpfun_cli/protocol/client.py b/src/pumpfun_cli/protocol/client.py index 25b6774..a4cbdbd 100644 --- a/src/pumpfun_cli/protocol/client.py +++ b/src/pumpfun_cli/protocol/client.py @@ -149,13 +149,21 @@ 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"; empty if the RPC can't answer.""" + 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: - return [] + 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) diff --git a/tests/test_commands/test_human_output.py b/tests/test_commands/test_human_output.py index 2fc9e21..2067272 100644 --- a/tests/test_commands/test_human_output.py +++ b/tests/test_commands/test_human_output.py @@ -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): @@ -411,11 +412,32 @@ def test_close_atas_reports_exact_rent_and_what_it_left(wallet): 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.003553 SOL" in out.output + 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" diff --git a/tests/test_commands/test_wallet_cmd.py b/tests/test_commands/test_wallet_cmd.py index b751f62..e11f513 100644 --- a/tests/test_commands/test_wallet_cmd.py +++ b/tests/test_commands/test_wallet_cmd.py @@ -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, diff --git a/tests/test_protocol/test_token_account.py b/tests/test_protocol/test_token_account.py index 158719e..1ec43c8 100644 --- a/tests/test_protocol/test_token_account.py +++ b/tests/test_protocol/test_token_account.py @@ -121,3 +121,17 @@ async def test_client_lists_the_owners_accounts_with_their_holdings(): rows = await client.get_token_holdings(OWNER, TOKEN_2022_PROGRAM) assert rows == [(ACCOUNT, MINT, TokenHolding(0, 5, 9, closer=OWNER))] assert client.rpc.get_token_accounts_by_owner.call_args.kwargs["commitment"] == "confirmed" + + +async def test_client_listing_failure_raises_without_the_url(): + """An unanswered listing must not read as "the wallet has no accounts".""" + import pytest + + client = RpcClient("http://secret-key.rpc") + client.rpc.get_token_accounts_by_owner = AsyncMock( + side_effect=OSError("http://secret-key.rpc timed out") + ) + with pytest.raises(RuntimeError) as info: + await client.get_token_holdings(OWNER, TOKEN_2022_PROGRAM) + assert "secret-key" not in str(info.value) + assert info.value.__cause__ is None and info.value.__context__ is None