@piprail/sdk 2.14.2 → 2.15.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.
package/dist/index.d.cts CHANGED
@@ -7169,6 +7169,34 @@ declare function toInvalidBody(result: {
7169
7169
  error: string;
7170
7170
  detail: string;
7171
7171
  }): X402InvalidBody;
7172
+ /**
7173
+ * The result of {@link PaymentGate.selfTest} — a read-only config check. NEVER throws, and never
7174
+ * touches the network beyond the same lazy driver/token resolution the first `challenge()` does
7175
+ * (no signing, no sending). `ok:true` with the resolved `rails` when the config is sound; `ok:false`
7176
+ * with a human `error` when something's wrong (no payTo, a malformed address for the family, an
7177
+ * unknown token, an unresolvable chain). Powers a scaffolder's "✅ your endpoint is configured"
7178
+ * step and a merchant's `npm run verify`.
7179
+ */
7180
+ interface GateSelfTest {
7181
+ ok: boolean;
7182
+ /** One entry per resolved payment option (empty when `ok:false`). */
7183
+ rails: Array<{
7184
+ /** CAIP-2 network, e.g. `eip155:8453`. */
7185
+ network: string;
7186
+ asset: string;
7187
+ symbol?: string;
7188
+ decimals: number;
7189
+ /** Human amount the gate charges (for a tip jar, the minimum/floor). */
7190
+ amount: string;
7191
+ payTo: AddressId;
7192
+ /** The schemes this rail offers, e.g. `['onchain-proof']` or `['exact', 'onchain-proof']`. */
7193
+ schemes: string[];
7194
+ }>;
7195
+ /** Non-fatal nudges (e.g. a custom token with no built-in symbol to double-check). */
7196
+ warnings: string[];
7197
+ /** Present only when `ok:false` — the human reason the config can't serve a payment. */
7198
+ error?: string;
7199
+ }
7172
7200
  interface PaymentGate {
7173
7201
  /** Build a fresh 402 challenge (new nonce) for a resource URL. */
7174
7202
  challenge(resourceUrl?: string): Promise<{
@@ -7203,6 +7231,13 @@ interface PaymentGate {
7203
7231
  * The SDK never serves it itself (headless by charter). Agents/crawlers keep the JSON 402.
7204
7232
  */
7205
7233
  landingPage(challenge: X402Challenge): string;
7234
+ /**
7235
+ * Read-only config check — resolve the gate's rails WITHOUT signing or sending, and report what
7236
+ * it would charge (or why it can't). Never throws; runs the same lazy resolution as the first
7237
+ * `challenge()`. The merchant's "did I wire this right?" and a scaffolder's post-deploy smoke
7238
+ * step. See {@link GateSelfTest}.
7239
+ */
7240
+ selfTest(): Promise<GateSelfTest>;
7206
7241
  }
7207
7242
  declare function createPaymentGate(options: RequirePaymentOptions): PaymentGate;
7208
7243
  interface ExpressLikeRequest {
@@ -7224,6 +7259,110 @@ type ExpressLikeMiddleware = (req: ExpressLikeRequest, res: ExpressLikeResponse,
7224
7259
  */
7225
7260
  declare function requirePayment(options: RequirePaymentOptions): ExpressLikeMiddleware;
7226
7261
 
7262
+ /**
7263
+ * The advanced gate options a preset forwards verbatim — every {@link RequirePaymentOptions} field
7264
+ * EXCEPT the `chain`/`token`/`amount`/`payTo` quartet (each preset re-declares those with its own
7265
+ * shape) and the multi-chain `accept` array (use {@link createPaymentGate} directly for a multi-rail
7266
+ * gate). So `onPaid`, `exact`, `receipts`, `discovery`, `isUsed`/`markUsed`, … all pass through.
7267
+ */
7268
+ type GateExtras = Omit<RequirePaymentOptions, 'chain' | 'token' | 'amount' | 'payTo' | 'accept'>;
7269
+ /** Options for {@link createPaywall}. */
7270
+ interface PaywallOptions extends GateExtras {
7271
+ /** Which chain to be paid on. EVM (`'base'`|`'bnb'`|…) or a non-EVM family name. */
7272
+ chain: ChainSelector;
7273
+ /** Token to charge in. Defaults to **USDC**. */
7274
+ token?: TokenInput;
7275
+ /** The fixed price, human-readable, e.g. `'0.05'`. */
7276
+ amount: string;
7277
+ /** Your receiving wallet address — no private key (receiving needs only the address). */
7278
+ payTo: AddressId;
7279
+ }
7280
+ /**
7281
+ * Gate one resource behind a fixed price — the API / SaaS / premium-content case. Sugar over
7282
+ * {@link createPaymentGate} with `token` defaulting to USDC; every other gate option is forwarded
7283
+ * unchanged, so the resulting gate (and its 402) is identical to the hand-written equivalent.
7284
+ */
7285
+ declare function createPaywall({ token, ...rest }: PaywallOptions): PaymentGate;
7286
+ /** Options for {@link createTipJar}. */
7287
+ interface TipJarOptions extends GateExtras {
7288
+ /** Which chain to be paid on. */
7289
+ chain: ChainSelector;
7290
+ /** Token to accept. Defaults to **USDC**. */
7291
+ token?: TokenInput;
7292
+ /**
7293
+ * The MINIMUM tip, human-readable, e.g. `'1.00'`. The gate accepts any payment **≥ min** — the
7294
+ * on-chain verify rejects only an under-payment (`amount_too_low`), so a payer can always give
7295
+ * more. There is no upper bound; the minimum is a floor, not a fixed price.
7296
+ */
7297
+ min: string;
7298
+ /** Your receiving wallet address. */
7299
+ payTo: AddressId;
7300
+ }
7301
+ /**
7302
+ * An open "pay what you want (≥ a minimum)" gate — the creator / tip / donation case. Sugar over
7303
+ * {@link createPaymentGate} that sets the challenge `amount` to `min`; because the gate accepts an
7304
+ * over-payment, the minimum is a floor. Everything else (`onPaid`, etc.) forwards unchanged.
7305
+ */
7306
+ declare function createTipJar({ token, min, ...rest }: TipJarOptions): PaymentGate;
7307
+
7308
+ /**
7309
+ * Built-in framework adapters — turn a {@link PaymentGate} into a request handler for any
7310
+ * WHATWG-`fetch` runtime. There are only TWO real shapes among fetch runtimes, so there are two
7311
+ * adapters: a plain handler **function** (Next.js, Netlify, Bun, Deno, Vercel Edge, Hono, Lambda),
7312
+ * and the `{ fetch }` **export object** (Cloudflare / Service Workers). Both run the same contract:
7313
+ * read the proof header, switch on the {@link VerifyPaymentResult} `kind`, write the right status +
7314
+ * headers back out — so a merchant's route is a single call instead of a switch.
7315
+ *
7316
+ * import { createPaywall, toFetchHandler, toWorker } from '@piprail/sdk'
7317
+ * const gate = createPaywall({ chain: 'base', amount: '0.05', payTo: '0xYourWallet' })
7318
+ *
7319
+ * export const GET = toFetchHandler(gate, () => Response.json({ secret: 42 })) // Next / Netlify / Bun / Deno / Hono …
7320
+ * export default toWorker(gate, () => Response.json({ secret: 42 })) // a Cloudflare Worker
7321
+ *
7322
+ * Pure + browser-safe — Web `Request`/`Response`/`Headers` only (no viem, no `node:`). Express keeps
7323
+ * its dedicated {@link requirePayment} middleware; a Node-native framework with its own `req`/`reply`
7324
+ * (Fastify, …) drives `gate.verify()` directly (see the framework-adapters docs). {@link proxyTo} is a
7325
+ * ready-made `serve` that forwards paid requests to an existing backend — gate any API, any language.
7326
+ */
7327
+
7328
+ /**
7329
+ * What to serve once a payment is verified — your protected resource, as a Web `Response`. It
7330
+ * receives the original `request` **plus whatever extra arguments the runtime passed the handler**
7331
+ * (a Cloudflare Worker's `env`/`ctx`, a Next.js route `context` with `params`, …), forwarded
7332
+ * untouched — so a protected handler can reach framework context without a second wrapper.
7333
+ */
7334
+ type Serve = (request: Request, ...rest: unknown[]) => Response | Promise<Response>;
7335
+ /**
7336
+ * The universal adapter: wrap a gate as a `fetch` handler `(request, ...rest) => Response`. Drop the
7337
+ * result into **any** runtime that hands a handler a `Request` and wants a `Response` back — Next.js
7338
+ * route handlers (`export const GET = …`), Netlify Functions, `Bun.serve({ fetch })`,
7339
+ * `Deno.serve(…)`, Vercel Edge, Hono (`(c) => handler(c.req.raw)`), an AWS Lambda Web adapter, Fastly
7340
+ * Compute. Any extra runtime arguments are forwarded to `serve` untouched.
7341
+ *
7342
+ * - **settled payment** → calls `serve`, returns its `Response` with the `payment-response` headers (v2 + v1) added;
7343
+ * - **missing / rejected proof** → a conformant `402` carrying the full challenge (so a standard x402 client can retry);
7344
+ * - **server-side settle failure** ({@link SettlementError}) → `502` — NEVER `402` (the buyer's authorization is still valid + unused).
7345
+ */
7346
+ declare function toFetchHandler(gate: PaymentGate, serve: Serve): (request: Request, ...rest: unknown[]) => Promise<Response>;
7347
+ /**
7348
+ * The `{ fetch }` export object for runtimes that take one — Cloudflare Workers / Service Workers:
7349
+ * `export default toWorker(gate, serve)`. Identical behaviour to {@link toFetchHandler}; the
7350
+ * runtime's `fetch(request, env, ctx)` arguments are forwarded to `serve` (so it can read bindings /
7351
+ * `ctx.waitUntil`). (Other runtimes that take an object — `Bun.serve`, `Deno.serve` — can use either
7352
+ * this or `toFetchHandler` in their `fetch` field.)
7353
+ */
7354
+ declare function toWorker(gate: PaymentGate, serve: Serve): {
7355
+ fetch: (request: Request, ...rest: unknown[]) => Promise<Response>;
7356
+ };
7357
+ /**
7358
+ * A {@link Serve} that forwards the (already-paid) request to an upstream `origin`, untouched — so you
7359
+ * can put a payment gate in FRONT of an existing API in any language, without changing it. Preserves
7360
+ * the method, path, query, body, and headers; strips the x402 proof headers so they don't leak
7361
+ * upstream. The origin NEVER sees an unpaid request — the gate rejects those before `serve` runs.
7362
+ * Compose with the adapters: `toWorker(gate, proxyTo('https://my-api.example.com'))`.
7363
+ */
7364
+ declare function proxyTo(origin: string): Serve;
7365
+
7227
7366
  /**
7228
7367
  * Mode-B settlement: delegate a standard `exact` payment to a THIRD-PARTY x402
7229
7368
  * facilitator the MERCHANT chooses (Coinbase CDP, x402.org, or any). PipRail hosts
@@ -8396,4 +8535,4 @@ interface McpPaymentTool {
8396
8535
  */
8397
8536
  declare function createMcpPaymentTool(options: McpPaymentToolOptions): McpPaymentTool;
8398
8537
 
8399
- export { type A2AArtifact, type A2AExtensionDeclaration, type A2AMessage, type A2AMetadata, type A2APart, type A2APaymentHandler, type A2APaymentHandlerOptions, type A2APaymentStatus, type A2ATask, type A2ATaskRecord, type A2ATaskState, type A2ATaskStore, A2A_ERROR_KEY, A2A_EXTENSIONS_HEADER, A2A_PAYLOAD_KEY, A2A_RECEIPTS_KEY, A2A_REQUIRED_KEY, A2A_STATUS_KEY, A2A_X402_EXTENSION_URI_V01, A2A_X402_EXTENSION_URI_V02, type AcceptOption, AddressId, type AgentTool, type AlgorandToken, type AptosToken, AssetId, BRAND, BUILTIN_DENOMS, type BazaarExtension, type BuildExactParams, CHAINS, Caip2, type ChainFamily, type ChainInput, type ChainName, type ChainPreset, type ChainSelector, type ChallengeTriage, type ChallengeVerdict, type ConfirmInfo, ConfirmationTimeoutError, type CostEstimate, type CountStatus, DENOM_PRECISION, DIRECTORY_INFO, type DeclineReasonCode, type DeliverAttempt, type DeliverReceiptOptions, type DeliverResult, type DenomRemaining, type DirectoryInfo, type DiscoverOptions, type DiscoveredRail, type DiscoveredResource, type DiscoveryDescriptor, type DiscoverySigner, type DiscoverySort, type DiscoverySource, type DomainClaim, type DomainVerification, EIP3009_TYPES, EXACT_NETWORK_SLUGS, type EvmToken, type ExactAccept, type ExactAuthorization, ExactPaymentPayloadAny, type ExactRailOption, type ExpressLikeMiddleware, type ExpressLikeNext, type ExpressLikeRequest, type ExpressLikeResponse, type FacilitatorConfig, type FacilitatorPaymentRequirements, type FacilitatorSupportedKind, type FailedPayment, GENERATOR, InsufficientFundsError, InvalidConfigError, InvalidEnvelopeError, KNOWN_FACILITATORS, type KnownFacilitator, type ListingVisibility, MCP_PAYMENT_META_KEY, MCP_PAYMENT_RESPONSE_META_KEY, type ManifestInput, MaxRetriesExceededError, type McpContentBlock, type McpPaymentMeta, type McpPaymentTool, type McpPaymentToolOptions, type McpToolCallParams, type McpToolResult, MissingDriverError, MultiChainPayer, type MultiChainPayerOptions, type NearToken, NoCompatibleAcceptError, NonReplayableBodyError, type OpenApiDocument, type OpenApiOperation, PERMIT2_ADDRESS, PERMIT2_PROXY_CHAIN_IDS, PERMIT2_UPTO_WITNESS_TYPES, PERMIT2_WITNESS_TYPES, PIPRAIL_AGENT_GUIDE, POWERED_BY, PaidReceipt, type PayBlocker, type PayOption, type PayWarning, type PayingClient, PaymentDeclinedError, type PaymentDriver, type PaymentGate, type PaymentIntent, type PaymentPlan, type PaymentPolicy, type PaymentRail, type PaymentScheme, PaymentTimeoutError, Permit2UptoPaymentPayload, PipRailClient, type PipRailClientOptions, type PipRailCostQuote, PipRailError, type PipRailEvent, type PipRailQuote, PipRailReceipt, type PolicyDecision, type PolicyDenyCode, REGISTER_ATTRIBUTION, type ReceiptInput, type ReceiptOption, type ReceiptVerification, RecipientNotReadyError, type RecipientReason, type RegisterInput, type RegisterOptions, type RegisterOutcome, type RequirePaymentOptions, type ResolveOptions, type ResolvedChain, type ResolvedNetwork, type ResolvedToken, type ResourceDescription, type SearchOpenIndexesOptions, type SelfDescribeEndpoint, type SelfDescribeRail, type SelfDescription, type SessionBudget, SettleOutcome, type SettleViaFacilitatorInput, SettlementError, SignedReceipt, type SolanaToken, SpendLedger, SpendRecord, type SpendRemaining, SpendStore, SpendSummary, type StellarToken, type SuiToken, type TokenInfo, type TokenInput, type TonToken, type ToolAnnotations, type TronToken, UPTO_PROXY_CHAIN_IDS, UnknownTokenError, UnsupportedNetworkError, UnsupportedSchemeError, type UptoRailOption, VERIFY_CODE_TO_A2A_ERROR, VerifyErrorCode, type VerifyPaymentResult, VerifyResult, type WalletBalance, type WalletHandle, type WalletInput, WalletRequiredError, type WellKnownX402, type WellKnownX402Item, type WellKnownX402Manifest, WrongChainError, WrongFamilyError, X402AcceptEntry, X402AnyAccept, X402Challenge, type X402DnsRecord, X402ExactAcceptEntry, type X402InvalidBody, X402Receipt, X402UptoAcceptEntry, X402_EXACT_PERMIT2_PROXY, X402_UPTO_PERMIT2_PROXY, type XrplToken, agentGuide, appendAttribution, appendKeywords, buildBazaarExtension, buildEndpointInfo, buildExactAuthorization, buildMcpPaymentMeta, buildOpenApi, buildSelfDescription, buildWellKnownX402, buildWellKnownX402Manifest, buildX402DnsTxt, chainIdForExactNetwork, claim402IndexDomain, classifyChallenge, createA2APaymentHandler, createMcpPaymentTool, createPaymentGate, decorateOutcome, deliverReceipt, denomOf, describeChallenge, discoveryHeaders, eip3009Abi, encodeXPaymentHeader, evaluatePolicy, explainDecline, facilitatorCoverage, fetchAcross, firstKeylessFacilitator, formatSpendReport, fromA2APaymentPayload, fromA2APaymentRequired, fromMcpPayment, fromMcpPaymentRequired, fromMcpPaymentResponse, getDirectoryInfo, isMcpPaymentRequired, isPermit2ProxyChain, isUptoProxyChain, knownFacilitatorsFor, normalizeNetwork, parseExactRequirements, parseFacilitatorSupported, paymentTools, planAcross, rankResources, readExactDomain, register402Index, registerDriver, registerX402Scan, renderLandingPage, requirePayment, resolveChain, scoreResource, searchOpenIndexes, settleViaFacilitator, summarizePlan, toA2AErrorCode, toA2APaymentFailed, toA2APaymentReceipts, toA2APaymentRequired, toInsufficientFundsError, toInvalidBody, toMcpPaymentRequired, toMcpPaymentResponse, verify402IndexDomain };
8538
+ export { type A2AArtifact, type A2AExtensionDeclaration, type A2AMessage, type A2AMetadata, type A2APart, type A2APaymentHandler, type A2APaymentHandlerOptions, type A2APaymentStatus, type A2ATask, type A2ATaskRecord, type A2ATaskState, type A2ATaskStore, A2A_ERROR_KEY, A2A_EXTENSIONS_HEADER, A2A_PAYLOAD_KEY, A2A_RECEIPTS_KEY, A2A_REQUIRED_KEY, A2A_STATUS_KEY, A2A_X402_EXTENSION_URI_V01, A2A_X402_EXTENSION_URI_V02, type AcceptOption, AddressId, type AgentTool, type AlgorandToken, type AptosToken, AssetId, BRAND, BUILTIN_DENOMS, type BazaarExtension, type BuildExactParams, CHAINS, Caip2, type ChainFamily, type ChainInput, type ChainName, type ChainPreset, type ChainSelector, type ChallengeTriage, type ChallengeVerdict, type ConfirmInfo, ConfirmationTimeoutError, type CostEstimate, type CountStatus, DENOM_PRECISION, DIRECTORY_INFO, type DeclineReasonCode, type DeliverAttempt, type DeliverReceiptOptions, type DeliverResult, type DenomRemaining, type DirectoryInfo, type DiscoverOptions, type DiscoveredRail, type DiscoveredResource, type DiscoveryDescriptor, type DiscoverySigner, type DiscoverySort, type DiscoverySource, type DomainClaim, type DomainVerification, EIP3009_TYPES, EXACT_NETWORK_SLUGS, type EvmToken, type ExactAccept, type ExactAuthorization, ExactPaymentPayloadAny, type ExactRailOption, type ExpressLikeMiddleware, type ExpressLikeNext, type ExpressLikeRequest, type ExpressLikeResponse, type FacilitatorConfig, type FacilitatorPaymentRequirements, type FacilitatorSupportedKind, type FailedPayment, GENERATOR, type GateSelfTest, InsufficientFundsError, InvalidConfigError, InvalidEnvelopeError, KNOWN_FACILITATORS, type KnownFacilitator, type ListingVisibility, MCP_PAYMENT_META_KEY, MCP_PAYMENT_RESPONSE_META_KEY, type ManifestInput, MaxRetriesExceededError, type McpContentBlock, type McpPaymentMeta, type McpPaymentTool, type McpPaymentToolOptions, type McpToolCallParams, type McpToolResult, MissingDriverError, MultiChainPayer, type MultiChainPayerOptions, type NearToken, NoCompatibleAcceptError, NonReplayableBodyError, type OpenApiDocument, type OpenApiOperation, PERMIT2_ADDRESS, PERMIT2_PROXY_CHAIN_IDS, PERMIT2_UPTO_WITNESS_TYPES, PERMIT2_WITNESS_TYPES, PIPRAIL_AGENT_GUIDE, POWERED_BY, PaidReceipt, type PayBlocker, type PayOption, type PayWarning, type PayingClient, PaymentDeclinedError, type PaymentDriver, type PaymentGate, type PaymentIntent, type PaymentPlan, type PaymentPolicy, type PaymentRail, type PaymentScheme, PaymentTimeoutError, type PaywallOptions, Permit2UptoPaymentPayload, PipRailClient, type PipRailClientOptions, type PipRailCostQuote, PipRailError, type PipRailEvent, type PipRailQuote, PipRailReceipt, type PolicyDecision, type PolicyDenyCode, REGISTER_ATTRIBUTION, type ReceiptInput, type ReceiptOption, type ReceiptVerification, RecipientNotReadyError, type RecipientReason, type RegisterInput, type RegisterOptions, type RegisterOutcome, type RequirePaymentOptions, type ResolveOptions, type ResolvedChain, type ResolvedNetwork, type ResolvedToken, type ResourceDescription, type SearchOpenIndexesOptions, type SelfDescribeEndpoint, type SelfDescribeRail, type SelfDescription, type Serve, type SessionBudget, SettleOutcome, type SettleViaFacilitatorInput, SettlementError, SignedReceipt, type SolanaToken, SpendLedger, SpendRecord, type SpendRemaining, SpendStore, SpendSummary, type StellarToken, type SuiToken, type TipJarOptions, type TokenInfo, type TokenInput, type TonToken, type ToolAnnotations, type TronToken, UPTO_PROXY_CHAIN_IDS, UnknownTokenError, UnsupportedNetworkError, UnsupportedSchemeError, type UptoRailOption, VERIFY_CODE_TO_A2A_ERROR, VerifyErrorCode, type VerifyPaymentResult, VerifyResult, type WalletBalance, type WalletHandle, type WalletInput, WalletRequiredError, type WellKnownX402, type WellKnownX402Item, type WellKnownX402Manifest, WrongChainError, WrongFamilyError, X402AcceptEntry, X402AnyAccept, X402Challenge, type X402DnsRecord, X402ExactAcceptEntry, type X402InvalidBody, X402Receipt, X402UptoAcceptEntry, X402_EXACT_PERMIT2_PROXY, X402_UPTO_PERMIT2_PROXY, type XrplToken, agentGuide, appendAttribution, appendKeywords, buildBazaarExtension, buildEndpointInfo, buildExactAuthorization, buildMcpPaymentMeta, buildOpenApi, buildSelfDescription, buildWellKnownX402, buildWellKnownX402Manifest, buildX402DnsTxt, chainIdForExactNetwork, claim402IndexDomain, classifyChallenge, createA2APaymentHandler, createMcpPaymentTool, createPaymentGate, createPaywall, createTipJar, decorateOutcome, deliverReceipt, denomOf, describeChallenge, discoveryHeaders, eip3009Abi, encodeXPaymentHeader, evaluatePolicy, explainDecline, facilitatorCoverage, fetchAcross, firstKeylessFacilitator, formatSpendReport, fromA2APaymentPayload, fromA2APaymentRequired, fromMcpPayment, fromMcpPaymentRequired, fromMcpPaymentResponse, getDirectoryInfo, isMcpPaymentRequired, isPermit2ProxyChain, isUptoProxyChain, knownFacilitatorsFor, normalizeNetwork, parseExactRequirements, parseFacilitatorSupported, paymentTools, planAcross, proxyTo, rankResources, readExactDomain, register402Index, registerDriver, registerX402Scan, renderLandingPage, requirePayment, resolveChain, scoreResource, searchOpenIndexes, settleViaFacilitator, summarizePlan, toA2AErrorCode, toA2APaymentFailed, toA2APaymentReceipts, toA2APaymentRequired, toFetchHandler, toInsufficientFundsError, toInvalidBody, toMcpPaymentRequired, toMcpPaymentResponse, toWorker, verify402IndexDomain };
package/dist/index.d.ts CHANGED
@@ -7169,6 +7169,34 @@ declare function toInvalidBody(result: {
7169
7169
  error: string;
7170
7170
  detail: string;
7171
7171
  }): X402InvalidBody;
7172
+ /**
7173
+ * The result of {@link PaymentGate.selfTest} — a read-only config check. NEVER throws, and never
7174
+ * touches the network beyond the same lazy driver/token resolution the first `challenge()` does
7175
+ * (no signing, no sending). `ok:true` with the resolved `rails` when the config is sound; `ok:false`
7176
+ * with a human `error` when something's wrong (no payTo, a malformed address for the family, an
7177
+ * unknown token, an unresolvable chain). Powers a scaffolder's "✅ your endpoint is configured"
7178
+ * step and a merchant's `npm run verify`.
7179
+ */
7180
+ interface GateSelfTest {
7181
+ ok: boolean;
7182
+ /** One entry per resolved payment option (empty when `ok:false`). */
7183
+ rails: Array<{
7184
+ /** CAIP-2 network, e.g. `eip155:8453`. */
7185
+ network: string;
7186
+ asset: string;
7187
+ symbol?: string;
7188
+ decimals: number;
7189
+ /** Human amount the gate charges (for a tip jar, the minimum/floor). */
7190
+ amount: string;
7191
+ payTo: AddressId;
7192
+ /** The schemes this rail offers, e.g. `['onchain-proof']` or `['exact', 'onchain-proof']`. */
7193
+ schemes: string[];
7194
+ }>;
7195
+ /** Non-fatal nudges (e.g. a custom token with no built-in symbol to double-check). */
7196
+ warnings: string[];
7197
+ /** Present only when `ok:false` — the human reason the config can't serve a payment. */
7198
+ error?: string;
7199
+ }
7172
7200
  interface PaymentGate {
7173
7201
  /** Build a fresh 402 challenge (new nonce) for a resource URL. */
7174
7202
  challenge(resourceUrl?: string): Promise<{
@@ -7203,6 +7231,13 @@ interface PaymentGate {
7203
7231
  * The SDK never serves it itself (headless by charter). Agents/crawlers keep the JSON 402.
7204
7232
  */
7205
7233
  landingPage(challenge: X402Challenge): string;
7234
+ /**
7235
+ * Read-only config check — resolve the gate's rails WITHOUT signing or sending, and report what
7236
+ * it would charge (or why it can't). Never throws; runs the same lazy resolution as the first
7237
+ * `challenge()`. The merchant's "did I wire this right?" and a scaffolder's post-deploy smoke
7238
+ * step. See {@link GateSelfTest}.
7239
+ */
7240
+ selfTest(): Promise<GateSelfTest>;
7206
7241
  }
7207
7242
  declare function createPaymentGate(options: RequirePaymentOptions): PaymentGate;
7208
7243
  interface ExpressLikeRequest {
@@ -7224,6 +7259,110 @@ type ExpressLikeMiddleware = (req: ExpressLikeRequest, res: ExpressLikeResponse,
7224
7259
  */
7225
7260
  declare function requirePayment(options: RequirePaymentOptions): ExpressLikeMiddleware;
7226
7261
 
7262
+ /**
7263
+ * The advanced gate options a preset forwards verbatim — every {@link RequirePaymentOptions} field
7264
+ * EXCEPT the `chain`/`token`/`amount`/`payTo` quartet (each preset re-declares those with its own
7265
+ * shape) and the multi-chain `accept` array (use {@link createPaymentGate} directly for a multi-rail
7266
+ * gate). So `onPaid`, `exact`, `receipts`, `discovery`, `isUsed`/`markUsed`, … all pass through.
7267
+ */
7268
+ type GateExtras = Omit<RequirePaymentOptions, 'chain' | 'token' | 'amount' | 'payTo' | 'accept'>;
7269
+ /** Options for {@link createPaywall}. */
7270
+ interface PaywallOptions extends GateExtras {
7271
+ /** Which chain to be paid on. EVM (`'base'`|`'bnb'`|…) or a non-EVM family name. */
7272
+ chain: ChainSelector;
7273
+ /** Token to charge in. Defaults to **USDC**. */
7274
+ token?: TokenInput;
7275
+ /** The fixed price, human-readable, e.g. `'0.05'`. */
7276
+ amount: string;
7277
+ /** Your receiving wallet address — no private key (receiving needs only the address). */
7278
+ payTo: AddressId;
7279
+ }
7280
+ /**
7281
+ * Gate one resource behind a fixed price — the API / SaaS / premium-content case. Sugar over
7282
+ * {@link createPaymentGate} with `token` defaulting to USDC; every other gate option is forwarded
7283
+ * unchanged, so the resulting gate (and its 402) is identical to the hand-written equivalent.
7284
+ */
7285
+ declare function createPaywall({ token, ...rest }: PaywallOptions): PaymentGate;
7286
+ /** Options for {@link createTipJar}. */
7287
+ interface TipJarOptions extends GateExtras {
7288
+ /** Which chain to be paid on. */
7289
+ chain: ChainSelector;
7290
+ /** Token to accept. Defaults to **USDC**. */
7291
+ token?: TokenInput;
7292
+ /**
7293
+ * The MINIMUM tip, human-readable, e.g. `'1.00'`. The gate accepts any payment **≥ min** — the
7294
+ * on-chain verify rejects only an under-payment (`amount_too_low`), so a payer can always give
7295
+ * more. There is no upper bound; the minimum is a floor, not a fixed price.
7296
+ */
7297
+ min: string;
7298
+ /** Your receiving wallet address. */
7299
+ payTo: AddressId;
7300
+ }
7301
+ /**
7302
+ * An open "pay what you want (≥ a minimum)" gate — the creator / tip / donation case. Sugar over
7303
+ * {@link createPaymentGate} that sets the challenge `amount` to `min`; because the gate accepts an
7304
+ * over-payment, the minimum is a floor. Everything else (`onPaid`, etc.) forwards unchanged.
7305
+ */
7306
+ declare function createTipJar({ token, min, ...rest }: TipJarOptions): PaymentGate;
7307
+
7308
+ /**
7309
+ * Built-in framework adapters — turn a {@link PaymentGate} into a request handler for any
7310
+ * WHATWG-`fetch` runtime. There are only TWO real shapes among fetch runtimes, so there are two
7311
+ * adapters: a plain handler **function** (Next.js, Netlify, Bun, Deno, Vercel Edge, Hono, Lambda),
7312
+ * and the `{ fetch }` **export object** (Cloudflare / Service Workers). Both run the same contract:
7313
+ * read the proof header, switch on the {@link VerifyPaymentResult} `kind`, write the right status +
7314
+ * headers back out — so a merchant's route is a single call instead of a switch.
7315
+ *
7316
+ * import { createPaywall, toFetchHandler, toWorker } from '@piprail/sdk'
7317
+ * const gate = createPaywall({ chain: 'base', amount: '0.05', payTo: '0xYourWallet' })
7318
+ *
7319
+ * export const GET = toFetchHandler(gate, () => Response.json({ secret: 42 })) // Next / Netlify / Bun / Deno / Hono …
7320
+ * export default toWorker(gate, () => Response.json({ secret: 42 })) // a Cloudflare Worker
7321
+ *
7322
+ * Pure + browser-safe — Web `Request`/`Response`/`Headers` only (no viem, no `node:`). Express keeps
7323
+ * its dedicated {@link requirePayment} middleware; a Node-native framework with its own `req`/`reply`
7324
+ * (Fastify, …) drives `gate.verify()` directly (see the framework-adapters docs). {@link proxyTo} is a
7325
+ * ready-made `serve` that forwards paid requests to an existing backend — gate any API, any language.
7326
+ */
7327
+
7328
+ /**
7329
+ * What to serve once a payment is verified — your protected resource, as a Web `Response`. It
7330
+ * receives the original `request` **plus whatever extra arguments the runtime passed the handler**
7331
+ * (a Cloudflare Worker's `env`/`ctx`, a Next.js route `context` with `params`, …), forwarded
7332
+ * untouched — so a protected handler can reach framework context without a second wrapper.
7333
+ */
7334
+ type Serve = (request: Request, ...rest: unknown[]) => Response | Promise<Response>;
7335
+ /**
7336
+ * The universal adapter: wrap a gate as a `fetch` handler `(request, ...rest) => Response`. Drop the
7337
+ * result into **any** runtime that hands a handler a `Request` and wants a `Response` back — Next.js
7338
+ * route handlers (`export const GET = …`), Netlify Functions, `Bun.serve({ fetch })`,
7339
+ * `Deno.serve(…)`, Vercel Edge, Hono (`(c) => handler(c.req.raw)`), an AWS Lambda Web adapter, Fastly
7340
+ * Compute. Any extra runtime arguments are forwarded to `serve` untouched.
7341
+ *
7342
+ * - **settled payment** → calls `serve`, returns its `Response` with the `payment-response` headers (v2 + v1) added;
7343
+ * - **missing / rejected proof** → a conformant `402` carrying the full challenge (so a standard x402 client can retry);
7344
+ * - **server-side settle failure** ({@link SettlementError}) → `502` — NEVER `402` (the buyer's authorization is still valid + unused).
7345
+ */
7346
+ declare function toFetchHandler(gate: PaymentGate, serve: Serve): (request: Request, ...rest: unknown[]) => Promise<Response>;
7347
+ /**
7348
+ * The `{ fetch }` export object for runtimes that take one — Cloudflare Workers / Service Workers:
7349
+ * `export default toWorker(gate, serve)`. Identical behaviour to {@link toFetchHandler}; the
7350
+ * runtime's `fetch(request, env, ctx)` arguments are forwarded to `serve` (so it can read bindings /
7351
+ * `ctx.waitUntil`). (Other runtimes that take an object — `Bun.serve`, `Deno.serve` — can use either
7352
+ * this or `toFetchHandler` in their `fetch` field.)
7353
+ */
7354
+ declare function toWorker(gate: PaymentGate, serve: Serve): {
7355
+ fetch: (request: Request, ...rest: unknown[]) => Promise<Response>;
7356
+ };
7357
+ /**
7358
+ * A {@link Serve} that forwards the (already-paid) request to an upstream `origin`, untouched — so you
7359
+ * can put a payment gate in FRONT of an existing API in any language, without changing it. Preserves
7360
+ * the method, path, query, body, and headers; strips the x402 proof headers so they don't leak
7361
+ * upstream. The origin NEVER sees an unpaid request — the gate rejects those before `serve` runs.
7362
+ * Compose with the adapters: `toWorker(gate, proxyTo('https://my-api.example.com'))`.
7363
+ */
7364
+ declare function proxyTo(origin: string): Serve;
7365
+
7227
7366
  /**
7228
7367
  * Mode-B settlement: delegate a standard `exact` payment to a THIRD-PARTY x402
7229
7368
  * facilitator the MERCHANT chooses (Coinbase CDP, x402.org, or any). PipRail hosts
@@ -8396,4 +8535,4 @@ interface McpPaymentTool {
8396
8535
  */
8397
8536
  declare function createMcpPaymentTool(options: McpPaymentToolOptions): McpPaymentTool;
8398
8537
 
8399
- export { type A2AArtifact, type A2AExtensionDeclaration, type A2AMessage, type A2AMetadata, type A2APart, type A2APaymentHandler, type A2APaymentHandlerOptions, type A2APaymentStatus, type A2ATask, type A2ATaskRecord, type A2ATaskState, type A2ATaskStore, A2A_ERROR_KEY, A2A_EXTENSIONS_HEADER, A2A_PAYLOAD_KEY, A2A_RECEIPTS_KEY, A2A_REQUIRED_KEY, A2A_STATUS_KEY, A2A_X402_EXTENSION_URI_V01, A2A_X402_EXTENSION_URI_V02, type AcceptOption, AddressId, type AgentTool, type AlgorandToken, type AptosToken, AssetId, BRAND, BUILTIN_DENOMS, type BazaarExtension, type BuildExactParams, CHAINS, Caip2, type ChainFamily, type ChainInput, type ChainName, type ChainPreset, type ChainSelector, type ChallengeTriage, type ChallengeVerdict, type ConfirmInfo, ConfirmationTimeoutError, type CostEstimate, type CountStatus, DENOM_PRECISION, DIRECTORY_INFO, type DeclineReasonCode, type DeliverAttempt, type DeliverReceiptOptions, type DeliverResult, type DenomRemaining, type DirectoryInfo, type DiscoverOptions, type DiscoveredRail, type DiscoveredResource, type DiscoveryDescriptor, type DiscoverySigner, type DiscoverySort, type DiscoverySource, type DomainClaim, type DomainVerification, EIP3009_TYPES, EXACT_NETWORK_SLUGS, type EvmToken, type ExactAccept, type ExactAuthorization, ExactPaymentPayloadAny, type ExactRailOption, type ExpressLikeMiddleware, type ExpressLikeNext, type ExpressLikeRequest, type ExpressLikeResponse, type FacilitatorConfig, type FacilitatorPaymentRequirements, type FacilitatorSupportedKind, type FailedPayment, GENERATOR, InsufficientFundsError, InvalidConfigError, InvalidEnvelopeError, KNOWN_FACILITATORS, type KnownFacilitator, type ListingVisibility, MCP_PAYMENT_META_KEY, MCP_PAYMENT_RESPONSE_META_KEY, type ManifestInput, MaxRetriesExceededError, type McpContentBlock, type McpPaymentMeta, type McpPaymentTool, type McpPaymentToolOptions, type McpToolCallParams, type McpToolResult, MissingDriverError, MultiChainPayer, type MultiChainPayerOptions, type NearToken, NoCompatibleAcceptError, NonReplayableBodyError, type OpenApiDocument, type OpenApiOperation, PERMIT2_ADDRESS, PERMIT2_PROXY_CHAIN_IDS, PERMIT2_UPTO_WITNESS_TYPES, PERMIT2_WITNESS_TYPES, PIPRAIL_AGENT_GUIDE, POWERED_BY, PaidReceipt, type PayBlocker, type PayOption, type PayWarning, type PayingClient, PaymentDeclinedError, type PaymentDriver, type PaymentGate, type PaymentIntent, type PaymentPlan, type PaymentPolicy, type PaymentRail, type PaymentScheme, PaymentTimeoutError, Permit2UptoPaymentPayload, PipRailClient, type PipRailClientOptions, type PipRailCostQuote, PipRailError, type PipRailEvent, type PipRailQuote, PipRailReceipt, type PolicyDecision, type PolicyDenyCode, REGISTER_ATTRIBUTION, type ReceiptInput, type ReceiptOption, type ReceiptVerification, RecipientNotReadyError, type RecipientReason, type RegisterInput, type RegisterOptions, type RegisterOutcome, type RequirePaymentOptions, type ResolveOptions, type ResolvedChain, type ResolvedNetwork, type ResolvedToken, type ResourceDescription, type SearchOpenIndexesOptions, type SelfDescribeEndpoint, type SelfDescribeRail, type SelfDescription, type SessionBudget, SettleOutcome, type SettleViaFacilitatorInput, SettlementError, SignedReceipt, type SolanaToken, SpendLedger, SpendRecord, type SpendRemaining, SpendStore, SpendSummary, type StellarToken, type SuiToken, type TokenInfo, type TokenInput, type TonToken, type ToolAnnotations, type TronToken, UPTO_PROXY_CHAIN_IDS, UnknownTokenError, UnsupportedNetworkError, UnsupportedSchemeError, type UptoRailOption, VERIFY_CODE_TO_A2A_ERROR, VerifyErrorCode, type VerifyPaymentResult, VerifyResult, type WalletBalance, type WalletHandle, type WalletInput, WalletRequiredError, type WellKnownX402, type WellKnownX402Item, type WellKnownX402Manifest, WrongChainError, WrongFamilyError, X402AcceptEntry, X402AnyAccept, X402Challenge, type X402DnsRecord, X402ExactAcceptEntry, type X402InvalidBody, X402Receipt, X402UptoAcceptEntry, X402_EXACT_PERMIT2_PROXY, X402_UPTO_PERMIT2_PROXY, type XrplToken, agentGuide, appendAttribution, appendKeywords, buildBazaarExtension, buildEndpointInfo, buildExactAuthorization, buildMcpPaymentMeta, buildOpenApi, buildSelfDescription, buildWellKnownX402, buildWellKnownX402Manifest, buildX402DnsTxt, chainIdForExactNetwork, claim402IndexDomain, classifyChallenge, createA2APaymentHandler, createMcpPaymentTool, createPaymentGate, decorateOutcome, deliverReceipt, denomOf, describeChallenge, discoveryHeaders, eip3009Abi, encodeXPaymentHeader, evaluatePolicy, explainDecline, facilitatorCoverage, fetchAcross, firstKeylessFacilitator, formatSpendReport, fromA2APaymentPayload, fromA2APaymentRequired, fromMcpPayment, fromMcpPaymentRequired, fromMcpPaymentResponse, getDirectoryInfo, isMcpPaymentRequired, isPermit2ProxyChain, isUptoProxyChain, knownFacilitatorsFor, normalizeNetwork, parseExactRequirements, parseFacilitatorSupported, paymentTools, planAcross, rankResources, readExactDomain, register402Index, registerDriver, registerX402Scan, renderLandingPage, requirePayment, resolveChain, scoreResource, searchOpenIndexes, settleViaFacilitator, summarizePlan, toA2AErrorCode, toA2APaymentFailed, toA2APaymentReceipts, toA2APaymentRequired, toInsufficientFundsError, toInvalidBody, toMcpPaymentRequired, toMcpPaymentResponse, verify402IndexDomain };
8538
+ export { type A2AArtifact, type A2AExtensionDeclaration, type A2AMessage, type A2AMetadata, type A2APart, type A2APaymentHandler, type A2APaymentHandlerOptions, type A2APaymentStatus, type A2ATask, type A2ATaskRecord, type A2ATaskState, type A2ATaskStore, A2A_ERROR_KEY, A2A_EXTENSIONS_HEADER, A2A_PAYLOAD_KEY, A2A_RECEIPTS_KEY, A2A_REQUIRED_KEY, A2A_STATUS_KEY, A2A_X402_EXTENSION_URI_V01, A2A_X402_EXTENSION_URI_V02, type AcceptOption, AddressId, type AgentTool, type AlgorandToken, type AptosToken, AssetId, BRAND, BUILTIN_DENOMS, type BazaarExtension, type BuildExactParams, CHAINS, Caip2, type ChainFamily, type ChainInput, type ChainName, type ChainPreset, type ChainSelector, type ChallengeTriage, type ChallengeVerdict, type ConfirmInfo, ConfirmationTimeoutError, type CostEstimate, type CountStatus, DENOM_PRECISION, DIRECTORY_INFO, type DeclineReasonCode, type DeliverAttempt, type DeliverReceiptOptions, type DeliverResult, type DenomRemaining, type DirectoryInfo, type DiscoverOptions, type DiscoveredRail, type DiscoveredResource, type DiscoveryDescriptor, type DiscoverySigner, type DiscoverySort, type DiscoverySource, type DomainClaim, type DomainVerification, EIP3009_TYPES, EXACT_NETWORK_SLUGS, type EvmToken, type ExactAccept, type ExactAuthorization, ExactPaymentPayloadAny, type ExactRailOption, type ExpressLikeMiddleware, type ExpressLikeNext, type ExpressLikeRequest, type ExpressLikeResponse, type FacilitatorConfig, type FacilitatorPaymentRequirements, type FacilitatorSupportedKind, type FailedPayment, GENERATOR, type GateSelfTest, InsufficientFundsError, InvalidConfigError, InvalidEnvelopeError, KNOWN_FACILITATORS, type KnownFacilitator, type ListingVisibility, MCP_PAYMENT_META_KEY, MCP_PAYMENT_RESPONSE_META_KEY, type ManifestInput, MaxRetriesExceededError, type McpContentBlock, type McpPaymentMeta, type McpPaymentTool, type McpPaymentToolOptions, type McpToolCallParams, type McpToolResult, MissingDriverError, MultiChainPayer, type MultiChainPayerOptions, type NearToken, NoCompatibleAcceptError, NonReplayableBodyError, type OpenApiDocument, type OpenApiOperation, PERMIT2_ADDRESS, PERMIT2_PROXY_CHAIN_IDS, PERMIT2_UPTO_WITNESS_TYPES, PERMIT2_WITNESS_TYPES, PIPRAIL_AGENT_GUIDE, POWERED_BY, PaidReceipt, type PayBlocker, type PayOption, type PayWarning, type PayingClient, PaymentDeclinedError, type PaymentDriver, type PaymentGate, type PaymentIntent, type PaymentPlan, type PaymentPolicy, type PaymentRail, type PaymentScheme, PaymentTimeoutError, type PaywallOptions, Permit2UptoPaymentPayload, PipRailClient, type PipRailClientOptions, type PipRailCostQuote, PipRailError, type PipRailEvent, type PipRailQuote, PipRailReceipt, type PolicyDecision, type PolicyDenyCode, REGISTER_ATTRIBUTION, type ReceiptInput, type ReceiptOption, type ReceiptVerification, RecipientNotReadyError, type RecipientReason, type RegisterInput, type RegisterOptions, type RegisterOutcome, type RequirePaymentOptions, type ResolveOptions, type ResolvedChain, type ResolvedNetwork, type ResolvedToken, type ResourceDescription, type SearchOpenIndexesOptions, type SelfDescribeEndpoint, type SelfDescribeRail, type SelfDescription, type Serve, type SessionBudget, SettleOutcome, type SettleViaFacilitatorInput, SettlementError, SignedReceipt, type SolanaToken, SpendLedger, SpendRecord, type SpendRemaining, SpendStore, SpendSummary, type StellarToken, type SuiToken, type TipJarOptions, type TokenInfo, type TokenInput, type TonToken, type ToolAnnotations, type TronToken, UPTO_PROXY_CHAIN_IDS, UnknownTokenError, UnsupportedNetworkError, UnsupportedSchemeError, type UptoRailOption, VERIFY_CODE_TO_A2A_ERROR, VerifyErrorCode, type VerifyPaymentResult, VerifyResult, type WalletBalance, type WalletHandle, type WalletInput, WalletRequiredError, type WellKnownX402, type WellKnownX402Item, type WellKnownX402Manifest, WrongChainError, WrongFamilyError, X402AcceptEntry, X402AnyAccept, X402Challenge, type X402DnsRecord, X402ExactAcceptEntry, type X402InvalidBody, X402Receipt, X402UptoAcceptEntry, X402_EXACT_PERMIT2_PROXY, X402_UPTO_PERMIT2_PROXY, type XrplToken, agentGuide, appendAttribution, appendKeywords, buildBazaarExtension, buildEndpointInfo, buildExactAuthorization, buildMcpPaymentMeta, buildOpenApi, buildSelfDescription, buildWellKnownX402, buildWellKnownX402Manifest, buildX402DnsTxt, chainIdForExactNetwork, claim402IndexDomain, classifyChallenge, createA2APaymentHandler, createMcpPaymentTool, createPaymentGate, createPaywall, createTipJar, decorateOutcome, deliverReceipt, denomOf, describeChallenge, discoveryHeaders, eip3009Abi, encodeXPaymentHeader, evaluatePolicy, explainDecline, facilitatorCoverage, fetchAcross, firstKeylessFacilitator, formatSpendReport, fromA2APaymentPayload, fromA2APaymentRequired, fromMcpPayment, fromMcpPaymentRequired, fromMcpPaymentResponse, getDirectoryInfo, isMcpPaymentRequired, isPermit2ProxyChain, isUptoProxyChain, knownFacilitatorsFor, normalizeNetwork, parseExactRequirements, parseFacilitatorSupported, paymentTools, planAcross, proxyTo, rankResources, readExactDomain, register402Index, registerDriver, registerX402Scan, renderLandingPage, requirePayment, resolveChain, scoreResource, searchOpenIndexes, settleViaFacilitator, summarizePlan, toA2AErrorCode, toA2APaymentFailed, toA2APaymentReceipts, toA2APaymentRequired, toFetchHandler, toInsufficientFundsError, toInvalidBody, toMcpPaymentRequired, toMcpPaymentResponse, toWorker, verify402IndexDomain };