isValid: false (/verify) or success: false (/settle), a code from
packages/stellar/src/codes.ts and a non-empty human-readable reason
(packages/facilitator/test/state.test.ts, “wire responses always carry a registered code and a
non-empty reason”). /settle never relies on an earlier /verify: it runs stages 1–5 again, and
upstream settlement runs stage 6 again before anything is signed or broadcast (see stage 8).
Rail402 does not reimplement verification. Its own checks (stages 1–5) run first, before any
simulation, so a payment that cannot settle is refused cheaply and with a specific code. The only
RPC data they use is the latest ledger number: /verify answers from a reading up to 5 seconds old
and refreshes it in the background, while /settle waits for a reading no older than 1 second
(packages/stellar/src/ledger-clock.ts, tested in ledger-clock.test.ts). The unmodified
@x402/stellar verifier (stage 6) then runs every check of the exact Stellar scheme, including
simulation. Rail402 only adds a diagnosis of why a simulation failed (stage 7) and makes settlement
idempotent and crash-safe (stage 8).
Configuration problems are not rejections: the service stops at startup with the codes in
Startup checks, and an in-process facilitator throws
FacilitatorSetupError with the codes in In-process facilitator
(for example config_pubnet_assets_missing when pubnet has no explicit accepted assets).
Test files, relative to the repository root:
Integration tests run against a private Stellar network (
docker compose --profile stellar up)
with real accounts, a real token contract and real balance changes.
0. Request
apps/rail402/src/app.ts, before any payment logic.
In this order:
1. Protocol envelope
preflight() in packages/facilitator/src/preflight.ts.
2. Operator policy on the requirements
checkRequirements() in packages/facilitator/src/preflight.ts. Limits come from configuration
(Configuration), never from the request.
A transfer to a muxed
M… address credits its base G… account, and its CAP-67 transfer event names that
base account with { amount, to_muxed_id } as data. The @x402/stellar exact verifier matches the event’s
recipient and amount against payTo literally, so such a payment can never verify; Rail402 refuses a muxed
payTo before any RPC call instead of failing in simulation; sellers put the base G… account in payTo
(preflight, muxed integration test).
3. Transaction structure
inspectExactTransaction() in packages/stellar/src/payload.ts. payload.transaction is taken
verbatim; nothing in it is rewritten.
4. Accounts and amounts
preflight(). The facilitator’s accounts are the sponsor and every channel account.
5. Authorization and expiry
preflight().
6. Upstream verifier
ExactStellarScheme.verify from @x402/stellar 2.30.0, unmodified, called by
packages/facilitator/src/scheme.ts. It simulates the transaction against the current ledger in
enforcing mode, which verifies the payer’s signature and runs a smart account’s __check_auth, and
then checks the simulated result. Its fee ceiling is checked at the inclusion-fee bid settlement
would use: a percentile of the network’s recent fee stats, reused for 5 seconds and answered stale
for up to 60 seconds while it is refreshed in the background (packages/facilitator/src/fees.ts,
tested in fees.test.ts). Its codes, which Rail402 returns unchanged:
These are covered by upstream’s own tests (
typescript/packages/mechanisms/stellar/test in
x402-foundation/x402), and on Rail402 by the settlement tests (every settlement passes through
them) and the upstream e2e run. Tampering is caught here: changing the amount after signing fails
simulation because the signature no longer verifies (settlement, “rejects tampering”).
7. Why a simulation failed
Upstream reports every failed simulation asinvalid_exact_stellar_payload_simulation_failed.
Rail402 re-simulates in enforcing mode and names the on-chain cause from the host’s diagnostic
events (explainSimulation() in packages/facilitator/src/explain.ts,
classifyTransferFailure() in packages/stellar/src/diagnostics.ts). The same mapping names the
cause of a settlement transaction that was included but failed.
Error numbers belong to the contract that raises them, so the SAC rows apply only to a Stellar Asset
Contract. The facilitator learns each accepted token’s kind from its contract instance (the service reads
it at startup). A custom SEP-41 token’s error
#N is reported as
invalid_exact_stellar_payload_token_rejected with the reason “The token contract rejected the transfer
with error #N.”, unless a read-only balance(from) shows the payer holds less than the amount, which is
insufficient_funds. A token whose kind cannot be read is treated as a custom one.
Failed account authentication is decided before the token’s errors. The host authenticates a G… payer
in the token’s frame: a key that is not the account’s signer, too little weight or no signature raises
Error(Contract, #5) there, followed by “failed account authentication”. That #5 is not the token’s own
error, so the payment is invalid_exact_stellar_payload_invalid_signature (for a C… payer,
invalid_exact_stellar_payload_smart_account_rejected) whatever the token’s kind. A payer account that does
not exist fails authentication on reading its own account entry and is
invalid_exact_stellar_payload_account_missing, also whatever the token’s kind.
Anything unrecognised keeps upstream’s invalid_exact_stellar_payload_simulation_failed.
A failure that names no fault of the payment is not a refusal of it: when the RPC fails the simulation
without running the host (its error carries no diagnostic event and no host error such as
Error(Contract, #10), for example an RPC whose ledger snapshot is incomplete under load), when the
re-simulation passes, or when the RPC cannot be asked again, /verify answers unexpected_verify_error
and /settle unexpected_settle_error, both retryable, with a reason saying the payment was not judged.
The upstream exact verifier builds its own RPC client, which has no call timeout, so /verify stops
waiting for it after the RPC timeout (10 seconds) and answers unexpected_verify_error too (tested by
verify-timeout).
Nothing was signed or submitted, so the same payment may be sent again. upto follows the same rule
(simulationRanOnHost() in packages/facilitator/src/explain.ts; tested by explain, settlement and
upto-facilitator).
8. Settlement
StellarExactScheme.settle() in packages/facilitator/src/scheme.ts first decodes the payload and
looks its authorization (network, payer, nonce) up in the settlement ledger. A request whose
settlement was already submitted is answered from the ledger before anything else is decided, so a
repeat gets the recorded result however late it arrives, even after the authorization expired or
while the sponsor guard refuses new settlements. Otherwise it runs stages 1–5 again. Then
SettlementEngine.settle() in packages/facilitator/src/engine.ts admits the settlement through the
sponsor guard, claims the authorization and leases a channel account. Upstream’s
ExactStellarScheme.settle runs stage 6 again, and a rejection there is diagnosed as in stage 7;
otherwise it settles the payment with the leased channel account as the transaction source and the
sponsor paying the fee through a fee bump. The facilitator is never
the source of the transferred funds (settlement, “payer debited, payTo credited, facilitator only
pays the fee”).
A repeat is the same request when its fingerprint matches: SHA-256 over the canonical JSON of the
scheme, network, asset, payTo, the settle-time amount and the signed transaction
(packages/facilitator/src/fingerprint.ts). Settlements recorded before fingerprints existed compare
the signed transaction alone. Rejections decided before anything is signed (stages 1–7, the sponsor
guard, settle_exact_stellar_channel_unavailable) leave no record, so the same payment can be retried
once the cause is fixed, for example after payTo adds a trustline.
settle_exact_stellar_transaction_submission_retryable is the code @x402/stellar gives a network
answer of TRY_AGAIN_LATER. It is registered but never returned: the engine treats that answer as bytes
the network does not hold yet and broadcasts the recorded bytes again.
Only the recorded bytes are ever resubmitted, so a lost response or a restart can never produce a
second transaction for the same authorization (settlement, “recovers after a lost submission
response”; crash recovery, which kills the service process at each step). After the time bound,
“not found” for the transaction’s own hash proves nothing by itself: its inner hash is looked up too (in
case someone wrapped it in their own fee bump), and the payer’s authorization nonce is read. Both reads
count as proof of absence only from an RPC at or past the ledger at which the bounds were seen to pass;
one from an RPC behind it (lagging, or another provider after a failover) leaves the settlement waiting
for a later read. A consumed nonce finishes the settlement only once the transaction that consumed it
is identified on chain. When neither landing nor absence can be proven (the RPC no longer retains the
ledgers since the claim, or the nonce was consumed by a transaction that cannot be identified), the
settlement stays unfinished and is reported as unresolvable instead of expired (see State, backups and
recovery).
Repeats are marked. A settle response answered from an earlier settlement carries
{"rail402":{"settlement":{"repeat":true,"settledBy":"rail402"}}} in the EXTENSION-RESPONSES
header, next to any bazaar outcome, and the body is the recorded response unchanged. The stock
HTTPFacilitatorClient exposes it as extensionResponses.rail402, and resource servers never forward
it to the buyer. A seller that must serve each payment once can refuse a request whose settlement is a
repeat. Repeats are counted in rail402_settlement_repeats_total, not in rail402_settlements_total,
and metered as repeat (see Operations).
Front-running. A settlement transaction carries the payer’s signed authorization, and anyone
who sees it before it lands can copy that authorization entry into a transaction of their own. If
the copy lands first, the payment still happens exactly as the payer signed it, and Rail402’s own
transaction then fails on the consumed nonce. Rail402 answers such a payment as settled, with the
other transaction’s hash, only when the chain proves it (packages/facilitator/src/third-party.ts):
- the payer’s nonce entry exists, and the ledger that consumed it closed no earlier than the settle request was claimed, so the authorization was not spent before Rail402 was asked;
- a successful transaction in that ledger carries an address-credential authorization entry for the payer with the same nonce and expiration ledger and a byte-equal root invocation;
- that transaction emitted the matching
transferevent from the asset contract.
exact, with any other cause, which leaves the authorization
usable until it expires (the failure rolls back, nonce included). Anything short of all three keeps the
failure, except that such a failure waits while the nonce reads unused at a ledger up to the
authorization’s expiration.
The settlement is recorded with settled_by = third_party; the response
is success with the other transaction’s hash, repeats return it with
"settledBy":"third_party" in the repeat marker, and the fee of Rail402’s failed transaction is
counted as wasted. Set RECONCILE_THIRD_PARTY_SETTLEMENTS=false to answer the failure instead.
A failure is kept only on reads from an RPC that has reached the ledger Rail402’s transaction failed
in (the nonce was consumed by then, if at all) and, for the scan, holds the ledger that consumed the
nonce. A read from an RPC behind those ledgers (lagging, or another provider after a failover), an RPC
whose history starts after the consuming ledger, or a read error, finishes nothing: the settlement
stays submitted, and the next look reads the failure again and searches with fresh reads. One that
stays undecided for a minute is reported as unresolvable (see State, backups and
recovery). Soroban keeps a consumed nonce’s entry until the
later of the authorization’s expiration and the consuming ledger plus the network’s minimum temporary
entry lifetime (currently 17,280 ledgers, about a day, on pubnet; 720, about an hour, on testnet). A
failure on the used nonce whose nonce then reads unused at or past the ledger it failed in can only
mean that the entry lapsed: the settlement is left unresolved and reported, never kept as failed. A
failure without diagnostics, or on an expired authorization, searched only after the entry lapsed finds
no consumption and is kept.
Verify reads the ledger. After stages 1–5,
/verify looks the authorization up, read-only, so an
authorization that is being settled, or was, is never reported as valid:
If the ledger cannot be read, the check is skipped and counted in
rail402_settlement_ledger_read_failures_total; verification stays available and the network’s own
nonce check still refuses a spent authorization.
upto payments
An upto payment carries one signed Soroban authorization entry instead of a transaction (see
upto payments). Rail402 checks it in the same spirit as exact: everything that
can be decided without the network first, then an enforcing simulation of the settlement itself, then
settlement through the same engine. /verify checks the payment for its cap; /settle checks it
again for the amount being settled. The static rules are checkUptoPayment() in
packages/upto/src/facilitator/rules.ts and inspectUptoAuthorization() in
packages/upto/src/authorization.ts, run by uptoPreflight() in
packages/facilitator/src/upto-preflight.ts; the simulation rules are in
packages/upto/src/facilitator/simulation.ts; StellarUptoScheme in
packages/facilitator/src/upto-scheme.ts puts them in order.
U1. Envelope and operator policy
U2. Requirements (rule 2)
U3. The authorization entry (rules 3–4)
U4. The signed terms (rules 5–6)
U5. Expiration, payer and delegated signers (rules 7–9)
too_far and not_yet_valid can be caused by a ledger reading a few seconds old, so /verify decides
them again on a fresh reading before refusing (upto-scheme).
U6. Readiness and the settlement ledger
U7. Simulation (rules 10–12)
The facilitator builds the settlement exactly as it would submit it,settle(payer, terms, amount)
with the settlement authority as the operation source and its source-account authorization, and
simulates it in enforcing mode for the phase’s amount: the cap at /verify, the amount at /settle.
The payer’s signature, a smart account’s __check_auth and the token’s balance and trustline rules
all run. A failure is named from the host’s diagnostic events; contract error numbers are attributed
to the contract that raised them, because the settlement contract and a Stellar Asset Contract share
numbers.
U8. Settlement
StellarUptoScheme.settle() first looks the authorization (network, payer, nonce) up in the settlement
ledger, as exact does, and the same engine settles it (stage 8): sponsor guard, claim, channel lease,
envelope recorded before broadcast, confirmation from the recorded bytes, crash recovery and
reconciliation. The transaction’s source is the leased channel, the settlement operation’s source is
the settlement authority, and the sponsor pays through a fee bump; its ledger bounds end at
expiration_ledger + 1. The fingerprint of an upto request covers the scheme, network, asset,
payTo, the authorization, any signer entries and the settle amount
(packages/facilitator/src/fingerprint.ts).
A refusal of Rail402’s own fee bump (for example once the sponsor key is frozen) does not stop anyone
else from wrapping the inner transaction in a fee bump of their own once a send the network may have
accepted exposed it. Such a settlement keeps waiting until no later ledger can include that transaction
(the ledger read is the last one its ledger bound admits, or one closed after its time bound). Then
the same reads decide: settled through the other fee bump if it landed there, otherwise refused or, once
the bounds have passed,
settle_upto_stellar_transaction_expired, with no funds moved. A settlement
whose sends were all refused finishes at once.
On-chain, independently of these checks: only the settlement authority can settle (a different
submitter fails in the host’s authorization check), the contract refuses an amount over the cap with
#3, and a second use of one authorization fails on the payer’s nonce (contract, upto-tamper,
upto-replicas).
Test files of the upto rules:
Expiration
A payment’s authorization is valid on-chain up to and including itssignatureExpirationLedger:
the network refuses it only once the current ledger is past that number. Two bounds decide which
expiration ledgers Rail402 accepts, one from upstream and one of its own.
Where the expiration comes from. The stock client (@x402/stellar’s ExactStellarScheme
client) signs with
latest is the RPC’s latest ledger and est is the average close time of the 20 most recent
ledgers on public Horizon (horizon-testnet.stellar.org for stellar:testnet,
horizon.stellar.org for stellar:pubnet), rounded up. If Horizon cannot be read, est is 5
seconds. With 5-second ledgers, maxTimeoutSeconds: 60 gives latest + 12 and 300 gives
latest + 60. Accepted maxTimeoutSeconds values are TIMEOUT_MIN_SECONDS–TIMEOUT_MAX_SECONDS
(10–300 by default); anything else is invalid_exact_stellar_requirements_timeout_out_of_range.
Upper bound (upstream). The upstream verifier computes maxLedger with the same formula at
verify time and refuses signatureExpirationLedger > maxLedger + 2 with
invalid_exact_stellar_signature_expiration_too_far. The two ledgers of tolerance absorb a ledger
closing between the client’s reading and the facilitator’s. Rail402 keeps this check as upstream
defines it and adds no upper bound of its own.
Lower bound (Rail402). With current the latest ledger Rail402 has read (stage 5):
The margin (
EXPIRATION_MARGIN_LEDGERS, 1 by default, 1 to 100) keeps the sponsor from paying for a
settlement that would land after the authorization expired: an authorization that expires at the
current ledger is still valid on the network, but a settlement submitted now lands in a later ledger.
A margin of 0 is refused at startup.
After submission. The settlement transaction’s time bound is maxTimeoutSeconds from when it is
built, and it can outlive the authorization. If the authorization expires after the transaction is
submitted but before it is included, the transaction fails on-chain with
invalid_exact_stellar_signature_expired, and the fee the sponsor paid is counted in
rail402_sponsor_fees_stroops_total{outcome="wasted"}. The host checks the expiration before the nonce,
so a copy of the authorization that someone else landed before the expiration fails Rail402’s
transaction the same way: the failure is searched like a front-run (see “Front-running” above), and a
payment that settled through the copy is answered as settled, with the copy’s hash. Otherwise the
response is the expiry with the transaction hash, the settlement is recorded as failed, and no funds
move. A later repeat of a payment that did settle returns the original success, however long after its
expiration it arrives (stage 8).
upto. An upto authorization carries its expiration twice: in the signed terms
(expiration_ledger) and in the credential (signatureExpirationLedger); the two must be equal
(invalid_upto_stellar_payload_expiration_mismatch). The upto client derives it with the same
formula, from its own ledger-time estimate. Rail402 checks the window itself, with the upto codes:
est is the network’s seconds per ledger: UPTO_LEDGER_SECONDS when set (at least 1), otherwise the
average close time over the ledgers the network’s own RPC retains, read at most once a minute (5 s while
the RPC cannot tell), and never less than 1 second. The in-process facilitator uses the same default for upto.ledgerSeconds; no other
service is asked. Capping est at the nominal 5 seconds means a client that assumed 5-second ledgers
on a slower network is never refused as too far.
One thing differs after submission: the settlement transaction’s ledger bounds end at
expiration_ledger + 1, so a transaction held past the authorization’s expiration is refused by the
network before inclusion (txTooLate) and the sponsor pays no fee. Rail402 finishes it as
settle_upto_stellar_transaction_expired once the ledger bound has passed and the payer’s nonce,
read at a ledger no later than expiration_ledger, shows that nothing carried the authorization.
Codes that are defined but not emitted
Kept so the code list matches the x402 specification and upstream, and so a response relayed from another component is still recognised:packages/stellar/test/codes.test.ts fails if an exact or upto code is added without being listed in
this document.
Bazaar cataloging
Cataloging runs after a successful settlement (and is previewed at/verify, which waits at most
250 ms for it) and never affects the payment. Its outcome is reported to the seller in the
EXTENSION-RESPONSES header, which never exceeds 4,096 bytes: reasons are cut to 300 characters and
an outcome too large for the budget is reduced to its status and code. Codes are in
packages/bazaar/src/codes.ts.
Discovery requests: a malformed or unknown query parameter returns
discovery_invalid_parameter
an unknown listing discovery_listing_not_found, and the usage of a listing whose seller keeps it
private, or whose content no origin confirmed (trust settled, such as an mcp:// tool),
discovery_usage_private (bazaar). A settlement whose payload declares rail402-private-usage makes the
listing’s usage private at once; only the listing’s origin can remove the declaration. A client over its discovery cost budget
(SEARCH_RATE_LIMIT_PER_MINUTE; uncached searches, deep offsets and long version-history pages cost more) receives 429
rate_limited with Retry-After (discovery). Discovery beyond what the service admits at once
(DISCOVERY_MAX_IN_FLIGHT requests served, DISCOVERY_QUEUE_LENGTH waiting, each for at most
DISCOVERY_QUEUE_TIMEOUT_MS), or a catalog read that gets no connection of the discovery pool within
DISCOVERY_DATABASE_ACQUIRE_TIMEOUT_MS or runs past its statement timeout, receives 503
discovery_overloaded with Retry-After: 1; a catalog database that cannot be reached receives 503
discovery_catalog_unavailable with Retry-After: 1 (discovery). Neither is ever a 500.
Response shapes
Verification and settlement outcomes are HTTP 200 with the x402 response body:/verify and /settle (stage 0) keep that shape, so the stock client
raises a typed VerifyError or SettleError, and add an error object. Every other endpoint returns
only the error object:
Transport codes
Defined inpackages/errors/src/index.ts, shared by every endpoint.
method_not_allowed (405) is defined but not currently returned.
Search codes
Defined inpackages/search/src/service.ts, returned by GET /discovery/search with HTTP 400.
Buyer safety on pubnet (client side)
Raised by the SDK, the rail402 command line and rail402-mcp before anything is signed; never returned by the service. Each carriespaid: "none". Defined in packages/sdk/src/codes.ts.
An MCP endpoint whose raw text carries control, line-break or bidirectional characters is refused with
egress_url_invalid before anything is signed (tested in packages/sdk/test/mcp-flow.test.ts), so the
resource a confirmation shows is the address that is called.
payment_session_expired (existing) is what a pubnet agent meets once its default window ends, since that
window does not renew unless RAIL402_SESSION_AUTO_RENEW=true or autoRenew: true.
A confirm function that throws a PaymentError is reported as a refused payment event with that code; any
other error it throws (rail402-mcp’s signal to ask the user first) reaches the caller without one.
MCP server refusals
Returned by rail402-mcp as a JSON-RPC error whosedata carries { code, reason, retryable, paid }, for a
request that never reaches a tool; nothing is paid (paid: "none"). Defined in rpcCodes (packages/mcp/src/codes.ts).
Explorer codes
Defined inapps/explorer/src/api/codes.ts (explorerCodes), returned by the Explorer’s read API as
{ error: { code, reason, retryable } } and shown on its error pages. The Explorer only reads public
ledgers; none of these concern a payment. The full table, with each code’s status and reason, is on the
Explorer read API page and the error-code reference. Tested in
apps/explorer/test/api.test.ts, apps/explorer/test/pages.test.ts and
apps/explorer/test/live-lookup.test.ts.