@redditech/x402-solana 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/LICENSE +21 -0
  3. package/README.md +301 -2
  4. package/dist/budget-policy.d.ts +68 -0
  5. package/dist/budget-policy.js +234 -0
  6. package/dist/buyer.d.ts +54 -0
  7. package/dist/buyer.js +147 -0
  8. package/dist/client.d.ts +80 -0
  9. package/dist/client.js +225 -0
  10. package/dist/direct-auth.d.ts +94 -0
  11. package/dist/direct-auth.js +120 -0
  12. package/dist/direct-payment.d.ts +33 -0
  13. package/dist/direct-payment.js +65 -0
  14. package/dist/ed25519.d.ts +6 -0
  15. package/dist/ed25519.js +42 -0
  16. package/dist/escrow-http.d.ts +125 -0
  17. package/dist/escrow-http.js +192 -0
  18. package/dist/escrow-readiness.d.ts +132 -0
  19. package/dist/escrow-readiness.js +171 -0
  20. package/dist/index.d.ts +26 -0
  21. package/dist/index.js +42 -0
  22. package/dist/jupiter.d.ts +36 -0
  23. package/dist/jupiter.js +120 -0
  24. package/dist/metered.d.ts +58 -0
  25. package/dist/metered.js +82 -0
  26. package/dist/middleware.d.ts +9 -0
  27. package/dist/middleware.js +71 -0
  28. package/dist/nonce.d.ts +57 -0
  29. package/dist/nonce.js +123 -0
  30. package/dist/payment.d.ts +202 -0
  31. package/dist/payment.js +967 -0
  32. package/dist/provider.d.ts +371 -0
  33. package/dist/provider.js +492 -0
  34. package/dist/rating.d.ts +552 -0
  35. package/dist/rating.js +829 -0
  36. package/dist/session-auth.d.ts +168 -0
  37. package/dist/session-auth.js +341 -0
  38. package/dist/session.d.ts +220 -0
  39. package/dist/session.js +297 -0
  40. package/dist/spl-token-observer.d.ts +70 -0
  41. package/dist/spl-token-observer.js +319 -0
  42. package/dist/token-escrow.d.ts +125 -0
  43. package/dist/token-escrow.js +163 -0
  44. package/dist/types.d.ts +148 -0
  45. package/dist/types.js +2 -0
  46. package/package.json +109 -4
package/CHANGELOG.md ADDED
@@ -0,0 +1,90 @@
1
+ # Changelog — @redditech/x402-solana
2
+
3
+ All notable changes to this package are documented here. Dates are AEST.
4
+
5
+ ## 0.1.1 — 2026-11-22
6
+
7
+ ### Changed
8
+
9
+ - The package description and README summary say what the package does: x402 payments on Solana for Reddi Agent Protocol, for buyers and providers.
10
+
11
+ ## 0.1.0 — 2026-11-22
12
+
13
+ ### Changed
14
+
15
+ - Every escrow exit names the escrow it ends, as the V1 program now requires: the escrow's lock slot (`created_slot`, u64 little-endian) follows the exit's data, rated or not. `withRatingAccount(exit, rated, createdSlot)` always appends it and throws without it; the SOL exit builders and `buildTokenEscrowExitInstruction` take `createdSlot` (or a rated job's `openedSlot`, the same slot). `meteredSettlement`, `meteredDecline` and `buildEscrowSellerExit` name the escrow from the verified lock or receipt. `verifyMeteredLock` refuses a rated lock whose rating's opened slot is not the escrow's lock slot. The session ledger and `sessionSettlement` refuse a lock at the session's address that was locked in another slot (`session_lock_mismatch`). `RATING_PROGRAM_ERRORS` names 6052 `EscrowJustLocked` and 6053 `EscrowInstanceMismatch`.
16
+
17
+ ### Added
18
+
19
+ - `session` module (re-exported from the root): the seller side of a metered session, one escrow paying for many calls with one settle (#863). `MeteredSessionLedger` (per-call sequence numbers, the worst-case check against the lock, running totals, saved through a `SessionStore` before each answer, `restore()` after a restart, `due()` for idle sessions and locks near their refund window), `readSessionHeaders` (`x402-session-sequence`, `x402-session: close`), `sessionSettlement` and `sessionPaymentHeader`. `verifyMeteredLock` gains `purpose` (`call`, `session-call`, `session-settle`) and returns the lock's `createdSlot`; `meteredEscrowReplayKey` is the key single calls and sessions share, so a lock pays for one or the other. It signs and sends nothing.
20
+ - `session-auth` module (re-exported from the root): proof that a session request comes from the payer (#863). The payer wallet signs a plain-text delegation of `{escrow, provider, sessionKey, expiresAt}` (at most seven days); each call, close and read is signed by that session key over the action, escrow, call number and body hash. `verifySessionRequest` (provider side, refusals `session_auth_required`, `session_auth_invalid`, `session_auth_expired`), `sessionDelegationHeaderValue` and `sessionSignatureHeaderValue` (buyer side, any signer). The session ledger keeps the key a session started with (`session_key_mismatch`).
21
+ - Single metered calls are signed too (#866): action `single` (sequence 0) in `session-auth`, `paidCallAuthHeaders` (buyer: payer signs directly or delegates to a fresh key) and `verifyPaidCallRequest` (provider). provider-kit and openrouter-specialists refuse an unsigned single call with `401` before reading the lock.
22
+ - `DEFAULT_DELEGATION_SECONDS` (a day) and `delegationExpiresAt()` for buyer clients: delegations should run a day, not the seven-day maximum, with the session key in memory only. README notes that hardware wallets signing off-chain messages with a header prefix (Ledger) are not accepted yet.
23
+ - Direct per-call payments need the payer's proof: `direct-auth` module (re-exported from the root). The request that presents a direct receipt carries `x402-payment-proof`, a signature over the network, the transaction signature, the payee and the SHA-256 of the raw body, by the wallet that paid or by a session key it delegated to this provider in `x402-payment-delegation` (at most seven days). `directPaymentProofHeaders` and `directPaymentDelegationHeaderValue` (buyer, any signer), `keypairSigner` and `devnetUsdcPaymentProofHeaders` for server-held keys, `verifyDirectPaymentProof` and `directPaymentProofCheck` (provider). The MCP bridge signs its paid devnet retry with it.
24
+ - `rating` module (`@redditech/x402-solana/rating`, also re-exported from the root): client side of the ratings and judge attestations the V1 program source ties to a job paid through escrow (#841). Builders for `open_rating`, `accept_rating`, `commit_rating`, `reveal_rating`, `expire_rating`, `close_rating`, `attest_quality`, `confirm_attestation`, `dispute_attestation` and `close_attestation`; `ratingPda`, `attestationPda`, `agentPda`, `solEscrowPda`; `decodeRatingAccount` and `decodeAttestationAccount`; `ratingCommitment`; the escrow flag bits (`escrowFlags`, `escrowAccountFlags`, `isRatedEscrow`); `withRatingAccount`, which adds the rating account to an exit of a rated escrow and returns the exit of any other escrow untouched; SOL escrow lock and exit builders; `buildRatedTokenEscrowLock` / `buildRatedSolEscrowLock` (lock and opt in, one transaction); `readRatingAccount` and `payerReleaseOpensRating` for a buyer deciding when to release; `readEscrowRatingStatus` and `buildSellerAcceptRating` for sellers. Every builder and decoder is tested byte for byte against `programs/pinocchio-escrow/interface/vectors.json`. `RATING_PROGRAM_ERRORS` and `ratingProgramErrorName` name the program's rating and attestation error codes (6010 to 6019, 6033 to 6051), held to `error.rs` by a test. The seller agrees to be rated by `accept_rating` or by being the authority of a claim or settle; a seller's claim transaction must not carry the payer's signature. It signs and sends nothing, and no deployed program answers these instructions yet.
25
+ - `provider` module (`@redditech/x402-solana/provider`, also re-exported from the root): the seller side of a per-token call (#826). `providerMeteredTerms`, `meteredOffer` (estimate, a suggested maximum of twice the estimate, the fee if the estimate holds, the minimum lock), `readMeteredPaymentHeader`, `meteredPaymentHeaderValue`, `checkProviderCluster` (the mainnet genesis hash cannot be replaced), `verifyMeteredLock`, `usageFrom`, `meteredSettlement` and `meteredDecline`. Moved from `packages/openrouter-specialists`, which now imports it; instruction encodings are unchanged. It reads no key and sends no transaction. New subpath exports: `./provider`, `./metered`, `./token-escrow`, `./escrow-readiness`.
26
+ - Read-only SPL `TransferChecked` observation verifier for parsed deterministic transaction fixtures. It checks successful transaction metadata, confirmation metadata, transaction-signature match, exact mint/program/payee owner/destination/amount, optional memo binding, exactly one match, and replay protection without RPC, wallets, signers, secrets, or live submission.
27
+ - AUDD bridge in `SolanaReceiptVerifier` that uses the stricter x402 v2 SVM `exact` verifier only when an AUDD mint is explicitly configured (never inferred from the receipt), while retaining legacy SOL/USDC compatibility.
28
+ - `token-escrow` and `escrow-http` modules, re-exported from the package root (no new subpath exports): classic SPL token-escrow instruction builders/decoder and the RAP-specific `rap-spl-escrow-v1` HTTP 402 → finalized lock → paid retry → `locked` receipt flow (`EscrowSeller`, `buyWithEscrow`, `verifyEscrowLock`). Mint, classic token program and decimals are explicit parameters. A runnable loopback-only seller/buyer example lives in `examples/` (not shipped in the tarball); see `examples/README.md`. No public npm publication, devnet signing, or settlement claim is established.
29
+ - `DatabaseReplayStore`: a durable replay store that calls an atomic database function (default `replay_check_and_store`, taking `p_key` and returning a boolean) through a caller-supplied `rpc`, so a key is accepted once across restarts and instances (#723). The package gains no database dependency. A database error or an unexpected answer throws and the payment is not accepted. The database function itself is proposed separately and is not applied anywhere by this package.
30
+ - `solAmountToLamports`, `SOLANA_GENESIS_HASHES` and `DEFAULT_MAX_TRANSACTION_AGE_SECONDS` exports.
31
+
32
+ ### Changed
33
+
34
+ - `SolanaReceiptVerifier` checks direct token payments on net credit. The matching `transferChecked` is still required, and now the destination token account's balance after the transaction minus its balance before must cover the provider's share (and the treasury account's must cover the fee); the account must belong to the payee (or treasury) before and after; and no instruction of the same transaction, inner instructions included, may name it as a source or act on it (burn, close, approve, set authority and so on). Transactions without readable before and after balances are refused.
35
+ - Replay keys: the receipt nonce must be 1 to 128 characters of letters, digits and `. _ : ~ -`, and is stored as `x402:nonce:<network>:<payTo>:<nonce>` (demo receipts as `x402:demo-nonce:<nonce>`), never as bare caller text. A real payment's transaction key and nonce key are stored together through the new optional `NonceReplayStore.checkAndStoreAll` (`checkAndStoreReplayKeys` falls back to one by one for stores without it). `MemoryNonceReplayStore`, the default store and `DatabaseReplayStore` implement it; the database store calls `replay_check_and_store_all` (`batchFunctionName`), added in `supabase/migrations/20261122000001_replay_check_and_store_all.sql`.
36
+ - Settles are bound to what the provider signed. `SettlementRecord` can carry the transaction's top-level `instructions`; `confirmMeteredSettlement` takes `expected.instruction` (`recordedInstruction(ix)`) and then accepts only a transaction that calls the escrow program exactly once, with that instruction's accounts and data (`transactionHasOnlyInstruction`). `verifyMeteredLock` with `purpose: 'session-settle'` sends the unused part to the payer's associated token account when the account that funded the lock is gone, and creates that account at the provider's cost only with `createRefundAccount: true`, so the provider can bound what it pays for. Sessions keep the lock's funding account and claim window, and `lockMatchesSession` (payer, maximum, creation slot, refund and claim windows, funding account) is required for each later call and for the settle, so a lock made again at the same address is never charged for an earlier session. `SessionState.pendingSettle` and `MeteredSessionLedger.markSettling` record a settle before it is sent; `finish` clears it.
37
+ - Session and single metered-call signatures name the network: `SessionDelegation.genesisHash` (sent as `network` in `x402-session-delegation` and shown as a `network:` line in the text the wallet signs) and `genesisHash` in each request signature, now `reddi-session/2`. `verifySessionRequest`, `verifyPaidCallRequest`, `sessionSignatureHeaderValue` and `paidCallAuthHeaders` require it, and a delegation or signature for another network, or one without a network, is refused. A session call that asks to close is signed under the new action `call-close` (`sessionCallAction(close)`), so the close cannot be added or removed in transit.
38
+ - `SolanaReceiptVerifier` requires a payer proof by default (`payerProof: 'required'`). `verifyReceipt` takes the check as a fourth argument; without one, or without `payer` in the receipt, it refuses with `payer_proof_required`. With the proof required, the payer must sign the transaction and be the source of the SOL transfer or the stated authority of the token transfer (a multisig authority does not count), and legacy AUDD receipts through `auddMint` are refused. The proof is checked before the transaction signature is recorded, so a stranger presenting someone else's payment uses nothing up. `payerProof: 'not-required'` is for a verifier that serves nothing, such as a job ledger. New failure reasons `payer_proof_required`, `payer_proof_invalid`, `payer_proof_expired`.
39
+ - Ratings name the job by the rating account's `opened_slot`, as the program now requires, because jobs can share an escrow address over time. `ratingCommitment(rating, openedSlot, signer, score, salt)` hashes it after the rating address; `buildAcceptRatingInstruction` and `buildAttestQualityInstruction` take a required `openedSlot: bigint` and append it as a u64 little-endian. `buildSellerAcceptRating` is now async: it reads the escrow and the rating account, returns the instruction with what the seller agrees to (opened slot, consumer, judge, amount, mint), and throws `SellerAcceptRatingError` when the job is not locked and rated, not payable to the seller, already paid or accepted, or differs from the seller's `expected` values; `sellerAcceptRatingFromAccounts` does the same for account data already read. `RATING_PROGRAM_ERRORS` adds 6050 `RatingJustOpened` (no exit of a rated escrow in the slot its rating was opened in) and 6051 `RatingJobMismatch`.
40
+ - Every exit of a rated escrow, `commit_rating`, `confirm_attestation` and `dispute_attestation` name the job too, as the program now requires. `withRatingAccount(exit, rated, openedSlot)` appends the slot (u64 little-endian) after the exit's data and throws when `rated` is true and no slot is given; the SOL exit builders and `buildTokenEscrowExitInstruction` take `openedSlot`, required when `rated` is true. `buildCommitRatingInstruction`, `buildConfirmAttestationInstruction` and `buildDisputeAttestationInstruction` take a required `openedSlot: bigint`. `decodeAttestationAccount` reads the 127-byte attestation (`ATTESTATION_ACCOUNT_LEN`, was 119) and exposes `openedSlot`. `verifyMeteredLock` reads the rating account of a rated lock and returns its `openedSlot`, which `meteredSettlement` and `meteredDecline` name; a rated lock whose rating account is missing or not this job's is refused (`invalid_receipt`). `verifyEscrowLock` likewise puts the slot on a rated receipt (`openedSlot`, a decimal string) and `buildEscrowSellerExit` names it. Unrated exits are unchanged.
41
+ - `decodeTokenEscrowAccount` reads `metered` as bit `0x01` of the flag byte and exposes `rated` (bit `0x02`). It used to compare the byte with 1, which read a rated metered escrow (3) as not metered.
42
+ - `verifyEscrowLock` and `EscrowSeller` (fixed-price seller) read the rated bit and refuse a rated escrow before serving (`rated escrow declined`) unless `acceptRatedEscrows` is set; an accepted one yields a receipt with `rated: true`, and `buildEscrowSellerExit` builds the seller's claim or decline with the rating account. Without it the program refuses every exit of a rated escrow (6033), so a seller that served one could not claim or decline it. Receipts and exits of an escrow that is not rated are unchanged.
43
+ - `verifyMeteredLock` refuses an escrow the buyer opted in to rating (`rated_escrow_declined`) before serving, unless the new `acceptRatedEscrows` option is true. A verified lock carries `rated`; for a rated lock `meteredSettlement` and `meteredDecline` pass the rating account, and `confirmMeteredSettlement` takes an optional `rating` the transaction must name. Nothing changes for an escrow that is not rated.
44
+ - Payout hardening for the seller side (#847). `verifyMeteredLock` now also reads the accounts a settle would pay into (`checkMeteredPayout`): the provider's token account or its recovery account (`MeteredTerms.payoutAccount`), the treasury's, and the source account the lock recorded for the unused part. Each must exist under the mint's token program, be initialised, not frozen, hold the mint, have the right owner and not require a memo; otherwise the lock is refused (`refund_account_unusable`, `provider_not_ready`) before it is recorded, so it stays usable. A verified lock carries `payout`, and `meteredSettlement` pays into it: one instruction, nothing created. For a Token-2022 mint with a transfer fee extension the mint is passed writable (`harvestWithheldFees`).
45
+ - `prepareTokenPayout` creates nothing by default. `createTreasuryAccount` and `createRefundAccount` are explicit options, and `refundTo` names another account of the payer. Callers that relied on the two idempotent creates must opt in.
46
+ - `checkTreasuryReadiness` decodes the whole token account and requires it initialised, not frozen and not memo-requiring (`checkTokenAccount`, also exported).
47
+ - `confirmMeteredSettlement` reads what a confirmed settle moved from a `SettlementRecord` (programs called, accounts named, token balances before and after): the provider's credit and the fee as the amount billed, the buyer's unused part, and any surplus returned on top. It refuses a failed or unrelated transaction and amounts that do not add up.
48
+
49
+ - `SolanaReceiptVerifier` limits transaction age and checks the network (#738). For a `solana-mainnet-beta` challenge it refuses a transaction whose block time is missing, more than 900 seconds old (`maxTransactionAgeSeconds` can change the limit, not remove it) or in the future, and it requires the connection to report the public mainnet genesis hash through `getGenesisHash`. On other networks both checks run only when `maxTransactionAgeSeconds` or `expectedGenesisHash` is set, so local validators and existing devnet callers behave as before. No mainnet payment has been verified with this code; these are checks, not a mainnet readiness claim.
50
+ - SOL amounts are converted to lamports with exact decimal arithmetic. Floating point multiplication could land one lamport high (0.00051 SOL became 510001 lamports) and reject an exact payment. A SOL amount with more than nine decimal places is now refused.
51
+ - `SolanaReceiptVerifier` binds a verified receipt to its transaction (#738). A real receipt now requires a replay store; the transaction signature is recorded after the payment is verified, so one transaction satisfies one challenge even when the presenter chooses a fresh nonce. USDC verification requires a configured `usdcMint` and never falls back to a receipt-supplied mint, and accepts only `transferChecked` (a plain `transfer` names no mint and reports raw base units). Callers that verified real SOL/USDC receipts without a replay store or without `usdcMint` are now refused with `unsupported_receipt`. The supplied in-memory store still does not survive a restart; a durable store is tracked in #723.
52
+ - `SplTransferCheckedObservation.blockTime` is optional: a confirmed transaction whose node reports no block time for the slot is still observable, and only a present-but-invalid `blockTime` is rejected. `slot` remains mandatory.
53
+ - An AUDD challenge verified without a configured `auddMint` now fails as `unsupported_receipt` (operator misconfiguration) rather than `invalid_receipt`, and AUDD observer failures surface their specific reason in the failure message.
54
+ - `SolanaReceiptVerifier` marks AUDD observations it derives from `getParsedTransaction` output as `evidence.source: 'parsed-rpc-transaction'` instead of leaving the fixture default.
55
+ - The SPL observer's replay key includes the normalized network and matched instruction index, so two distinct transfers settled in one transaction each get their own replay slot while a genuine replay of the same transfer is still rejected. `SolanaReceiptVerifier` now applies that signature/instruction replay guard to AUDD receipts before accepting them.
56
+ - SPL `TransferChecked` observation now requires the expected payment signature to be the transaction's first/canonical signature, not merely any secondary signer signature.
57
+
58
+ ## 0.1.0 — 2026-07-06
59
+
60
+ First release-candidate cut of the HTTP 402 payment primitives for Solana-oriented RAP (Reddi Agent Protocol) workflows. This package is a repo-local v0.1 OSS candidate: it is not yet published on npm and must not be treated as production payment, custody, escrow-finality, or mainnet infrastructure.
61
+
62
+ ### Added
63
+
64
+ Module areas (one subpath export per module, plus the root export — see `exports` in `package.json`):
65
+
66
+ - **`./types`** — x402 request/challenge/receipt type definitions.
67
+ - **`./payment`** — x402 header parsing and validation (`parseX402Header`, `createX402Header`, challenge building, payment-address format validation).
68
+ - **`./nonce`** — nonce-based replay protection (`checkAndStoreNonce`).
69
+ - **`./middleware`** — Express middleware (`createX402Middleware`) that parses the `x402-request` header, checks nonces, verifies demo or explicitly approved receipts per configured policy, and sets the `x402-payment` response header.
70
+ - **`./budget-policy`** — pure local buyer budget preflight (`evaluateBudgetPolicy`): per-request, per-session, per-source, per-specialist, per-asset/network, and call-count limits, evaluated before any signer, hosted facilitator, or downstream call is used.
71
+ - **`./client`** — fail-closed devnet USDC helpers. Any real devnet payment path is explicit (gated behind a literal approval phrase), capped, allowlisted, and outside the default OSS smoke.
72
+ - **`./jupiter`** — swap-client interface abstraction (mock-friendly; tests do not require Solana devnet access).
73
+
74
+ The legacy `sendPayment` demo helper remains for local tests only — it is not a production payment path.
75
+
76
+ ### Quickstart
77
+
78
+ The package is repo-local until the OSS release smoke and package-publication gates are complete:
79
+
80
+ ```bash
81
+ npm --prefix packages/x402-solana test -- --runInBand
82
+ npm --prefix packages/x402-solana run build
83
+
84
+ # Full local release gate (from packages/x402-solana)
85
+ npm run release:dry-run
86
+ ```
87
+
88
+ ### Boundaries
89
+
90
+ **No spend, no custody, no live settlement.** Clean-checkout OSS success must not require wallet material, RPC calls, Pay.sh activation, hosted Reddi infrastructure, paid providers, marketplace publication, trust/reputation mutation, mainnet, custody, or settlement-finality claims. These boundaries match the README and are enforced mechanically by the claim-boundary scan in `npm run check:oss-release-smoke`.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Redditech Pty Ltd
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,302 @@
1
- # Temporary Holding Version
1
+ # @redditech/x402-solana
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ x402 payments on Solana for Reddi Agent Protocol: per-token pricing, metered escrow, payment checks and receipts, for both the buyer and the provider side.
4
+
5
+ > Payments prove transfer; RAP Assurance proves paid work.
6
+
7
+ This package is currently a repo-local v0.1 OSS candidate. It is not yet published on npm, and it should not be treated as production payment, custody, escrow-finality, settlement-finality, or mainnet infrastructure.
8
+
9
+ ## Overview
10
+
11
+ **x402** is an HTTP status code indicating that payment is required. This package implements local parsing, policy, middleware, demo receipt, and gated devnet-helper primitives for Solana/x402 workflows. RAP consumers should treat verified payment proof as transfer evidence, then bind it to work evidence through RAP receipts.
12
+
13
+ ### Core Features
14
+
15
+ - **Nonce-based replay protection** — prevents duplicate payment attempts
16
+ - **x402 standard compliance** — parses/validates x402-request headers
17
+ - **Local buyer budget preflight** — evaluates spend/call limits before payment authorization
18
+ - **Modular design** — nonce store, payment logic, and middleware are separately testable
19
+ - **Mock-friendly** — tests don't require Solana devnet access
20
+ - **Fail-closed devnet helpers** — any real devnet payment path is explicit, capped, allowlisted, and outside default OSS smoke
21
+ - **Read-only SPL observation** — verifies parsed `TransferChecked` transaction fixtures without RPC, wallets, signers, secrets, or live submission
22
+
23
+ ## Installation
24
+
25
+ The package is repo-local until the OSS release smoke and package-publication gates are complete:
26
+
27
+ ```bash
28
+ npm --prefix packages/x402-solana test -- --runInBand
29
+ npm --prefix packages/x402-solana run build
30
+ ```
31
+
32
+ ## Provider side: metered calls
33
+
34
+ `@redditech/x402-solana/provider` is the seller side of a per-token call. A buyer locks the most it will pay in a metered token escrow; the provider checks the lock on chain, serves the call, and settles the actual cost.
35
+
36
+ ```typescript
37
+ import { providerMeteredTerms, meteredOffer, readMeteredPaymentHeader, checkProviderCluster, verifyMeteredLock, usageFrom, meteredSettlement } from '@redditech/x402-solana/provider';
38
+
39
+ const terms = providerMeteredTerms({ currency: 'USDC', inputPerMillion: '0.15', outputPerMillion: '0.60', programId, mint, payee: wallet });
40
+
41
+ // No payment yet: tell the buyer the price, the estimate and the maximum to lock (twice the estimate by default).
42
+ const offer = meteredOffer(terms, messages, body.max_tokens, 'solana-devnet');
43
+
44
+ // Payment presented: confirm the cluster once, then check the lock.
45
+ await checkProviderCluster(() => connection.getGenesisHash(), 'solana-devnet');
46
+ const lock = await verifyMeteredLock({ header, terms, minimum, readAccount, readSlot, replayStore });
47
+
48
+ // After the model answers: build the settle for the tokens used. You sign and send it.
49
+ const { settlement, instructions } = meteredSettlement(terms, lock, usageFrom(upstreamAnswer, inputEstimate));
50
+ ```
51
+
52
+ `verifyMeteredLock` also checks that the payout can land (the provider's, the treasury's and the buyer's token accounts), and `confirmMeteredSettlement` reads what a confirmed settle moved, for the receipt. It reads no key and sends no transaction. `packages/provider-kit` wraps it in a runnable server. Token currencies only (USDC, AUDD, PYUSD, USDG).
53
+
54
+ ## Ratings and attestations
55
+
56
+ `@redditech/x402-solana/rating` builds the rating and judge attestation instructions of the V1 program source (`programs/pinocchio-escrow`), derives their addresses and decodes their accounts. The program README and `interface/vectors.json` are the interface; this module is tested against that file byte for byte. No deployed program answers these instructions yet.
57
+
58
+ ```ts
59
+ import { buildRatedTokenEscrowLock, buildSellerAcceptRating, readEscrowRatingStatus, readRatingAccount, withRatingAccount, ratingCommitment } from '@redditech/x402-solana/rating';
60
+ import { buildSettleTokenEscrowInstruction, decodeTokenEscrowAccount } from '@redditech/x402-solana/token-escrow';
61
+
62
+ // Buyer: lock and opt in to rating in one transaction (opting in later is refused).
63
+ const { instructions, escrow, rating } = buildRatedTokenEscrowLock(terms, { judge });
64
+
65
+ // Seller: before serving, read at `confirmed` whether the job is rated.
66
+ const status = await readEscrowRatingStatus(connection, escrow, programId);
67
+
68
+ // Read the escrow's lock slot when serving it, and keep it with the job. A rated job's
69
+ // rating opens in that slot, so its opened slot is the same number.
70
+ const { createdSlot } = decodeTokenEscrowAccount((await connection.getAccountInfo(escrow, 'confirmed'))!.data);
71
+
72
+ // Every exit names its escrow by the lock slot; an exit of a rated escrow also carries the rating account.
73
+ const settle = withRatingAccount(buildSettleTokenEscrowInstruction(terms, false, payee, { actual }), status.ok && status.rated, createdSlot);
74
+
75
+ // Seller of a fixed-price job the payer will release: read the job and agree to it. Throws
76
+ // SellerAcceptRatingError when the escrow or the rating is not what the seller expects.
77
+ const accept = await buildSellerAcceptRating(connection, { programId, escrow, seller, expected: { judge, amount } });
78
+
79
+ // Each party commits, then reveals the same score and salt. Keep both until the reveal.
80
+ // `openedSlot` comes from the rating account (`readRatingAccount(...).openedSlot`).
81
+ const commitment = ratingCommitment(rating, openedSlot, signer, score, salt);
82
+ ```
83
+
84
+ Jobs can share an address: once an escrow has ended, the same payer can lock another job for the same payee under the same nonce. The escrow's lock slot tells them apart, so every exit, rated or not, names it: `withRatingAccount(exit, rated, createdSlot)`, the SOL exit builders and `buildTokenEscrowExitInstruction` append it (u64 little-endian) after the exit's data and throw without it, and the program refuses an exit naming another slot (`EscrowInstanceMismatch`, 6053) or landing in the lock slot (`EscrowJustLocked`, 6052). `buildSettleTokenEscrowInstruction` alone builds a bare exit the program refuses. A rating opens in its escrow's lock slot, so its `openedSlot` is the same number: `ratingCommitment`, `buildAcceptRatingInstruction`, `buildCommitRatingInstruction`, `buildAttestQualityInstruction`, `buildConfirmAttestationInstruction` and `buildDisputeAttestationInstruction` take it as a required bigint, and the program refuses a missing or other one (`RatingJobMismatch`, 6051). A decision on an attestation names the slot the attestation stores (`decodeAttestationAccount(...).openedSlot`; the account is 127 bytes). Read the slot when the job is agreed or verified and keep it: an exit built from a slot re-read later would name whichever job holds the address by then. No exit of a rated escrow is accepted in the slot its rating was opened in (`RatingJustOpened`, 6050): lock and opt in go in one transaction, any exit in a later one.
85
+
86
+ Consent: the seller agrees to be rated by `accept_rating`, or by being the authority of a claim or settle, and must then commit and reveal within the program's windows. Seller claim transactions must not carry the payer's signature: if the payer signs one, even only as fee payer, the program treats the payer as the authority, so it is a release by the payer and not the seller's agreement. Both seller paths here decline a rated escrow before serving unless `acceptRatedEscrows` is set: `verifyMeteredLock` (metered) and `verifyEscrowLock` / `EscrowSeller` (fixed price). When set, they read the rating account with the lock (a verified lock's `openedSlot`, a receipt's `openedSlot` as a decimal string), and their exits carry the rating account and that slot (`meteredSettlement`, `meteredDecline`, `buildEscrowSellerExit`).
87
+
88
+ Buyers of a fixed-price rated job: a release by the payer opens the rating only after the seller has called `accept_rating`. Before that, a release pays the seller as usual and closes the job unrated; the payee co-signing the release changes nothing. A rated exit that pays the seller nothing also closes the rating unrated. `RATING_PROGRAM_ERRORS` / `ratingProgramErrorName(code)` name the program's rating, attestation and escrow-instance errors (6010 to 6019, 6033 to 6053). Read the rating account (`readRatingAccount`) and release when `payerReleaseOpensRating(rating)` is true, or leave the seller to claim.
89
+
90
+ ## Usage
91
+
92
+ ### Express Middleware
93
+
94
+ ```typescript
95
+ import express from 'express';
96
+ import { createX402Middleware } from '@redditech/x402-solana';
97
+
98
+ const app = express();
99
+
100
+ // Add x402 middleware
101
+ app.use(createX402Middleware());
102
+
103
+ app.get('/api/data', (req, res) => {
104
+ res.json({ data: 'sensitive information' });
105
+ });
106
+
107
+ app.listen(3000);
108
+ ```
109
+
110
+ ### Creating x402 Requests
111
+
112
+ ```typescript
113
+ import { createX402Header } from '@redditech/x402-solana';
114
+
115
+ // Create header for payment request
116
+ const header = createX402Header(
117
+ 1000, // lamports
118
+ 'BaDZtpgWpDx6H1y8Dga2cfyxs3RXj5y2fkBo7HoT2pdv', // payment address
119
+ 'uuid-v4-nonce-here' // unique nonce
120
+ );
121
+
122
+ // Send request with header
123
+ const response = await fetch('/api/data', {
124
+ headers: { 'x402-request': header }
125
+ });
126
+ ```
127
+
128
+ ## API
129
+
130
+ ### `createX402Middleware()`
131
+
132
+ Returns an Express middleware that:
133
+ 1. Checks for `x402-request` header
134
+ 2. Parses and validates payment details
135
+ 3. Checks nonce for replay attacks
136
+ 4. Verifies demo or explicitly approved payment receipts according to configured policy
137
+ 5. Sets `x402-payment` response header with receipt metadata when verification succeeds
138
+
139
+ **Errors:**
140
+ - `400` — Invalid request (bad JSON, missing fields)
141
+ - `409` — Duplicate nonce (replay attempt)
142
+ - `503` — RPC timeout
143
+
144
+ ### `parseX402Header(header: string): X402Request`
145
+
146
+ Parses and validates an x402-request header.
147
+
148
+ ```typescript
149
+ const request = parseX402Header('{"amount":1000,"currency":"SOL",...}');
150
+ // { amount: 1000, currency: 'SOL', paymentAddress: '...', nonce: '...' }
151
+ ```
152
+
153
+ ### `checkAndStoreNonce(nonce: string): boolean`
154
+
155
+ Checks if nonce is new (true) or duplicate (false), and stores it.
156
+
157
+ ```typescript
158
+ if (checkAndStoreNonce(nonce)) {
159
+ // First time seeing this nonce
160
+ } else {
161
+ // Duplicate detected
162
+ }
163
+ ```
164
+
165
+ ### `verifySplTransferCheckedObservation({ parsedTransaction, expected, commitment })`
166
+
167
+ Read-only verifier for SVM SPL Token / Token-2022 `TransferChecked` observations. It consumes an already parsed transaction object and checks transaction success, confirmation metadata, transaction-signature match, exact mint, exact token program, destination token-account ownership by `payTo`, exact base-unit amount, optional authority, optional decimals, exactly one matching transfer, replay store, and required memo binding. It does not fetch RPC, submit transactions, load wallets, sign, or hold funds.
168
+
169
+ `SolanaReceiptVerifier` also requires, by default, proof that the request presenting a direct receipt comes from the wallet that paid, because a confirmed transfer is public and anyone could otherwise present it first. A provider passes the check for each request; the buyer adds the headers after its transfer confirms:
170
+
171
+ ```ts
172
+ // Provider: `rawBody` is the request body exactly as received.
173
+ const result = await verifier.verifyReceipt(receipt, challenge, replayStore, directPaymentProofCheck({ headers, body: rawBody }));
174
+
175
+ // Buyer: sign with the paying wallet, or with a session key it delegated once
176
+ // (directPaymentDelegationHeaderValue) and pass that as `delegation`.
177
+ const proof = await directPaymentProofHeaders({ network, txSignature, payTo, body, sign: (m) => wallet.signMessage(m) });
178
+ ```
179
+
180
+ A verifier that serves nothing, such as a job ledger recording calls after they are served, sets `payerProof: 'not-required'`.
181
+
182
+ Session and single metered-call signatures (`session-auth`) name the network by its genesis hash, in the delegation (`genesisHash`, sent as `network`) and in each request's signature (`reddi-session/2`), so a signature made for devnet is refused on mainnet and the other way round; providers pass the genesis hash of the cluster they checked they are on (`SOLANA_GENESIS_HASHES[network]`). A session call that asks to close the session is signed as `call-close` (`sessionCallAction(close)`). Signatures in the earlier `reddi-session/1` form, without a network, are refused.
183
+
184
+ Delegations (session and direct payment) may run for up to seven days, but a buyer client should use `delegationExpiresAt()`, a day, and keep the session key in memory only, never in localStorage or on disk: whoever holds the key can sign for the payer until the delegation expires.
185
+
186
+ Hardware wallets such as Ledger sign Solana off-chain messages with a header prefix, which these checks do not accept yet. A payer that uses one cannot sign the delegation or the request; pay from a software wallet for now.
187
+
188
+ `SolanaReceiptVerifier` requires a replay store for real receipts and records the transaction signature, so one transaction satisfies one challenge; USDC needs a configured `usdcMint` and a `transferChecked` instruction. A token payment counts for what stays with the payee: the payee's (and the treasury's) token account must gain at least its share between the balances before and after the transaction, belong to them before and after, and not be debited or have its authority changed by any instruction of the same transaction, inner instructions included. A Token-2022 mint that charges a transfer fee delivers less than the amount sent, so its payments fail this check; the accepted mints are expected to keep the fee at zero. The receipt nonce is 1 to 128 characters of letters, digits and `. _ : ~ -`, and is recorded under `x402:nonce:<network>:<payTo>:`, so it cannot collide with another payment's transaction or escrow key. It bridges AUDD receipts to this stricter x402 v2 SVM `exact` verifier only when the verifier is configured with an explicit `auddMint`; it will not trust a receipt-supplied mint as the AUDD identity. AUDD amounts are base units, not UI decimal strings.
189
+
190
+ For a `solana-mainnet-beta` challenge the verifier also refuses a transaction older than 900 seconds (`maxTransactionAgeSeconds`) or without a block time, and requires the connection to report the public mainnet genesis hash. On other networks those two checks run only when `maxTransactionAgeSeconds` or `expectedGenesisHash` is set.
191
+
192
+ `MemoryNonceReplayStore` forgets everything on restart. `DatabaseReplayStore` keeps replay keys in a database through an atomic function you provide:
193
+
194
+ ```ts
195
+ // server side only; `client` is a database client with a service credential
196
+ const replayStore = new DatabaseReplayStore({ rpc: (fn, args) => client.rpc(fn, args) });
197
+ ```
198
+
199
+ It throws when the database is unreachable, so a payment is never accepted without being recorded. A real payment is recorded under two keys at once through `replay_check_and_store_all` (`p_keys`, a text array; all or none), so the database needs both functions from `supabase/migrations/`. A custom store can do the same by implementing `checkAndStoreAll`.
200
+
201
+ ### `sendPayment(request: X402Request): Promise<PaymentReceipt>`
202
+
203
+ Legacy demo helper for local tests. Do not use it as a production payment path.
204
+
205
+ ```typescript
206
+ const receipt = await sendPayment(request);
207
+ // { txSignature: '...', slot: 12345, lamports: 1000, nonce: '...' }
208
+ ```
209
+
210
+ ### `evaluateBudgetPolicy({ policy, quote, usage }): BudgetPolicyDecision`
211
+
212
+ Runs a pure local buyer preflight check before any signer, hosted facilitator, or downstream x402/OpenRouter call is used. Amounts are represented in the payment asset's smallest unit.
213
+
214
+ ```typescript
215
+ import { assetNetworkKey, evaluateBudgetPolicy } from '@redditech/x402-solana';
216
+
217
+ const decision = evaluateBudgetPolicy({
218
+ policy: {
219
+ schemaVersion: 'reddi.budget-policy.v1',
220
+ limits: {
221
+ perRequest: { maxAmount: '100000' },
222
+ perSession: { maxAmount: '500000' },
223
+ perSource: { 'source:planning': { maxAmount: '250000' } },
224
+ perSpecialist: { 'specialist:coder': { maxAmount: '300000' } },
225
+ perAssetNetwork: [
226
+ { asset: 'USDC', network: 'solana-devnet', maxAmount: '400000' },
227
+ ],
228
+ callCount: { maxCalls: 5 },
229
+ },
230
+ },
231
+ quote: {
232
+ amount: '50000',
233
+ asset: 'USDC',
234
+ network: 'solana-devnet',
235
+ source: 'source:planning',
236
+ specialist: 'specialist:coder',
237
+ },
238
+ usage: {
239
+ sessionSpent: '100000',
240
+ sourceSpent: { 'source:planning': '25000' },
241
+ specialistSpent: { 'specialist:coder': '50000' },
242
+ assetNetworkSpent: { [assetNetworkKey('USDC', 'solana-devnet')]: '100000' },
243
+ callCount: 2,
244
+ },
245
+ });
246
+
247
+ if (!decision.allowed) {
248
+ throw new Error(`budget_preflight_denied:${decision.reasonCodes.join(',')}`);
249
+ }
250
+ ```
251
+
252
+ Buyer-client integration for #342: parse the x402 quote/challenge, call `evaluateBudgetPolicy` with the operator's local policy and current local usage ledger, persist the returned audit notes with the receipt attempt, and only then continue to payment preparation. Hosted/live delegation paths should stay fail-closed until they combine this local decision with explicit operator approval.
253
+
254
+ ## Testing
255
+
256
+ ```bash
257
+ npm test
258
+ ```
259
+
260
+ Runs Jest test suite covering:
261
+ - Header parsing and validation
262
+ - Nonce replay protection
263
+ - Amount validation
264
+ - Payment address format validation
265
+ - Error handling
266
+
267
+ ## Architecture
268
+
269
+ ```
270
+ x402-request (client)
271
+ ↓
272
+ middleware.ts (intercept)
273
+ ↓
274
+ payment.ts (parse + validate)
275
+ ↓
276
+ nonce.ts (replay check)
277
+ ↓
278
+ payment verifier or explicitly approved devnet helper
279
+ ↓
280
+ x402-payment (response receipt)
281
+ ```
282
+
283
+ ## Phases
284
+
285
+ - **Phase 0**: Historical devnet/escrow research exists, but is not a current release claim
286
+ - **Phase 1**: x402 primitives (header parsing, nonce, validation, demo receipts, local budget preflight)
287
+ - **Phase 2**: Gated devnet USDC helpers behind explicit approval records and spend caps
288
+ - **Phase 2a**: Non-live AUDD/SPL `TransferChecked` observation from deterministic parsed fixtures; no RPC or signer path is added
289
+ - **Phase 3**: Framework adapters only after #519 decides retention/deprecation scope
290
+ - **Phase 4**: Future private/Quasar settlement work only behind separate program-boundary approval
291
+
292
+ ## Boundaries
293
+
294
+ Clean-checkout OSS success must not require wallet material, RPC calls, Pay.sh activation, hosted Reddi, paid providers, marketplace publication, trust/reputation mutation, mainnet, custody, or settlement-finality claims.
295
+
296
+ ## License
297
+
298
+ MIT
299
+
300
+ ## Classic SPL escrow challenge flow
301
+
302
+ The repo-local `token-escrow` and `escrow-http` modules, re-exported from the package root, add a RAP-specific HTTP 402 → finalized SPL lock → paid retry → seller verification → locked receipt flow. See [the runnable synthetic puzzle seller/buyer](examples/README.md). Mint address, classic token program and decimals are explicit configuration; the disposable validator harness uses a labelled local test mint, not AUDD. The locked receipt is distinct from settlement and from service correctness. These additions do not establish public npm publication or authorize devnet signing.
@@ -0,0 +1,68 @@
1
+ export type BudgetPolicyAmount = bigint | number | string;
2
+ export type BudgetPolicyReasonCode = 'allowed' | 'budget_policy_missing' | 'invalid_quote' | 'malformed_limit' | 'request_amount_exceeds_limit' | 'session_budget_exceeded' | 'source_budget_exceeded' | 'specialist_budget_exceeded' | 'asset_network_budget_exceeded' | 'call_count_exceeded' | 'unsupported_asset_network';
3
+ export type BudgetPolicyAssetNetwork = {
4
+ asset: string;
5
+ network: string;
6
+ };
7
+ export type BudgetAmountLimit = {
8
+ /** Maximum spend in the asset's smallest unit. */
9
+ maxAmount: BudgetPolicyAmount;
10
+ note?: string;
11
+ };
12
+ export type BudgetAssetNetworkLimit = BudgetPolicyAssetNetwork & BudgetAmountLimit;
13
+ export type BudgetCallCountLimit = {
14
+ maxCalls: number;
15
+ note?: string;
16
+ };
17
+ export type BudgetPolicy = {
18
+ schemaVersion: 'reddi.budget-policy.v1';
19
+ limits: {
20
+ perRequest?: BudgetAmountLimit;
21
+ perSession?: BudgetAmountLimit;
22
+ perSource?: Record<string, BudgetAmountLimit>;
23
+ perSpecialist?: Record<string, BudgetAmountLimit>;
24
+ perAssetNetwork?: BudgetAssetNetworkLimit[];
25
+ callCount?: BudgetCallCountLimit;
26
+ };
27
+ };
28
+ export type BudgetPolicyUsage = {
29
+ sessionSpent?: BudgetPolicyAmount;
30
+ sourceSpent?: Record<string, BudgetPolicyAmount>;
31
+ specialistSpent?: Record<string, BudgetPolicyAmount>;
32
+ assetNetworkSpent?: Record<string, BudgetPolicyAmount>;
33
+ callCount?: number;
34
+ };
35
+ export type BudgetPolicyQuote = BudgetPolicyAssetNetwork & {
36
+ /** Quoted spend in the asset's smallest unit. */
37
+ amount: BudgetPolicyAmount;
38
+ source?: string;
39
+ specialist?: string;
40
+ };
41
+ export type BudgetRemaining = {
42
+ perRequest?: string;
43
+ perSession?: string;
44
+ perSource?: string;
45
+ perSpecialist?: string;
46
+ perAssetNetwork?: string;
47
+ callCount?: number;
48
+ };
49
+ export type BudgetPolicyDecision = {
50
+ schemaVersion: 'reddi.budget-policy-decision.v1';
51
+ allowed: boolean;
52
+ reasonCodes: BudgetPolicyReasonCode[];
53
+ quotedAmount: {
54
+ amount: string;
55
+ asset: string;
56
+ network: string;
57
+ source?: string;
58
+ specialist?: string;
59
+ } | null;
60
+ remainingBudget: BudgetRemaining;
61
+ auditNotes: string[];
62
+ };
63
+ export declare function evaluateBudgetPolicy(input: {
64
+ policy?: BudgetPolicy | null;
65
+ quote: BudgetPolicyQuote;
66
+ usage?: BudgetPolicyUsage;
67
+ }): BudgetPolicyDecision;
68
+ export declare function assetNetworkKey(asset: string, network: string): string;