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.2"
"version": "1.1.3"
},
"plugins": [
{
Expand All @@ -15,7 +15,7 @@
"skills": [
"./skills/x402"
],
"version": "1.1.2"
"version": "1.1.3"
}
]
}
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,10 @@ Storage costs $0.05 per GB-month with a 1,000-sat minimum per upload.

All payment is automatic - no confirmation prompts for typical micropayments (1–100,000 sats).

## 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.

## Wallet selection and sessions

Every wallet call goes to `X402_WALLET_URL` (default `http://localhost:3321`). Set it to use a second wallet daemon, e.g. `X402_WALLET_URL=http://localhost:3322`.
Expand All @@ -195,6 +199,8 @@ Run checks with `python3 -m pytest -q`. Regenerate the Available Services table

## Changelog

- **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.

- **1.1.1** - Sessions keyed by (server URL, client identity key); a session opened by one wallet is never reused by another (a wallet switch on the same server previously made the server derive the BRC-29 payee key from the wrong identity). Wallet URL configurable via `X402_WALLET_URL`. `createAction` accepts `tx` returned as an index-keyed object. Added `tests/` (`python3 -m pytest -q`).
Expand Down
4 changes: 4 additions & 0 deletions skills/x402/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ All operations use the helper script bundled with this skill. All commands outpu
| `python3 ./scripts/brc31_helpers.py discover <name_or_url>` | Learn server endpoints, auth requirements, costs |
| `python3 ./scripts/brc31_helpers.py auth <METHOD> <name_or_url> [body]` | Authenticated request (no payment) |
| `python3 ./scripts/brc31_helpers.py pay <METHOD> <name_or_url> [body]` | Authenticated + paid request (auto-handles 402) |
| `python3 ./scripts/brc31_helpers.py retry-payment <saved-file>` | Replay a saved payment with the original wallet |
| `python3 ./scripts/brc31_helpers.py import-refund <saved-file>` | Import a saved refund without resending the payment |
| `python3 ./scripts/brc31_helpers.py upload <file> <name_or_url> [retention_min] [--public-base URL]` | UHRP file upload: pays `/upload`, PUTs the bytes, returns the public URL |
| `python3 ./scripts/brc31_helpers.py identity` | Get wallet's 66-char hex identity key |
| `python3 ./scripts/brc31_helpers.py execute-action <json>` | Execute a pending action template (broadcasts inscription tx after user confirms) |
Expand Down Expand Up @@ -148,6 +150,8 @@ 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.

## Payment Transport

Payment is sent via `x-bsv-payment` header as JSON: `{"derivationPrefix":"...","derivationSuffix":"...","transaction":"<base64 BEEF>"}`. The client handles this automatically.
Expand Down
17 changes: 16 additions & 1 deletion skills/x402/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

# payment.py may not exist yet (built in parallel); import conditionally.
try:
from lib.payment import paid_request, PaymentError, PaymentRequired
from lib.payment import paid_request, retry_payment, PaymentError, PaymentRequired
HAS_PAYMENT = True
except ImportError:
HAS_PAYMENT = False
Expand Down Expand Up @@ -373,6 +373,17 @@ def cmd_pay(args):
return 0


def cmd_retry_payment(args):
"""Replay a saved payment without creating a new transaction."""
try:
response = retry_payment(args.file)
except (PaymentError, OSError, ValueError) as exc:
print_err(str(exc))
return 1
print_response(response)
return int(response.status_code >= 400 or response.signature_verdict != "signed")


def cmd_upload(args):
"""End-to-end UHRP file upload: pay /upload, PUT bytes, print public URL."""
from lib.upload import do_upload, UploadError
Expand Down Expand Up @@ -517,6 +528,9 @@ def build_parser() -> argparse.ArgumentParser:
help="Request body (JSON string). Optional.",
)

p_retry = subparsers.add_parser("retry-payment", help="Replay a saved payment.")
p_retry.add_argument("file", help="Saved payment JSON file.")

# --- upload ---
p_up = subparsers.add_parser(
"upload",
Expand Down Expand Up @@ -575,6 +589,7 @@ def main() -> int:
"session": cmd_session,
"auth": cmd_auth,
"pay": cmd_pay,
"retry-payment": cmd_retry_payment,
"upload": cmd_upload,
}

Expand Down
3 changes: 2 additions & 1 deletion skills/x402/lib/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ def paid_request(
) -> requests.Response
```
- **Purpose:** High-level entry point for paid endpoints. Makes an authenticated request, and if the server returns 402, automatically constructs and submits a BRC-29 payment, then retries.
- **Flow:** `authenticated_request()` → if 402: parse payment headers → `create_payment()` → retry with `x-bsv-payment` header → repeat up to `max_payment_attempts`
- **Flow:** `authenticated_request()` → if 402: parse payment headers → `create_payment()` → retry with `x-bsv-payment` header → retry identical payment up to `max_payment_attempts` times (2, 5, 10 seconds, within five minutes)
- **Recovery:** Save request and payment before sending in `~/.x402/pending/<txid>.json`; `retry-payment <file>` replays it with the original wallet and never creates a payment. Signed success or an imported refund removes the file.
- **Payment transport:** If payment JSON exceeds 8KB (`MULTIPART_THRESHOLD`) **and** the server advertises multipart support (`x-bsv-payment-transports: multipart`), sends payment (+ any original body) as BRC-105 multipart/form-data; otherwise sends payment JSON in the `x-bsv-payment` header. Typical payments (~2KB) use the header.

### do_handshake (handshake.py)
Expand Down
11 changes: 10 additions & 1 deletion skills/x402/lib/auth_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import logging
import base64
import sys
import time
import requests as _requests
from urllib.parse import urlparse

Expand Down Expand Up @@ -92,6 +93,8 @@ def authenticated_request(
body: bytes | str | None = None,
session: Session | None = None,
_allow_session_refresh: bool = True,
timeout: float = 300,
_deadline: float | None = None,
) -> _requests.Response:
"""Make an authenticated BRC-31 request.

Expand Down Expand Up @@ -256,13 +259,17 @@ def authenticated_request(
# -----------------------------------------------------------------------
# 10. Send the HTTP request
# -----------------------------------------------------------------------
if _deadline is not None:
remaining = _deadline - time.time()
if remaining <= 0:
raise AuthRequestError("Payment quote window expired before send.")
try:
response = _requests.request(
method=method.upper(),
url=url,
headers=merged_headers,
data=body_bytes,
timeout=300,
timeout=timeout,
)
except _requests.RequestException as e:
raise AuthRequestError(f"HTTP request failed: {e}") from e
Expand Down Expand Up @@ -296,6 +303,8 @@ def authenticated_request(
headers=headers,
body=body,
session=None, # force get_or_create_session -> handshake
timeout=timeout,
_deadline=_deadline,
_allow_session_refresh=False, # only retry once; avoid loops
)

Expand Down
Loading
Loading