Skip to content

SDK API reference

This is the map of everything @piprail/sdk exports — grouped by the job it does, with the headline APIs marked and the advanced tiers (wire codecs, low-level exact, the driver SPI) kept clearly separate. Each group links to the page that documents it in full.

Two entry points cover the 99% case: requirePayment / createPaymentGate to get paid, and PipRailClient to pay. Everything else is built on those.

import { requirePayment, PipRailClient } from '@piprail/sdk'

The server-side surface. requirePayment is Express/Connect middleware; createPaymentGate is the same logic, framework-free.

ExportKindMarked
requirePaymentfnHeadline
createPaymentGatefnHeadline
createPaywall, createTipJarfnPresets — named sugar over createPaymentGate (fixed-price paywall / pay-what-you-want tip jar). See Presets & self-test
toFetchHandler, toWorker, proxyTofnAdapters for every fetch runtime — toFetchHandler (universal (request, …) => Response) + toWorker (the { fetch } export). proxyTo(origin) is a serve that forwards paid requests to an existing backend → gate any API. See Framework adapters
deliverReceiptfnReliable receipt webhook — signed + retried POST to your endpoint
toInvalidBodyfnDeprecated
RequirePaymentOptions, AcceptOption, ExactRailOptiontypecarries onPaid / onPaidError / awaitOnPaid and their failure mirrors onFailed / onFailedError / awaitOnFailed; mimeType (→ v2 resource.mimeType + the self-describe endpoint)
UptoRailOptiontypeThe createPaymentGate({ upto }) rail option — metered / variable-amount billing (buyer signs a MAX, you settle the actual ≤ max). See upto rail (seller)
ReceiptOptiontypeThe createPaymentGate({ receipt }) rail option — emit a signed, anyone-verifiable verifiable receipt alongside the response
ChainSelector, TokenInputtype
PaymentGate, VerifyPaymentResulttype
GateSelfTesttypeThe result of gate.selfTest(){ ok, rails, warnings, error? } (read-only, never-throw config check)
PaywallOptions, TipJarOptions, ServetypeThe preset + adapter option types
PaidReceipttypeThe enriched receipt onPaid receives
FailedPaymenttypeThe failure object onFailed receives — { code, detail, transient } (the mirror of PaidReceipt)
DeliverReceiptOptions, DeliverAttempt, DeliverResulttype
X402InvalidBodytype
ExpressLike{Request,Response,Next,Middleware}type

See requirePayment & createPaymentGate, Defining accepts, Verifying payments, and Receipts & onPaid (the PaidReceipt, onPaidError, awaitOnPaid, and deliverReceipt — plus the failure mirror onFailed / FailedPayment / onFailedError / awaitOnFailed, fired when a submitted proof is rejected).

The client. One PipRailClient binds a chain + wallet and exposes the read-only trio (quoteestimateCostplanPayment) plus fetch. MultiChainPayer carries one wallet per chain and auto-routes a 402 to whichever chain can settle it.

ExportKindMarked
PipRailClientclassHeadline
MultiChainPayerclassHeadline — one buyer, a wallet per chain
planAcross, fetchAcrossfnplan / pay across an array of single-chain clients
PipRailClientOptions, MultiChainPayerOptions, WalletInput, PaymentSchemetype
PayingClienttypethe read-+-pay surface both PipRailClient and MultiChainPayer satisfy
PipRailQuote, PipRailCostQuote, PipRailEventtypethe payment-failed event gained code? / detail? and ALSO fires on a pre-send DECLINE (policy / onBeforePay / no settleable rail)
PaymentPlan, PayOption, PayBlocker, PayWarningtype
SessionBudget, SpendRemainingtype
ReceiptVerificationtypeThe verdict returned by the static PipRailClient.verifyReceipt / PipRailClient.verifyAttestation — re-verify a verifiable receipt against the chain, wallet-free (never throws). client.lastReceipt() returns the most recent one the client received.

See Quote, Estimate cost, planPayment(), fetch & autoRoute, Multi-chain buying, Events, and Wallets by family.

The policy + ledger primitives. evaluatePolicy is the pure decision function the client and MCP both call before any spend. The ledger + store are how caps survive a restart and span chains — still no backend, no database, no fee: SpendLedger is in-memory and a SpendStore is a caller-owned file (or anything you implement).

ExportKindMarked
evaluatePolicyfnHeadline
SpendLedgerclassShare one across several clients for a cross-chain grand total (MultiChainPayer.fromWallets wires it for you)
memorySpendStorefnA SpendStore backed by an in-memory array — memorySpendStore(seed?); from @piprail/sdk
fileSpendStorefnA durable JSONL SpendStorefileSpendStore(path); from @piprail/sdk/node (Node-only, keeps node:fs out of the browser bundle)
denomOffnPure — denomOf(symbol, asset, policy) → the unit a token folds into, or none
BUILTIN_DENOMS, DENOM_PRECISIONconstthe built-in symbol→unit map (USDC/USDT/USD1/FDUSD/U/RLUSD → 'USD', EURC → 'EUR') and the fixed-point precision (24)
PaymentPolicy, PaymentIntent, PolicyDecision, PolicyDenyCodetypePaymentPolicy gained maxTotalPerDenom / denomFor / maxPayments / maxPaymentsPerWindow / warnAtFraction; PolicyDenyCode gained MAX_TOTAL_DENOM / MAX_PAYMENTS / WINDOW_COUNT
SpendStoretype{ load(): SpendRecord[]; append(record): void } — pass as the client’s spendStore to persist the ledger (never throws)
SpendRecord, SpendSummary, SpendAssetTotal, SpendDenomTotaltypeSpendSummary gained byDenom: SpendDenomTotal[]; SpendRecord gained optional decimals / denom
DenomRemaining, CountStatustypethe per-denomination remaining row + the payment-count status SessionBudget now also reports

See Payment policy, Total budget, Time envelope, evaluatePolicy(), and Spend ledger.

paymentTools(client) returns the tool set an autonomous LLM drives; the renderers and guide make a bound client legible to the model.

ExportKindMarked
paymentToolsfnHeadline
AgentTool, ToolAnnotationstype
summarizePlan, explainDecline, formatSpendReport, describeChallengefn
PIPRAIL_AGENT_GUIDE, agentGuideconst / fn
classifyChallengefn
ChallengeTriage, ChallengeVerdicttype
buildSelfDescription, buildEndpointInfo, BRANDfn / constthe extensions.piprail self-description builder, the endpoint sub-block assembler, + brand single-source-of-truth
SelfDescription, SelfDescribeRail, SelfDescribeEndpointtypethe self-describe block, a rail in it, and the agent-readable endpoint (summary/input/output)

See Payment tools, The agent tools, Renderers, Agent guide, and Challenge triage.

CHAINS is the built-in EVM mainnet registry (each preset carries its canonical token addresses); resolveChain turns a chain value into a ResolvedChain.

ExportKind
CHAINS, resolveChainconst / fn
ChainInput, ChainName, ResolvedChaintype
ChainPreset, TokenInfotype

See Chains overview and Chains & tokens.

Be found, and find others — on the open x402 indexes, with nothing PipRail-hosted. The builders are pure (emit static artifacts); the register* / searchOpenIndexes functions talk to the free public directories.

ExportKind
buildOpenApi, buildWellKnownX402, buildWellKnownX402Manifest, buildX402DnsTxt, buildBazaarExtension, GENERATORfn / const
discoveryHeaders, POWERED_BY, renderLandingPagefn / const
searchOpenIndexes, register402Index, registerX402Scanfn
claim402IndexDomain, verify402IndexDomainfn
normalizeNetwork, getDirectoryInfo, decorateOutcome, DIRECTORY_INFOfn / const
rankResources, scoreResourcefn
appendKeywordsfn
appendAttribution, REGISTER_ATTRIBUTIONfn / const
PaymentRail, ResourceDescription, ManifestInputtype
OpenApiDocument, OpenApiOperation, WellKnownX402, WellKnownX402Manifest, WellKnownX402Item, X402DnsRecordtype
DiscoveryDescriptor, BazaarExtensiontype
DiscoverySource, DiscoverySort, DiscoveredRail, DiscoveredResourcetype
RegisterOutcome, RegisterInput, SearchOpenIndexesOptionstype
DirectoryInfo, ListingVisibility, DomainClaim, DomainVerificationtype
DiscoverOptions, RegisterOptionstype

See Discover & register, Open indexes, Emitters, and Domain verification.

Every thrown error is a typed PipRailError subclass with a stable .code.

ExportKind
PipRailErrorclass (base)
InsufficientFundsError, RecipientNotReadyErrorclass
WrongChainError, WrongFamilyError, UnknownTokenErrorclass
InvalidConfigErrorclass
MissingDriverError, UnsupportedNetworkError, UnsupportedSchemeErrorclass
PaymentTimeoutError, ConfirmationTimeoutError, MaxRetriesExceededErrorclass
PaymentDeclinedError, InvalidEnvelopeError, NoCompatibleAcceptErrorclass
NonReplayableBodyError, SettlementError, WalletRequiredErrorclass
toInsufficientFundsErrorfn
DeclineReasonCodetype

See Error model, Error hierarchy, VerifyErrorCode, and Why payments fail.

The raw envelope codecs, for building a client or server by hand. PipRailClient and createPaymentGate cover the 99% case — reach for these only when you’re hand-rolling the wire format (server: buildChallengeHeader → verify → buildReceiptHeader; client: parseChallengebuildSignatureHeaderparseReceipt).

ExportKind
pickAcceptfn
parseChallenge, parseReceipt, parseReceiptExtension, parseSettleResponsefn
parseSignatureHeader, parseExactPaymentHeader, parseUptoPaymentHeaderfn
parseSignatureObject, parseExactObject, parseUptoObject, decodeBase64Jsonfn — the object-accepting parser cores the base64 header parsers wrap, for a transport that carries the SAME payload as raw JSON (A2A), fed via gate.verifyObject
buildChallengeHeader, buildSignatureHeader, buildExactSignatureHeader, buildUptoSignatureHeader, buildReceiptHeaderfn
buildReceiptExtension, EXT_OFFER_RECEIPTfn / const
buildPaymentIdentifierAdvertisement, readPaymentIdentifier, EXT_PAYMENT_IDENTIFIERfn / const
HEADER_REQUIRED, HEADER_SIGNATURE, HEADER_RESPONSE, HEADER_SIGNATURE_V1, HEADER_RESPONSE_V1const
Caip2, AssetId, AddressIdtype
VerifyResult, VerifyErrorCodetype
X402AcceptEntry, X402ExactAcceptEntry, X402UptoAcceptEntry, X402AnyAccept, X402Challengetype
X402PaymentSignature, X402Receipt, X402ResourceObject, SettleOutcometype
PipRailReceipt, SignedReceipttype
ExactAuthorizationWire, ExactPaymentPayload, ExactPaymentPayloadAny, ParsedExactPaymenttype
Permit2Authorization, Permit2PaymentPayload, Permit2UptoAuthorization, Permit2UptoPaymentPayload, ParsedUptoPaymenttype

See Wire codecs and VerifyErrorCode.

Advanced: low-level exact (EVM — EIP-3009 + Permit2)

Section titled “Advanced: low-level exact (EVM — EIP-3009 + Permit2)”

The standard x402 exact scheme at the codec tier. For the high-level paths use PipRailClient({ schemes: ['exact'] }) (buyer) or createPaymentGate({ exact }) (seller) — these exports are for hand-rolled clients, v1 servers, and custom flows. The exact scheme has six asset-transfer methods: EIP-3009 (transferWithAuthorization, on EVM tokens that implement it) and Permit2 (for EVM ERC-20s that don’t — e.g. Binance-Peg USDC/USDT on BNB), plus SVM (Solana — any SPL token, the merchant is the fee payer), Algorand, Aptos, and NEAR on their respective L1s. The codecs in the table below are the EVM tier (EIP-3009 + Permit2); the non-EVM payloads — SVM’s { transaction } shape (ExactSvmPaymentPayload), Algorand (ExactAlgorandPaymentPayload), Aptos (ExactAptosPaymentPayload), NEAR (ExactNearPaymentPayload) — are built/verified inside their respective drivers — they are variants of the exported ExactPaymentPayloadAny union (reached via ParsedExactPayment), not importable individually. See Gasless payments.

ExportKindNote
parseExactRequirements, chainIdForExactNetwork, encodeXPaymentHeaderfnEVM tier
readExactDomain, eip3009Abifn / constreads/uses a token’s true on-chain EIP-712 domain (EVM)
EXACT_NETWORK_SLUGS, EIP3009_TYPESconst
PERMIT2_ADDRESS, X402_EXACT_PERMIT2_PROXY, PERMIT2_WITNESS_TYPESconstPermit2 method: the canonical Permit2 + x402ExactPermit2Proxy + witness types
PERMIT2_PROXY_CHAIN_IDS, isPermit2ProxyChainconst / fnEVM chains where the x402 Permit2 proxy is deployed (where the Permit2 exact method can settle)
buildExactAuthorizationfnDeprecated — trusts the server-supplied domain
ExactAccept, ExactAuthorization, BuildExactParamstype
Permit2Authorization, Permit2PaymentPayload, ExactPaymentPayloadAnytypethe per-method wire payloads (EIP-3009 / Permit2 / SVM / Algorand / Aptos / NEAR); ParsedExactPayment is a union on method ('eip3009'/'permit2'/'svm'/'algorand'/'aptos'/'near')

Advanced: upto rail (EVM — metered / variable-amount Permit2)

Section titled “Advanced: upto rail (EVM — metered / variable-amount Permit2)”

The upto (metered) scheme — the buyer signs a Permit2 witness transfer for a MAX, and the merchant settles the actual (≤ max) after serving. EVM-Permit2 only. The high-level paths are createPaymentGate({ upto }) (seller) and PipRailClient({ schemes: ['onchain-proof', 'upto'] }) (buyer) — these constants are the canonical proxy + witness types, for reference / advanced use. The proxy (vanity …0002, distinct from the exact …0001) is BOTH the signature spender and the seller’s settle contract.

ExportKindNote
X402_UPTO_PERMIT2_PROXYconstThe canonical x402 upto Permit2 proxy address (vanity …0002).
UPTO_PROXY_CHAIN_IDS, isUptoProxyChainconst / fnEVM chains where the upto Permit2 proxy is deployed (where the upto rail can settle).
PERMIT2_UPTO_WITNESS_TYPESconstThe EIP-712 witness type set for the upto Permit2 signature.

See the upto rail (seller) page for how to wire it.

Advanced: A2A transport (x402 over Google Agent2Agent)

Section titled “Advanced: A2A transport (x402 over Google Agent2Agent)”

The seller-side A2A adapter — the A2A analogue of requirePayment. Wrap a PaymentGate and map A2A Task/Message metadata ⇄ x402’s existing envelopes, backendless: zero driver/scheme/chain changes, so every family rides A2A for free. The raw-JSON dispatch seam it relies on, gate.verifyObject, is a method on the already-exported PaymentGate.

ExportKindNote
createA2APaymentHandlerfnHeadline (A2A) — wrap a PaymentGate into an A2A payment handler.
toA2APaymentRequired, toA2APaymentReceipts, toA2APaymentFailedfnMap an x402 challenge / receipts / failure into A2A Task/Message metadata.
fromA2APaymentRequired, fromA2APaymentPayloadfnRead an A2A payment-required / payment payload back out of A2A metadata.
toA2AErrorCode, VERIFY_CODE_TO_A2A_ERRORfn / constMap a VerifyErrorCode to its A2A error code.
A2A_X402_EXTENSION_URI_V01, A2A_X402_EXTENSION_URI_V02constThe x402-over-A2A extension URIs (v0.1 / v0.2).
A2A_STATUS_KEY, A2A_REQUIRED_KEY, A2A_PAYLOAD_KEY, A2A_RECEIPTS_KEY, A2A_ERROR_KEYconstThe A2A metadata keys the envelopes ride on.
A2A_EXTENSIONS_HEADERconstThe HTTP header that activates the A2A x402 extension.
A2APaymentHandler, A2APaymentHandlerOptionstypethe handler + its options
A2AArtifact, A2AExtensionDeclaration, A2AMessage, A2AMetadata, A2APart, A2APaymentStatus, A2ATask, A2ATaskRecord, A2ATaskState, A2ATaskStoretypethe A2A wire types

See A2A transport.

Advanced: x402-over-MCP transport (the third official transport)

Section titled “Advanced: x402-over-MCP transport (the third official transport)”

The seller-side MCP adapter — the MCP analogue of requirePayment / createA2APaymentHandler. Carry x402’s existing envelopes over MCP tool calls instead of HTTP headers, backendless: verify/settle/ replay all run through the gate’s verifyObject (zero new crypto, zero driver/scheme/chain changes), so every family rides MCP for free.

ExportKindNote
createMcpPaymentToolfnHeadline (MCP) — wrap a PaymentGate as a paid MCP tool. A fulfill() throw after settle still returns a success _meta payment-response, never a re-challenge (B7 at-most-once).
toMcpPaymentRequired, toMcpPaymentResponsefnBuild the 402-challenge (isError + structuredContent + a byte-equal content[0].text) and the settled tool result.
fromMcpPayment, fromMcpPaymentRequired, fromMcpPaymentResponse, isMcpPaymentRequiredfnBuyer/seller read helpers — pull the payment / challenge / settlement out of an MCP message.
buildMcpPaymentMetafnFrame an already-produced { accepted, payload } into the retry call’s params._meta["x402/payment"].
MCP_PAYMENT_META_KEY, MCP_PAYMENT_RESPONSE_META_KEYconstThe spec _meta keys (x402/payment / x402/payment-response — a slash, not A2A’s dot).
McpPaymentTool, McpPaymentToolOptions, McpContentBlock, McpToolCallParams, McpToolResult, McpPaymentMetatypethe MCP wire types (duck-typed; zero @modelcontextprotocol/sdk dependency)

A fully-automatic McpPayer (the buyer side) is a documented fast-follow, exactly as A2A shipped seller-first. See MCP transport (seller).

Advanced: exact facilitator (Mode B) — facilitator.js

Section titled “Advanced: exact facilitator (Mode B) — facilitator.js”

The Mode-B facilitator path (createPaymentGate({ exact: { settle: { facilitator } } })) delegates verify + settle to a third-party facilitator you choose. PipRail hosts nothing.

ExportKindNote
settleViaFacilitatorfnRun the two-POST verify→settle contract against a facilitator URL.
parseFacilitatorSupported, facilitatorCoveragefnRead a facilitator’s GET /supported → which (scheme, network) pairs it settles (never throws).
KNOWN_FACILITATORS, knownFacilitatorsFor, firstKeylessFacilitatorconst / fnThe keyless-facilitator coverage data map (which keyless facilitator settles exact on a network).
FacilitatorConfigtypeThe facilitator’s base url + optional authHeaders provider.
FacilitatorPaymentRequirementstypeThe trusted exact requirements posted to the facilitator.
SettleViaFacilitatorInput, FacilitatorSupportedKind, KnownFacilitatortypeinput to settleViaFacilitator; the /supported kinds; a coverage-map entry.

See the exact rail (seller) page for how to wire it, and Facilitator coverage for the keyless-facilitator data map.

See Low-level exact, exact rail (seller), and exact (buyer).

Bring your own chain family. registerDriver adds a family that implements the PaymentDriver contract; the rest are the contract’s types.

ExportKind
registerDriverfn
PaymentDriver, ChainFamilytype
ReceiptInputtype
ResolvedNetwork, ResolveOptions, ResolvedToken, CostEstimatetype
WalletHandle, WalletBalance, DiscoverySigner, ConfirmInfotype
RecipientReasontype
EvmToken, SolanaToken, TonToken, StellarToken, XrplTokentype
TronToken, NearToken, SuiToken, AptosToken, AlgorandTokentype

See Driver SPI and PaymentDriver architecture.