@piprail/sdk 1.8.0 → 1.10.0

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 (30) hide show
  1. package/CHAINS.md +5 -3
  2. package/CHANGELOG.md +59 -0
  3. package/ERRORS.md +21 -8
  4. package/README.md +23 -0
  5. package/STANDARDS.md +5 -2
  6. package/dist/{algorand-IJJKE35X.cjs → algorand-MXUSKX46.cjs} +17 -17
  7. package/dist/{algorand-B67G4335.js → algorand-WGVF4KTU.js} +1 -1
  8. package/dist/{aptos-YQWTGFRZ.js → aptos-LPBLSEIQ.js} +1 -1
  9. package/dist/{aptos-X3G2UBYW.cjs → aptos-YT7SXWPF.cjs} +16 -16
  10. package/dist/{chunk-IQGT65WS.cjs → chunk-MDLZJGLY.cjs} +20 -16
  11. package/dist/{chunk-QDS6FBZP.js → chunk-SVMGHASK.js} +4 -0
  12. package/dist/index.cjs +823 -253
  13. package/dist/index.d.cts +458 -35
  14. package/dist/index.d.ts +458 -35
  15. package/dist/index.js +746 -176
  16. package/dist/{near-GGUHLXAF.cjs → near-7ZDNISUX.cjs} +19 -19
  17. package/dist/{near-7MBBCDUE.js → near-K6BDBABG.js} +1 -1
  18. package/dist/{solana-W24TCJV4.cjs → solana-PU7N2M64.cjs} +14 -14
  19. package/dist/{solana-7WJVZGDW.js → solana-S3UFI3FE.js} +1 -1
  20. package/dist/{stellar-HV6VGZX3.js → stellar-Q5PO23SC.js} +1 -1
  21. package/dist/{stellar-YMY3K2YB.cjs → stellar-VDQOFQEO.cjs} +21 -21
  22. package/dist/{sui-32KVESR5.cjs → sui-FKSMLKRF.cjs} +17 -17
  23. package/dist/{sui-2WFWVFJX.js → sui-WOXRKJXS.js} +1 -1
  24. package/dist/{ton-FIQGV2LC.cjs → ton-VK6KRJHP.cjs} +14 -14
  25. package/dist/{ton-DGZB7W4U.js → ton-WPTXGLVK.js} +1 -1
  26. package/dist/{tron-RLIL2FDI.js → tron-6GXBXTR4.js} +1 -1
  27. package/dist/{tron-ZSXAPZ2C.cjs → tron-WLOF5OUV.cjs} +24 -24
  28. package/dist/{xrpl-2PKP7HOI.cjs → xrpl-CMNI25BV.cjs} +21 -21
  29. package/dist/{xrpl-UEC2GYVV.js → xrpl-HEAPEXAM.js} +1 -1
  30. package/package.json +2 -2
package/dist/index.d.cts CHANGED
@@ -2,7 +2,7 @@ import * as viem_zksync from 'viem/zksync';
2
2
  import * as abitype from 'abitype';
3
3
  import * as viem_chains from 'viem/chains';
4
4
  import * as viem from 'viem';
5
- import { Chain, Account, Hex } from 'viem';
5
+ import { Chain, Account, Hex, PublicClient } from 'viem';
6
6
 
7
7
  /**
8
8
  * The on-the-wire payment protocol. Self-contained — it runs entirely
@@ -40,6 +40,8 @@ type AddressId = string;
40
40
  interface X402ResourceObject {
41
41
  url: string;
42
42
  description?: string;
43
+ /** The resource's response content-type, e.g. 'application/json' (v2 ResourceInfo, optional). */
44
+ mimeType?: string;
43
45
  }
44
46
  interface X402AcceptEntry {
45
47
  scheme: 'onchain-proof';
@@ -63,11 +65,55 @@ interface X402AcceptEntry {
63
65
  symbol?: string;
64
66
  };
65
67
  }
68
+ /**
69
+ * A standard x402 `exact` rail (EVM / EIP-3009) — the interop rail a PipRail gate
70
+ * advertises ALONGSIDE its `onchain-proof` rail (dual-advertise) so any standard
71
+ * x402 client can pay it. Same v2 PaymentRequirements skeleton as
72
+ * {@link X402AcceptEntry}; only `scheme` and `extra` differ. The `extra` carries
73
+ * the EIP-712 domain a payer signs over — `name`/`version` are READ from the token
74
+ * contract by the gate (never assumed), since e.g. USDC's domain name is "USD Coin",
75
+ * not the "USDC" symbol.
76
+ */
77
+ interface X402ExactAcceptEntry {
78
+ scheme: 'exact';
79
+ network: Caip2;
80
+ amount: string;
81
+ asset: AssetId;
82
+ payTo: AddressId;
83
+ maxTimeoutSeconds: number;
84
+ extra: {
85
+ /** The exact-EVM transfer method. PipRail self-settles EIP-3009 today. */
86
+ assetTransferMethod: 'eip3009';
87
+ /** EIP-712 domain name of the token (USDC: "USD Coin"; EURC: "EURC"). Read on-chain. */
88
+ name: string;
89
+ /** EIP-712 domain version of the token (USDC/EURC: "2"). Read on-chain. */
90
+ version: string;
91
+ /** Confirmations the gate waits for before granting access — mirrors the gate's
92
+ * `minConfirmations`, so the exact rail honours the same reorg safety as onchain-proof.
93
+ * A PipRail convenience (standard clients ignore unknown keys). */
94
+ minConfirmations?: number;
95
+ /** Token decimals — a PipRail convenience (standard clients ignore unknown keys). */
96
+ decimals?: number;
97
+ /** Human-readable amount, e.g. "0.05" — a PipRail convenience. */
98
+ amountFormatted?: string;
99
+ symbol?: string;
100
+ };
101
+ }
102
+ /** A challenge `accepts[]` entry — either PipRail's `onchain-proof` rail or a standard `exact` rail. */
103
+ type X402AnyAccept = X402AcceptEntry | X402ExactAcceptEntry;
66
104
  interface X402Challenge {
67
105
  x402Version: 2;
68
- error: string | null;
106
+ /**
107
+ * Optional human-readable reason (v2 `error?: string`). PipRail EMITS it only on a
108
+ * rejected-proof re-challenge (omitted on a fresh challenge). Typed to also tolerate
109
+ * `null` when PARSING a foreign challenge — some deployed servers send `error: null`.
110
+ */
111
+ error?: string | null;
69
112
  resource: X402ResourceObject;
70
- accepts: X402AcceptEntry[];
113
+ accepts: X402AnyAccept[];
114
+ /** v2 optional extensions. PipRail stamps the machine-readable rejection reason here on a
115
+ * rejected-proof re-challenge: `{ piprail: { code, detail } }`. Omitted otherwise. */
116
+ extensions?: Record<string, unknown>;
71
117
  }
72
118
  interface X402PaymentSignature {
73
119
  x402Version: 2;
@@ -86,8 +132,43 @@ interface X402PaymentSignature {
86
132
  txHash: string;
87
133
  };
88
134
  }
135
+ /**
136
+ * The EIP-3009 authorization a payer signs for a standard `exact` rail. All
137
+ * numeric fields are DECIMAL strings on the wire (value, validAfter, validBefore);
138
+ * `nonce` is a 0x-prefixed 32-byte hex. Identical shape across x402 v1 and v2.
139
+ */
140
+ interface ExactAuthorizationWire {
141
+ from: string;
142
+ to: string;
143
+ value: string;
144
+ validAfter: string;
145
+ validBefore: string;
146
+ nonce: string;
147
+ }
148
+ /** The `payload` a client sends for an `exact` rail: an EIP-3009 signature + its authorization. */
149
+ interface ExactPaymentPayload {
150
+ signature: string;
151
+ authorization: ExactAuthorizationWire;
152
+ }
153
+ /**
154
+ * What {@link parseExactPaymentHeader} extracts from an inbound `exact` payment,
155
+ * normalised across the v1 (`X-PAYMENT`, flat `{scheme,network,payload}`, network
156
+ * slug) and v2 (`PAYMENT-SIGNATURE`, `{accepted,payload}`, CAIP-2 network) wire
157
+ * shapes. `network`/`asset` are the CLIENT's claim — used only to MATCH an offered
158
+ * rail; the gate re-derives every verified field from its own trusted rail.
159
+ */
160
+ interface ParsedExactPayment {
161
+ x402Version: number;
162
+ /** The client's claimed network (slug or CAIP-2) — for matching, not trust. */
163
+ network: string;
164
+ /** The client's claimed asset, if present (v2 `accepted.asset`). */
165
+ asset?: string;
166
+ payload: ExactPaymentPayload;
167
+ /** The full decoded PaymentPayload, for verbatim forwarding to a facilitator (Mode B). */
168
+ raw: Record<string, unknown>;
169
+ }
89
170
  interface X402Receipt {
90
- scheme: 'onchain-proof';
171
+ scheme: 'onchain-proof' | 'exact';
91
172
  /**
92
173
  * x402 v2 SettlementResponse: settlement succeeded. Always `true` here — a
93
174
  * failed verification returns a 402, never a receipt.
@@ -122,7 +203,7 @@ interface X402Receipt {
122
203
  * `maxPaymentRetries` (a short backoff absorbs RPC lag); it does not branch on
123
204
  * the code.
124
205
  */
125
- type VerifyErrorCode = 'tx_not_found' | 'insufficient_confirmations' | 'tx_reverted' | 'no_meta' | 'wrong_recipient' | 'amount_too_low' | 'transfer_not_found' | 'payment_expired' | 'tx_already_used';
206
+ type VerifyErrorCode = 'tx_not_found' | 'insufficient_confirmations' | 'tx_reverted' | 'no_meta' | 'wrong_recipient' | 'amount_too_low' | 'transfer_not_found' | 'payment_expired' | 'tx_already_used' | 'signature_invalid';
126
207
  /** The shape every driver's `verify()` returns. Shared by drivers + protocol. */
127
208
  type VerifyResult = {
128
209
  ok: true;
@@ -132,6 +213,14 @@ type VerifyResult = {
132
213
  error: VerifyErrorCode;
133
214
  detail: string;
134
215
  };
216
+ declare const HEADER_REQUIRED = "payment-required";
217
+ declare const HEADER_SIGNATURE = "payment-signature";
218
+ declare const HEADER_RESPONSE = "payment-response";
219
+ /** Legacy x402 v1 header names. PipRail EMITS v2 (the constants above) but also
220
+ * READS the v1 client header and ECHOES the v1 response header, so a deprecated
221
+ * v1 client (still ~half the installed base) interoperates on the `exact` rail. */
222
+ declare const HEADER_SIGNATURE_V1 = "x-payment";
223
+ declare const HEADER_RESPONSE_V1 = "x-payment-response";
135
224
  declare function buildChallengeHeader(challenge: X402Challenge): string;
136
225
  declare function buildReceiptHeader(receipt: X402Receipt): string;
137
226
  declare function buildSignatureHeader(signature: X402PaymentSignature): string;
@@ -144,6 +233,15 @@ declare function parseChallenge(response: Response): Promise<X402Challenge | nul
144
233
  declare function parseReceipt(response: Response): X402Receipt | null;
145
234
  /** Parse a PAYMENT-SIGNATURE header value (server side). */
146
235
  declare function parseSignatureHeader(value: string): X402PaymentSignature | null;
236
+ /**
237
+ * Parse an inbound `exact` payment from a base64 header value (`PAYMENT-SIGNATURE`
238
+ * v2 or `X-PAYMENT` v1). Tolerant of BOTH wire shapes — the inner
239
+ * `{ signature, authorization }` payload is identical across versions, so we read
240
+ * `scheme`/`network` from either the v2 `accepted` object or the v1 flat fields.
241
+ * Returns null when the value isn't a recognisable `exact` payment (e.g. it's an
242
+ * `onchain-proof` proof, or malformed).
243
+ */
244
+ declare function parseExactPaymentHeader(value: string): ParsedExactPayment | null;
147
245
  /**
148
246
  * Pick the first accepts[] entry on the `onchain-proof` scheme whose network
149
247
  * satisfies `matches` (any chain family). Returns null if none match.
@@ -838,7 +936,7 @@ declare const CHAINS: {
838
936
  gasPrice: bigint;
839
937
  maxFeePerBlobGas?: undefined | undefined;
840
938
  maxFeePerGas?: undefined | undefined;
841
- maxPriorityFeePerGas? /** Native coin metadata. Defaults to 18-decimal ETH. */: undefined | undefined;
939
+ maxPriorityFeePerGas?: undefined | undefined;
842
940
  isSystemTx?: undefined | undefined;
843
941
  mint?: undefined | undefined;
844
942
  sourceHash?: undefined | undefined;
@@ -3340,9 +3438,7 @@ declare const CHAINS: {
3340
3438
  value: bigint;
3341
3439
  yParity: number;
3342
3440
  accessList: viem.AccessList;
3343
- authorizationList
3344
- /** JSON-RPC endpoint. */
3345
- ? /** JSON-RPC endpoint. */: undefined | undefined;
3441
+ authorizationList?: undefined | undefined;
3346
3442
  blobVersionedHashes?: undefined | undefined;
3347
3443
  chainId: number;
3348
3444
  type: "eip2930";
@@ -3732,6 +3828,62 @@ declare const CHAINS: {
3732
3828
  };
3733
3829
  };
3734
3830
  };
3831
+ kaia: {
3832
+ chain: {
3833
+ blockExplorers: {
3834
+ readonly default: {
3835
+ readonly name: "KaiaScan";
3836
+ readonly url: "https://kaiascan.io";
3837
+ readonly apiUrl: "https://api-cypress.klaytnscope.com/api";
3838
+ };
3839
+ };
3840
+ blockTime?: number | undefined | undefined;
3841
+ contracts: {
3842
+ readonly multicall3: {
3843
+ readonly address: "0xcA11bde05977b3631167028862bE2a173976CA11";
3844
+ readonly blockCreated: 96002415;
3845
+ };
3846
+ };
3847
+ ensTlds?: readonly string[] | undefined;
3848
+ id: 8217;
3849
+ name: "Kaia";
3850
+ nativeCurrency: {
3851
+ readonly decimals: 18;
3852
+ readonly name: "Kaia";
3853
+ readonly symbol: "KAIA";
3854
+ };
3855
+ experimental_preconfirmationTime?: number | undefined | undefined;
3856
+ rpcUrls: {
3857
+ readonly default: {
3858
+ readonly http: readonly ["https://public-en.node.kaia.io"];
3859
+ };
3860
+ };
3861
+ sourceId?: number | undefined | undefined;
3862
+ testnet?: boolean | undefined | undefined;
3863
+ custom?: Record<string, unknown> | undefined;
3864
+ extendSchema?: Record<string, unknown> | undefined;
3865
+ fees?: viem.ChainFees<undefined> | undefined;
3866
+ formatters?: undefined;
3867
+ prepareTransactionRequest?: ((args: viem.PrepareTransactionRequestParameters, options: {
3868
+ client: viem.Client;
3869
+ phase: "beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters";
3870
+ }) => Promise<viem.PrepareTransactionRequestParameters>) | [fn: ((args: viem.PrepareTransactionRequestParameters, options: {
3871
+ client: viem.Client;
3872
+ phase: "beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters";
3873
+ }) => Promise<viem.PrepareTransactionRequestParameters>) | undefined, options: {
3874
+ runAt: readonly ("beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters")[];
3875
+ }] | undefined;
3876
+ serializers?: viem.ChainSerializers<undefined, viem.TransactionSerializable> | undefined;
3877
+ verifyHash?: ((client: viem.Client, parameters: viem.VerifyHashActionParameters) => Promise<viem.VerifyHashActionReturnType>) | undefined;
3878
+ };
3879
+ tokens: {
3880
+ USDT: {
3881
+ address: "0xd077A400968890Eacc75cdc901F0356c943e4fDb";
3882
+ decimals: number;
3883
+ symbol: string;
3884
+ };
3885
+ };
3886
+ };
3735
3887
  };
3736
3888
  /** A built-in EVM chain name. */
3737
3889
  type ChainName = keyof typeof CHAINS;
@@ -4014,6 +4166,38 @@ interface ResolvedNetwork {
4014
4166
  discoverySigner?(wallet: WalletHandle): DiscoverySigner | null;
4015
4167
  /** Verify `ref` satisfies `accept`, RPC-only, in-process. */
4016
4168
  verify(ref: string, accept: X402AcceptEntry): Promise<VerifyResult>;
4169
+ /**
4170
+ * OPTIONAL (EVM-only today) — the on-chain EIP-712 domain `{ name, version }` of an
4171
+ * EIP-3009 token `asset`, read from the contract (`name()`/`version()`). Returns
4172
+ * `null` when the asset is NOT an EIP-3009 token (no `transferWithAuthorization` —
4173
+ * e.g. USDT, native coin, or a plain ERC-20), so the gate can refuse to advertise a
4174
+ * standard `exact` rail for it. Never derived from the symbol (USDC's domain name is
4175
+ * "USD Coin", not "USDC"; EURC's is "EURC"). Called once at exact-rail resolution
4176
+ * (cached by the gate). RPC-read; may throw on a transient read (the gate surfaces a
4177
+ * clear config error). The first of two optional server methods for the `exact` rail.
4178
+ */
4179
+ exactDomain?(asset: string): Promise<{
4180
+ name: string;
4181
+ version: string;
4182
+ } | null>;
4183
+ /**
4184
+ * OPTIONAL (EVM-only today) — verify a standard x402 `exact` (EIP-3009) payment
4185
+ * locally, then SELF-SETTLE it by broadcasting `transferWithAuthorization` from the
4186
+ * merchant's own `relayer` wallet (the merchant pays gas to receive; the signature
4187
+ * binds `to`, so no redirect risk). RETURNS a `VerifyResult`:
4188
+ * - `{ ok:false, error }` for a CLIENT-fixable fault (bad signature, expired,
4189
+ * wrong recipient/amount, used nonce, simulation revert) → gate replies 402;
4190
+ * - `{ ok:true, receipt }` once the settle tx is mined.
4191
+ * THROWS {@link SettlementError} when a VALID + simulated payment fails to BROADCAST
4192
+ * (relayer out of gas / RPC down) → gate replies 5xx (the payer's authorization is
4193
+ * still good and its nonce unused). Re-derives every checked field from the trusted
4194
+ * `accept`, never the client echo.
4195
+ */
4196
+ settleExactSelf?(input: {
4197
+ relayer: WalletHandle;
4198
+ payload: ExactPaymentPayload;
4199
+ accept: X402ExactAcceptEntry;
4200
+ }): Promise<VerifyResult>;
4017
4201
  }
4018
4202
  interface ResolveOptions {
4019
4203
  /** The developer-supplied `chain` selector. */
@@ -4606,7 +4790,10 @@ declare class PipRailClient {
4606
4790
  * `quote()` (read-only) and `fetch()` (which then authorises + pays).
4607
4791
  */
4608
4792
  private resolveChallenge;
4609
- /** The candidate accepts this client could pay: our scheme, on the bound network. */
4793
+ /** The candidate accepts this client could pay: our scheme, on the bound network.
4794
+ * A dual-advertised challenge may also carry standard `exact` rails — the PipRail
4795
+ * client ignores those (it pays the backendless `onchain-proof` rail); the type
4796
+ * predicate narrows the `X402AnyAccept` union to the rails we settle. */
4610
4797
  private gatherCandidates;
4611
4798
  /** Build the full {@link PaymentPlan} from an already-parsed challenge + bound
4612
4799
  * net/wallet. Shared by `planPayment` (read-only) and `fetch`'s autoRoute. */
@@ -4714,7 +4901,8 @@ declare function paymentTools(client: PipRailClient): AgentTool[];
4714
4901
  * consumed by every emitter below.
4715
4902
  */
4716
4903
  interface PaymentRail {
4717
- scheme: 'onchain-proof';
4904
+ /** `onchain-proof` (PipRail's default) or the standard `exact` rail (dual-advertise). */
4905
+ scheme: 'onchain-proof' | 'exact';
4718
4906
  network: Caip2;
4719
4907
  asset: AssetId;
4720
4908
  payTo: AddressId;
@@ -4877,6 +5065,30 @@ interface AcceptOption {
4877
5065
  /** RPC override for this chain (defaults to the top-level `rpcUrl`). */
4878
5066
  rpcUrl?: string;
4879
5067
  }
5068
+ /**
5069
+ * Opt into ALSO advertising a standard x402 `exact` rail (EIP-3009) beside the
5070
+ * default `onchain-proof` rail, so ANY standard x402 client can pay this gate
5071
+ * (dual-advertise). EVM + EIP-3009 tokens only (USDC, EURC — NOT USDT, NOT native).
5072
+ * Omitting `exact` leaves the gate byte-identical to today (onchain-proof only).
5073
+ *
5074
+ * Two settlement modes, both backendless (PipRail hosts nothing):
5075
+ * - `settle: 'self'` — your own `relayer` key broadcasts `transferWithAuthorization`.
5076
+ * You pay gas to RECEIVE (the inverse of onchain-proof, where the payer pays gas)
5077
+ * and must keep the relayer funded. The signature binds `to`, so there's no
5078
+ * redirect risk. This is the on-brand default for the rail.
5079
+ * - `settle: { facilitator }` — delegate verify+settle to a third-party x402
5080
+ * facilitator YOU choose (Coinbase CDP, x402.org, …). No relayer key needed; the
5081
+ * facilitator pays gas. Also the only path onto Coinbase's Bazaar directory.
5082
+ */
5083
+ interface ExactRailOption {
5084
+ settle: 'self' | {
5085
+ facilitator: string;
5086
+ authHeaders?: () => Promise<Record<string, string>>;
5087
+ };
5088
+ /** Required for `settle: 'self'` — the gas-paying relayer wallet: EVM `{ privateKey }`
5089
+ * or a bring-your-own `{ walletClient }`. (Distinct from `payTo`, the receive address.) */
5090
+ relayer?: unknown;
5091
+ }
4880
5092
  interface RequirePaymentOptions {
4881
5093
  /**
4882
5094
  * Single-chain form: which chain to accept payment on. EVM ('bnb'|'base'|…),
@@ -4925,6 +5137,12 @@ interface RequirePaymentOptions {
4925
5137
  markUsed?: (ref: string) => void | Promise<void>;
4926
5138
  /** Fired when a payment verifies successfully. */
4927
5139
  onPaid?: (receipt: X402Receipt) => void;
5140
+ /**
5141
+ * ALSO advertise a standard x402 `exact` rail (EIP-3009) so any standard x402
5142
+ * client can pay this gate — opt-in, EVM/EIP-3009 only. See {@link ExactRailOption}.
5143
+ * Omit to keep the gate exactly as today (`onchain-proof` only).
5144
+ */
5145
+ exact?: ExactRailOption;
4928
5146
  }
4929
5147
  type VerifyPaymentResult = {
4930
5148
  kind: 'paid';
@@ -4936,12 +5154,21 @@ type VerifyPaymentResult = {
4936
5154
  requiredHeader: string;
4937
5155
  statusCode: 402;
4938
5156
  } | {
5157
+ /**
5158
+ * A submitted proof was rejected. Conformant: this carries a FRESH
5159
+ * re-`challenge` (full v2 PaymentRequired with `accepts[]` + the reason in
5160
+ * `error` + the machine code in `extensions.piprail`) so a standard x402
5161
+ * client can immediately retry. Adapters emit `challenge` + the
5162
+ * `PAYMENT-REQUIRED` header — NOT the legacy {@link toInvalidBody}.
5163
+ */
4939
5164
  kind: 'invalid';
4940
5165
  error: string;
4941
5166
  detail: string;
5167
+ challenge: X402Challenge;
5168
+ requiredHeader: string;
4942
5169
  statusCode: 402;
4943
5170
  };
4944
- /** The canonical x402 v2 JSON body for a rejected proof (a 402 'invalid'). */
5171
+ /** A minimal 402 'invalid' JSON body. @deprecated see {@link toInvalidBody}. */
4945
5172
  interface X402InvalidBody {
4946
5173
  x402Version: 2;
4947
5174
  status: 'invalid';
@@ -4949,9 +5176,14 @@ interface X402InvalidBody {
4949
5176
  detail: string;
4950
5177
  }
4951
5178
  /**
4952
- * Build the canonical 402 'invalid' body. Use this in EVERY framework adapter
4953
- * (Express, Hono, Fastify, Workers, …) so a rejected proof returns the IDENTICAL
4954
- * envelope everywhere `verify()` produces the reason, this shapes the body.
5179
+ * @deprecated LEGACY minimal rejection body. The gate now returns a fully
5180
+ * **conformant** rejection: `gate.verify()`'s `kind:'invalid'` result carries a full
5181
+ * v2 PaymentRequired re-`challenge` (with `accepts[]` so a standard x402 client can
5182
+ * retry, the reason in `error`, and the machine code in `extensions.piprail`). The
5183
+ * built-in `requirePayment` adapter emits `result.challenge` + the `PAYMENT-REQUIRED`
5184
+ * header. PREFER that. This helper (a bare `{ status:'invalid', error, detail }` with
5185
+ * NO `accepts[]`) remains only for back-compat with hand-rolled adapters; a standard
5186
+ * client that receives it can't retry. Migrate to `result.challenge`.
4955
5187
  */
4956
5188
  declare function toInvalidBody(result: {
4957
5189
  error: string;
@@ -5004,6 +5236,68 @@ type ExpressLikeMiddleware = (req: ExpressLikeRequest, res: ExpressLikeResponse,
5004
5236
  */
5005
5237
  declare function requirePayment(options: RequirePaymentOptions): ExpressLikeMiddleware;
5006
5238
 
5239
+ /**
5240
+ * Mode-B settlement: delegate a standard `exact` payment to a THIRD-PARTY x402
5241
+ * facilitator the MERCHANT chooses (Coinbase CDP, x402.org, or any). PipRail hosts
5242
+ * nothing — this is two HTTP POSTs to the merchant's configured facilitator URL.
5243
+ *
5244
+ * PROTOCOL LAYER — pure `fetch`, ZERO chain libraries (STANDARDS §1). The other
5245
+ * settlement mode (self-settle with the merchant's own relayer key) lives in the
5246
+ * EVM driver; this one is chain-agnostic because the facilitator does the chain work.
5247
+ *
5248
+ * The wire contract (x402 v2, verified against coinbase/x402 core):
5249
+ * POST {url}/verify body { x402Version, paymentPayload, paymentRequirements } → { isValid, invalidReason?, payer? }
5250
+ * POST {url}/settle SAME body → { success, transaction, network, payer?, errorReason? }
5251
+ * Both protocol outcomes are HTTP 200 (the boolean flips); a non-200 is a
5252
+ * transport/auth failure. There is no registration and no idempotency key — so a
5253
+ * SELF-settling merchant must guard replay itself (the gate's used-proof set does).
5254
+ */
5255
+
5256
+ /** Standard x402 `exact` PaymentRequirements, built from the gate's TRUSTED rail. */
5257
+ interface FacilitatorPaymentRequirements {
5258
+ scheme: 'exact';
5259
+ network: string;
5260
+ asset: string;
5261
+ amount: string;
5262
+ payTo: string;
5263
+ maxTimeoutSeconds: number;
5264
+ extra: {
5265
+ name: string;
5266
+ version: string;
5267
+ };
5268
+ }
5269
+ /** A merchant-chosen facilitator: its base URL + optional per-request auth headers. */
5270
+ interface FacilitatorConfig {
5271
+ /** Base URL, e.g. 'https://x402.org/facilitator' (trailing slash stripped). */
5272
+ url: string;
5273
+ /** Optional async auth-header provider (e.g. CDP JWT). Omit for the free, no-auth facilitators. */
5274
+ authHeaders?: () => Promise<Record<string, string>>;
5275
+ }
5276
+ interface SettleViaFacilitatorInput extends FacilitatorConfig {
5277
+ x402Version: number;
5278
+ /** The decoded PaymentPayload the client sent — forwarded verbatim. */
5279
+ paymentPayload: Record<string, unknown>;
5280
+ /** PaymentRequirements built from the gate's trusted rail (never the client echo). */
5281
+ paymentRequirements: FacilitatorPaymentRequirements;
5282
+ /** The receipt's network (CAIP-2) + asset/amount/payTo, for building the X402Receipt on success. */
5283
+ receipt: {
5284
+ network: Caip2;
5285
+ asset: AssetId;
5286
+ payTo: AddressId;
5287
+ amount: string;
5288
+ };
5289
+ /** authorization.from, for the receipt's `payer`. */
5290
+ payerHint?: string;
5291
+ }
5292
+ /**
5293
+ * Verify-then-settle a standard `exact` payment through a third-party facilitator.
5294
+ * Returns a {@link VerifyResult}: `{ ok:false, error }` for a client-fixable
5295
+ * facilitator rejection (verify isValid:false, or settle success:false) → 402;
5296
+ * `{ ok:true, receipt }` on a settled payment. THROWS {@link SettlementError} on a
5297
+ * transport/auth failure (non-200) — the gate replies 5xx, never a misleading 402.
5298
+ */
5299
+ declare function settleViaFacilitator(input: SettleViaFacilitatorInput): Promise<VerifyResult>;
5300
+
5007
5301
  /**
5008
5302
  * The driver registry — the ONLY place the families meet. Routing decides a
5009
5303
  * family from the `chain` value (synchronously), then asks that family's
@@ -5148,6 +5442,22 @@ declare class PaymentDeclinedError extends PipRailError {
5148
5442
  declare class ConfirmationTimeoutError extends PipRailError {
5149
5443
  readonly code = "CONFIRMATION_TIMEOUT";
5150
5444
  }
5445
+ /**
5446
+ * A standard `exact` payment was VALID (signature recovered, params checked,
5447
+ * simulation passed) but SETTLEMENT failed for a SERVER-side reason — the
5448
+ * merchant's own relayer couldn't broadcast `transferWithAuthorization` (out of
5449
+ * gas, RPC down, dropped tx), or a Mode-B facilitator returned a transport/auth
5450
+ * error. This is NOT the payer's fault: their signed EIP-3009 authorization is
5451
+ * still valid and its nonce UNUSED, so it can be re-presented once the merchant
5452
+ * fixes their relayer/facilitator. The gate THROWS this (it's an operational
5453
+ * problem to fix, not a proof to reject), so a framework adapter returns 5xx —
5454
+ * never a 402, which would wrongly tell the payer to re-pay. `.cause` carries the
5455
+ * raw chain/HTTP error. (Server-side; the `onchain-proof` rail can't raise it —
5456
+ * there the payer broadcasts, so there's nothing for the merchant to settle.)
5457
+ */
5458
+ declare class SettlementError extends PipRailError {
5459
+ readonly code = "SETTLEMENT_FAILED";
5460
+ }
5151
5461
  /** Server returned 402 but the PAYMENT-REQUIRED envelope was missing or malformed. */
5152
5462
  declare class InvalidEnvelopeError extends PipRailError {
5153
5463
  readonly code = "INVALID_ENVELOPE";
@@ -5202,28 +5512,29 @@ declare class UnsupportedNetworkError extends PipRailError {
5202
5512
  }
5203
5513
 
5204
5514
  /**
5205
- * ── EVM SECTION: x402 `exact` scheme (interop building block) ──────────────
5515
+ * ── EVM SECTION: x402 `exact` scheme (EIP-3009) BUYER + SELLER ───────────
5206
5516
  *
5207
- * EXPERIMENTAL / ADVANCED. PipRail's own gates use the `onchain-proof` scheme
5208
- * (client pays first, proves with a tx ref, server verifies locally no
5209
- * facilitator). This module is the opposite end: the building blocks to PAY a
5210
- * server that speaks the mainstream x402 `exact` scheme (Coinbase-style), where
5211
- * the client signs an EIP-3009 `transferWithAuthorization` and a third-party
5212
- * facilitator broadcasts it. It lets a PipRail agent buy from `exact` servers
5213
- * too — making PipRail a *universal* x402 client — while our servers stay
5214
- * backendless.
5517
+ * PipRail's own gates default to the `onchain-proof` scheme (client pays first,
5518
+ * proves with a tx ref, server verifies locally). This module is the standard
5519
+ * x402 `exact` interop, in BOTH directions, EVM + EIP-3009 only, on the existing
5520
+ * `viem` peer (no new dep):
5215
5521
  *
5216
- * What's here is the deterministic, unit-testable core: parse an `exact`
5217
- * requirement, build + EIP-712-sign the authorization, and encode the
5218
- * `X-PAYMENT` header. It is intentionally NOT wired into `PipRailClient.fetch`'s
5219
- * default flow: `exact` is a cross-vendor wire protocol whose live acceptance
5220
- * can only be confirmed against a real facilitator, and bolting a second
5221
- * payment protocol into the core would cut against PipRail's keep-it-simple
5222
- * design. Use these helpers to hand-roll an `exact` payment, and validate
5223
- * against your target facilitator before production. See
5224
- * `.claude/plans/agent-readiness/04-universal-exact.md`.
5522
+ * BUYER side (client) parse an `exact` requirement, build + EIP-712-sign the
5523
+ * EIP-3009 authorization, encode the `X-PAYMENT` header. Deterministic,
5524
+ * unit-testable; NOT wired into `PipRailClient.fetch`'s default (see
5525
+ * `.claude/plans/agent-readiness/04-universal-exact.md`).
5225
5526
  *
5226
- * EVM + EIP-3009 only (USDC and kin). Uses the existing `viem` peer no new dep.
5527
+ * SELLER side (gate) {@link readExactDomain} (read the token's true EIP-712
5528
+ * domain so the gate can advertise + verify it) and {@link verifyAndSettleExactEvm}
5529
+ * (verify an inbound EIP-3009 authorization locally, then SELF-SETTLE it by
5530
+ * broadcasting `transferWithAuthorization` from the merchant's own relayer key —
5531
+ * no third-party facilitator). This is what lets a PipRail gate get PAID by ANY
5532
+ * standard x402 client. See `.claude/plans/compliance/`.
5533
+ *
5534
+ * Self-settle uses `transferWithAuthorization` (NOT `receiveWithAuthorization`,
5535
+ * which requires `msg.sender == payTo` and so can't be broadcast by a separate
5536
+ * relayer key). The signature binds `to`=payTo, so a front-runner can only push
5537
+ * the same funds to the same payTo and waste their own gas — no redirect risk.
5227
5538
  */
5228
5539
 
5229
5540
  /** x402 network slug → EVM chain id, for the chains PipRail ships with EIP-3009
@@ -5316,5 +5627,117 @@ declare function encodeXPaymentHeader(input: {
5316
5627
  /** x402 envelope version (Coinbase's reference uses 1). */
5317
5628
  x402Version?: number;
5318
5629
  }): string;
5630
+ /**
5631
+ * The minimal EIP-3009 ABI the seller needs: both `transferWithAuthorization`
5632
+ * overloads (the 65-byte `(v,r,s)` form and the `(bytes signature)` ERC-1271 form),
5633
+ * the `authorizationState` replay check, and `name()`/`version()` for the EIP-712
5634
+ * domain. Mirrors Circle's deployed FiatToken.
5635
+ */
5636
+ declare const eip3009Abi: readonly [{
5637
+ readonly type: "function";
5638
+ readonly name: "transferWithAuthorization";
5639
+ readonly stateMutability: "nonpayable";
5640
+ readonly outputs: readonly [];
5641
+ readonly inputs: readonly [{
5642
+ readonly name: "from";
5643
+ readonly type: "address";
5644
+ }, {
5645
+ readonly name: "to";
5646
+ readonly type: "address";
5647
+ }, {
5648
+ readonly name: "value";
5649
+ readonly type: "uint256";
5650
+ }, {
5651
+ readonly name: "validAfter";
5652
+ readonly type: "uint256";
5653
+ }, {
5654
+ readonly name: "validBefore";
5655
+ readonly type: "uint256";
5656
+ }, {
5657
+ readonly name: "nonce";
5658
+ readonly type: "bytes32";
5659
+ }, {
5660
+ readonly name: "v";
5661
+ readonly type: "uint8";
5662
+ }, {
5663
+ readonly name: "r";
5664
+ readonly type: "bytes32";
5665
+ }, {
5666
+ readonly name: "s";
5667
+ readonly type: "bytes32";
5668
+ }];
5669
+ }, {
5670
+ readonly type: "function";
5671
+ readonly name: "transferWithAuthorization";
5672
+ readonly stateMutability: "nonpayable";
5673
+ readonly outputs: readonly [];
5674
+ readonly inputs: readonly [{
5675
+ readonly name: "from";
5676
+ readonly type: "address";
5677
+ }, {
5678
+ readonly name: "to";
5679
+ readonly type: "address";
5680
+ }, {
5681
+ readonly name: "value";
5682
+ readonly type: "uint256";
5683
+ }, {
5684
+ readonly name: "validAfter";
5685
+ readonly type: "uint256";
5686
+ }, {
5687
+ readonly name: "validBefore";
5688
+ readonly type: "uint256";
5689
+ }, {
5690
+ readonly name: "nonce";
5691
+ readonly type: "bytes32";
5692
+ }, {
5693
+ readonly name: "signature";
5694
+ readonly type: "bytes";
5695
+ }];
5696
+ }, {
5697
+ readonly type: "function";
5698
+ readonly name: "authorizationState";
5699
+ readonly stateMutability: "view";
5700
+ readonly inputs: readonly [{
5701
+ readonly name: "authorizer";
5702
+ readonly type: "address";
5703
+ }, {
5704
+ readonly name: "nonce";
5705
+ readonly type: "bytes32";
5706
+ }];
5707
+ readonly outputs: readonly [{
5708
+ readonly type: "bool";
5709
+ }];
5710
+ }, {
5711
+ readonly type: "function";
5712
+ readonly name: "name";
5713
+ readonly stateMutability: "view";
5714
+ readonly inputs: readonly [];
5715
+ readonly outputs: readonly [{
5716
+ readonly type: "string";
5717
+ }];
5718
+ }, {
5719
+ readonly type: "function";
5720
+ readonly name: "version";
5721
+ readonly stateMutability: "view";
5722
+ readonly inputs: readonly [];
5723
+ readonly outputs: readonly [{
5724
+ readonly type: "string";
5725
+ }];
5726
+ }];
5727
+ /**
5728
+ * Read an EIP-3009 token's true EIP-712 domain `{ name, version }` from the
5729
+ * contract — what a payer must sign over. Returns `null` if the asset is NOT an
5730
+ * EIP-3009 token (no `authorizationState`/`version` — e.g. USDT, native coin, a
5731
+ * plain ERC-20), so the gate refuses to advertise a standard `exact` rail for it.
5732
+ *
5733
+ * The name is NEVER assumed from the symbol: canonical USDC's domain name is
5734
+ * "USD Coin" (not "USDC"), EURC's is "EURC". `eip712Domain()` (EIP-5267) reverts
5735
+ * on these proxies, so we read `name()`+`version()` and probe `authorizationState`
5736
+ * to confirm EIP-3009 support.
5737
+ */
5738
+ declare function readExactDomain(publicClient: PublicClient, asset: string): Promise<{
5739
+ name: string;
5740
+ version: string;
5741
+ } | null>;
5319
5742
 
5320
- export { type AcceptOption, type AddressId, type AgentTool, type AlgorandToken, type AptosToken, type AssetId, type BuildExactParams, CHAINS, type Caip2, type ChainFamily, type ChainInput, type ChainName, type ChainPreset, type ChainSelector, type ConfirmInfo, ConfirmationTimeoutError, type CostEstimate, type DiscoverOptions, type DiscoveredRail, type DiscoveredResource, type DiscoverySigner, type DiscoverySource, EIP3009_TYPES, EXACT_NETWORK_SLUGS, type EvmToken, type ExactAccept, type ExactAuthorization, type ExpressLikeMiddleware, type ExpressLikeNext, type ExpressLikeRequest, type ExpressLikeResponse, GENERATOR, InsufficientFundsError, InvalidEnvelopeError, type ManifestInput, MaxRetriesExceededError, MissingDriverError, type NearToken, NoCompatibleAcceptError, NonReplayableBodyError, type OpenApiDocument, type OpenApiOperation, type PayBlocker, type PayOption, type PayWarning, PaymentDeclinedError, type PaymentDriver, type PaymentGate, type PaymentIntent, type PaymentPlan, type PaymentPolicy, type PaymentRail, PaymentTimeoutError, PipRailClient, type PipRailClientOptions, type PipRailCostQuote, PipRailError, type PipRailEvent, type PipRailQuote, type PolicyDecision, RecipientNotReadyError, type RecipientReason, type RegisterInput, type RegisterOptions, type RegisterOutcome, type RequirePaymentOptions, type ResolveOptions, type ResolvedChain, type ResolvedNetwork, type ResolvedToken, type ResourceDescription, type SearchOpenIndexesOptions, type SolanaToken, type SpendAssetTotal, type SpendRecord, type SpendSummary, type StellarToken, type SuiToken, type TokenInfo, type TokenInput, type TonToken, type ToolAnnotations, type TronToken, UnknownTokenError, UnsupportedNetworkError, type VerifyErrorCode, type VerifyPaymentResult, type VerifyResult, type WalletBalance, type WalletHandle, type WalletInput, type WellKnownX402, WrongChainError, WrongFamilyError, type X402AcceptEntry, type X402Challenge, type X402DnsRecord, type X402InvalidBody, type X402PaymentSignature, type X402Receipt, type X402ResourceObject, type XrplToken, buildChallengeHeader, buildExactAuthorization, buildOpenApi, buildReceiptHeader, buildSignatureHeader, buildWellKnownX402, buildX402DnsTxt, chainIdForExactNetwork, createPaymentGate, encodeXPaymentHeader, evaluatePolicy, normalizeNetwork, parseChallenge, parseExactRequirements, parseReceipt, parseSignatureHeader, paymentTools, pickAccept, planAcross, register402Index, registerDriver, registerX402Scan, requirePayment, resolveChain, searchOpenIndexes, toInsufficientFundsError, toInvalidBody };
5743
+ export { type AcceptOption, type AddressId, type AgentTool, type AlgorandToken, type AptosToken, type AssetId, type BuildExactParams, CHAINS, type Caip2, type ChainFamily, type ChainInput, type ChainName, type ChainPreset, type ChainSelector, type ConfirmInfo, ConfirmationTimeoutError, type CostEstimate, type DiscoverOptions, type DiscoveredRail, type DiscoveredResource, type DiscoverySigner, type DiscoverySource, EIP3009_TYPES, EXACT_NETWORK_SLUGS, type EvmToken, type ExactAccept, type ExactAuthorization, type ExactAuthorizationWire, type ExactPaymentPayload, type ExactRailOption, type ExpressLikeMiddleware, type ExpressLikeNext, type ExpressLikeRequest, type ExpressLikeResponse, type FacilitatorConfig, type FacilitatorPaymentRequirements, GENERATOR, HEADER_REQUIRED, HEADER_RESPONSE, HEADER_RESPONSE_V1, HEADER_SIGNATURE, HEADER_SIGNATURE_V1, InsufficientFundsError, InvalidEnvelopeError, type ManifestInput, MaxRetriesExceededError, MissingDriverError, type NearToken, NoCompatibleAcceptError, NonReplayableBodyError, type OpenApiDocument, type OpenApiOperation, type ParsedExactPayment, type PayBlocker, type PayOption, type PayWarning, PaymentDeclinedError, type PaymentDriver, type PaymentGate, type PaymentIntent, type PaymentPlan, type PaymentPolicy, type PaymentRail, PaymentTimeoutError, PipRailClient, type PipRailClientOptions, type PipRailCostQuote, PipRailError, type PipRailEvent, type PipRailQuote, type PolicyDecision, RecipientNotReadyError, type RecipientReason, type RegisterInput, type RegisterOptions, type RegisterOutcome, type RequirePaymentOptions, type ResolveOptions, type ResolvedChain, type ResolvedNetwork, type ResolvedToken, type ResourceDescription, type SearchOpenIndexesOptions, type SettleViaFacilitatorInput, SettlementError, type SolanaToken, type SpendAssetTotal, type SpendRecord, type SpendSummary, type StellarToken, type SuiToken, type TokenInfo, type TokenInput, type TonToken, type ToolAnnotations, type TronToken, UnknownTokenError, UnsupportedNetworkError, type VerifyErrorCode, type VerifyPaymentResult, type VerifyResult, type WalletBalance, type WalletHandle, type WalletInput, type WellKnownX402, WrongChainError, WrongFamilyError, type X402AcceptEntry, type X402AnyAccept, type X402Challenge, type X402DnsRecord, type X402ExactAcceptEntry, type X402InvalidBody, type X402PaymentSignature, type X402Receipt, type X402ResourceObject, type XrplToken, buildChallengeHeader, buildExactAuthorization, buildOpenApi, buildReceiptHeader, buildSignatureHeader, buildWellKnownX402, buildX402DnsTxt, chainIdForExactNetwork, createPaymentGate, eip3009Abi, encodeXPaymentHeader, evaluatePolicy, normalizeNetwork, parseChallenge, parseExactPaymentHeader, parseExactRequirements, parseReceipt, parseSignatureHeader, paymentTools, pickAccept, planAcross, readExactDomain, register402Index, registerDriver, registerX402Scan, requirePayment, resolveChain, searchOpenIndexes, settleViaFacilitator, toInsufficientFundsError, toInvalidBody };