Introducing a new way to review your PRs.

Read the announcement

solana-foundation / pay

CLI for Agentic payments (x402, MPP, AP2).

View on GitHub

30 documents · Updated Nov 11, 2026

docs / runtime-client-payment-flows

Runtime client payment flows

The runtime client turns a wallet and an HTTP payment challenge into an approved request. It supports authentication, balance-aware payments, sends, fetch and wrapped command calls, one-time and metered access, subscriptions, sandbox use, and receipts. Read it with Rust payment runtime, runtime payment gateway, remote wallet providers, runtime session channels and metering, runtime API and workers, runtime benchmark harness, cloud payment onboarding, and HTTP payment proxy.

Client boundary

The client is the shared boundary between command or agent callers and payment-aware network requests. It resolves a wallet, checks the server terms, asks for approval, creates a protocol credential, retries the request, and reports the result. It does not own the gateway that verifies or settles the payment.

The main actors have distinct roles:

  • The caller chooses the request and can force a protocol or network.
  • The client reads the server offer and selects a supported payment path.
  • The signer supplies wallet proof after the approval policy allows it.
  • The server verifies the proof and returns the resource or a payment result.

Account and signer access

An account is a named wallet on a network. The client uses an explicit account when one is given. Otherwise it uses the active account for the selected network. Mainnet needs a configured wallet. A local or sandbox request can use a new ephemeral wallet for test funds.

This boundary keeps wallet storage separate from payment logic. A local store or remote wallet provider can supply the secret. Payment flows only need a signer and its public key. Network selection stays tied to wallet lookup so a request cannot silently sign on another ledger.

References: rust/…/mpp.rs• L87-113 rust/…/mpp.rs• L166-177 rust/…/x402.rs• L142-168 rust/…/x402.rs• L214-237

Balance and currency state

The client reads native SOL from the Solana network and stablecoin balances from the pay-api service. SOL covers network fees and native wallet state. Stablecoin balances show which payment offer or send currency the wallet can fund. The same balance view can include committable channel funds and program-backed credits, but those values remain separate from wallet token balances.

The pay-api result is the normal source for token, credit, and channel data. If pay-api is unavailable, direct RPC can recover known token holdings. That fallback is suitable for display, but payment builders use only spendable associated-token balances. An unavailable stablecoin lookup is not the same as a zero balance. Payment selection can use the cheapest usable compatibility option when the service cannot answer, but callers must not show unavailable data as proof that the wallet has no funds.

References: rust/…/balance.rs• L93-109 rust/…/balance.rs• L221-283 rust/…/balance.rs• L355-404 rust/…/balance.rs• L496-562 rust/…/mpp.rs• L397-461 rust/…/mpp.rs• L486-590

Approval prompts

Each payment path creates an approval intent with the amount and reason for the action. A local account can use a platform approval prompt. An MCP host can route the same decision through its own approval surface. Channel escrow has a distinct intent so the approval describes the amount placed into the channel.

File access has a separate approval boundary in callers that send local files. The file must be approved before the client reads its bytes. A later payment prompt approves the payment, not a new version of the file.

References: rust/…/mpp.rs• L119-184 rust/…/x402.rs• L245-260 rust/…/x402.rs• L489-509 rust/…/session.rs• L381-402

Reusable access credentials

Subscription activation creates a reusable access proof for the activated resource. The client stores it with the active subscription and can attach it to later requests until the proof or subscription expires. The older authenticate path remains for older servers and saved account records.

Cached access is usable only for the selected account and network. The stored delegation must belong to that account, and the URL must be the exact resource or a bounded path below it. A host name that only shares a text prefix is not a valid match. A canonical subscription proof can remain usable without a legacy authenticate expiry when the subscription itself is active.

References: rust/…/authenticate.rs• L31-48 rust/…/authenticate.rs• L50-115 rust/…/authenticate.rs• L148-287 rust/…/runner.rs• L383-405

Request lifecycle

Payment-aware requests follow one common cycle. The client first sends the user's request. A normal response ends the cycle. A 402 Payment Required response pauses it while the client checks the offer and obtains approval.

The diagram shows the shared path from an API request to a normal result or a signed retry.

flowchart TD
    A[Build request] --> B[Send request]
    B -->|not 402| C[Return response and headers]
    B -->|402| D[Decode all payment offers]
    D --> E[Select supported protocol and network]
    E --> F[Resolve wallet and approval]
    F --> G[Build credential]
    G --> H[Retry the same request]
    H -->|success| I[Return result and receipt]
    H -->|rejection or second 402| J[Return payment error]

Request preparation

The built-in fetch path accepts a method, headers, and an owned request body that can be reused for the paid retry. It supports text, files, and multipart data. The raw response keeps status, headers, and body bytes together so callers can inspect payment metadata and return binary resources without changing the data.

Request bodies are captured as owned snapshots before the request starts. This lets the client send the same bytes again after approval and prevents a retry from rereading a changed file. File sources must be regular non-symlink files and multipart bodies stay within the client size limit.

The normal fetch path follows redirects. A caller can disable forwarding for a body-bearing request so the body stays bound to its original URL. In that mode, a redirect returns guidance to use the final Location URL. A payment challenge uses the effective response URL after redirects, which keeps the resource scope tied to the resource that issued the challenge.

The curl, wget, and HTTPie wrappers preserve the normal behavior of their underlying tools while capturing enough response data to detect a payment challenge. Before credentials are attached, curl and wget must describe one transfer and pass the cached request rules. They can attach a cached subscription proof before the first request when the user has not supplied an authorization header. HTTPie shorthand URLs are expanded before this lookup so the proof is matched to the URL that will be called.

References: rust/…/fetch.rs• L228-261 rust/…/fetch.rs• L525-583 rust/…/fetch.rs• L613-682 rust/…/fetch.rs• L795-922 rust/…/runner.rs• L154-205 rust/…/runner.rs• L383-439 rust/…/runner.rs• L1492-1610 rust/…/runner.rs• L1702-1758

Hosted outbound access

Hosted curl uses a public-internet-only policy to keep payment-aware requests away from local and cloud-internal targets. It validates the destination and request headers before connecting. It also filters DNS answers and checks each followed redirect, bypasses ambient proxy settings and the local debugger proxy, and limits the response body to 64 MiB.

This policy protects the hosted caller without changing the normal payment challenge and response path. Public destinations can still return payment challenges, raw response headers, binary bodies, and settlement data through the same client boundary.

References: rust/…/fetch.rs• L29-40 rust/…/fetch.rs• L107-195 rust/…/fetch.rs• L633-647 rust/…/fetch.rs• L804-913

Challenge classification

The runner converts a 402 into a typed payment outcome. It decodes all advertised offers for diagnostics, then chooses the most suitable Solana path for the caller. Specific and stateful intents take priority over a generic one-time charge.

Server offerClient meaning
MPP chargeOne signed payment and retry
MPP sessionOpen a payment channel for repeated calls
MPP subscriptionActivate recurring access and save its proof
x402 exactMake the exact payment and retry
x402 uptoOpen a ceiling-based channel for later settlement
x402 batch-settlementReuse escrow and send cumulative vouchers
x402 sign-inSign in to use existing access or fall back to payment
Unknown offerReturn an unsupported-payment error

The caller can force MPP or x402. A forced protocol that is not available becomes an explicit error instead of a silent fallback. A response that reports verification_failed or session_failed is treated as a rejection of the previous credential, so the client does not start another automatic payment loop.

References: rust/…/runner.rs• L11-151 rust/…/runner.rs• L925-1088 rust/…/runner.rs• L1100-1385

Payment selection

MPP and x402 offers can appear in the same response. When wallet balances are available, the client compares advertised currencies and costs across MPP charge, x402 exact, and x402 upto choices. It chooses the cheapest payable option, with MPP charge preferred over x402 upto and x402 exact when costs tie. If the wallet is missing or balance lookup fails, it keeps the cheapest usable MPP charge as a compatibility fallback. If balances are known and no offer is fundable, it rejects the payment before signing.

Signer capability also affects selection. An operator session proof, x402 sign-in, and batch voucher need a raw message signature. A transaction-only wallet skips those offers when another payment offer exists. Charges, x402 exact payments, and client-signed sessions remain available to that wallet.

References: rust/…/mpp.rs• L397-461 rust/…/mpp.rs• L463-590 rust/…/runner.rs• L702-904

Payment retries

After approval, the client adds the protocol credential to the original request and sends it again. It keeps the same method, destination, headers, and body. A successful retry returns the result and response headers. A verifier rejection or another payment challenge ends the flow with an error.

The client can check cached API request rules before signing when catalog data exists. This prevents an invalid request from consuming an approval or payment.

References: rust/…/runner.rs• L180-205 rust/…/runner.rs• L407-439 rust/…/runner.rs• L1702-1758

Logical payment attempts

A logical payment attempt identifies one request by its method, URL, and body. While the result is unknown, the client reuses the same signed payment material for the same payer, network, and offer. This protects a retry after a timeout or lost response from creating a second transfer or channel.

The same attempt state covers MPP charge credentials, x402 v2 payment identifiers, x402 upto headers, and session-open salts. Concurrent builders use one in-flight result. A definitive response clears the material, while a failed build leaves no cached credential.

References: rust/…/attempt.rs• L21-33 rust/…/attempt.rs• L46-93 rust/…/attempt.rs• L96-193 rust/…/mpp.rs• L296-355 rust/…/session.rs• L332-355 rust/…/x402.rs• L184-195 rust/…/x402.rs• L781-850

Payment methods

The client supports several payment shapes because a provider may charge once, meter use, or grant recurring access. They share wallet resolution, network checks, approval, and retry rules. They differ in what the credential authorizes and when settlement occurs.

Stablecoin sends

The send flow moves a selected stablecoin to a validated recipient through pay-api. The currency carries both its display symbol and mint, so the request can use remote stablecoin definitions when available and local definitions as a fallback. A max or * amount reads the sender's spendable balance first and turns it into an exact request amount.

A successful transfer returns a settlement reference and the recipient amount, total charge, and fee refund when the challenge provides them. If pay-api returns a payment challenge, the client selects a fundable MPP charge, signs it, retries the transfer, and reports the resulting signature. A confidential send marks the request for the separate confidential-transfer challenge and settlement path.

References: rust/…/send.rs• L43-83 rust/…/send.rs• L131-275 rust/…/send.rs• L311-357 rust/…/mpp.rs• L397-461

MPP charge payments

MPP, the Machine Payments Protocol, expresses a one-time payment as a server challenge. The client decodes the amount, currency, and network. It checks any forced network before it loads the wallet. It then builds a signed credential and retries the request.

When the server offers several stablecoins, the client maps each currency to a mint and compares it with wallet balances. A sandbox challenge can also trigger test funding before selection or signing so the wallet and server use the same local ledger. If the paid retry has no definitive result, the attempt cache resends the same charge credential instead of signing a new transfer.

References: rust/…/mpp.rs• L21-76 rust/…/mpp.rs• L117-226 rust/…/mpp.rs• L397-461 rust/…/attempt.rs• L46-193

x402 payments

x402 is an alternative HTTP payment protocol. The client reads an exact offer and builds the payment header for the version and wire data it parsed. It keeps the selected version tied to the header or body that supplied the offer.

For x402 v2, the retry echoes the server extensions. If the server requires a payment identifier, the client adds one that stays stable for the unresolved logical request. The client keeps version detection tied to the payload that supplied the parsed offer, so it does not build a wire format from a different response field. Sign-in-with-x can appear with payment in the same challenge, so the client can send both proofs when the server asks for both. A sign-in-only response uses a raw-message signature and can fall back to payment when sign-in does not grant access. The sign-in challenge is accepted only when its domain and URI match the resource origin.

References: rust/…/x402.rs• L31-133 rust/…/x402.rs• L141-178 rust/…/x402.rs• L184-396 rust/…/x402.rs• L1230-1285 rust/…/x402.rs• L1336-1409

Batch-settlement access

x402 batch settlement keeps one escrow channel open for many low-cost requests. A client-signed channel carries a cumulative voucher, while a server-authorized channel carries a bounded authorization that the server later settles. A channel opens or tops up only when its escrow cannot cover the next request. This reduces repeated funding while keeping each credential bound to the channel offer.

The process keeps channel state for the host lifetime and separates channels by their network, asset, receiver, fee payer, withdrawal delay, and signer mode. Public channel discovery can recover a channel after a process restart or a lost receipt. A resident signer can serve later requests only for an origin that already approved use of that escrow, so matching channel terms alone does not grant access to its funds. The local watermark and approved authorization budget advance only from verified settlement evidence. If a response has no settlement header, the client keeps the prior watermark and preserves the uncertain budget because transport failure does not prove that the server did not charge. A corrective response can resynchronize a verifiable watermark. An unverifiable correction leaves trusted state unchanged and requires a fresh channel.

The diagram shows how one channel turns repeated requests into confirmed cumulative charges.

flowchart TD
    A[Batch offer] --> B[Recover compatible channel]
    B --> C{Escrow covers request?}
    C -->|no| D[Open or top up escrow]
    C -->|yes| E[Sign voucher or authorization]
    D --> F[Retry with payment]
    E --> F
    F --> G{Verified settlement evidence?}
    G -->|yes| H[Advance watermark and budget]
    G -->|no header| I[Keep trusted state and budget]
    G -->|corrective 402| J[Verify corrective watermark]
    J -->|valid| H
    J -->|invalid| K[Require a fresh channel]

References: rust/…/batch.rs• L37-73 rust/…/batch.rs• L131-213 rust/…/batch.rs• L281-338 rust/…/batch.rs• L341-729 rust/…/x402.rs• L852-982 rust/…/x402.rs• L984-1203

Session access

An MPP session opens a pre-funded payment channel for repeated API calls. A client-signed session advances a cumulative voucher for each call. An operator-signed session sends a reusable payer proof while the operator measures use.

The session handle also supports top-up and close. A client close can settle a final increment or authenticate the current watermark without increasing it. Session scope uses the HTTP origin of the resource. The client rejects relative URLs, non-HTTP resources, and URLs with embedded credentials.

Agent runtimes use the operator-signed form and receive both the initial open authorization and the reusable use authorization. A wallet that cannot sign raw messages cannot use that form, but it can use a client-signed session when the challenge permits it. Concurrent client voucher requests sign the same next watermark until one accepted request records it.

References: rust/…/session.rs• L36-70 rust/…/session.rs• L111-212 rust/…/session.rs• L214-273 rust/…/session.rs• L277-356 rust/…/session.rs• L589-640 rust/…/session.rs• L680-697 rust/…/session.rs• L1301-1334

Subscription access

An MPP subscription creates recurring access from one activation request. The challenge states the plan, token, recipient, puller, cadence, and network. The client checks that the amount and cadence agree across the challenge before it asks for approval.

Activation creates both the on-chain authorization and a canonical reusable access proof. After the retry succeeds, the client saves the subscription under the account and network. A typed receipt supplies the subscription identity, delegation, period state, and activation reference. Renewals happen on the server and do not repeat this HTTP activation flow.

If a wrapper does not expose the receipt, the client can save a local record from the deterministic delegation identity. A later refresh can fill in a missing activation signature. The legacy authenticate challenge is still parsed for older servers, but current activation uses the canonical proof and does not require a second signing action.

References: rust/…/subscription.rs• L35-111 rust/…/subscription.rs• L113-209 rust/…/subscription.rs• L211-408 rust/…/subscription.rs• L410-510 rust/…/subscription.rs• L532-626 rust/…/authenticate.rs• L31-115

Receipt handling

A receipt records what the server accepted after a paid retry. The client keeps response headers so callers can decode MPP or x402 settlement data. Subscription activation uses typed receipt fields to create the durable local record.

Receipt availability depends on the caller. The built-in request path and curl-like paths can retain response headers and raw response bytes. When a wrapper does not expose a receipt, the subscription fallback uses the deterministic delegation identity and leaves signature reconciliation to refresh. Batch settlement treats missing evidence as uncertain state rather than confirmed spend.

References: rust/…/receipt.rs• L1-120 rust/…/fetch.rs• L535-583 rust/…/fetch.rs• L753-766 rust/…/fetch.rs• L1488-1508 rust/…/subscription.rs• L410-510 rust/…/batch.rs• L515-643

Sandbox execution

Sandbox mode runs payment flows against a Surfpool-backed local ledger instead of real funds. The client can create or use an ephemeral wallet and request test funds. A challenge can identify the sandbox through its network or a Surfpool blockhash.

The client checks a forced network before signing. It also routes the wallet, RPC calls, and funding to the ledger that issued the challenge. If automatic funding fails, signing may still succeed but the later broadcast can fail because the wallet has no funds.

MPP and x402 share the same sandbox signal. An explicit localnet or sandbox choice enables funding. Without a flag, a blockhash with the Surfpool prefix can identify the sandbox and select its RPC endpoint. A forced localnet request rejects a challenge whose network or blockhash does not match that intent.

References: rust/…/mpp.rs• L186-257 rust/…/mpp.rs• L741-830 rust/…/x402.rs• L184-243 rust/…/x402.rs• L286-357 rust/…/x402.rs• L418-455

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep challenge classification, protocol preference, signer capability checks, and retry handling aligned. A new offer must reach both the shared outcome model and the caller that builds its retry.
  • Keep network normalization aligned with account keys, RPC selection, and sandbox detection. A challenge network and the wallet lookup must name the same ledger.
  • Preserve the original request body and destination across the initial request and paid retry. File-backed requests must keep their approval and redirect boundary. When redirects are not followed, keep the body bound to the first URL and use the final Location as new caller input.
  • Keep logical-attempt identity aligned with every idempotency field. Method, URL, body, payer, network, and payment terms must not collide across different payments, while fresh blockhash and slot hints must not force a duplicate charge.
  • Keep raw response bytes, content type, effective URL, receipt headers, and settlement parsing aligned. Text decoding is for text or payment challenge data only.
  • Keep receipt headers, settlement parsing, and subscription persistence aligned. Wrapper paths need a deterministic reconciliation path when they cannot expose a receipt.
  • Keep cached subscription proof checks aligned with active status, expiry, account delegation, network, and URL boundaries. Do not widen a reusable proof from one origin to another host.
  • Keep legacy authenticate persistence separate from canonical subscription activation. Do not add a second signing prompt to current activation.
  • Keep x402 version detection tied to the payload that supplied the parsed offer. Echo required v2 extensions and preserve the payment identifier across unresolved retries.
  • Keep x402 sign-in origin checks and fallback tied to the same 402. A malformed optional sign-in extension must not hide a valid payment offer.
  • Keep session origin checks aligned with session cache keys and host approval scope. Operator sessions must continue to return operator open and use authorizations.
  • Keep batch-settlement channel keys aligned with receiver, fee payer, withdrawal delay, asset, network, operator, and signer mode. Register server authorizations before dispatch and advance watermarks only from verified settlement evidence.
  • Keep display balances separate from spendable balances. RPC fallback may include custom token accounts for display, but funding and send paths must use associated-token balances.
  • Keep HTTPie URL expansion aligned with cached authorization lookup. The canonical URL must be the resource that the wrapped command will call.
  • Keep hosted outbound checks aligned across the initial URL, DNS answers, redirects, and forwarded headers. Do not let proxy settings or debugger routing bypass public-only restrictions, and preserve the response-size limit.

Important failure modes

TriggerConsequenceGuard
Mainnet has no configured accountThe client cannot sign a paymentRequire account setup instead of creating a silent mainnet wallet.
Forced network differs from the challengeThe credential could target the wrong ledgerReject before wallet access or signing.
A sandbox flag meets a non-Surfpool localnet blockhashThe signed transaction could use a different local ledgerReject the challenge unless its network and blockhash match the forced sandbox intent.
Balance lookup failsThe client cannot prove which offer is fundableMark balance state unavailable and use only the defined compatibility fallback.
Display-only custom token balance is used for fundingThe payment builder may select an account the transfer path cannot debitUse spendable associated-token balances for payment selection and sends.
Cached proof matches an attacker-controlled host prefixA reusable credential could leak to another hostRequire an exact URL or a path, query, or fragment boundary.
Cached proof belongs to another account or networkOne wallet could spend another wallet's accessMatch the subscription delegation, account, and network before attaching it.
Server rejects a submitted paymentA second automatic payment could repeat a bad credentialSurface the verification or session rejection and stop the loop.
Transport fails after a paid retryThe payment may have settled, but a new retry could charge againReuse the unresolved attempt's signed material and clear it only after a definitive answer.
Operator session is used with a transaction-only signerThe caller cannot create the required raw message proofReject the operator form or select a compatible payment offer.
Session URL is relative, non-HTTP, or credential-bearingSession authorization could use an unsafe scopeRequire an absolute HTTP(S) URL without embedded credentials.
Batch channel is reused after a payer or channel property changesA voucher could be redeemable by the wrong partyKey and validate channels by payer, network, asset, receiver, fee payer, withdrawal delay, operator, and signer mode.
Batch authorization is dispatched without registrationA later receipt cannot be safely matched to its approved budgetRegister every authorization before dispatch and retain uncertainty when no receipt arrives.
Batch settlement confirms a different voucherThe local cumulative amount can diverge from the serverReject the response and keep the prior watermark.
Batch corrective state cannot be verifiedLater vouchers may use an unsafe cumulative amountLeave trusted state unchanged and require a fresh channel.
x402 v2 extensions or required identifier are not preservedThe server can reject the retry or lose idempotencyEcho inbound extensions and reuse the identifier for the unresolved attempt.
x402 version is inferred from a different payload than the parsed offerThe client can send a v2 proof to a v1 server or the reverseDetect the version from the payload source used by challenge parsing.
x402 sign-in names another originThe wallet could sign access for an unintended hostRequire both the challenge domain and URI to match the resource origin.
Subscription challenge terms disagreeThe user could approve a different amount or cadence than the server activatesValidate the amount, cadence, plan, recipient, mint, decimals, and network before approval.
Sandbox funding failsBroadcast can fail after signing because the wallet is emptyWarn and verify that signing and settlement use the same sandbox ledger.
A binary response is decoded as textImage, PDF, or other binary data can be changed before the caller receives itKeep response bodies as bytes and decode text only for text responses or payment challenge parsing.
A body-bearing request follows an unsafe redirect policyThe request body can be sent to a redirect destination that the caller did not approveDisable forwarding when required and rerun against the stated final URL.
Hosted curl targets a local, private, or internal destinationThe request is rejected before it can reach a protected networkValidate the URL and every DNS answer against the public-internet policy.
Hosted curl follows a redirect to a restricted destinationThe redirect fails instead of reaching the restricted hostApply the public destination check to every followed redirect.
Hosted curl sends a routing or metadata header, or uses a proxyThe caller could alter routing or reach a cloud metadata serviceReject the header and bypass ambient proxy and debugger routing.
Hosted curl receives a response larger than 64 MiBThe response is rejected while it is readEnforce both declared and streamed response size limits.

Key files

FileWhy to read it
rust/…/runner.rsDefines the common request outcome model, 402 classification, protocol preference, signer capability fallback, wrapped command behavior, redirect handling, and cached authorization attachment.
rust/…/attempt.rsDefines the logical request identity and the single-flight cache that prevents duplicate payment material during unresolved retries.
rust/…/mpp.rsExplains MPP parsing, network intent checks, balance-aware cross-protocol selection, sandbox-aware charge credentials, and charge retry reuse.
rust/…/x402.rsExplains x402 exact, sign-in, upto, and batch-settlement offer handling. It also preserves protocol version, extension data, and payment identifiers for retries.
rust/…/session.rsExplains payment-channel opening, client and operator voucher models, origin scope, retry-safe opens, top-up, and close.
rust/…/subscription.rsExplains subscription validation, activation, reusable proof creation, receipt mapping, and persistence.
rust/…/authenticate.rsExplains the legacy authenticate path and safe lookup of reusable access credentials.
rust/…/batch.rsExplains x402 batch channel reuse, payer-bound recovery, origin-bound resident signers, authorization budgets, settlement confirmation, missing-header handling, and corrective resynchronization.
rust/…/balance.rsExplains the separate native SOL, stablecoin, credit, committable-channel, display, spendable, and unavailable-state balance sources used by payment selection.
rust/…/send.rsExplains the stablecoin send request, max-balance handling, confidential flag, fee path, and payment retry.
rust/…/fetch.rsExplains the built-in request path, replayable bodies, raw byte responses, response metadata, redirect policy, hosted public-only outbound restrictions, debugger routing, and file safety boundary.
rust/…/receipt.rsExplains the protocol-neutral receipt view used after payment.