diff --git a/AGENTS.md b/AGENTS.md index 14304ae..0f2a068 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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. diff --git a/README.md b/README.md index 0351c06..95524cc 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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 diff --git a/pyproject.toml b/pyproject.toml index c95eb44..bd8b128 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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"} diff --git a/src/pumpfun_cli/__init__.py b/src/pumpfun_cli/__init__.py index 2013f91..96cea45 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.6" +__version__ = "0.3.7" diff --git a/src/pumpfun_cli/commands/trade.py b/src/pumpfun_cli/commands/trade.py index 484ea65..ebb149f 100644 --- a/src/pumpfun_cli/commands/trade.py +++ b/src/pumpfun_cli/commands/trade.py @@ -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']}") diff --git a/src/pumpfun_cli/commands/wallet.py b/src/pumpfun_cli/commands/wallet.py index 66ab1a6..f4aa620 100644 --- a/src/pumpfun_cli/commands/wallet.py +++ b/src/pumpfun_cli/commands/wallet.py @@ -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", [])) @@ -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"): diff --git a/src/pumpfun_cli/core/trade.py b/src/pumpfun_cli/core/trade.py index 49c253c..771b2ed 100644 --- a/src/pumpfun_cli/core/trade.py +++ b/src/pumpfun_cli/core/trade.py @@ -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, @@ -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}" + 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, @@ -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() @@ -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 @@ -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: @@ -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. @@ -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( @@ -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: diff --git a/src/pumpfun_cli/core/wallet.py b/src/pumpfun_cli/core/wallet.py index 5bc1ce1..9d8ed58 100644 --- a/src/pumpfun_cli/core/wallet.py +++ b/src/pumpfun_cli/core/wallet.py @@ -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 @@ -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: + 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: @@ -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, ) @@ -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"), diff --git a/src/pumpfun_cli/protocol/client.py b/src/pumpfun_cli/protocol/client.py index a4cbdbd..4dbed96 100644 --- a/src/pumpfun_cli/protocol/client.py +++ b/src/pumpfun_cli/protocol/client.py @@ -4,7 +4,7 @@ import httpx from solana.rpc.async_api import AsyncClient -from solana.rpc.core import TokenAccountOpts, TxOptsModel +from solana.rpc.core import RPCException, TokenAccountOpts, TxOptsModel from solders.compute_budget import set_compute_unit_limit, set_compute_unit_price from solders.hash import Hash from solders.instruction import Instruction @@ -76,6 +76,10 @@ def build_message( ) +class TransactionNotSentError(RuntimeError): + """The transaction never reached the network: nothing ran and nothing was spent.""" + + class TransactionFailedError(RuntimeError): """Raised when a confirmed transaction fails on-chain.""" @@ -103,6 +107,9 @@ def __init__(self, rpc_url: str, timeout: float = DEFAULT_RPC_TIMEOUT): self.rpc_url = rpc_url self.timeout = timeout self.rpc = AsyncClient(rpc_url, timeout=timeout) + # Sends get one attempt: after a retry, a refusal could answer the second + # attempt while the first already reached the node. + self.sender = AsyncClient(rpc_url, timeout=timeout, max_transport_retries=0) async def get_blockhash(self) -> Hash: resp = await self.rpc.get_latest_blockhash() @@ -210,21 +217,37 @@ async def get_program_accounts( return resp.value async def _send_and_confirm(self, tx: VersionedTransaction, confirm: bool) -> str: - resp = await self.rpc.send_transaction(tx, opts=TxOptsModel(skip_preflight=True)) + # Errors are raised outside the handlers so the originals, whose text can + # carry the RPC URL, aren't chained onto them. + refused = unknown = None + try: + resp = await self.sender.send_transaction(tx, opts=TxOptsModel(skip_preflight=True)) + except RPCException as exc: # a JSON-RPC error: the node turned it down + refused = str(exc) + except Exception as exc: # noqa: BLE001 - e.g. a timeout after the node took it + unknown = type(exc).__name__ + if refused is not None: + raise TransactionNotSentError(f"The RPC refused the transaction: {refused}") + if unknown is not None: + raise RuntimeError( + f"Sending {tx.signatures[0]} failed ({unknown}); the RPC may have taken it," + " so it may still land." + ) signature = str(resp.value) if confirm: try: - await self.rpc.confirm_transaction( + confirmed = await self.rpc.confirm_transaction( resp.value, commitment="confirmed", sleep_seconds=1 ) - status = await self.get_transaction(signature) except Exception as exc: # noqa: BLE001 - the send already happened raise RuntimeError( f"Sent {signature} but could not confirm it ({type(exc).__name__}). " f"Check it with: pumpfun tx-status {signature}" ) from None - if status and status["err"]: - raise TransactionFailedError(status["err"]) + # The confirmed status carries the on-chain result. + landed = confirmed.value[0] + if landed is not None and landed.err is not None: + raise TransactionFailedError(landed.err) return signature async def send_tx( @@ -239,7 +262,15 @@ async def send_tx( Sent as v0 when it fits, otherwise as v1; see `build_message`. """ - blockhash = await self.get_blockhash() + failure = None + try: + blockhash = await self.get_blockhash() + except Exception as exc: # noqa: BLE001 - its text can carry the RPC URL + failure = type(exc).__name__ + if failure is not None: + raise TransactionNotSentError( + f"Couldn't get a recent blockhash from the RPC ({failure}); nothing was sent." + ) msg = build_message( signers[0].pubkey(), instructions, blockhash, compute_units, priority_fee ) @@ -298,3 +329,4 @@ async def get_transaction(self, signature_str: str) -> dict | None: async def close(self): await self.rpc.close() + await self.sender.close() diff --git a/tests/test_commands/test_human_output.py b/tests/test_commands/test_human_output.py index 2067272..6fef552 100644 --- a/tests/test_commands/test_human_output.py +++ b/tests/test_commands/test_human_output.py @@ -149,25 +149,6 @@ def test_collect_and_claim_forward_quote_mint(wallet): assert k.exit_code == 0 and claim.call_args.args[3] == MINT -def test_collect_tells_how_many_coins_still_hold_fees(wallet): - with ( - _human("trade"), - patch( - "pumpfun_cli.commands.trade.collect_creator_fees_core", new_callable=AsyncMock - ) as col, - ): - col.return_value = { - "quote_symbol": "SOL", - "pump_recovered": 1.0, - "pumpswap_recovered": 0.0, - "coins_swept": 8, - "coins_still_waiting": 3, - "explorer": "x", - } - c = runner.invoke(app, ["--rpc", "http://rpc", "collect-creator-fee"]) - assert c.exit_code == 0 and "3 more coins hold fees" in c.output - - def test_info(wallet): with ( _human("info"), @@ -413,7 +394,8 @@ def test_close_atas_reports_exact_rent_and_what_it_left(wallet): "closed": 2, "recovered_sol": 0.00355312, "recovered_sol_raw": 3_553_120, - "signature": "s", + "signature": "s1", + "signatures": ["s1", "s2"], "explorer": "x", "skipped": [{"address": "a", "mint": "m", "reason": "frozen"}], } @@ -421,6 +403,7 @@ def test_close_atas_reports_exact_rent_and_what_it_left(wallet): 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 + assert "tx/s1" in out.output and "tx/s2" in out.output def test_close_atas_reports_a_failed_listing_instead_of_nothing_to_close(wallet): diff --git a/tests/test_core/test_close_atas.py b/tests/test_core/test_close_atas.py index 9478c5a..154dddc 100644 --- a/tests/test_core/test_close_atas.py +++ b/tests/test_core/test_close_atas.py @@ -2,11 +2,13 @@ from unittest.mock import AsyncMock, MagicMock, patch +import pytest 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.client import TransactionFailedError 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 @@ -96,13 +98,57 @@ async def test_nothing_closable_sends_nothing(tmp_path): 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) +async def test_every_account_closes_twenty_per_transaction(tmp_path): + result, client, _ = await _run(tmp_path, [(TOKEN_PROGRAM, {"lamports": 1_000})] * 45) + batches = [c.args[0] for c in client.send_tx.call_args_list] + assert [len(b) for b in batches] == [20, 20, 5] + assert sum((closed_accounts(b) for b in batches), []) == [row[0] for row in client.rows] + assert [c.kwargs["compute_units"] for c in client.send_tx.call_args_list] == [ + 100_000, + 100_000, + 25_000, + ] + assert result["closed"] == 45 + assert result["recovered_sol"] == 45_000 / 10**9 + assert result["recovered_sol_raw"] == 45_000 + assert result["signatures"] == ["sig", "sig", "sig"] + assert "incomplete" not in result + + +async def test_a_failed_later_batch_reports_what_closed(tmp_path): + keyfile, user = _wallet(tmp_path) + client = _client([(TOKEN_PROGRAM, TokenHolding(lamports=1, closer=user))] * 25) + client.send_tx = AsyncMock(side_effect=["sig1", TransactionFailedError({"err": 1})]) + with patch("pumpfun_cli.protocol.client.RpcClient", return_value=client): + result = await close_empty_atas("http://rpc", keyfile, "testpass") 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 + assert result["signatures"] == ["sig1"] + assert result["incomplete"].startswith("5 account(s) not closed") + + +async def test_a_failed_first_batch_raises(tmp_path): + keyfile, user = _wallet(tmp_path) + client = _client([(TOKEN_PROGRAM, TokenHolding(closer=user))]) + client.send_tx = AsyncMock(side_effect=TransactionFailedError({"err": 1})) + with ( + patch("pumpfun_cli.protocol.client.RpcClient", return_value=client), + pytest.raises(TransactionFailedError), + ): + await close_empty_atas("http://rpc", keyfile, "testpass") 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 + + +async def test_an_rpc_refusal_on_a_later_batch_reports_what_closed(tmp_path): + from pumpfun_cli.protocol.client import TransactionNotSentError + + keyfile, user = _wallet(tmp_path) + client = _client([(TOKEN_PROGRAM, TokenHolding(lamports=1, closer=user))] * 25) + client.send_tx = AsyncMock(side_effect=["sig1", TransactionNotSentError("refused")]) + with patch("pumpfun_cli.protocol.client.RpcClient", return_value=client): + result = await close_empty_atas("http://rpc", keyfile, "testpass") + assert result["closed"] == 20 and result["signatures"] == ["sig1"] + assert result["incomplete"] == "5 account(s) not closed: refused" diff --git a/tests/test_core/test_trade.py b/tests/test_core/test_trade.py index 6ef3d85..a132329 100644 --- a/tests/test_core/test_trade.py +++ b/tests/test_core/test_trade.py @@ -526,6 +526,33 @@ def _sweeps(sent: dict) -> list: ] +def _land_sweeps(client: FakeClient, creator: Pubkey, fees: dict, then_raise=None) -> None: + """Make sweep-only transactions move their fees into the creator's vaults, as on + chain; `fees` maps a curve's mint or a pool's address to its waiting fee. + `then_raise` is raised after the first one lands, as when a confirmation is lost.""" + real_send = client.send_tx + amm_ata = find_ata(derive_amm_creator_vault(creator), WSOL_MINT, TOKEN_PROGRAM) + + async def send(instructions, signers, **kw): + sig = await real_send(instructions, signers, **kw) + sweeps = _sweeps({"instructions": instructions}) + if sweeps and len(sweeps) == len(instructions): + for ix in sweeps: + key = next(m.pubkey for m in ix.accounts if m.pubkey in fees) + if ix.program_id == PUMP_PROGRAM: + vault = derive_creator_vault(creator) + client.balances[vault] = client.balances.get(vault, 0) + fees[key] + else: + client.token_balances[amm_ata] = ( + client.token_balances.get(amm_ata, 0) + fees[key] + ) + if then_raise is not None: + raise then_raise + return sig + + client.send_tx = send + + async def test_collect_sweeps_fees_waiting_on_curves_and_pools_first(tmp_keystore): user = _user_from(tmp_keystore) client = FakeClient() @@ -564,16 +591,72 @@ async def test_collect_sweeps_only_the_requested_quote_asset(tmp_keystore): assert result["error"] == "no_fees" -async def test_collect_sweeps_the_largest_fees_and_reports_the_rest(tmp_keystore): +async def test_collect_sweeps_every_waiting_coin(tmp_keystore): + """The largest go with the collect; the rest are swept, and confirmed, first.""" user = _user_from(tmp_keystore) client = FakeClient() - fees = [1_000 * (i + 1) for i in range(MAX_SWEEPS + 3)] + client.balances[derive_creator_vault(user)] = 650_240 # only the rent floor + fees = [1_000 * (i + 1) for i in range(2 * MAX_SWEEPS + 3)] mints = {_waiting_curve(client, user, fee): fee for fee in fees} + _land_sweeps(client, user, mints) + with _patched(client): + result = await collect_creator_fees("http://rpc", tmp_keystore, "testpass") + ahead, collect = client.sent[:-1], client.sent[-1] + assert [len(_sweeps(tx)) for tx in ahead] == [MAX_SWEEPS, 3] + assert all(tx["confirm"] for tx in ahead) + assert all(len(_sweeps(tx)) == len(tx["instructions"]) for tx in ahead) + swept_with_collect = {mints[ix.accounts[2].pubkey] for ix in _sweeps(collect)} + assert swept_with_collect == set(sorted(fees)[-MAX_SWEEPS:]) + all_swept = [mints[ix.accounts[2].pubkey] for tx in client.sent for ix in _sweeps(tx)] + assert sorted(all_swept) == fees + assert result["coins_swept"] == len(fees) + assert result["pump_recovered"] == sum(fees) / 10**9 + assert "coins_still_waiting" not in result + + +async def test_a_sweep_that_landed_unconfirmed_is_still_collected(tmp_keystore): + """A lost confirmation doesn't mean the sweep failed: the vaults are read again, + so a pool's fees that reached an empty PumpSwap vault still get collected.""" + user = _user_from(tmp_keystore) + client = FakeClient() + client.balances[derive_creator_vault(user)] = 650_240 # only the rent floor + fees = { + _waiting_curve(client, user, 1_000_000 * (i + 2)): 1_000_000 * (i + 2) + for i in range(MAX_SWEEPS) + } + pool = _waiting_pool(client, user, 500) + fees[pool] = 500 + _land_sweeps(client, user, fees, then_raise=RuntimeError("Sent x but could not confirm it")) + with _patched(client): + result = await collect_creator_fees("http://rpc", tmp_keystore, "testpass") + collect = client.sent[-1]["instructions"] + assert any(bytes(ix.data[:8]) == COLLECT_COIN_CREATOR_FEE_DISCRIMINATOR for ix in collect) + assert result["pumpswap_recovered"] == 500 / 10**9 + assert "outcome is unknown" in result["sweep_warning"] + + +async def test_a_failed_sweep_ahead_still_collects_what_landed(tmp_keystore): + user = _user_from(tmp_keystore) + client = FakeClient() + client.balances[derive_creator_vault(user)] = 650_240 # only the rent floor + fees = [1_000 * (i + 1) for i in range(MAX_SWEEPS + 2)] + for fee in fees: + _waiting_curve(client, user, fee) + sends = [] + real_send = client.send_tx + + async def send(instructions, signers, **kw): + sends.append(instructions) + if len(sends) == 1: + raise TransactionFailedError({"InstructionError": [0, {"Custom": 1}]}) + return await real_send(instructions, signers, **kw) + + client.send_tx = send with _patched(client): result = await collect_creator_fees("http://rpc", tmp_keystore, "testpass") - swept = {mints[ix.accounts[2].pubkey] for ix in _sweeps(client.sent[0])} - assert swept == set(sorted(fees)[-MAX_SWEEPS:]) - assert result["coins_still_waiting"] == 3 + assert result["coins_swept"] == MAX_SWEEPS + assert result["pump_recovered"] == sum(sorted(fees)[-MAX_SWEEPS:]) / 10**9 + assert result["sweep_warning"].startswith("2 coin(s) not swept") async def test_collect_without_get_program_accounts_collects_the_vaults(tmp_keystore): diff --git a/tests/test_core/test_wallet.py b/tests/test_core/test_wallet.py index d028fc7..4940218 100644 --- a/tests/test_core/test_wallet.py +++ b/tests/test_core/test_wallet.py @@ -764,3 +764,38 @@ async def test_transfer_sol_below_one_lamport_sends_nothing(tmp_path): assert result["error"] == "invalid_amount" client_cls.assert_not_called() + + +@pytest.mark.asyncio +async def test_drain_waits_for_the_closes_before_moving_sol(tmp_path): + """The rent has to be back before the balance to send is read, even unconfirmed.""" + from pumpfun_cli.core.wallet import drain_wallet + + keyfile, pubkey = _make_keyfile(tmp_path) + with ( + patch( + "pumpfun_cli.core.wallet.list_token_accounts", + new_callable=AsyncMock, + return_value={"pubkey": pubkey, "token_accounts": []}, + ), + patch( + "pumpfun_cli.core.wallet.close_empty_atas", + new_callable=AsyncMock, + return_value={ + "closed": 1, + "recovered_sol": 0.002, + "signature": "a", + "incomplete": "x", + }, + ) as close, + patch( + "pumpfun_cli.core.wallet.transfer_all_sol", + new_callable=AsyncMock, + return_value={"action": "transfer", "sol_amount": 0.5, "signature": "s"}, + ), + ): + result = await drain_wallet( + "http://rpc", keyfile, "testpass", "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" + ) + assert close.call_args.kwargs["confirm"] is True + assert result["ata_incomplete"] == "x" diff --git a/tests/test_protocol/test_client.py b/tests/test_protocol/test_client.py index fef0235..15e6c2c 100644 --- a/tests/test_protocol/test_client.py +++ b/tests/test_protocol/test_client.py @@ -183,14 +183,13 @@ async def test_get_transaction_http_error_hides_the_url(respx_mock): @pytest.mark.asyncio -async def test_failed_confirmation_reports_the_signature(): +async def test_failed_confirmation_reports_the_signature(mocked): from unittest.mock import AsyncMock, MagicMock from solders.signature import Signature sig = Signature.default() - client = RpcClient("https://rpc.test") - client.rpc = MagicMock() + client = mocked client.rpc.send_transaction = AsyncMock(return_value=MagicMock(value=sig)) client.rpc.confirm_transaction = AsyncMock(side_effect=TimeoutError()) with pytest.raises(RuntimeError, match=str(sig)): @@ -208,3 +207,139 @@ async def test_get_transaction_non_json_is_a_runtime_error(respx_mock): await client.get_transaction(_SIG) finally: await client.close() + + +def _blockhash_rpc(): + from types import SimpleNamespace + from unittest.mock import AsyncMock, MagicMock + + from solders.hash import Hash + + rpc = MagicMock() + rpc.get_latest_blockhash = AsyncMock( + return_value=SimpleNamespace(value=SimpleNamespace(blockhash=Hash.default())) + ) + return rpc + + +def _transfer(): + from solders.keypair import Keypair + from solders.system_program import TransferParams, transfer + + payer = Keypair() + ix = transfer(TransferParams(from_pubkey=payer.pubkey(), to_pubkey=payer.pubkey(), lamports=1)) + return ix, payer + + +@pytest.fixture +async def mocked(): + """An RpcClient whose RPC calls are one mock; its real HTTP clients are closed afterwards.""" + client = RpcClient("http://secret-key.rpc") + real = client.rpc, client.sender + client.rpc = client.sender = _blockhash_rpc() + yield client + for http in real: + await http.close() + + +@pytest.fixture +def sending(mocked): + return (mocked, *_transfer()) + + +@pytest.mark.asyncio +async def test_no_blockhash_means_nothing_was_sent(sending): + from unittest.mock import AsyncMock + + from pumpfun_cli.protocol.client import TransactionNotSentError + + client, ix, payer = sending + client.rpc.get_latest_blockhash = AsyncMock(side_effect=OSError("http://secret-key.rpc down")) + with pytest.raises(TransactionNotSentError, match="nothing was sent") as info: + await client.send_tx([ix], [payer]) + assert "secret-key" not in str(info.value) + assert info.value.__context__ is None + + +@pytest.mark.asyncio +async def test_a_refused_send_is_not_sent_and_says_why(sending): + from unittest.mock import AsyncMock + + from solana.rpc.core import RPCException + + from pumpfun_cli.protocol.client import TransactionNotSentError + + client, ix, payer = sending + client.rpc.send_transaction = AsyncMock(side_effect=RPCException("Blockhash not found")) + with pytest.raises(TransactionNotSentError, match="Blockhash not found"): + await client.send_tx([ix], [payer]) + + +@pytest.mark.asyncio +async def test_a_send_that_timed_out_may_still_land(sending): + from unittest.mock import AsyncMock + + import httpx + + from pumpfun_cli.protocol.client import TransactionNotSentError + + client, ix, payer = sending + client.rpc.send_transaction = AsyncMock(side_effect=httpx.ReadTimeout("http://secret-key.rpc")) + with pytest.raises(RuntimeError, match="may still land") as info: + await client.send_tx([ix], [payer]) + assert not isinstance(info.value, TransactionNotSentError) + assert "secret-key" not in str(info.value) and info.value.__context__ is None + + +@pytest.mark.asyncio +async def test_a_send_gets_one_attempt(): + """A retry could turn a send that reached the node into a refusal.""" + from unittest.mock import AsyncMock + + import httpx2 + + from pumpfun_cli.protocol.client import TransactionNotSentError + + client = RpcClient("http://secret-key.rpc") + real_rpc, client.rpc = client.rpc, _blockhash_rpc() + ix, payer = _transfer() + refusal = httpx2.Response( + 200, + json={"jsonrpc": "2.0", "id": 0, "error": {"code": -32602, "message": "refused"}}, + request=httpx2.Request("POST", "http://secret-key.rpc"), + ) + post = AsyncMock(side_effect=[httpx2.ReadTimeout("http://secret-key.rpc"), refusal]) + client.sender._provider._post_request_once = post + try: + with pytest.raises(RuntimeError, match="may still land") as info: + await client.send_tx([ix], [payer]) + finally: + await real_rpc.close() + await client.sender.close() + assert not isinstance(info.value, TransactionNotSentError) + assert post.await_count == 1 + + +@pytest.mark.asyncio +async def test_a_confirmed_failure_needs_no_read_back(mocked): + """The confirmed status has the error; a failing read-back must not hide it.""" + from unittest.mock import AsyncMock, MagicMock + + from solders.rpc.responses import GetSignatureStatusesResp + from solders.signature import Signature + + from pumpfun_cli.protocol.client import TransactionFailedError + + failed = GetSignatureStatusesResp.from_json( + '{"jsonrpc":"2.0","id":1,"result":{"context":{"slot":1},"value":[{"slot":1,' + '"confirmations":null,"err":{"InstructionError":[2,{"Custom":6001}]},' + '"status":{"Err":{"InstructionError":[2,{"Custom":6001}]}},' + '"confirmationStatus":"confirmed"}]}}' + ) + client = mocked + client.rpc.send_transaction = AsyncMock(return_value=MagicMock(value=Signature.default())) + client.rpc.confirm_transaction = AsyncMock(return_value=failed) + client.get_transaction = AsyncMock(side_effect=TimeoutError()) + with pytest.raises(TransactionFailedError) as info: + await client._send_and_confirm(MagicMock(), confirm=True) + assert (info.value.instruction_index, info.value.error_code) == (2, 6001) diff --git a/uv.lock b/uv.lock index c3318e7..9939dfc 100644 --- a/uv.lock +++ b/uv.lock @@ -571,7 +571,7 @@ wheels = [ [[package]] name = "pumpfun-cli" -version = "0.3.6" +version = "0.3.7" source = { editable = "." } dependencies = [ { name = "base58" },