diff --git a/AGENTS.md b/AGENTS.md index 0f2a068..29e2bce 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -66,6 +66,8 @@ tests/ **Output:** Use `render(data, json_mode)` for all output — returns `True` if it emitted JSON (non-TTY or `--json`), `False` in TTY mode. Commands use `if not render(...):` to branch into human-readable output. Use `error(msg, hint, exit_code)` for failures — prints to stderr and raises `SystemExit`. Never use `print()`. +**Sending:** a command that sends a transaction waits for its outcome by default and takes `--fast` to skip that; wire both through `commands/sending.py` (`fast_option`, the hidden legacy `confirm_option`, `wait_for_outcome`) and pass `confirm=` to core. Core results always carry `confirmed`, and human output wraps its summary line in `outcome()` so an unconfirmed send never reads as done. `RpcClient` waits until the transaction lands, fails (`TransactionFailedError`) or can no longer land (`TransactionExpiredError`); commands catch `RuntimeError` for all of them. Never tell the user to run another command to learn an outcome. + **Error handling:** `error()` raises `SystemExit` — code after it is unreachable. Core functions return `dict` with `"error"` key for expected failures (graduated tokens, not found, slippage exceeded, insufficient_balance). Catch `ValueError` for wrong wallet password in every command that decrypts. Buy/sell functions perform pre-trade balance validation — SOL for fees and rent, the quote asset for the spend, token balance for sells with specific amounts. **Auto-routing:** `_route` in `commands/trade.py` picks the venue from the errors core returns: `{"error": "graduated"}` from `buy_token` / `sell_token` retries on PumpSwap, `{"error": "not_found"}` retries on LaunchLab (`buy_launchlab` / `sell_launchlab`), and LaunchLab's `graduated` retries on Raydium CPMM (`buy_cpmm` / `sell_cpmm`). `--force-amm` tries PumpSwap and falls back to CPMM only when PumpSwap reports no pool (`pool_missing`); PumpSwap's error stands unless CPMM recognises the coin as LaunchLab's. Never suppress or swallow those errors in core — the routing decision belongs in the command layer. `info` falls back to LaunchLab, and to its CPMM pool, the same way in `core/info.py`. diff --git a/README.md b/README.md index 95524cc..53e4a9e 100644 --- a/README.md +++ b/README.md @@ -71,13 +71,15 @@ The wallet is stored encrypted in `~/.config/pumpfun-cli/wallet.enc`, and the co ```bash pumpfun info # where it trades, price, quote asset pumpfun buy 0.1 --dry-run # preview: nothing is sent -pumpfun buy 0.1 --confirm # spend exactly 0.1 of the coin's quote asset -pumpfun sell all --confirm +pumpfun buy 0.1 # spend exactly 0.1 of the coin's quote asset +pumpfun sell all pumpfun tx-status # did it land? ``` `--json` makes any command answer in JSON; it is on automatically when the output is piped. +Every command that sends a transaction waits for it to land and reports what happened on chain: the amounts, or the error it failed with. A transaction that can no longer land (its blockhash expired) is reported as such; it cost nothing and is safe to send again. `--fast` sends without waiting, for when latency matters more than knowing the result: the output then says the transaction was sent but not confirmed (`"confirmed": false`). `wallet drain` always waits. + ### 5. Launch a coin ```bash @@ -93,12 +95,12 @@ Token info (requires RPC): pumpfun info [--timeout S] Venue, price, bonding progress, reserves Trading (requires RPC + wallet): - pumpfun buy [--slippage N] [--force-amm] [--dry-run] [--confirm] - pumpfun sell [--slippage N] [--force-amm] [--dry-run] [--confirm] - pumpfun migrate [--confirm] - pumpfun claim-cashback [--quote-mint M] [--confirm] - pumpfun collect-creator-fee [--quote-mint M] [--confirm] - pumpfun close-volume-acc [--confirm] + pumpfun buy [--slippage N] [--force-amm] [--dry-run] [--fast] + pumpfun sell [--slippage N] [--force-amm] [--dry-run] [--fast] + pumpfun migrate [--fast] + pumpfun claim-cashback [--quote-mint M] [--fast] + pumpfun collect-creator-fee [--quote-mint M] [--fast] + pumpfun close-volume-acc [--fast] Transaction inspection (requires RPC): pumpfun tx-status Confirmation status, slot, fee, errors @@ -106,7 +108,7 @@ Transaction inspection (requires RPC): Token launch (requires RPC + wallet): pumpfun launch --name X --ticker Y [--uri U | --desc D --image P] [--buy N] [--quote-mint M] [--creator-fee-bps N] [--holder-reward] - [--mayhem] [--slippage N] [--confirm] + [--mayhem] [--slippage N] [--fast] Token discovery (price and progress added when an RPC is set): pumpfun tokens trending [--limit N] pump.fun's movers board @@ -174,7 +176,7 @@ A sell that empties the coin's token account (`all`, or exactly the balance) clo ### 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. +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: the `collect-creator-fee` totals, and a trade's `tokens_received` or `quote_received` after `--fast`. Otherwise a trade reads what it received from the confirmed transaction; if that transaction cannot be read back, it reports the estimate without the `_raw` field, so check for it. 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. An error comes back as `{"error": , "hint": ..., "exit_code": ...}` with a non-zero exit status. diff --git a/pyproject.toml b/pyproject.toml index bd8b128..94be596 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "pumpfun-cli" -version = "0.3.7" +version = "0.4.0" 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 96cea45..55a464e 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.7" +__version__ = "0.4.0" diff --git a/src/pumpfun_cli/commands/launch.py b/src/pumpfun_cli/commands/launch.py index 1136603..2ab5156 100644 --- a/src/pumpfun_cli/commands/launch.py +++ b/src/pumpfun_cli/commands/launch.py @@ -4,6 +4,7 @@ import typer +from pumpfun_cli.commands.sending import confirm_option, fast_option, outcome, wait_for_outcome from pumpfun_cli.core.launch import launch_token from pumpfun_cli.output import error, render @@ -41,9 +42,11 @@ def launch( slippage: int = typer.Option( 15, "--slippage", help="Slippage tolerance percent for the opening buy (default: 15)" ), - confirm: bool = typer.Option(False, "--confirm", help="Wait for transaction confirmation"), + fast: bool = fast_option(), + confirm: bool = confirm_option(), ): """Launch a new token on pump.fun (create_v2 + extend_account).""" + confirm = wait_for_outcome(fast, confirm) state = ctx.obj if not name.strip(): error("Token name cannot be empty.", exit_code=2) @@ -99,7 +102,7 @@ def launch( if result.get("error"): error(result["message"]) if not render(result, state.json_mode): - typer.echo("Token launched!") + typer.echo(outcome(result, "Token launched.")) typer.echo(f" Name: {result['name']}") typer.echo(f" Ticker: {result['ticker']}") typer.echo(f" Mint: {result['mint']}") diff --git a/src/pumpfun_cli/commands/sending.py b/src/pumpfun_cli/commands/sending.py new file mode 100644 index 0000000..0d25600 --- /dev/null +++ b/src/pumpfun_cli/commands/sending.py @@ -0,0 +1,35 @@ +"""Options and wording shared by every command that sends a transaction. + +A command waits for its transaction's outcome by default and reports what +happened on chain. `--fast` sends without waiting, for when latency matters +more than knowing the result. +""" + +import typer + +from pumpfun_cli.output import error + +FAST_HELP = "Send without waiting for the outcome: fastest, but whether it landed isn't checked" + + +def fast_option() -> bool: + return typer.Option(False, "--fast", help=FAST_HELP) + + +def confirm_option() -> bool: + # Waiting is the default now; the flag stays so existing scripts keep working. + return typer.Option(False, "--confirm", hidden=True) + + +def wait_for_outcome(fast: bool, confirm: bool) -> bool: + """Whether to wait for the transaction's outcome.""" + if fast and confirm: + error("--fast and --confirm contradict each other; pass one.", exit_code=2) + return not fast + + +def outcome(result: dict, summary: str) -> str: + """`summary` once the transaction landed; otherwise, that it was only sent.""" + if result.get("confirmed"): + return summary + return f"Sent, not confirmed (--fast). Expected: {summary}" diff --git a/src/pumpfun_cli/commands/trade.py b/src/pumpfun_cli/commands/trade.py index ebb149f..11bc84e 100644 --- a/src/pumpfun_cli/commands/trade.py +++ b/src/pumpfun_cli/commands/trade.py @@ -4,6 +4,7 @@ import typer +from pumpfun_cli.commands.sending import confirm_option, fast_option, outcome, wait_for_outcome from pumpfun_cli.core.cpmm import buy_cpmm, sell_cpmm from pumpfun_cli.core.launchlab import buy_launchlab, sell_launchlab from pumpfun_cli.core.pumpswap import buy_pumpswap, sell_pumpswap @@ -110,12 +111,14 @@ def buy( "--force-amm", help="Skip the bonding curve, buy in the pool (PumpSwap, or CPMM for LaunchLab coins)", ), - confirm: bool = typer.Option(False, "--confirm", help="Wait for transaction confirmation"), + fast: bool = fast_option(), + confirm: bool = confirm_option(), dry_run: bool = typer.Option( False, "--dry-run", help="Simulate trade without sending transaction" ), ): """Buy tokens, spending an exact amount of the coin's quote asset.""" + confirm = wait_for_outcome(fast, confirm) _validate_mint(mint) if amount <= 0: error("Amount must be greater than 0.", hint=f"Got: {amount}", exit_code=2) @@ -168,8 +171,11 @@ def buy( state = ctx.obj if not render(result, state.json_mode): typer.echo( - f"Bought {result['tokens_received']:.2f} tokens" - f" for {result['quote_spent']} {result['quote_symbol']}" + outcome( + result, + f"Bought {result['tokens_received']:.2f} tokens" + f" for {result['quote_spent']} {result['quote_symbol']}", + ) ) typer.echo(f"TX: {result['explorer']}") @@ -186,12 +192,14 @@ def sell( "--force-amm", help="Skip the bonding curve, sell in the pool (PumpSwap, or CPMM for LaunchLab coins)", ), - confirm: bool = typer.Option(False, "--confirm", help="Wait for transaction confirmation"), + fast: bool = fast_option(), + confirm: bool = confirm_option(), dry_run: bool = typer.Option( False, "--dry-run", help="Simulate trade without sending transaction" ), ): """Sell tokens for the coin's quote asset (SOL for most coins).""" + confirm = wait_for_outcome(fast, confirm) _validate_mint(mint) _validate_slippage(slippage) rpc, keyfile, password = _require_rpc_and_wallet(ctx) @@ -245,8 +253,11 @@ def sell( state = ctx.obj if not render(result, state.json_mode): typer.echo( - f"Sold {result['tokens_sold']:.2f} tokens" - f" for {result['quote_received']:.6f} {result['quote_symbol']}" + outcome( + result, + f"Sold {result['tokens_sold']:.2f} tokens" + f" for {result['quote_received']:.6f} {result['quote_symbol']}", + ) ) if "tokens_kept" in result: typer.echo( @@ -267,9 +278,11 @@ def sell( def claim_cashback( ctx: typer.Context, quote_mint: str | None = typer.Option(None, "--quote-mint", help=_QUOTE_MINT_HELP), - confirm: bool = typer.Option(False, "--confirm", help="Wait for transaction confirmation"), + fast: bool = fast_option(), + confirm: bool = confirm_option(), ): """Claim volume-based cashback rewards in one quote asset.""" + confirm = wait_for_outcome(fast, confirm) rpc, keyfile, password = _require_rpc_and_wallet(ctx) overrides = _get_overrides(ctx) try: @@ -282,15 +295,17 @@ def claim_cashback( error(result["message"]) state = ctx.obj if not render(result, state.json_mode): - typer.echo("Cashback claimed!") + typer.echo(outcome(result, "Cashback claimed.")) typer.echo(f"TX: {result['explorer']}") def close_volume_acc( ctx: typer.Context, - confirm: bool = typer.Option(False, "--confirm", help="Wait for transaction confirmation"), + fast: bool = fast_option(), + confirm: bool = confirm_option(), ): """Close volume accumulator account, recover rent.""" + confirm = wait_for_outcome(fast, confirm) rpc, keyfile, password = _require_rpc_and_wallet(ctx) overrides = _get_overrides(ctx) try: @@ -303,16 +318,18 @@ def close_volume_acc( error(result["message"]) state = ctx.obj if not render(result, state.json_mode): - typer.echo("Volume accumulator closed, rent recovered.") + typer.echo(outcome(result, "Volume accumulator closed, rent recovered.")) typer.echo(f"TX: {result['explorer']}") def migrate( ctx: typer.Context, mint: str = typer.Argument(..., help="Token mint address"), - confirm: bool = typer.Option(False, "--confirm", help="Wait for transaction confirmation"), + fast: bool = fast_option(), + confirm: bool = confirm_option(), ): """Trigger migration from bonding curve to PumpSwap AMM.""" + confirm = wait_for_outcome(fast, confirm) _validate_mint(mint) rpc, keyfile, password = _require_rpc_and_wallet(ctx) overrides = _get_overrides(ctx) @@ -326,16 +343,18 @@ def migrate( error(result["message"]) state = ctx.obj if not render(result, state.json_mode): - typer.echo(f"Migrated {result['mint']} to PumpSwap!") + typer.echo(outcome(result, f"Migrated {result['mint']} to PumpSwap.")) typer.echo(f"TX: {result['explorer']}") def collect_creator_fee( ctx: typer.Context, quote_mint: str | None = typer.Option(None, "--quote-mint", help=_QUOTE_MINT_HELP), - confirm: bool = typer.Option(False, "--confirm", help="Wait for transaction confirmation"), + fast: bool = fast_option(), + confirm: bool = confirm_option(), ): """Collect creator fees in one quote asset from pump.fun and PumpSwap vaults.""" + confirm = wait_for_outcome(fast, confirm) rpc, keyfile, password = _require_rpc_and_wallet(ctx) overrides = _get_overrides(ctx) try: @@ -351,6 +370,7 @@ def collect_creator_fee( state = ctx.obj if not render(result, state.json_mode): symbol = result["quote_symbol"] + typer.echo(outcome(result, "Creator fees collected.")) typer.echo(f"Pump.fun fees: {result['pump_recovered']:.6f} {symbol}") typer.echo(f"PumpSwap fees: {result['pumpswap_recovered']:.6f} {symbol}") if result.get("sweep_warning"): diff --git a/src/pumpfun_cli/commands/wallet.py b/src/pumpfun_cli/commands/wallet.py index f4aa620..aaeb58c 100644 --- a/src/pumpfun_cli/commands/wallet.py +++ b/src/pumpfun_cli/commands/wallet.py @@ -8,6 +8,7 @@ import typer +from pumpfun_cli.commands.sending import confirm_option, fast_option, outcome, wait_for_outcome from pumpfun_cli.core.config import get_config_dir, resolve_value from pumpfun_cli.core.wallet import ( close_empty_atas, @@ -213,9 +214,11 @@ def wallet_transfer( recipient: str = typer.Argument(..., help="Recipient public key"), amount: str = typer.Argument(..., help="Amount to send (or 'all' to send max)"), mint: str = typer.Option(None, "--mint", help="Token mint address (omit for SOL transfer)"), - confirm: bool = typer.Option(False, "--confirm", help="Wait for transaction confirmation"), + fast: bool = fast_option(), + confirm: bool = confirm_option(), ): """Transfer SOL or tokens to another wallet.""" + confirm = wait_for_outcome(fast, confirm) if amount.lower() != "all": try: value = float(amount) @@ -270,24 +273,26 @@ def wallet_transfer( rpc, path, password, recipient, float(amount), confirm=confirm, **overrides ) ) - except ValueError as exc: + except (ValueError, RuntimeError) as exc: error(str(exc)) if result.get("error"): error(result["message"]) if not render(result, ctx.obj and ctx.obj.json_mode): if mint: - typer.echo(f"Sent {result['amount']} tokens to {result['to']}") + typer.echo(outcome(result, f"Sent {result['amount']} tokens to {result['to']}")) else: - typer.echo(f"Sent {result['sol_amount']} SOL to {result['to']}") + typer.echo(outcome(result, f"Sent {result['sol_amount']} SOL to {result['to']}")) typer.echo(f"TX: {result['explorer']}") @app.command("close-atas") def wallet_close_atas( ctx: typer.Context, - confirm: bool = typer.Option(False, "--confirm", help="Wait for transaction confirmation"), + fast: bool = fast_option(), + confirm: bool = confirm_option(), ): """Close empty token accounts and recover rent SOL.""" + confirm = wait_for_outcome(fast, confirm) path = _get_keystore_path(ctx) if not Path(path).exists(): error("No wallet found.", hint="Run: pumpfun wallet create") @@ -309,8 +314,11 @@ def wallet_close_atas( typer.echo("No empty token accounts to close.") else: typer.echo( - f"Closed {result['closed']} empty account(s)," - f" recovered {sol_text(result['recovered_sol_raw'])} SOL" + outcome( + result, + f"Closed {result['closed']} empty account(s)," + f" recovered {sol_text(result['recovered_sol_raw'])} SOL", + ) ) for sig in result["signatures"]: typer.echo(f"TX: https://solscan.io/tx/{sig}") @@ -331,9 +339,12 @@ def _echo_skipped(skipped: list[dict]) -> None: def wallet_drain( ctx: typer.Context, recipient: str = typer.Argument(..., help="Recipient address for remaining SOL"), - confirm: bool = typer.Option(False, "--confirm", help="Wait for transaction confirmation"), + confirm: bool = confirm_option(), ): """Close empty ATAs, then transfer all remaining SOL to recipient.""" + # Always waits: the closes have to land before the SOL moves, and the + # transfer's outcome is the point of the command. + confirm = True state = ctx.obj rpc = _require_rpc(ctx) path = _get_keystore_path(ctx) @@ -354,6 +365,8 @@ def wallet_drain( ) except ValueError: error("Wrong wallet password.") + except RuntimeError as exc: + error(str(exc)) if result.get("error"): error(result["message"]) diff --git a/src/pumpfun_cli/core/amounts.py b/src/pumpfun_cli/core/amounts.py index 9de168d..b69af1b 100644 --- a/src/pumpfun_cli/core/amounts.py +++ b/src/pumpfun_cli/core/amounts.py @@ -68,26 +68,61 @@ def total(rows: list | None) -> int | None: return None if post is None or pre is None else post - pre -async def confirmed_token_delta( - client: RpcClient, signature: str, owner: Pubkey, mint: Pubkey -) -> int | None: - """Raw tokens a confirmed buy moved into `owner`'s account, or None when - the transaction cannot be read back or shows no tokens received.""" +async def _read_landed(client: RpcClient, signature: str) -> dict | None: + """The landed transaction, or None if it failed or cannot be read back.""" for attempt in range(_TX_READ_ATTEMPTS): try: tx = await client.get_transaction(signature) except RuntimeError: return None if tx is not None: - if tx["err"]: - return None - delta = token_delta(tx, owner, mint) - return delta if delta is not None and delta > 0 else None + return None if tx["err"] else tx if attempt < _TX_READ_ATTEMPTS - 1: await asyncio.sleep(1) return None +async def confirmed_token_delta( + client: RpcClient, signature: str, owner: Pubkey, mint: Pubkey +) -> int | None: + """Raw tokens a confirmed buy moved into `owner`'s account, or None when + the transaction cannot be read back or shows no tokens received.""" + tx = await _read_landed(client, signature) + if tx is None: + return None + delta = token_delta(tx, owner, mint) + return delta if delta is not None and delta > 0 else None + + +async def confirmed_quote_received( + client: RpcClient, + signature: str, + owner: Pubkey, + quote_mint: Pubkey, + *, + sol_quote: bool, + rent_returned: int = 0, +) -> int | None: + """Raw quote a confirmed sell paid `owner`, or None when it can't be read back. + + A SOL payout is the payer's lamport change plus the fee it paid, less any + token-account rent the same transaction returned; `owner` signs and pays + for the sells this CLI sends, so it is account 0. Any other quote asset is + the change in `owner`'s balance of `quote_mint`. + """ + tx = await _read_landed(client, signature) + if tx is None: + return None + if sol_quote: + pre, post = tx.get("pre_balances"), tx.get("post_balances") + if not pre or not post or tx.get("fee") is None: + return None + received = post[0] - pre[0] + tx["fee"] - rent_returned + else: + received = token_delta(tx, owner, quote_mint) + return received if received is not None and received > 0 else None + + def close_if_emptied( *, user: Pubkey, diff --git a/src/pumpfun_cli/core/cpmm.py b/src/pumpfun_cli/core/cpmm.py index 418e728..f8d4094 100644 --- a/src/pumpfun_cli/core/cpmm.py +++ b/src/pumpfun_cli/core/cpmm.py @@ -13,6 +13,7 @@ from pumpfun_cli.core.amounts import ( amount_fields, close_if_emptied, + confirmed_quote_received, confirmed_token_delta, received_fields, to_raw, @@ -41,7 +42,7 @@ platform_name, withheld_fee, ) -from pumpfun_cli.protocol.quote import quote_symbol +from pumpfun_cli.protocol.quote import is_sol, quote_symbol CPMM_COMPUTE_UNITS = 150_000 _TOKEN_AMOUNT_OFFSET = 64 @@ -252,8 +253,7 @@ async def buy_cpmm( "signature": sig, "explorer": f"https://solscan.io/tx/{sig}", } - if confirm: - result["confirmed"] = True + result["confirmed"] = confirm return result except _NoPool as exc: return exc.result @@ -374,18 +374,29 @@ async def sell_cpmm( ) except TransactionFailedError as exc: return _handle_tx_error(exc, CPMM_SLIPPAGE_ERROR_CODES) + received = ( + await confirmed_quote_received( + client, + sig, + user, + quote_mint, + sol_quote=is_sol(quote_mint), + rent_returned=closed.get("rent_recovered_sol_raw", 0), + ) + if confirm + else None + ) result = { "action": "sell", "mint": mint_str, **_pool_fields(pool), **amount_fields("tokens_sold", token_amount, base_decimals), - "quote_received": quote_out / 10**quote_decimals, + **received_fields("quote_received", received, quote_out, quote_decimals), **closed, "signature": sig, "explorer": f"https://solscan.io/tx/{sig}", } - if confirm: - result["confirmed"] = True + result["confirmed"] = confirm return result except _NoPool as exc: return exc.result diff --git a/src/pumpfun_cli/core/launch.py b/src/pumpfun_cli/core/launch.py index d614175..946454d 100644 --- a/src/pumpfun_cli/core/launch.py +++ b/src/pumpfun_cli/core/launch.py @@ -254,8 +254,7 @@ async def launch_token( "explorer": f"https://solscan.io/tx/{sig}", "pump_url": f"https://pump.fun/coin/{mint}", } - if confirm: - result["confirmed"] = True + result["confirmed"] = confirm return result finally: await client.close() diff --git a/src/pumpfun_cli/core/launchlab.py b/src/pumpfun_cli/core/launchlab.py index ac36b3f..6ecb4be 100644 --- a/src/pumpfun_cli/core/launchlab.py +++ b/src/pumpfun_cli/core/launchlab.py @@ -14,6 +14,7 @@ from pumpfun_cli.core.amounts import ( amount_fields, close_if_emptied, + confirmed_quote_received, confirmed_token_delta, received_fields, to_raw, @@ -291,8 +292,7 @@ async def buy_launchlab( "signature": sig, "explorer": f"https://solscan.io/tx/{sig}", } - if confirm: - result["confirmed"] = True + result["confirmed"] = confirm return result except (RuntimeError, ValueError) as exc: return {"error": "launchlab_error", "message": str(exc)} @@ -421,18 +421,29 @@ async def sell_launchlab( ) except TransactionFailedError as exc: return _handle_tx_error(exc, LAUNCHLAB_SLIPPAGE_ERROR_CODES) + received = ( + await confirmed_quote_received( + client, + sig, + user, + quote_mint, + sol_quote=is_sol(quote_mint), + rent_returned=closed.get("rent_recovered_sol_raw", 0), + ) + if confirm + else None + ) result = { "action": "sell", "mint": mint_str, **_market_fields(market), **amount_fields("tokens_sold", token_amount, base_decimals), - "quote_received": quote_out / 10**quote_decimals, + **received_fields("quote_received", received, quote_out, quote_decimals), **closed, "signature": sig, "explorer": f"https://solscan.io/tx/{sig}", } - if confirm: - result["confirmed"] = True + result["confirmed"] = confirm return result except (RuntimeError, ValueError) as exc: return {"error": "launchlab_error", "message": str(exc)} diff --git a/src/pumpfun_cli/core/pumpswap.py b/src/pumpfun_cli/core/pumpswap.py index dbcfb18..a17f247 100644 --- a/src/pumpfun_cli/core/pumpswap.py +++ b/src/pumpfun_cli/core/pumpswap.py @@ -11,6 +11,7 @@ from pumpfun_cli.core.amounts import ( amount_fields, close_if_emptied, + confirmed_quote_received, confirmed_token_delta, received_fields, to_raw, @@ -234,8 +235,7 @@ async def buy_pumpswap( "signature": sig, "explorer": f"https://solscan.io/tx/{sig}", } - if confirm: - result["confirmed"] = True + result["confirmed"] = confirm return result except PoolNotFoundError as exc: # Same error as before, marked so a caller can tell "no pool" apart. @@ -360,6 +360,18 @@ async def sell_pumpswap( ) except TransactionFailedError as exc: return _handle_tx_error(exc, PUMPSWAP_SLIPPAGE_ERROR_CODES) + received = ( + await confirmed_quote_received( + client, + sig, + user, + quote_mint, + sol_quote=is_sol(quote_mint), + rent_returned=closed.get("rent_recovered_sol_raw", 0), + ) + if confirm + else None + ) result = { "action": "sell", "venue": "pumpswap", @@ -367,13 +379,12 @@ async def sell_pumpswap( "quote_mint": str(quote_mint), "quote_symbol": symbol, **amount_fields("tokens_sold", token_amount, base_decimals), - "quote_received": expected_quote / 10**quote_decimals, + **received_fields("quote_received", received, expected_quote, quote_decimals), **closed, "signature": sig, "explorer": f"https://solscan.io/tx/{sig}", } - if confirm: - result["confirmed"] = True + result["confirmed"] = confirm return result except PoolNotFoundError as exc: # Same error as before, marked so a caller can tell "no pool" apart. diff --git a/src/pumpfun_cli/core/trade.py b/src/pumpfun_cli/core/trade.py index 771b2ed..d5cd36f 100644 --- a/src/pumpfun_cli/core/trade.py +++ b/src/pumpfun_cli/core/trade.py @@ -13,6 +13,7 @@ from pumpfun_cli.core.amounts import ( amount_fields, close_if_emptied, + confirmed_quote_received, confirmed_token_delta, received_fields, to_raw, @@ -28,6 +29,7 @@ ) from pumpfun_cli.protocol.client import ( RpcClient, + TransactionExpiredError, TransactionFailedError, TransactionNotSentError, ) @@ -111,8 +113,7 @@ def _tx_result(action: str, sig: str, confirm: bool, **fields) -> dict: "signature": sig, "explorer": f"https://solscan.io/tx/{sig}", } - if confirm: - result["confirmed"] = True + result["confirmed"] = confirm return result @@ -440,6 +441,18 @@ async def sell_token( ) except TransactionFailedError as exc: return _handle_tx_error(exc, PUMP_SLIPPAGE_ERROR_CODES) + received = ( + await confirmed_quote_received( + client, + sig, + user, + quote_mint, + sol_quote=is_sol(quote_mint), + rent_returned=closed.get("rent_recovered_sol_raw", 0), + ) + if confirm + else None + ) return _tx_result( "sell", sig, @@ -449,7 +462,7 @@ async def sell_token( quote_mint=str(quote_mint), quote_symbol=symbol, **amount_fields("tokens_sold", token_amount, TOKEN_DECIMALS), - quote_received=quote_out / 10**quote_decimals, + **received_fields("quote_received", received, quote_out, quote_decimals), **partial, **closed, ) @@ -635,7 +648,7 @@ async def _sweep_ahead( 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: + except (TransactionFailedError, TransactionNotSentError, TransactionExpiredError) 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: diff --git a/src/pumpfun_cli/core/wallet.py b/src/pumpfun_cli/core/wallet.py index 9d8ed58..b9a2c79 100644 --- a/src/pumpfun_cli/core/wallet.py +++ b/src/pumpfun_cli/core/wallet.py @@ -8,6 +8,11 @@ from pumpfun_cli.core.amounts import amount_fields, to_raw from pumpfun_cli.core.validate import invalid_pubkey_error, parse_pubkey from pumpfun_cli.crypto import decrypt_keypair, encrypt_keypair, get_pubkey +from pumpfun_cli.protocol.client import ( + TransactionExpiredError, + TransactionFailedError, + TransactionNotSentError, +) from pumpfun_cli.protocol.contracts import SOL_DECIMALS @@ -145,8 +150,7 @@ async def transfer_sol( "signature": sig, "explorer": f"https://solscan.io/tx/{sig}", } - if confirm: - result["confirmed"] = True + result["confirmed"] = confirm return result finally: await client.close() @@ -179,7 +183,8 @@ async def transfer_all_sol( client = RpcClient(rpc_url) try: - balance = await client.get_balance(keypair.pubkey()) + # "confirmed", so rent from closes that just landed (drain) is included. + balance = await client.get_balance(keypair.pubkey(), commitment="confirmed") total_fees = BASE_TX_FEE + math.ceil(pf * cu / 1_000_000) send_lamports = balance - total_fees if send_lamports <= 0: @@ -210,8 +215,7 @@ async def transfer_all_sol( "signature": sig, "explorer": f"https://solscan.io/tx/{sig}", } - if confirm: - result["confirmed"] = True + result["confirmed"] = confirm return result finally: await client.close() @@ -296,8 +300,7 @@ async def transfer_token( "signature": sig, "explorer": f"https://solscan.io/tx/{sig}", } - if confirm: - result["confirmed"] = True + result["confirmed"] = confirm return result finally: await client.close() @@ -372,13 +375,26 @@ async def close_empty_atas( if compute_units is not None else _CLOSE_COMPUTE_UNITS * len(batch), ) - except RuntimeError as exc: + except ( + TransactionFailedError, + TransactionNotSentError, + TransactionExpiredError, + ) as exc: if not signatures: raise result["incomplete"] = ( f"{len(closable) - result['closed']} account(s) not closed: {exc}" ) break + except RuntimeError as exc: + if not signatures: + raise + result["incomplete"] = ( + f"{len(closable) - result['closed']} account(s) not confirmed closed;" + f" a batch's outcome is unknown, so up to {len(batch)} of them may have" + f" closed: {exc}" + ) + break signatures.append(sig) recovered += sum(holding.lamports for *_, holding in batch) result["closed"] += len(batch) @@ -392,8 +408,7 @@ async def close_empty_atas( "explorer": f"https://solscan.io/tx/{signatures[0]}", } ) - if confirm: - result["confirmed"] = True + result["confirmed"] = confirm return result finally: await client.close() diff --git a/src/pumpfun_cli/protocol/client.py b/src/pumpfun_cli/protocol/client.py index 4dbed96..d8f0db4 100644 --- a/src/pumpfun_cli/protocol/client.py +++ b/src/pumpfun_cli/protocol/client.py @@ -1,5 +1,6 @@ """Stateless Solana RPC client for CLI usage.""" +import asyncio import re import httpx @@ -13,12 +14,19 @@ from solders.pubkey import Pubkey from solders.signature import Signature from solders.transaction import VersionedTransaction +from solders.transaction_status import TransactionConfirmationStatus from pumpfun_cli.protocol.contracts import TX_V1_LOADED_ACCOUNTS_DATA_LIMIT from pumpfun_cli.protocol.token_account import TokenHolding, parse_token_account DEFAULT_RPC_TIMEOUT = 30.0 +# Waiting for a sent transaction: how often to look, and how long the RPC may +# fail to answer before the outcome is given up as unknown. +CONFIRM_POLL_SECONDS = 1.0 +CONFIRM_RPC_SILENCE_SECONDS = 60.0 +_LANDED = (TransactionConfirmationStatus.Confirmed, TransactionConfirmationStatus.Finalized) + # Serialized size limits: a v0 transaction must fit one 1232-byte packet, a v1 # transaction may carry up to 4096 bytes. TX_V0_MAX_BYTES = 1232 @@ -80,6 +88,16 @@ class TransactionNotSentError(RuntimeError): """The transaction never reached the network: nothing ran and nothing was spent.""" +class TransactionExpiredError(RuntimeError): + """The transaction's blockhash expired before it landed: it never ran and cost nothing.""" + + def __init__(self, signature: str) -> None: + super().__init__( + f"Transaction {signature} did not land before its blockhash expired." + " It never ran and nothing was spent; it is safe to send again." + ) + + class TransactionFailedError(RuntimeError): """Raised when a confirmed transaction fails on-chain.""" @@ -216,39 +234,71 @@ async def get_program_accounts( resp = await self.rpc.get_program_accounts(program_id, encoding="base64", filters=filters) return resp.value - async def _send_and_confirm(self, tx: VersionedTransaction, confirm: bool) -> str: + async def _send_and_confirm( + self, tx: VersionedTransaction, confirm: bool, last_valid_block_height: int + ) -> str: # Errors are raised outside the handlers so the originals, whose text can # carry the RPC URL, aren't chained onto them. + signature = tx.signatures[0] refused = unknown = None try: - resp = await self.sender.send_transaction(tx, opts=TxOptsModel(skip_preflight=True)) + 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: + if unknown is not None and not confirm: raise RuntimeError( - f"Sending {tx.signatures[0]} failed ({unknown}); the RPC may have taken it," + f"Sending {signature} failed ({unknown}); the RPC may have taken it," " so it may still land." ) - signature = str(resp.value) + # A send that may have reached the node is waited on like any other: + # it lands, fails, or expires. if confirm: + await self._await_outcome(signature, last_valid_block_height) + return str(signature) + + async def _await_outcome(self, signature: Signature, last_valid_block_height: int) -> None: + """Wait until the transaction lands, or until it no longer can. + + Returns once it is confirmed without error. Raises TransactionFailedError + if it landed and failed, TransactionExpiredError once the chain is past its + blockhash and no node has it, and RuntimeError if the RPC stops answering + for `CONFIRM_RPC_SILENCE_SECONDS`. + """ + loop = asyncio.get_running_loop() + silent_since = None + while True: try: - confirmed = await self.rpc.confirm_transaction( - resp.value, commitment="confirmed", sleep_seconds=1 - ) - 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 - # 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 + status = (await self.rpc.get_signature_statuses([signature])).value[0] + if status is None: + height = (await self.rpc.get_block_height(commitment="confirmed")).value + if height > last_valid_block_height: + # Too late to land; make sure no node saw it land first. + history = await self.rpc.get_signature_statuses( + [signature], search_transaction_history=True + ) + status = history.value[0] + if status is None: + raise TransactionExpiredError(str(signature)) + silent_since = None + except (TransactionExpiredError, TransactionFailedError): + raise + except Exception as exc: # noqa: BLE001 - one unanswered poll is not an outcome + silent_since = silent_since or loop.time() + if loop.time() - silent_since > CONFIRM_RPC_SILENCE_SECONDS: + raise RuntimeError( + f"Sent {signature}, but the RPC stopped answering" + f" ({type(exc).__name__}), so whether it landed is unknown." + ) from None + status = None + if status is not None and status.confirmation_status in _LANDED: + if status.err: + raise TransactionFailedError(status.err) + return + await asyncio.sleep(CONFIRM_POLL_SECONDS) async def send_tx( self, @@ -264,7 +314,7 @@ async def send_tx( """ failure = None try: - blockhash = await self.get_blockhash() + latest = (await self.rpc.get_latest_blockhash()).value except Exception as exc: # noqa: BLE001 - its text can carry the RPC URL failure = type(exc).__name__ if failure is not None: @@ -272,9 +322,11 @@ async def send_tx( 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 + signers[0].pubkey(), instructions, latest.blockhash, compute_units, priority_fee + ) + return await self._send_and_confirm( + VersionedTransaction(msg, signers), confirm, latest.last_valid_block_height ) - return await self._send_and_confirm(VersionedTransaction(msg, signers), confirm) async def get_transaction(self, signature_str: str) -> dict | None: """Fetch a confirmed transaction's outcome by signature. @@ -325,6 +377,9 @@ async def get_transaction(self, signature_str: str) -> dict | None: # None when the node did not record them, distinct from an empty list. "pre_token_balances": meta.get("preTokenBalances"), "post_token_balances": meta.get("postTokenBalances"), + # Lamports per account key; index 0 is the fee payer. + "pre_balances": meta.get("preBalances"), + "post_balances": meta.get("postBalances"), } async def close(self): diff --git a/tests/test_commands/test_human_output.py b/tests/test_commands/test_human_output.py index 6fef552..f1e4a47 100644 --- a/tests/test_commands/test_human_output.py +++ b/tests/test_commands/test_human_output.py @@ -424,3 +424,56 @@ def test_sol_text_is_exact(): assert sol_text(3_002_280) == "0.003002280" assert sol_text(12_000_000_001) == "12.000000001" assert sol_text(0) == "0.000000000" + + +_SOLD = { + "action": "sell", + "quote_symbol": "SOL", + "quote_received": 0.5, + "tokens_sold": 10.0, + "explorer": "x", +} + + +@pytest.mark.parametrize("flags,waits", [([], True), (["--confirm"], True), (["--fast"], False)]) +def test_sends_wait_for_the_outcome_unless_fast(wallet, flags, waits): + with ( + _human("trade"), + patch("pumpfun_cli.commands.trade.sell_token", new_callable=AsyncMock) as sell, + ): + sell.return_value = {**_SOLD, "confirmed": waits} + out = runner.invoke(app, ["--rpc", "http://rpc", "sell", MINT, "all", *flags]) + assert out.exit_code == 0 + assert sell.call_args.kwargs["confirm"] is waits + if waits: + assert out.output.startswith("Sold 10.00 tokens for 0.500000 SOL") + else: + assert out.output.startswith("Sent, not confirmed (--fast). Expected: Sold 10.00 tokens") + + +def test_fast_and_confirm_contradict(wallet): + out = runner.invoke(app, ["--rpc", "http://rpc", "sell", MINT, "all", "--fast", "--confirm"]) + assert out.exit_code == 2 + + +def test_a_transfer_that_never_landed_is_a_clean_error(wallet): + from pumpfun_cli.protocol.client import TransactionExpiredError + + with patch( + "pumpfun_cli.commands.wallet.transfer_sol", + new_callable=AsyncMock, + side_effect=TransactionExpiredError("sig"), + ): + out = runner.invoke(app, ["--rpc", "http://rpc", "wallet", "transfer", MINT, "0.1"]) + assert out.exit_code == 1 + assert "safe to send again" in out.output + assert "Traceback" not in out.output + + +def test_drain_always_waits_and_has_no_fast(wallet): + with patch("pumpfun_cli.commands.wallet.drain_wallet", new_callable=AsyncMock) as drain: + drain.return_value = {"error": "x", "message": "stop"} + runner.invoke(app, ["--rpc", "http://rpc", "wallet", "drain", MINT]) + fast = runner.invoke(app, ["--rpc", "http://rpc", "wallet", "drain", MINT, "--fast"]) + assert drain.call_args.kwargs["confirm"] is True + assert fast.exit_code == 2 diff --git a/tests/test_commands/test_smoke.py b/tests/test_commands/test_smoke.py index 893e441..ee0e5cd 100644 --- a/tests/test_commands/test_smoke.py +++ b/tests/test_commands/test_smoke.py @@ -57,7 +57,7 @@ def test_info_invalid_mint_shows_error(): def test_collect_creator_fee_help(): result = runner.invoke(app, ["collect-creator-fee", "--help"]) assert result.exit_code == 0 - assert "--confirm" in _strip_ansi(result.output) + assert "--fast" in _strip_ansi(result.output) def test_wallet_transfer_help_shows_mint(): @@ -65,13 +65,13 @@ def test_wallet_transfer_help_shows_mint(): assert result.exit_code == 0 out = _strip_ansi(result.output) assert "--mint" in out - assert "--confirm" in out + assert "--fast" in out -def test_buy_help_shows_confirm(): +def test_buy_help_shows_fast(): result = runner.invoke(app, ["buy", "--help"]) assert result.exit_code == 0 - assert "--confirm" in _strip_ansi(result.output) + assert "--fast" in _strip_ansi(result.output) def test_config_roundtrip_json(tmp_path, monkeypatch): diff --git a/tests/test_core/test_close_atas.py b/tests/test_core/test_close_atas.py index 154dddc..fada9d8 100644 --- a/tests/test_core/test_close_atas.py +++ b/tests/test_core/test_close_atas.py @@ -152,3 +152,25 @@ async def test_an_rpc_refusal_on_a_later_batch_reports_what_closed(tmp_path): 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" + + +async def test_a_later_batch_with_an_unknown_outcome_may_have_closed(tmp_path): + keyfile, user = _wallet(tmp_path) + client = _client([(TOKEN_PROGRAM, TokenHolding(lamports=1, closer=user))] * 45) + client.send_tx = AsyncMock(side_effect=["sig1", RuntimeError("RPC stopped answering")]) + 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"].startswith("25 account(s) not confirmed closed") + assert "up to 20 of them may have closed" in result["incomplete"] + + +async def test_an_expired_later_batch_did_not_close(tmp_path): + from pumpfun_cli.protocol.client import TransactionExpiredError + + keyfile, user = _wallet(tmp_path) + client = _client([(TOKEN_PROGRAM, TokenHolding(lamports=1, closer=user))] * 25) + client.send_tx = AsyncMock(side_effect=["sig1", TransactionExpiredError("sig2")]) + with patch("pumpfun_cli.protocol.client.RpcClient", return_value=client): + result = await close_empty_atas("http://rpc", keyfile, "testpass") + assert result["incomplete"].startswith("5 account(s) not closed") diff --git a/tests/test_core/test_exact_amounts.py b/tests/test_core/test_exact_amounts.py index 6c0fc05..7dbe8a8 100644 --- a/tests/test_core/test_exact_amounts.py +++ b/tests/test_core/test_exact_amounts.py @@ -136,3 +136,107 @@ def test_token_delta_refuses_to_guess(): } assert token_delta(unrecorded, owner, COIN) is None assert token_delta(ownerless, owner, COIN) is None + + +# --- a confirmed sell reads what it was paid from the landed transaction --- + + +def _lamports(paid_out: int, fee: int, rent: int) -> dict: + """A landed SOL sell: the payer gained the payout and any rent, less the fee.""" + return { + "err": None, + "fee": fee, + "pre_balances": [1_000_000_000, 7], + "post_balances": [1_000_000_000 + paid_out + rent - fee, 7], + "pre_token_balances": [], + "post_token_balances": [], + } + + +async def test_a_confirmed_sell_reports_the_quote_it_was_paid(tmp_keystore): + from tests.test_core.helpers import TOKEN_ACCOUNT_LAMPORTS, hold + + client = chain_with_coin() + hold(client, _user(tmp_keystore), COIN, 5_000_000) # selling all closes the account + client.transaction = _lamports(123_456_789, fee=35_000, rent=TOKEN_ACCOUNT_LAMPORTS) + with patch("pumpfun_cli.core.trade.RpcClient", return_value=client): + sold = await sell_token( + "http://rpc", tmp_keystore, "testpass", MINT_STR, "all", confirm=True + ) + assert sold["token_account_closed"] is True + assert sold["quote_received_raw"] == 123_456_789 + assert sold["quote_received"] == 123_456_789 / 10**9 + + +async def test_a_confirmed_partial_sell_has_no_rent_to_subtract(tmp_keystore): + from tests.test_core.helpers import hold + + client = chain_with_coin() + hold(client, _user(tmp_keystore), COIN, 5_000_000) + client.transaction = _lamports(1_000, fee=5_000, rent=0) + with patch("pumpfun_cli.core.trade.RpcClient", return_value=client): + sold = await sell_token( + "http://rpc", tmp_keystore, "testpass", MINT_STR, "1", confirm=True + ) + assert "token_account_closed" not in sold + assert sold["quote_received_raw"] == 1_000 + + +async def test_a_confirmed_pumpswap_sell_reports_the_quote_it_was_paid(tmp_keystore): + from tests.test_core.helpers import TOKEN_ACCOUNT_LAMPORTS, hold + + client = chain_with_coin(curve=build_curve_data(complete=True, virtual_quote=0)) + add_pool(client) + hold(client, _user(tmp_keystore), COIN, LOSSY_RAW) + client.transaction = _lamports(987_654, fee=10_000, rent=TOKEN_ACCOUNT_LAMPORTS) + with patch("pumpfun_cli.core.pumpswap.RpcClient", return_value=client): + sold = await sell_pumpswap( + "http://rpc", tmp_keystore, "testpass", MINT_STR, "all", confirm=True + ) + assert sold["quote_received_raw"] == 987_654 + + +async def test_a_confirmed_sell_in_another_quote_reads_its_token_balance(tmp_keystore): + from tests.test_core.helpers import T22_QUOTE, hold + + user = _user(tmp_keystore) + client = chain_with_coin( + curve=build_curve_data(quote_mint=T22_QUOTE), quote_mint=T22_QUOTE, quote_decimals=6 + ) + hold(client, user, COIN, 1_000_000) + + def rows(amount: int) -> list[dict]: + return [ + {"mint": str(T22_QUOTE), "owner": str(user), "uiTokenAmount": {"amount": str(amount)}} + ] + + client.transaction = { + "err": None, + "fee": 5_000, + "pre_balances": [1, 1], + "post_balances": [1, 1], + "pre_token_balances": rows(10), + "post_token_balances": rows(10 + 4_321), + } + with patch("pumpfun_cli.core.trade.RpcClient", return_value=client): + sold = await sell_token( + "http://rpc", tmp_keystore, "testpass", MINT_STR, "all", confirm=True + ) + assert sold["quote_received_raw"] == 4_321 + assert sold["quote_received"] == 4_321 / 10**6 + + +async def test_an_unreadable_sell_falls_back_to_the_estimate(tmp_keystore): + from tests.test_core.helpers import hold + + client = chain_with_coin() + hold(client, _user(tmp_keystore), COIN, 5_000_000) + client.transaction = None # not found on any read + with ( + patch("pumpfun_cli.core.trade.RpcClient", return_value=client), + patch("pumpfun_cli.core.amounts.asyncio.sleep"), + ): + sold = await sell_token( + "http://rpc", tmp_keystore, "testpass", MINT_STR, "all", confirm=True + ) + assert "quote_received" in sold and "quote_received_raw" not in sold diff --git a/tests/test_core/test_trade.py b/tests/test_core/test_trade.py index a132329..4daacee 100644 --- a/tests/test_core/test_trade.py +++ b/tests/test_core/test_trade.py @@ -22,7 +22,11 @@ find_ata, find_user_volume_accumulator, ) -from pumpfun_cli.protocol.client import TransactionFailedError +from pumpfun_cli.protocol.client import ( + TransactionExpiredError, + TransactionFailedError, + TransactionNotSentError, +) from pumpfun_cli.protocol.contracts import ( ASSOCIATED_TOKEN_PROGRAM, BUY_EXACT_QUOTE_IN_V2_DISCRIMINATOR, @@ -635,7 +639,16 @@ async def test_a_sweep_that_landed_unconfirmed_is_still_collected(tmp_keystore): assert "outcome is unknown" in result["sweep_warning"] -async def test_a_failed_sweep_ahead_still_collects_what_landed(tmp_keystore): +@pytest.mark.parametrize( + "never_ran", + [ + TransactionFailedError({"InstructionError": [0, {"Custom": 1}]}), + TransactionNotSentError("The RPC refused the transaction"), + TransactionExpiredError("sig"), + ], + ids=["failed", "not_sent", "expired"], +) +async def test_a_sweep_ahead_that_never_ran_still_collects_what_landed(tmp_keystore, never_ran): user = _user_from(tmp_keystore) client = FakeClient() client.balances[derive_creator_vault(user)] = 650_240 # only the rent floor @@ -648,7 +661,7 @@ async def test_a_failed_sweep_ahead_still_collects_what_landed(tmp_keystore): async def send(instructions, signers, **kw): sends.append(instructions) if len(sends) == 1: - raise TransactionFailedError({"InstructionError": [0, {"Custom": 1}]}) + raise never_ran return await real_send(instructions, signers, **kw) client.send_tx = send diff --git a/tests/test_core/test_wallet.py b/tests/test_core/test_wallet.py index 4940218..241cce3 100644 --- a/tests/test_core/test_wallet.py +++ b/tests/test_core/test_wallet.py @@ -225,6 +225,8 @@ async def test_transfer_all_sol_sends_balance_minus_fees(tmp_path): assert result["action"] == "transfer" assert result["sol_amount"] == expected_lamports / 1_000_000_000 assert result["signature"] == "fakesig123" + # Confirmed, so a drain sends the rent of closes that just landed. + assert mock_client.get_balance.call_args.kwargs.get("commitment") == "confirmed" # Verify the system transfer instruction used the right lamports call_args = mock_client.send_tx.call_args assert call_args is not None diff --git a/tests/test_protocol/test_client.py b/tests/test_protocol/test_client.py index 15e6c2c..7e599c5 100644 --- a/tests/test_protocol/test_client.py +++ b/tests/test_protocol/test_client.py @@ -1,6 +1,8 @@ +from unittest.mock import MagicMock + import pytest -from pumpfun_cli.protocol.client import RpcClient +from pumpfun_cli.protocol.client import RpcClient, TransactionExpiredError, TransactionFailedError def test_client_creation(): @@ -129,7 +131,12 @@ async def test_get_transaction_reads_v1_result(respx_mock): "blockTime": 99, "version": 1, "transaction": ["AAAA", "base64"], - "meta": {"err": None, "fee": 5000}, + "meta": { + "err": None, + "fee": 5000, + "preBalances": [100, 1], + "postBalances": [95, 1], + }, }, }, ) @@ -146,6 +153,8 @@ async def test_get_transaction_reads_v1_result(respx_mock): "block_time": 99, "pre_token_balances": None, "post_token_balances": None, + "pre_balances": [100, 1], + "post_balances": [95, 1], } body = respx_mock.calls.last.request.content assert b'"maxSupportedTransactionVersion":1' in body.replace(b" ", b"") @@ -182,18 +191,123 @@ async def test_get_transaction_http_error_hides_the_url(respx_mock): assert info.value.__cause__ is None and info.value.__context__ is None -@pytest.mark.asyncio -async def test_failed_confirmation_reports_the_signature(mocked): - from unittest.mock import AsyncMock, MagicMock +def _waiting(client, statuses, heights=(), history=None): + """Make `client`'s polls pop the next status; returns the signature it sends. + + `statuses` entries: None (not seen), "processed", "confirmed", ("confirmed", err) + or an Exception to raise. + """ + from types import SimpleNamespace + from unittest.mock import AsyncMock from solders.signature import Signature + from solders.transaction_status import TransactionConfirmationStatus as S + levels = {"processed": S.Processed, "confirmed": S.Confirmed} sig = Signature.default() - 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)): - await client._send_and_confirm(MagicMock(), confirm=True) + queue, heights = list(statuses), list(heights) + + def status(entry): + if entry is None: + return None + level, err = entry if isinstance(entry, tuple) else (entry, None) + return SimpleNamespace(confirmation_status=levels[level], err=err) + + async def statuses_call(sigs, search_transaction_history=False): + if search_transaction_history: + return SimpleNamespace(value=[status(history)]) + entry = queue.pop(0) if len(queue) > 1 else queue[0] + if isinstance(entry, Exception): + raise entry + return SimpleNamespace(value=[status(entry)]) + + async def height_call(commitment=None): + return SimpleNamespace(value=heights.pop(0) if len(heights) > 1 else heights[0]) + + client.sender.send_transaction = AsyncMock(return_value=MagicMock(value=sig)) + client.rpc.get_signature_statuses = statuses_call + client.rpc.get_block_height = height_call + return sig + + +def _tx(sig): + from types import SimpleNamespace + + return SimpleNamespace(signatures=[sig]) + + +@pytest.fixture +def waiting(mocked): + """(client, waiting(statuses, ...) -> signature) on a client closed afterwards.""" + return mocked, lambda *args, **kwargs: _waiting(mocked, *args, **kwargs) + + +@pytest.fixture +def no_wait(monkeypatch): + import pumpfun_cli.protocol.client as client_module + + monkeypatch.setattr(client_module, "CONFIRM_POLL_SECONDS", 0) + + +@pytest.mark.asyncio +async def test_confirm_waits_until_the_transaction_lands(no_wait, waiting): + client, wait = waiting + sig = wait([None, "processed", "confirmed"], heights=[10]) + assert await client._send_and_confirm(_tx(sig), True, 100) == str(sig) + + +@pytest.mark.asyncio +async def test_a_landed_failure_raises_with_its_error_code(no_wait, waiting): + err = {"InstructionError": [2, {"Custom": 6004}]} + client, wait = waiting + sig = wait([("confirmed", err)]) + with pytest.raises(TransactionFailedError) as info: + await client._send_and_confirm(_tx(sig), True, 100) + assert info.value.error_code == 6004 + + +@pytest.mark.asyncio +async def test_past_its_blockhash_and_unseen_it_never_landed(no_wait, waiting): + client, wait = waiting + sig = wait([None], heights=[99, 101]) + with pytest.raises(TransactionExpiredError, match="nothing was spent") as info: + await client._send_and_confirm(_tx(sig), True, 100) + assert str(sig) in str(info.value) + + +@pytest.mark.asyncio +async def test_past_its_blockhash_but_in_history_it_landed(no_wait, waiting): + """A node that lags can miss a landed transaction; history has the last word.""" + client, wait = waiting + sig = wait([None], heights=[101], history="confirmed") + assert await client._send_and_confirm(_tx(sig), True, 100) == str(sig) + + +@pytest.mark.asyncio +async def test_a_silent_rpc_makes_the_outcome_unknown(no_wait, waiting, monkeypatch): + import pumpfun_cli.protocol.client as client_module + + monkeypatch.setattr(client_module, "CONFIRM_RPC_SILENCE_SECONDS", 0) + client, wait = waiting + sig = wait([TimeoutError(), TimeoutError()]) + with pytest.raises(RuntimeError, match="whether it landed is unknown") as info: + await client._send_and_confirm(_tx(sig), True, 100) + assert str(sig) in str(info.value) + assert "tx-status" not in str(info.value) + + +@pytest.mark.asyncio +async def test_one_unanswered_poll_is_not_an_outcome(no_wait, waiting): + client, wait = waiting + sig = wait([TimeoutError(), "confirmed"]) + assert await client._send_and_confirm(_tx(sig), True, 100) == str(sig) + + +@pytest.mark.asyncio +async def test_fast_sends_without_waiting(no_wait, waiting): + client, wait = waiting + sig = wait([TimeoutError()]) + assert await client._send_and_confirm(_tx(sig), False, 100) == str(sig) @pytest.mark.asyncio @@ -211,13 +325,15 @@ async def test_get_transaction_non_json_is_a_runtime_error(respx_mock): def _blockhash_rpc(): from types import SimpleNamespace - from unittest.mock import AsyncMock, MagicMock + from unittest.mock import AsyncMock from solders.hash import Hash rpc = MagicMock() rpc.get_latest_blockhash = AsyncMock( - return_value=SimpleNamespace(value=SimpleNamespace(blockhash=Hash.default())) + return_value=SimpleNamespace( + value=SimpleNamespace(blockhash=Hash.default(), last_valid_block_height=100) + ) ) return rpc @@ -321,25 +437,21 @@ async def test_a_send_gets_one_attempt(): @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 +async def test_a_send_with_no_answer_is_waited_on_until_it_lands(no_wait, waiting): + import httpx - from solders.rpc.responses import GetSignatureStatusesResp - from solders.signature import Signature + client, wait = waiting + sig = wait(["confirmed"]) + client.sender.send_transaction.side_effect = httpx.ReadTimeout("http://secret-key.rpc") + assert await client._send_and_confirm(_tx(sig), True, 100) == str(sig) - 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) +@pytest.mark.asyncio +async def test_a_send_with_no_answer_that_never_lands_expires(no_wait, waiting): + import httpx + + client, wait = waiting + sig = wait([None], heights=[101]) + client.sender.send_transaction.side_effect = httpx.ReadTimeout("http://secret-key.rpc") + with pytest.raises(TransactionExpiredError, match="safe to send again"): + await client._send_and_confirm(_tx(sig), True, 100) diff --git a/uv.lock b/uv.lock index 9939dfc..7b29ee5 100644 --- a/uv.lock +++ b/uv.lock @@ -571,7 +571,7 @@ wheels = [ [[package]] name = "pumpfun-cli" -version = "0.3.7" +version = "0.4.0" source = { editable = "." } dependencies = [ { name = "base58" },