@rail402.dev/sdk is a buyer for x402 resources on Stellar: HTTP endpoints and paid MCP tools. It signs
exact payments with the unmodified @x402/stellar client and capped, usage-based upto payments with the
@rail402.dev/upto client, behind a signing guard that checks every authorization against your spending policy
immediately before it is signed. It also searches the Rail402 Bazaar and pays a listing
bound to its owner.
Requires Node.js 24.11 or later. Any x402 seller on Stellar whose facilitator sponsors fees can be paid; the
seller does not have to use Rail402.
Create a buyer
networkis required. There is no default network, so a buyer can never fall back to the wrong one.signeris a key source ({ secretFile }, preferred, or{ secret }) or any SEP-43 signer withaddressandsignAuthEntry, such as a wallet. Without a signer the buyer can search and quote, and paying is refused withpayment_signer_unavailable.- A key file must not be readable or writable by group or others (
key_file_insecure). Therail402 keys newcommand of the CLI creates one with mode0600, tagged with its network on a first line# rail402-key network=stellar:testnet(orstellar:pubnet). A file tagged for another network than the buyer’s is refused withkey_network_mismatch; an untagged file works on testnet only (see below).
stellar:testnet the buyer uses https://soroban-testnet.stellar.org and the Bazaar at
https://testnet.rail402.dev unless rpcUrl and bazaarUrl say otherwise, and Circle’s testnet USDC with
default caps of 0.10 USDC per call and 1.00 USDC per 24-hour budget window.
Choose the network
The network isstellar:testnet or stellar:pubnet, named by its CAIP-2 identifier. The same code runs on both; pubnet only asks for more to be
explicit:
payment_policy_invalid. So is a pubnet bazaarUrl or facilitatorUrl that is
not https, carries credentials, or names an IP address, localhost, a single label or a private-network
suffix such as .internal: the Bazaar’s listings decide whom the buyer pays. USDC caps above 1 USDC per call or 10 USDC per window
are refused with payment_cap_invalid unless the policy sets allowLargeCaps: true; any other pubnet asset
has no built-in ceiling (unit values differ), so caps on it also need allowLargeCaps: true. A key file that is not
tagged for pubnet is refused with key_network_untagged (or key_network_mismatch when it is tagged for
testnet) unless allowUntaggedKey: true is set.
Confirm before signing
confirm(intent) is called after the payment option is chosen and before anything is reserved or signed.
The intent holds network, scheme, asset (contract, symbol, decimals), amount (the most the
authorization can move: the price for exact, the cap for upto), payTo, resource, listingId,
facilitator (the upto settlement authority), the budget session (name, window, expiresAt, and the
perCall cap and the budget remaining for this asset before this payment) and approvalScope: payment
when approving covers this payment only, or recipient when it also covers later payments of this window to
the same recipient base account for the same listing (or, without a listing, the same resource), asset and
settlement authority, each within the per-call cap and the budget left, until session.expiresAt. Show the
person that scope. Returning anything but true
refuses the payment with payment_confirmation_declined and paid: "none"; an error the function throws
reaches the caller unchanged. A thrown PaymentError (such as payment_confirmation_unavailable) is also
reported to onEvent as a refused event with its code; any other thrown error is not a decision and
produces no event.
onBeforeSign(intent) is called right before every signature, after any confirmation. It observes only: it
cannot approve or refuse. Every authorization is also checked for the network it is valid on: a preimage
for the other network is refused with payment_network_not_permitted, and a seller option on another network
is never chosen.
Pay a resource by URL
maxAmount is required on every call; it is clamped to the policy’s per-call ceiling for the asset. The
flow makes an unpaid request, reads the seller’s PAYMENT-REQUIRED, picks the option the policy allows, checks
that the payer holds the asset and the recipient can receive it, signs one authorization through the guard,
sends the paid request once, and verifies the reported settlement on chain before returning.
An MCP tool is paid the same way:
https://demo.rail402.dev/mcp serves the paid tools forecast, air_quality and
the metered hourly_forecast.
HTTP requests carry only accept, accept-language and x-request-id headers from the caller; other
headers are refused with payment_request_invalid. Paid requests never follow redirects: a 3xx answer to
a paid request is payment_redirect_after_payment.
Pay upto resources
Anupto option names a cap: the buyer authorizes at most that much, and the seller settles what the call
used, from zero up to the cap, after serving it. The buyer pays upto resources the same way as exact ones:
- The cap counts against
maxAmount, the per-call ceiling and the budget window: an option whose cap is above the effective cap is refused withpayment_per_call_cap_exceeded, whatever it may end up charging. - The guard signs only
settle(terms)on a pinned settlement contract, with exactly one child that approves the cap to that contract, for the selected recipient, asset, cap, expiry and settlement authority. The contract comes frompolicy.uptoContracts(on testnet the canonical deployment by default), never from the seller; anything else fails closed withpayment_authorization_rejected. - The settlement authority (
extra.facilitatorAddress) is the only address that can settle the terms. It must be neither the payer nor the recipient, and, whenpolicy.uptoFacilitatorslists authorities, one of them (payment_facilitator_not_permitted). On pubnet a buyer with a signer always pins them: frompolicy.uptoFacilitators, or else from thefacilitatorAddressvalues thatfacilitatorUrl’s/supportedadvertises for upto on pubnet, read once at creation. With neither,createBuyerrefuses withpayment_policy_invalid, so a seller can never name its own key as the authority that settles the cap. It must also be aG…account: for aC…address the upto client refuses to build the payment, and the call fails withpayment_simulation_failedbefore anything is signed. Muxed (M…) recipients are refused. - The upto client signs for at most 300 seconds, even when
policy.maxAuthorizationSecondsallows more: an option with a longermaxTimeoutSecondsalso fails withpayment_simulation_failedbefore anything is signed. - The budget reserves the cap when the authorization is signed. The reported charge counts as spent at once,
and the rest of the cap stays pending until the chain proves the settlement; with the default
verify: "sync"that happens beforepayreturns (areleasedevent with reasonsettled_below_cap). A zero charge proven on chain returns the whole cap; a zero settled off chain returns it once the authorization expires unused.
upto scheme signs for the first pinned contract:
Search the Bazaar and pay a listing
minTrust, and its live payment requirements must pay the listing’s owner and cost no more than the
listed price (for HTTP resources and for MCP tools alike), otherwise the call is refused with listing_not_payable or
payment_listing_mismatch before anything is signed. list, listing and listingVersions read the catalog
without paying.
The binding authenticates the payee, not the endpoint: money can only go to the listing’s owner, but the
listing’s URL is whatever was cataloged for that owner. What vouches for the endpoint is the listing’s trust:
origin_verified means the endpoint’s own 402 names the owner, and domain_verified means the endpoint’s
host and the owner’s account name each other under SEP-1 (see Trust).
Quote without paying
Results, errors and idempotency
Every failure is aPaymentError with a stable code, a non-empty reason, retryable, details and
paid, which says whether money may have moved: none, not_settled, settled or unknown. retryable
says whether making the same call again, which signs a new payment, can succeed. For payment_rejected, both
follow the facilitator’s code the seller passed on (details.upstream.code): a refusal after which the payment
may still settle, such as settlement_pending, is paid: "unknown" and never retryable. The table is exported
as refusalOutcomes, and rail402-mcp and the CLI report the same values; see
refused payments. All codes are listed in the
error-code reference.
idempotencyKey, repeating a call never pays twice for as long as the buyer’s ledger keeps the key.
The key belongs to the payer on its network, not to a budget window: a retry after the window renewed or a
new session started still finds the earlier call. The payment identifier sent to the seller is chosen at
random the first time the key pays and kept with it, so it stays the same for the key and cannot be worked out
from it. The SQLite ledger keeps keys for good. The default in-memory ledger forgets them when the
process exits, and StorageSpendLedger drops a key with its window seven days after that window ended, once
all of the window’s payments are resolved on chain. A call still running is refused with
payment_in_progress. A key names one call: using it again for another URL or tool is refused
with payment_request_invalid and never answered with the other call’s result. For a call that finished, the retry first checks that
call’s own payment on chain if its outcome is still open, then:
- returns the stored result with
replayed: truewhen the call succeeded; - raises the stored error again while the payment’s outcome is still open;
- raises
payment_resource_failedwithpaid: "settled"and the receipt when the chain shows the payment was consumed but no response was received; - pays again with the same key only when the chain shows the authorization expired without being used (no money moved);
- raises
payment_settlement_unconfirmedwhen the payment’s ledgers are older than the RPC keeps. The payment counts as spent; use a new key to pay again.
status is unknown means the payment was sent but no settlement was confirmed. Its amount
stays pending in the budget until the chain proves it settled or its authorization expires unused. The
spending policy explains how payments are proven.
buyer.inspectTransaction(hash) reads a transaction over RPC and reports its fee sponsor, authorizations,
token transfers, whether it has the shape of an x402 payment and, with facilitatorUrl set, whether its fee
source is one of that facilitator’s advertised signers. Its shape checks say an exact payer authorized
the transfer only when the chain proves it: the token is a Stellar Asset Contract, which requires that
authorization, or the payer’s own key signed the entry. Otherwise they call it an authorization entry
that the chain does not prove: a token that is not a Stellar Asset Contract can succeed without checking
it.
Explorer links
Receipts carryexplorerUrl, built by explorerUrl(network, hash, provider); explorerAccountUrl(network, address, provider) links a G… account or C… contract. The explorer option selects the provider:
A receipt’s link carries the hash the facilitator’s settle response returns: for a sponsored payment, the
fee bump’s outer hash. The Rail402 Explorer opens a payment by that hash (and by its inner hash), and a
payment it has not indexed yet is looked up live, so the link works as soon as the receipt arrives.
Every provider, whether passed in code or read from the environment, is checked when the buyer is created:
templates and
rail402BaseUrl must be https without credentials, and any other value is refused
(payment_policy_invalid).
Budget, sessions and ledgers
Each payment reserves its amount in a budget window before it is signed. The decision and the reservation happen in one synchronous step, so concurrent calls can never jointly exceed a cap.buyer.budget() returns
what each asset has spent, holds pending and has left. The default window is named default and lasts 24
hours. On testnet it renews when it ends; on pubnet it does not, and paying after it ends is
payment_session_expired until a new session starts. session: { name, ttlMs, autoRenew } changes this.
The default ledger is in memory. To share one budget between processes, such as several agents paying from
one key, use the SQLite ledger (its directory is created with mode 0700 and the file with 0600). The CLI
and the MCP server use the same file by default, so they share one budget per key and session. Every process
that shares a ledger must run the same version: an earlier version refuses a ledger a later one has opened
(payment_ledger_unavailable), since it would check idempotency keys differently. A process that already had
the ledger open keeps its own rules until it stops, so restart running processes (such as rail402-mcp) after
upgrading:
@rail402.dev/safe-fetch; see Outbound requests.
Events
onEvent receives one event per step (probe, quote, reserved, signed, sent, settled,
unresolved, released, refused, window). Events carry call ids, codes, amounts and transaction hashes,
never keys, signatures or signed payloads; see Secret handling.
In a browser
@rail402.dev/sdk/browser is the same buyer for pages and other runtimes without Node: the spending policy,
the signing guard, the budget ledgers, discovery, the payment flows and the on-chain checks, with no Node
module in its import graph (a test bundles it for the browser and fails on any Node built-in). It leaves out
the seller helpers, configuration loading and the SQLite ledger.
The
./browser entry is in @rail402.dev/sdk from version 0.4.0 on.seller carries probes and paid calls and must keep the SafeFetch contract of
@rail402.dev/safe-fetch/shared (refuse what its policy forbids with an EgressError, and record each
answer with markFinalRequest); operator reads the Bazaar and the facilitator’s /supported:
StorageSpendLedger keeps the budget in any synchronous key-value store, such as localStorage, so a reload
keeps what was spent and held; a stored ledger that cannot be read is refused with payment_ledger_unavailable
until reset(). The Playground is built on this entry, with a same-origin relay
as its seller transport. On pubnet the same rules as createBuyer apply: an https RPC, and a seller transport
whose policy allows https only and no private network (payment_policy_invalid).
Discovery only
@rail402.dev/sdk/discovery reads the Bazaar without being able to pay: DiscoveryClient, toHit (a
discovery item as a search hit, judged against a spending policy), resolvePolicy, amounts, networks,
redaction and the error codes. Nothing in its import graph loads a key, signs, reserves budget or runs a
payment flow, so a process that imports only this entry cannot pay. The
hosted discovery MCP is built on it. Besides search, list, listing and
versions, DiscoveryClient reads usage on its network: settlements(hashes)
(the listing each settlement paid for), usage(id) and sellerUsage(payTo).
Configure it like the CLI
resolveAgentConfig(process.env) reads the same RAIL402_* variables as the CLI and the
MCP server, and egressFromConfig(config) turns the development switches into an egress
policy. examples/sdk-buyer in the repository uses them to pay by URL and then by search in about 40 lines.