Files
pumpfun-bonkfun-bot_github/tests/regression/verify_rpc_deadline.py
T
41b971147a refactor(cookbook): restructure learning-examples, add missing actions, fix quote decimals (#216)
* refactor(tests): move the regression verifiers into tests/regression

verify_*.py are not standalone examples: each imports src/, stubs the RPC
client, and asserts one previously fixed bug stays fixed. Their checks are
unchanged; PROJECT_ROOT, the usage lines and the bonk fixture lookup are
adjusted for the new depth. run_all.py runs the set and reports failures.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(tools): move the dev harness and listener benchmarks into tools/

simulate_*, live_*, both compare_* scripts and the account cleanup import
src/ and several spend real funds — they exercise the bot rather than teach
anything. compare_listeners.py reaches the repo root one level higher than
before; nothing else changes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(cookbook): reorganise learning-examples into cookbook/

The directory is a reference collection — one runnable script per action — but
nothing said so: no index, scripts grouped by the transport they happened to
use, fixtures loose at the root.

Now grouped by platform, then by what you are doing:
pumpfun/{listen,read,trade,graduation,decode}, pumpswap, letsbonk, legacy.
Fixtures sit beside the script that reads them, manual_sell.py becomes
sell_token.py, and the legacy create example moves to legacy/ and says why.
pump_v2.py and tx_status.py stay at the cookbook root as the only two shared
helpers; subdirectories add that root to sys.path before importing them.
cookbook/README.md indexes every script and marks the ones that spend funds.

Also fixes create_v2's account list: the five mayhem accounts are mandatory
whatever is_mayhem_mode says, so mint_and_buy_v2.py could never have worked
with mayhem off. 11 accounts fails AnchorError 3005 (AccountNotEnoughKeys) on
sol_vault, 16 succeeds with the argument either way — simulateTransaction
against mainnet. Seven scripts gain a module docstring they were missing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(cookbook): add buy, create, balance and status examples

  buy_token.py <MINT>        buy_v2 against one coin; --dry-run simulates
  create_token.py            create_v2 on its own
  get_balances.py            SOL and tokens across both token programs
  check_tx_status.py <SIG>   success, reverted, or not visible yet

Buying previously meant manual_buy.py, which waits for the next coin created
anywhere before it trades — there was no way to buy a coin you already know.
Creating one meant bundling a buy with it, and the transaction-status helper
was a library with no entry point.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(cookbook): move pump_v2 next to the scripts that use it

pump_v2.py holds the buy_v2/sell_v2 account layouts, and only the pump.fun
trade scripts import it — it sat at the cookbook root because tx_status.py
does, not because anything outside pumpfun/trade/ needed it. The five callers
now pick it up as a plain sibling; legacy/ and the layout verifier reach into
that directory. tx_status.py stays at the root, where all four platforms use it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* refactor(cookbook): name every script protocol_verb_noun_variant

manual_buy.py did not just buy — it waited for the next coin created anywhere,
then bought, so the verb was wrong. Protocol was encoded three different ways:
directory, suffix, or not at all. And three scripts sat under pumpfun/ that have
nothing to do with pump.fun.

Filenames are now <protocol>_<verb>_<noun>[_<variant>].py, so a basename says
which chain, what it does and which instruction version without opening it:

  manual_buy.py            -> pumpfun_snipe_token_blocksubscribe.py
  manual_buy_geyser.py     -> pumpfun_snipe_token_geyser.py
  buy_token.py             -> pumpfun_buy_token_v2.py
  mint_and_buy_v2.py       -> pumpfun_create_and_buy_token_v2.py
  manual_buy_pumpswap.py   -> pumpswap_buy_token.py
  manual_buy_exact_in.py   -> letsbonk_buy_token_exact_in.py
  legacy/mint_and_buy.py   -> legacy/pumpfun_create_and_buy_token_v1.py

The sniper was named for logsSubscribe in an earlier draft; it sends
blockSubscribe, and the name now says so.

Balances, transaction status and the Anchor discriminator calculator are not
pump.fun-specific and move to a new cookbook/solana/. The two non-runnable
helpers take no verb — pump_v2.py becomes pumpfun_instructions_v2.py beside its
callers, tx_status.py becomes solana_transaction_status.py in solana/. Both are
imported under a short alias so the 106 call sites stay readable.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(cookbook): resolve a coin's quote mint before pricing it

quote_units() defaulted to 9 decimals for an unresolved mint, and every trade
script called it before resolve_quote_token_program() warmed the decimals
cache. pump.fun's QuoteControl registry admits mints at 6, 8 and 9 decimals —
79 of the 170 admitted are tokenized equities, 8 decimals for xStocks and 6 for
Backpack Securities — so those coins were sized against the wrong power of ten.

The error compounds rather than cancels: price_per_token() divides by the same
wrong unit, so the price reads low by the factor, the token amount comes out
high by it, and the inflated cap authorises the overspend instead of catching
it. 10x on an xStock pair, 1000x on a Backpack one.

This is not hypothetical. A 75s sample of live curve updates on 2026-09-22
caught 8 stock-paired curves out of 124 — IONQ across 5 of them, plus QUBT,
PLTRx and COPX.

quote_units() now raises for an unresolved mint instead of guessing, the four
trade paths resolve before they price, and pumpfun_read_price.py reads decimals
from chain rather than from a two-entry table. The geyser sniper never resolved
at all: it also passed SPL Token as the quote token program, which fails the
account constraints for any Token-2022 quote, and created no quote ATA.

verify_quote_decimals_resolved.py checks the fail-closed contract, that
resolution costs no extra RPC call, and that no function prices before it
resolves — confirmed to fail when the ordering is put back.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR

* feat(cookbook): read the quote-mint registry and Token-2022 mint state

Two reads that were unreachable without knowing an undocumented PDA seed.

pumpfun_read_quote_mints.py decodes QuoteControl (PDA ["quote-control"]), the
second quote-mint registry added in the 2026-09-15 upgrade. Reading only
Global.whitelisted_quote_mints under-reports: a coin can be paired with a mint
Global has never heard of. 170 admitted today, 79 of them tokenized equities,
each with the initial virtual quote reserves that set a new curve's opening
price. --stocks narrows to the equities, identified by the Token-2022 extension
set create_v2 requires of them rather than by a name lookup.

solana_read_token2022_mint.py reads the extensions that change what a balance
means: scaled UI amount, pausable, permanent delegate, transfer hook, default
account state. It exists mainly for one trap — the RPC returns both `multiplier`
and `newMultiplier` with an effective timestamp, and once that timestamp passes
the field named `multiplier` is the stale one. On AAPLx it passed on 2026-08-08,
so the obvious field has been wrong for six weeks. This compares against the
clock and says which is in force.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR

* feat(cookbook): add the exact-quote-in buy

buy_exact_quote_in_v2 was uncovered. It is the mirror of buy_v2 — buy_v2 fixes
the tokens received and caps the spend, this fixes the spend and floors the
tokens — and it takes the same 27 accounts in the same order, so it reuses
build_v2_accounts and differs only in discriminator and arguments.

Worth having because pinning the spend is the natural direction once a coin is
priced in something other than SOL: "spend exactly one AAPLx" is something you
can mean, where a token count is a number derived from a price that moved while
you derived it.

Verified by simulateTransaction against a live COPX-paired coin: the program
executes the full buy and stops at TransferChecked with insufficient funds,
which is as far as a wallet holding none of the quote asset can go.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR

* feat(cookbook): add the exact-SOL-in buy

buy_exact_sol_in was uncovered. SOL only — it pre-dates non-SOL quote assets and
carries no quote accounts, so the script checks the curve and points at the
exact-quote version for anything else rather than failing obscurely.

Its account list is the reason to have it. The IDL lists 16; the program needs
18, the extras being the bonding-curve-v2 PDA and a buyback fee recipient.
Determined by simulation rather than assumed: 16 accounts fails AnchorError 6062
(BuybackFeeRecipientMissing), 18 simulates clean at 96k CU. The v2 instructions
are complete in the IDL and this family is not, which is worth a newcomer
knowing before they trust the file.

The docstring carries the IDL's own fee arithmetic, since fees come out of the
amount you name rather than on top of it, and the printed estimate ignores that
split while min_tokens_out is what the program enforces.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR

* feat(cookbook): add the creator-fee and cashback payouts

Two payout paths that had no script. Both take no arguments and, per the IDL,
no signer — the funds can only reach the wallet they already belong to, so
either can be run for anyone, which --creator and --user expose.

collect_creator_fee_v2 sweeps a creator vault. The vault is per creator and per
quote asset, so a creator whose coins are priced in several assets collects each
separately; --quote picks which.

claim_cashback_v2 pays out an accrued cashback balance. create_v2 has rejected
new cashback coins since 2026-09-15 (error 6082), but coins minted before that
keep accruing and stay claimable, which is why the cashback handling elsewhere
in this repo is not dead code.

Both verified by simulateTransaction against mainnet: 10 accounts each, 8 data
bytes, no error.

Also repairs two cookbook README rows that the earlier rename mangled —
pumpswap_buy_token.py had been rewritten to pumpswap_pumpfun_buy_token_v2.py
because its name contains the string that rename matched on.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR

* refactor(cookbook): take every script's input on the command line

A reference collection only works if you can run a script against your own coin
without editing it. Several carried the coin as a module-level constant instead:

    TOKEN_MINT = Pubkey.from_string(sys.argv[1] if len(sys.argv) > 1 else "...")

which reads as optional but raises at import, so running the script the way its
own usage line described it died on ValueError: Invalid Base58 string before
printing anything. Nine scripts did this. Four more took their amount and
slippage from environment variables that no usage line mentioned.

Every script now builds an ArgumentParser in main(): required values are
positionals, tunables are --options, and the literals live in DEFAULT_* constants
that supply the defaults. --help works on all 32 that take input; the seven
listeners take none and are exempt. The decode scripts keep defaulting to the
fixture beside them, so they still run bare.

Behaviour is unchanged. create_and_buy's mayhem flag defaulted to on, so it takes
--mayhem/--no-mayhem via BooleanOptionalAction rather than a store_true that
would have silently flipped it off.

Two fixes found while threading the values through: the wallet listener read a
global `wallet` from four functions that no longer had one, and find_pool raised
IndexError on a coin that has not graduated instead of saying so.

verify_cookbook_arguments.py enforces the shape — no module-level sys.argv, no
placeholder values, argparse wherever there is input, and every default a usable
value. Confirmed to fail when the old pattern is put back.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR

* fix(docs): replace three dead links and check the rest

The Anchor discriminator citation in anchor_calculate_discriminator.py pointed
at book.anchor-lang.com/anchor_bts/discriminator.html, which Anchor removed when
it restructured its docs. Two links in the README had also moved:
docs.chainstack.com/quickstart/ and docs.chainstack.com/docs/trader-nodes.

  book.anchor-lang.com/anchor_bts/discriminator.html
    -> www.anchor-lang.com/docs/basics/idl          (has a Discriminators section)
  docs.chainstack.com/quickstart/
    -> docs.chainstack.com/reference/blockchain-apis
  docs.chainstack.com/docs/trader-nodes
    -> docs.chainstack.com/docs/solana-trader-nodes

All 28 real URLs in the repo now return 200, checked by fetching each one.

verify_documentation_links.py keeps them honest: offline it asserts every URL is
https and that none of the four dead endpoints has come back, and --live fetches
each and fails on 4xx/5xx. It skips the unroutable hosts the offline verifiers
point stub clients at, and example.com, which RFC 2606 reserves for exactly the
placeholder metadata URI a test coin is created with.

The discriminator script also still asked you to edit a constant, which the
argument rule had just outlawed, so it takes the name on the command line and
prints the u64, the byte list and the hex. Cross-checks against the constants in
pumpfun_instructions_v2.py: global:buy_v2 gives [184, 23, 238, 97, 103, 197,
211, 61], which is BUY_V2_DISCRIMINATOR.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR

* fix(cookbook,tools): detect coins via logs so v1 transactions are not skipped

Solana transaction v1 has been live since 2026-09-15 and solders cannot
deserialize one until 0.29. Three scripts detected coins by deserializing the
transaction envelope, so each went blind to v1:

  cookbook/pumpfun/listen/pumpfun_listen_tokens_blocksubscribe.py
      30,080 "skipping a v1 transaction" lines in 150s
  tools/compare_listeners.py
      601 "Failed to process transaction: io error: unexpected end of file"
      in 100s, which its own comment read as a transport difference
  cookbook/pumpfun/trade/pumpfun_snipe_token_blocksubscribe.py
      skipped v1 silently, so a coin created in one was never sniped

All three now route on meta.logMessages, which the RPC has already decoded and
which reads the same for every version. The blocks example keeps the envelope
decode as a genuine fallback for providers that return blocks without logs; the
sniper derives the associated bonding curve from the mint and curve instead of
reading the instruction's account list, verified against
pumpfun_derive_curve_addresses.py on a live coin.

Measured live after the change: the blocks example decoded 88 v0, 6 v1 and 4
legacy creates with zero skips and zero errors, and compare_listeners' block
lane now appears alongside logs and geyser for the same coins.

Upgrading solders was tried first and reverted. 0.29 does decode v1 — 0.26,
0.27.1 and 0.28 all raise "io error: unexpected end of file" on the committed
fixture — but it requires solana>=0.40, which moved TxOpts, MemcmpOpts and
TokenAccountOpts out of solana.rpc.types. 22 files import them and 16 of 19
verifiers failed on the import alone, so that is a migration of its own.

verify_transaction_v1.py gains a check that no cookbook or tools listener
detects by opening the envelope. It found the sniper, which this had missed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR

* fix(cookbook): label the transaction version and restore the lost fields

The blocks listener printed "Found CreateEvent in a 0 transaction", which reads
as a count rather than what it is — Solana's transaction version. It now prints
v0, v1 or legacy.

Routing detection through the CreateEvent also dropped two fields the
instruction path used to fill, so every detection showed "Token Standard: N/A"
and no Associated BC. Both come from the event's token_program: the standard is
that program, and the associated bonding curve is an ordinary ATA of the curve
under it. Verified against pumpfun_derive_curve_addresses.py on a live coin —
curve E94izXvHd7dd... derives to He94dArnuprt..., matching what the listener
now prints.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ5HdjTadNUad8i6xis3TR

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 09:34:40 +02:00

384 lines
12 KiB
Python

"""Verify post_rpc bounds wall time, not just attempts.
`SolanaClient.post_rpc` bounded how many times it retried but never how long it
could take. With the defaults a stalled or rate-limiting endpoint could keep one
call going for minutes: three error retries backing off 1, 2, 4 ... 16s, or ten
429 retries waiting up to 30s each and honouring a `Retry-After` header of any
size. Every caller inherits that, and on the trade path a buy confirmation that
blocks for minutes holds up the whole bot.
`_get_transaction_result` is the caller that showed it. It takes a
`budget_seconds` and checks the deadline *between* attempts, so the check only
runs once `post_rpc` has returned — making the real worst case
`budget_seconds + one post_rpc worst case` rather than the budget it advertises.
The fix belongs in `post_rpc` itself, as an overall deadline separate from the
attempt count, so a caller can say how long an answer is worth waiting for.
Wrapping the lookup in `asyncio.timeout` would instead cut off an in-flight
`getTransaction` and report None, which is the same "can't see it, so call it
failed" conflation that #206 removed.
Offline machine checks, no network and no funds moved. The real `post_rpc` runs
against a stub session on a virtual clock, so a 30s backoff costs no real time:
1. Without a deadline, behaviour is unchanged - attempts still bound the call.
2. A deadline stops the retries early instead of running the full schedule.
3. A backoff that would overshoot the deadline is not slept at all.
4. 429 retries honour the deadline, including an oversized Retry-After.
5. A deadline already spent returns without sending anything.
6. A successful response is unaffected by the deadline.
7. _get_transaction_result hands each lookup only the budget that is left.
Usage:
uv run tests/regression/verify_rpc_deadline.py
"""
import asyncio
import sys
from itertools import pairwise
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(PROJECT_ROOT / "src"))
import core.client as client_module # noqa: E402
from core.client import SolanaClient # noqa: E402
BODY = {"jsonrpc": "2.0", "id": 1, "method": "getTransaction", "params": []}
# post_rpc's own defaults, restated so a change to them fails a check here
# rather than silently weakening one.
DEFAULT_MAX_RETRIES = 3
DEFAULT_MAX_429_RETRIES = 10
# 1 + 2 + 4s of backoff sits well inside this, so a deadline this size must not
# change the unbounded outcome; 2.5s cuts the schedule after the first retry.
GENEROUS_DEADLINE = 120.0
TIGHT_DEADLINE = 2.5
ATTEMPTS_BEFORE_TIGHT_DEADLINE = 2
HUGE_RETRY_AFTER = "600" # a provider asking for ten minutes
TX_BUDGET = 5.0
class VirtualClock:
"""A monotonic clock that only advances when something sleeps on it."""
def __init__(self) -> None:
self.now = 1000.0
self.slept: list[float] = []
def monotonic(self) -> float:
"""Read the clock.
Returns:
Current virtual time in seconds
"""
return self.now
async def sleep(self, seconds: float) -> None:
"""Advance the clock instead of waiting.
Args:
seconds: How far to move the clock forward
"""
self.slept.append(seconds)
self.now += seconds
class StubResponse:
"""Minimal stand-in for an aiohttp response."""
def __init__(self, status: int, payload: dict, headers: dict | None = None) -> None:
self.status = status
self.headers = headers or {}
self._payload = payload
async def __aenter__(self) -> "StubResponse":
return self
async def __aexit__(self, *_exc: object) -> bool:
return False
def raise_for_status(self) -> None:
"""No-op: any non-200 case here is expressed through status directly."""
async def json(self) -> dict:
"""Return the scripted payload.
Returns:
The response body
"""
return self._payload
class StubSession:
"""Serves a scripted sequence of outcomes and counts the requests."""
def __init__(self, outcomes: list) -> None:
self.outcomes = list(outcomes)
self.requests = 0
def post(self, _url: str, json: dict) -> StubResponse: # noqa: ARG002
"""Answer one request.
Args:
_url: Ignored
json: Ignored request body
Returns:
The next scripted response
Raises:
TimeoutError: When the script says this attempt times out
"""
self.requests += 1
outcome = self.outcomes.pop(0) if self.outcomes else self.outcomes_default()
if outcome == "timeout":
raise TimeoutError
return outcome
def outcomes_default(self) -> str:
"""Keep timing out once the script runs dry.
Returns:
The repeating outcome
"""
return "timeout"
def _make_client(session: StubSession) -> SolanaClient:
"""Build a client carrying only what post_rpc touches.
Args:
session: Stub session to serve requests
Returns:
A SolanaClient wired to the stub
"""
class _NoRateLimit:
async def acquire(self) -> None:
pass
solana_client = object.__new__(SolanaClient)
solana_client.rpc_endpoint = "https://stub.invalid"
solana_client._rate_limiter = _NoRateLimit() # noqa: SLF001
async def _get_session() -> StubSession:
return session
solana_client._get_session = _get_session # noqa: SLF001
return solana_client
def _check(label: str, passed: bool, detail: str) -> bool: # noqa: FBT001
"""Print one check result.
Args:
label: What was checked
passed: Whether it held
detail: Evidence behind the verdict
Returns:
The value of `passed`
"""
print(f"{'PASS' if passed else 'FAIL'} {label}\n {detail}")
return passed
async def _run(outcomes: list, clock: VirtualClock, **kwargs: float) -> tuple:
"""Drive the real post_rpc against the stub on a virtual clock.
Args:
outcomes: Scripted responses
clock: Virtual clock to install
**kwargs: Passed through to post_rpc
Returns:
(result, session, elapsed virtual seconds)
"""
session = StubSession(outcomes)
solana_client = _make_client(session)
started = clock.now
real_sleep, real_monotonic = asyncio.sleep, client_module.monotonic
asyncio.sleep = clock.sleep
client_module.monotonic = clock.monotonic
try:
result = await solana_client.post_rpc(BODY, **kwargs)
finally:
asyncio.sleep = real_sleep
client_module.monotonic = real_monotonic
return result, session, clock.now - started
async def check_no_deadline_is_unchanged() -> bool:
"""Without a deadline the call still runs its full attempt budget.
Returns:
Whether the check passed
"""
clock = VirtualClock()
result, session, elapsed = await _run(["timeout"] * 10, clock)
return _check(
"no deadline: attempts still bound the call, wall time does not",
result is None and session.requests == DEFAULT_MAX_RETRIES,
f"{session.requests} request(s) over {elapsed:.1f}s virtual "
f"(max_retries={DEFAULT_MAX_RETRIES})",
)
async def check_deadline_stops_retrying() -> bool:
"""A deadline cuts the retry schedule short.
Returns:
Whether the check passed
"""
clock = VirtualClock()
result, session, elapsed = await _run(
["timeout"] * 10, clock, deadline_seconds=TIGHT_DEADLINE
)
return _check(
"deadline: retries stop early instead of running the full schedule",
result is None
and session.requests == ATTEMPTS_BEFORE_TIGHT_DEADLINE
and elapsed <= TIGHT_DEADLINE,
f"{session.requests} request(s) in {elapsed:.1f}s virtual, "
f"deadline {TIGHT_DEADLINE}s",
)
async def check_backoff_never_overshoots() -> bool:
"""No sleep is taken that would run past the deadline.
Returns:
Whether the check passed
"""
clock = VirtualClock()
_result, _session, elapsed = await _run(
["timeout"] * 10, clock, deadline_seconds=TIGHT_DEADLINE
)
return _check(
"deadline: a backoff that would overshoot is not slept at all",
elapsed <= TIGHT_DEADLINE and all(s <= TIGHT_DEADLINE for s in clock.slept),
f"slept {clock.slept} for {elapsed:.1f}s total, deadline {TIGHT_DEADLINE}s",
)
async def check_429_honours_deadline() -> bool:
"""An oversized Retry-After cannot push the call past its deadline.
Returns:
Whether the check passed
"""
clock = VirtualClock()
rate_limited = [
StubResponse(429, {}, {"Retry-After": HUGE_RETRY_AFTER}) for _ in range(10)
]
result, session, elapsed = await _run(
rate_limited, clock, deadline_seconds=TIGHT_DEADLINE
)
return _check(
"deadline: 429 retries honour it, Retry-After included",
result is None and elapsed <= TIGHT_DEADLINE and session.requests == 1,
f"Retry-After {HUGE_RETRY_AFTER}s, gave up after {session.requests} "
f"request(s) in {elapsed:.1f}s virtual",
)
async def check_spent_deadline_sends_nothing() -> bool:
"""A deadline of zero returns before any request goes out.
Returns:
Whether the check passed
"""
clock = VirtualClock()
result, session, _elapsed = await _run(["timeout"], clock, deadline_seconds=0.0)
return _check(
"deadline already spent: returns without sending a request",
result is None and session.requests == 0,
f"{session.requests} request(s) sent",
)
async def check_success_is_unaffected() -> bool:
"""A deadline does not disturb the happy path.
Returns:
Whether the check passed
"""
clock = VirtualClock()
payload = {"result": {"meta": {"err": None}}}
result, session, elapsed = await _run(
[StubResponse(200, payload)], clock, deadline_seconds=TIGHT_DEADLINE
)
return _check(
"success: a deadline does not disturb a first-try answer",
result == payload and session.requests == 1 and elapsed == 0,
f"{session.requests} request(s), {elapsed:.1f}s virtual, result returned",
)
async def check_tx_result_passes_remaining_budget() -> bool:
"""_get_transaction_result gives each lookup only the budget that is left.
Returns:
Whether the check passed
"""
clock = VirtualClock()
solana_client = _make_client(StubSession([]))
deadlines: list[float] = []
async def fake_post_rpc(_body: dict, **kwargs: float) -> None:
deadlines.append(kwargs.get("deadline_seconds"))
await clock.sleep(1.0) # each lookup burns a second of the budget
solana_client.post_rpc = fake_post_rpc
real_sleep, real_monotonic = asyncio.sleep, client_module.monotonic
asyncio.sleep = clock.sleep
client_module.monotonic = clock.monotonic
try:
result = await solana_client._get_transaction_result( # noqa: SLF001
"sig", budget_seconds=TX_BUDGET
)
finally:
asyncio.sleep = real_sleep
client_module.monotonic = real_monotonic
passed_any = bool(deadlines)
all_bounded = all(d is not None and d <= TX_BUDGET for d in deadlines)
shrinking = all(later <= earlier for earlier, later in pairwise(deadlines))
return _check(
"_get_transaction_result hands each lookup the time it has left",
result is None and passed_any and all_bounded and shrinking,
f"deadlines passed: {[round(d, 1) for d in deadlines]} (budget {TX_BUDGET}s)",
)
async def main() -> None:
"""Run every check and exit non-zero if any failed."""
print("=" * 72)
print("Verifying post_rpc bounds wall time, not just attempts")
print("=" * 72)
results = [
await check_no_deadline_is_unchanged(),
await check_deadline_stops_retrying(),
await check_backoff_never_overshoots(),
await check_429_honours_deadline(),
await check_spent_deadline_sends_nothing(),
await check_success_is_unaffected(),
await check_tx_result_passes_remaining_budget(),
]
print("\n" + "=" * 72)
if all(results):
print(f"ALL {len(results)} CHECKS PASSED")
else:
print(f"{results.count(False)}/{len(results)} CHECKS FAILED")
sys.exit(1)
if __name__ == "__main__":
asyncio.run(main())