Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .claude-plugin/marketplace.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
},
"metadata": {
"description": "BSV micropayment skill for Claude Code - BRC-31 auth + BRC-29 payment via a BRC-100 wallet",
"version": "1.1.3"
"version": "1.1.4"
},
"plugins": [
{
Expand All @@ -15,7 +15,7 @@
"skills": [
"./skills/x402"
],
"version": "1.1.3"
"version": "1.1.4"
}
]
}
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ All payment is automatic - no confirmation prompts for typical micropayments (1

## Refunds

If a paid response is lost, the helper retries the identical payment up to three times after 2, 5, and 10 seconds. Each send must start within the quote's five-minute window; a started request retains its full 300-second response timeout so slow work can finish. It never pays twice for that quote. Before sending, it saves the payment and request in `~/.x402/pending/<txid>.json`. Unresolved calls report the txid and an exact `retry-payment` command while the window remains open. A signed `ERR_PAYMENT_REPLAYED` refusal stops retries and removes the file because the payment was already claimed for service or refund. A signed `ERR_QUOTE_EXPIRED` refusal stops retries and keeps the file marked `expired-unclaimed` with the time, server code and message: the quote expired; the server may not have claimed this payment; the sats are yours if no service was delivered; keep this file and recover with the server operator using its saved payment details through the refund path or a later receipt query, then use `import-refund` when refund data is available. Local quote expiry also retains and marks the file, without an unusable retry command. Other unconfirmed responses retain a terminal recovery record. A signed HTTP 200 for the same payment or successfully imported refund removes the file. If refund import fails, the response is returned and saved in the pending file, with an `import-refund` command to recover the refund without resending the payment.
If a paid response is lost, the helper retries the identical payment up to three times after 2, 5, and 10 seconds. Signed retryable 503 responses use a separate six-attempt bound and honour `Retry-After`. Signed 202 and retryable 503 waits are capped at the remaining quote window. Each send must start within the quote's five-minute window; a started request retains its full 300-second response timeout so slow work can finish. It never pays twice for that quote. Before sending, it saves the payment and request in `~/.x402/pending/<txid>.json`. Unresolved calls report the txid and an exact `retry-payment` command while the window remains open. A signed `ERR_PAYMENT_REPLAYED` refusal stops retries and removes the file because the payment was already claimed for service or refund. A signed `ERR_QUOTE_EXPIRED` refusal stops retries and keeps the file marked `expired-unclaimed` with the time, server code and message: the quote expired; the server may not have claimed this payment; the sats are yours if no service was delivered; keep this file and recover with the server operator using its saved payment details through the refund path or a later receipt query, then use `import-refund` when refund data is available. Local quote expiry also retains and marks the file, without an unusable retry command. Other unconfirmed responses retain a terminal recovery record. A signed HTTP 200 for the same payment or successfully imported refund removes the file. If refund import fails, the response is returned and saved in the pending file, with an `import-refund` command to recover the refund without resending the payment.

## Wallet selection and sessions

Expand All @@ -199,6 +199,8 @@ Run checks with `python3 -m pytest -q`. Regenerate the Available Services table

## Changelog

- **1.1.4** - Honour Retry-After on signed 503 payment-unavailable or retryable responses, reusing the identical payment and retaining expired recovery records. Both signed 202 and retryable 503 waits are capped at the remaining quote window and retain an expired-unclaimed record at expiry. Signed retryable 503s have a separate six-attempt bound, independent of the ordinary retry budget; exhaustion keeps the record for `retry-payment`.

- **1.1.3** - Retry identical payments after lost responses without paying twice. Save pending requests by txid and provide a `retry-payment` recovery command. Stop on signed replay or expired-quote codes; retain expired payments as `expired-unclaimed` with recovery instructions, time and server details, and remove records only for signed HTTP 200, claimed replay, or imported refunds. Report unsigned or signed paid 402 refusals with the txid. Bound send starts by the quote window while retaining the 300-second response timeout and one session refresh. Preserve delivered responses and refund bytes on import failure, with an `import-refund` command. Normalize the body once before quoting, tolerate stale server clocks beyond 60 seconds, suppress expired retry commands, and print payment JSON if the initial recovery-file write fails.

- **1.1.2** - Document the MetaNet Client and headless wallet paths, including gaps in the wallet README. Generate all service rows, exact registry tier ranges, and sync/async delivery from the public registry.
Expand Down
3 changes: 2 additions & 1 deletion skills/x402/SKILL.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
---
name: x402
version: 1.1.4
description: "Make BSV-authenticated or paid API requests. Use for: BRC-31 auth, 402 payment, BSV micropayments, x402, paid API calls. Requires a BRC-100 wallet (MetaNet Client at localhost:3321, or X402_WALLET_URL)."
argument-hint: [URL or description of API to call]
---
Expand Down Expand Up @@ -150,7 +151,7 @@ Servers that support BRC-29 refunds will automatically return refund data when a

The `discover` command shows which endpoints support refunds. The `pay` command output includes a `refund` block when a refund was received and internalized.

If a paid response is lost, the helper retries the identical payment after 2, 5, and 10 seconds. Sends must start within the quote's five-minute window; each started request retains its 300-second response timeout. It never creates another payment for that quote. Unresolved calls retain `~/.x402/pending/<txid>.json` and print the txid and an exact `retry-payment` command while the window remains open. Use that command with the original wallet instead of starting another `pay` call. Signed `ERR_PAYMENT_REPLAYED` stops retries and removes the already-claimed payment file. Signed `ERR_QUOTE_EXPIRED` stops retries and retains the file marked `expired-unclaimed`, with the time, server code and message: the server may not have claimed this payment; the sats are yours if no service was delivered. Keep the file and recover with the server operator through the refund path or a later receipt query, then use `import-refund` when refund data is available. Local quote expiry also marks and retains the file without a retry command; other unconfirmed responses retain a terminal recovery record. Only signed HTTP 200 for the same payment, claimed replay, or an imported refund removes the pending file. Failed refund imports preserve and return the delivered response and print an `import-refund` command; use it with the original wallet to import the saved refund without resending the payment.
If a paid response is lost, the helper retries the identical payment after 2, 5, and 10 seconds. Signed retryable 503 responses use a separate six-attempt bound and honour `Retry-After`. Signed 202 and retryable 503 waits are capped at the remaining quote window. Sends must start within the quote's five-minute window; each started request retains its 300-second response timeout. It never creates another payment for that quote. Unresolved calls retain `~/.x402/pending/<txid>.json` and print the txid and an exact `retry-payment` command while the window remains open. Use that command with the original wallet instead of starting another `pay` call. Signed `ERR_PAYMENT_REPLAYED` stops retries and removes the already-claimed payment file. Signed `ERR_QUOTE_EXPIRED` stops retries and retains the file marked `expired-unclaimed`, with the time, server code and message: the server may not have claimed this payment; the sats are yours if no service was delivered. Keep the file and recover with the server operator through the refund path or a later receipt query, then use `import-refund` when refund data is available. Local quote expiry also marks and retains the file without a retry command; other unconfirmed responses retain a terminal recovery record. Only signed HTTP 200 for the same payment, claimed replay, or an imported refund removes the pending file. Failed refund imports preserve and return the delivered response and print an `import-refund` command; use it with the original wallet to import the saved refund without resending the payment.

## Payment Transport

Expand Down
47 changes: 36 additions & 11 deletions skills/x402/lib/payment.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,10 @@
# BRC-29 payment protocol version. Must match server expectation.
PAYMENT_VERSION = "1.0"

# Maximum number of retries after the first paid send.
# Maximum number of ordinary retries after the first paid send.
MAX_PAYMENT_ATTEMPTS = 3
PAYMENT_BACKOFF = (2, 5, 10)
MAX_UNAVAILABLE_ATTEMPTS = 6
QUOTE_WINDOW = 300
PENDING_DIR = Path.home() / ".x402" / "pending"

Expand Down Expand Up @@ -619,13 +620,28 @@ def _send_pending(record: dict, path: Path, max_retries: int) -> requests.Respon
body = base64.b64decode(record["body"]) if record["body"] is not None else None
last_error = "quote window expired"
retry_after = None
for attempt in range(min(max(0, max_retries), len(PAYMENT_BACKOFF)) + 1):
if attempt:
delay = retry_after if retry_after is not None else PAYMENT_BACKOFF[attempt - 1]
retry_after = None
if time.time() + delay >= record["expires_at"]:
ordinary_retries = 0
unavailable_attempts = 0
unavailable_retry = False
first_send = True
retry_limit = min(max(0, max_retries), len(PAYMENT_BACKOFF))
while True:
if not first_send:
if not unavailable_retry:
if ordinary_retries >= retry_limit:
break
ordinary_retries += 1
delay = retry_after if retry_after is not None else PAYMENT_BACKOFF[ordinary_retries - 1]
if retry_after is not None:
delay = min(delay, max(0, record["expires_at"] - time.time()))
time.sleep(delay)
retry_after = None
elif time.time() + delay >= record["expires_at"]:
break
time.sleep(delay)
else:
time.sleep(delay)
first_send = False
unavailable_retry = False
remaining = record["expires_at"] - time.time()
if remaining <= 0:
break
Expand Down Expand Up @@ -661,8 +677,16 @@ def _send_pending(record: dict, path: Path, max_retries: int) -> requests.Respon
"to the first request or will be refunded. No payment remains to retry.")
if response.status_code == 402:
raise _unresolved(record, path, "paid request returned HTTP 402; no new payment created")
if response.status_code == 202:
last_error = "payment outcome still pending"
unavailable = response.status_code == 503 and isinstance(parsed, dict) and (
code == "ERR_PAYMENT_UNAVAILABLE" or parsed.get("retryable") is True
)
if response.status_code == 202 or unavailable:
last_error = "payment unavailable" if unavailable else "payment outcome still pending"
if unavailable:
unavailable_attempts += 1
if unavailable_attempts >= MAX_UNAVAILABLE_ATTEMPTS:
break
unavailable_retry = True
try:
retry_after = max(0, int(response.headers.get("Retry-After", "5")))
except ValueError:
Expand Down Expand Up @@ -740,9 +764,10 @@ def paid_request(
body: bytes | str | None = None,
max_payment_attempts: int = MAX_PAYMENT_ATTEMPTS,
) -> requests.Response:
"""Pay a verified quote once; retry the identical payment at most three times.
"""Pay a verified quote once; retry the identical payment within bounded budgets.

``max_payment_attempts`` limits retries after the first paid send. All sends
``max_payment_attempts`` limits ordinary retries after the first paid send.
Signed retryable 503s have a separate six-attempt budget. All sends
must begin within five minutes of receiving the quote (or the server's
earlier Date within 60 seconds of local time). Responses may take 300 seconds
after a send starts. Failures before payment creation propagate without paid retries.
Expand Down
75 changes: 74 additions & 1 deletion tests/test_payment_retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def request(method, url, headers, data, timeout):
outcome = outcomes.pop(0)
if isinstance(outcome, Exception):
raise outcome
status, body, signed = outcome
status, body, signed, *extra = outcome
response = requests.Response()
response.status_code = status
response._content = json.dumps(body).encode() if body is not None else b""
Expand All @@ -82,6 +82,8 @@ def request(method, url, headers, data, timeout):
response.headers["x-bsv-auth-your-nonce"] = load_session(URL.rsplit("/", 1)[0]).client_nonce_b64
if status == 402:
response.headers.update(quote_headers)
if len(calls) > 1 and extra:
response.headers.update(extra[0])
if signed:
rid = base64.b64decode(headers["x-bsv-auth-request-id"])
payload = serialize_response(rid, status, filter_signable_headers(response.headers), response.content or None)
Expand Down Expand Up @@ -482,3 +484,74 @@ def test_unconfirmed_response_keeps_terminal_record(server, status, code):
with pytest.raises(payment.PaymentError, match="keep this file"):
payment.retry_payment(path)
assert len(actions) == 1 and len(calls) == 2


@pytest.mark.parametrize("body", [{"code": "ERR_PAYMENT_UNAVAILABLE"},
{"code": "OTHER", "retryable": True}])
@pytest.mark.parametrize("header, delay", [("7", 7), ("invalid", 5), (None, 5)])
def test_unavailable_retries_identical_payment(server, body, header, delay):
outcomes, actions, calls, sleeps, _, _ = server
headers = {} if header is None else {"Retry-After": header}
outcomes.extend([(503, body, True, headers), (200, {"ok": True}, True)])
assert payment.paid_request("POST", URL, body="same payload").status_code == 200
assert sleeps == [delay] and len(actions) == 1
assert calls[1][1] == calls[2][1]
assert calls[1][0]["x-bsv-payment"] == calls[2][0]["x-bsv-payment"]
assert not (payment.PENDING_DIR / f"{TXID}.json").exists()


@pytest.mark.parametrize("status", [202, 503])
def test_retry_after_capped_at_quote_expiry(server, status):
outcomes, actions, calls, sleeps, now, _ = server
outcomes.append((status, {"code": "ERR_PAYMENT_UNAVAILABLE", "retryable": True},
True, {"Retry-After": "900"}))
with pytest.raises(payment.PaymentError, match="the quote expired"):
payment.paid_request("POST", URL)
saved = json.loads((payment.PENDING_DIR / f"{TXID}.json").read_text())
assert saved["state"] == "expired-unclaimed"
assert saved["terminal_at"] == now[0] == saved["expires_at"]
assert sleeps == [300] and len(actions) == 1 and len(calls) == 2


def test_unsigned_unavailable_ignores_retry_after(server):
outcomes, actions, calls, sleeps, _, _ = server
outcomes.extend([(503, {"code": "ERR_PAYMENT_UNAVAILABLE", "retryable": True},
False, {"Retry-After": "900"}), (200, {"ok": True}, True)])
assert payment.paid_request("POST", URL).status_code == 200
assert sleeps == [2] and len(actions) == 1 and len(calls) == 3


def test_nonretryable_signed_503_keeps_existing_handling(server):
outcomes, actions, calls, sleeps, _, _ = server
outcomes.append((503, {"code": "OTHER", "retryable": False}, True,
{"Retry-After": "7"}))
assert payment.paid_request("POST", URL).status_code == 503
saved = json.loads((payment.PENDING_DIR / f"{TXID}.json").read_text())
assert saved["state"] == "terminal-unresolved"
assert sleeps == [] and len(actions) == 1 and len(calls) == 2


@pytest.mark.parametrize("retry_after", ["0", "1"])
def test_unavailable_exhausts_separate_six_attempt_budget(server, retry_after):
outcomes, actions, calls, sleeps, now, _ = server
outcomes.extend([(503, {"code": "ERR_PAYMENT_UNAVAILABLE"}, True,
{"Retry-After": retry_after})] * 6)
with pytest.raises(payment.PaymentError, match="identical-payment retries exhausted"):
payment.paid_request("POST", URL, body="same payload", max_payment_attempts=0)
saved = json.loads((payment.PENDING_DIR / f"{TXID}.json").read_text())
assert saved.get("state") not in ("expired-unclaimed", "terminal-unresolved")
assert now[0] < saved["expires_at"]
assert len(actions) == 1 and len(calls) == 7
assert sleeps == [int(retry_after)] * 5
assert all(call[1] == calls[1][1] for call in calls[1:])
assert all(call[0]["x-bsv-payment"] == calls[1][0]["x-bsv-payment"]
for call in calls[1:])


def test_unavailable_does_not_consume_ordinary_retry_budget(server):
outcomes, actions, calls, sleeps, _, _ = server
outcomes.extend([(503, {"retryable": True}, True, {"Retry-After": "1"})] * 5)
outcomes.extend([(503, None, False), (200, {"ok": True}, True)])
assert payment.paid_request("POST", URL, max_payment_attempts=1).status_code == 200
assert sleeps == [1] * 5 + [2]
assert len(actions) == 1 and len(calls) == 8
Loading