Rust payment runtime
The Rust payment runtime coordinates paid client requests, server payment checks, usage metering, payment-channel state, and on-chain settlement. It gives clients, gateways, sellers, and API services one set of payment rules while keeping signing, chain reads, durable state, and workers as separate support layers.
Runtime boundary
The runtime is a group of Rust libraries around pay-kit, the shared protocol SDK. pay-core owns common client and server payment behavior. The HTTP proxy, API services, workers, shared types, and keystore provide the runtime edges used by production hosts.
The focused pages cover the main product paths:
- Client payment flows
- Payment gateway operation
- Remote wallet providers
- Session channels and metering
- Credit providers and channel profiles
- API and worker services
- Benchmark harness
- Pay Connect onboarding
- HTTP payment proxying
- Deployment payment policy
- Inference marketplace selling
Runtime role
The runtime turns a request for a paid resource into a payment challenge, a verified request, or a safe error. It also carries the state needed to explain what was paid and to finish settlement after delivery. Hosts provide API definitions, protocol handlers, stores, signer roles, and optional telemetry through PaymentState.
PaymentState also gives hosts a common boundary for completed HTTP exchange records and live inference usage. Hosts that do not need this telemetry keep the default no-op behavior.
References: rust/…/lib.rs• L1-42 rust/…/lib.rs• L58-146 rust/…/lib.rs• L148-198 rust/…/Cargo.toml• L7-30
Request path
The request path keeps payment decisions separate from HTTP framework code. A client receives an offer, retries with a credential, and reaches an upstream only after the gateway verifies the payment. Session and response-metered paths keep state active while the response is delivered.
The framework-neutral gate is used by both the Axum middleware and the standalone Pingora proxy. On the client side, the runner can inspect MPP and x402 offers, apply an explicit protocol choice, and retry through curl, wget, HTTPie, or the built-in fetch path. This keeps challenge, verification, routing, and settlement choices consistent across data planes and client tools.
This diagram shows the broad path from a client request to delivery and later settlement.
flowchart LR
C[Client or HTTP tool] -->|challenge or credential| G[Payment gate]
G -->|402| C
G -->|verified request| R[Routing]
R --> U[Paid upstream]
U --> M[Usage metering]
M --> S[Channel store]
S --> W[Settlement worker]
W --> X[Solana]
References: rust/…/gate.rs• L1-14 rust/…/gate.rs• L471-496 rust/…/payment.rs• L58-129 rust/…/proxy.rs• L186-205 rust/…/runner.rs• L383-437
Endpoint discovery
Endpoint discovery presents the paid surface to clients and agents. The runtime can create a document from the paywall or filter an upstream OpenAPI or Google Discovery document, then point its URLs at the gateway and carry payment offers and metering data into the result.
The skills catalog adds a cached provider index around this surface. Provider details are loaded on demand, while probing sends safe requests to paid endpoints and records the full Solana-compatible payment choices for catalog publication.
References: rust/…/openapi.rs• L1-18 rust/…/openapi.rs• L80-197 rust/…/mod.rs• L1-13 rust/…/mod.rs• L45-120 rust/…/probe.rs• L1-10 rust/…/probe.rs• L102-169
Payment enforcement
Payment enforcement decides whether an endpoint is free, needs payment, or can accept a supplied proof. It uses endpoint policy and safe request metadata so challenge generation and credential verification use the same terms.
Protocol gate
The PaymentGate is the common decision point for MPP and x402. MPP covers charge, session, subscription, and authentication paths. x402 covers exact, upto, and batch-settlement paths. The gate advertises only schemes that the endpoint accepts and the host can run. If no usable backend exists, it fails closed.
The first decision does not read the request body. This permits large or streamed bodies to continue upstream after verification and keeps payment credentials separate from normal upstream authentication.
References: rust/…/gate.rs• L73-86 rust/…/gate.rs• L700-971 rust/…/gate.rs• L973-1211
Subscription access
Subscription access turns recurring payment into a durable access right. The server confirms activation on-chain and then checks a reusable proof against the live delegation, plan, billing period, endpoint identity, and network.
Legacy authenticate credentials remain supported during migration, but identity proof alone does not grant access. The server also checks the live subscription state.
References: rust/…/subscription.rs• L22-63 rust/…/subscription.rs• L310-415 rust/…/authenticate.rs• L19-24 rust/…/authenticate.rs• L93-123
Metering model
Metering turns an API description into a price for a request or response. It can select a model variant, apply a tier, record shared or per-wallet volume, and extract usage from response headers, JSON, or live streams. The resolved price informs both the offer and the later settlement.
Fixed schemes cannot price response-only usage before authorization. The gate therefore leaves those schemes out when their quantity is unknown. Response-aware schemes settle measured usage under a ceiling and a configured missing-usage policy.
When pricing depends on a request model or input size, the runtime prepares the same body that it forwards. It rejects compressed bodies when their decoded content is needed for pricing and keeps unrelated streaming uploads untouched.
References: rust/…/metering.rs• L10-48 rust/…/metering.rs• L205-237 rust/…/metering.rs• L415-487 rust/…/metered_body.rs• L1-7 rust/…/metered_body.rs• L103-181
Upstream routing
Routing connects a paid endpoint to a provider or a direct response. It can rewrite paths and add provider authentication only after payment succeeds. It strips payment and internal identity headers before forwarding, so provider credentials stay inside the gateway.
The same prepared route serves the Axum adapter and the standalone proxy. Body-dependent provider signatures use a buffered body rather than signing a placeholder.
References: rust/…/proxy.rs• L37-93 rust/…/proxy.rs• L148-184 rust/…/proxy.rs• L380-600
Deployment payment policy
Deployment payment policy gives a cloud deployment a short-lived price and payout plan without trusting a caller-supplied policy header. The gateway checks the exact host and path, validates authenticated policy data, and binds it to an MPP session.
Missing, expired, deleted, mismatched, redirected, oversized, or unavailable policy data blocks admission. Deployment policy accepts only the supported session scheme.
References: rust/…/deployment_policy.rs• L52-95 rust/…/deployment_policy.rs• L215-241 rust/…/gate.rs• L592-697
Response completion
Response completion distinguishes a successful HTTP response from a completed seller result. The runtime persists settlement before releasing an explicit terminal frame and releases reservations when a response fails or ends without completion.
This rule is shared by fixed-price batch and delegated session responses. A client cannot read a useful partial result and then disconnect before the related charge is committed.
References: rust/…/completion_stream.rs• L18-75 rust/…/completion_stream.rs• L132-209 rust/…/payment.rs• L225-325
Client payment behavior
The client libraries parse server offers, select a signer-compatible payment, request user approval, and build a retry credential. They share network checks, stablecoin identity, balance checks, and retry rules with the server's payment contracts.
One-shot payments
MPP charge and x402 exact authorize one request. The client selects a usable currency or protocol, signs the offer, and sends the proof on retry. x402 upto authorizes a ceiling and settles measured usage after delivery. Sign-in can be sent with an optional payment fallback.
The selector can compare MPP and x402 offers against the wallet's funded stablecoins. A caller can keep the default preference or require MPP or x402. An unresolved logical request reuses its payment identifier or exact signed upto header for a bounded retry window. The reuse is scoped to the request, payer, network, and offer, so one wallet cannot reuse another wallet's pending material.
An x402 sign-in proof is accepted only when its domain and URI name the challenged resource's origin. This prevents a payment response from redirecting a wallet's authentication proof to another site.
References: rust/…/mpp.rs• L280-355 rust/…/mpp.rs• L463-589 rust/…/x402.rs• L41-85 rust/…/x402.rs• L136-356 rust/…/x402.rs• L742-810 rust/…/attempt.rs• L46-193 rust/…/runner.rs• L925-950
Subscription access
The client treats a subscription challenge as activation. It validates the plan, amount, mint, decimals, recipient, and period before signing, then stores the subscription after a successful retry. Later requests use the stored proof while the subscription and its resource boundary remain live.
The current activation creates a reusable subscription proof. Legacy authenticate-token handling remains available for older account records and servers.
References: rust/…/subscription.rs• L84-209 rust/…/subscription.rs• L211-407 rust/…/authenticate.rs• L148-288
Session channels
A session channel funds reusable access with cumulative vouchers. The client opens the channel, sends a voucher or reusable payer proof for each request, records an accepted watermark, and closes when work ends. Operator-signed channels let the gateway meter responses while the client proves payer control.
Session handles can be shared across async tasks. Signing does not advance the settled watermark, and a close can authenticate the current watermark without adding a charge.
References: rust/…/session.rs• L37-57 rust/…/session.rs• L111-185 rust/…/session.rs• L299-356
Batch channels
x402 batch settlement uses one escrow channel for many small requests. The client discovers or opens a compatible channel, signs cumulative vouchers or operator authorizations, and tops up when capacity is low. The cache binds a channel to its offer terms and payer, so a changed receiver, sponsor, operator, or wallet cannot reuse the old escrow.
The client registers an authorization before dispatch and advances local state only after the response confirms the payment. Corrective challenges resynchronize a stale watermark after an uncertain transport result. Missing receipts do not prove that a charge failed, so funding and approved capacity remain reserved until a receipt or safe rejection proves what happened.
References: rust/…/batch.rs• L38-59 rust/…/batch.rs• L132-170 rust/…/batch.rs• L341-569 rust/…/batch.rs• L571-729 rust/…/x402.rs• L852-1202
HTTP transport
The built-in HTTP client keeps request and response bytes replayable so a paid retry uses the same body. The command runner gives curl, wget, and HTTPie the same challenge classification and paid retry behavior. It preserves binary responses, classifies 402 responses, and supports explicit redirect behavior.
Hosted callers reject local destinations, unsafe routing headers, ambient proxy use, and cross-origin redirects. Payment headers remain on the challenged resource and are not carried into a credential-free redirect.
References: rust/…/fetch.rs• L18-40 rust/…/fetch.rs• L228-261 rust/…/fetch.rs• L535-683 rust/…/runner.rs• L154-205 rust/…/runner.rs• L383-437
Channel settlement and durable state
Payment channels separate fast request authorization from slower chain settlement. The runtime records accepted vouchers and activity while a channel is open, then pushes a watermark or closes and distributes the channel through a controlled lifecycle.
Channel lifecycle
A channel moves from open activity to watermark settlement or close. An operator can push a sufficiently large accepted watermark before close. Close work settles the latest accepted amount, distributes funds when the refund account is ready, and later permits payout or rent recovery when chain timing requires it. Lifecycle ownership can be embedded in a gateway or assigned to an external worker.
stateDiagram-v2
[*] --> Open
Open --> Open: voucher or usage watermark
Open --> Open: periodic watermark settlement
Open --> Closing: close request or idle deadline
Closing --> Sealed: settle and seal
Sealed --> Distributed: refund and distribute
Distributed --> Reclaimed: rent reclaim
References: rust/…/session.rs• L406-493 rust/…/session.rs• L546-607 rust/…/session.rs• L767-905 rust/…/session.rs• L940-1018
Stream metering
Stream metering observes cumulative bytes, characters, requests, tokens, or quota units. It holds chargeable chunks until the matching voucher or operator authorization is durable. It supports common SSE and NDJSON forms and performs a final check when a stream ends.
References: rust/…/session_stream.rs• L136-187 rust/…/session_stream.rs• L273-415 rust/…/session_stream.rs• L691-744 rust/…/session_stream.rs• L851-879
Durable state
Durable session state records channel identity, cumulative value, proof, activity, and close status. Capacity leases prevent concurrent requests from spending the same funds and prevent close from racing with an in-flight request. A failed or cancelled lease releases its reservation so the channel can be used again. Redis-backed stores support multi-instance gateways when enabled.
References: rust/…/session.rs• L331-354 rust/…/session.rs• L1198-1237 rust/…/session.rs• L1250-1320 rust/…/session.rs• L1420-1500 rust/…/subscription.rs• L90-264 rust/…/Cargo.toml• L27-30
Settlement workers
Settlement workers reconcile durable records with on-chain channel accounts. They push newer watermarks and advance due channels through close, distribution, and rent reclaim while confirmation and coordination rules make retries safe.
References: rust/…/Cargo.toml• L7-19 rust/…/settle_sessions.rs• L304-670 rust/…/close_channels.rs• L213-358
Shared contracts
Shared types define the values that must agree across configuration, request processing, chain actions, and public API responses. They keep stablecoin identity, schemes, metering, splits, receipts, accounts, and channel state consistent.
Payment types
pay-types describes endpoints, routing, accepted schemes, session policy, pricing dimensions, and recipient splits. Stablecoin symbols resolve through the shared mint registry so client and server use the same token identity.
References: rust/…/lib.rs• L8-120 rust/…/metering.rs• L818-878 rust/…/splits.rs• L102-165
Inference pricing
Inference pricing maps a model to input and output rates per million tokens. It supports defaults and model variants, validates rates before publication, and feeds response-aware session and upto settlement.
References: rust/…/pricing.rs• L22-48 rust/…/pricing.rs• L108-170 rust/…/sell_inference.rs• L49-116
Inference selling
Inference selling publishes a paid OpenAI-shaped chat route and a free model route. Paid requests wait for a seller agent through a queue, while the common gateway performs challenge, metering, and settlement work.
Flat request pricing offers session, upto, and batch settlement. Per-token pricing offers response-aware session and upto paths because the final amount is not known before the response. The generated paywall carries the seller's recipient, currencies, network, model rates, session cap, and idle-close policy into the same gateway contracts used by other paid APIs.
References: rust/…/sell_inference.rs• L1-19 rust/…/sell_inference.rs• L49-79 rust/…/sell_inference.rs• L241-385 rust/…/sell_inference.rs• L740-989
Account routing and signing
The account registry maps named wallets to networks and stores public subscription data. Secret material may remain in a keystore, file, ephemeral account, hardware device, or remote provider. Network intent is checked before protected key material is read or a payment is signed.
Mainnet uses an explicit wallet setup. Localnet and devnet can create and persist an ephemeral wallet when no account exists. A mainnet-beta challenge uses the same canonical mainnet account and approval policy as mainnet.
References: rust/…/accounts.rs• L46-72 rust/…/accounts.rs• L118-184 rust/…/accounts.rs• L453-620 rust/…/signer.rs• L170-271 rust/…/signer.rs• L284-377
Remote wallet signing
Remote signing keeps private keys with a custody provider or hardware device while exposing the same signer contract to payment paths. Provider resolution validates credentials, selects a wallet, and checks its address against the configured account. Hardware support can be limited to transaction signing.
References: rust/…/mod.rs• L48-87 rust/…/mod.rs• L351-476 rust/…/ledger.rs• L123-155 rust/…/signer.rs• L26-103
API and receipt types
pay-api-types defines public shapes for balances, receipts, channel events, subscriptions, transfers, and amounts. Receipts provide protocol-aware chain results without requiring each caller to decode Solana instructions.
References: rust/…/lib.rs• L44-116 rust/…/lib.rs• L143-239 rust/…/receipt.rs• L60-115
Chain access
pay-api-core is the shared read path for balances, token programs, channel accounts, transaction status, and receipts. It resolves both the original SPL Token program and Token-2022 before account reads or settlement.
References: rust/…/rpc.rs• L14-93 rust/…/channel_state.rs• L44-111 rust/…/stablecoin.rs• L74-121
Key protection
pay-keystore separates user approval from secret storage. Public keys support account discovery, while private key access requires the selected authentication boundary. Payment prompts describe the amount and purpose before signing.
References: rust/…/lib.rs• L1-75 rust/…/auth.rs• L13-35 rust/…/signer.rs• L134-168
Test chain boundary
The test RPC gives payment builders a loopback-only chain view for tests that sign canned challenges. It answers only blockhash validity and latest-blockhash calls, so test payments cannot reach a real cluster through this path.
References: rust/…/test_rpc.rs• L1-7 rust/…/test_rpc.rs• L18-42 rust/…/test_rpc.rs• L80-101 rust/…/config.rs• L9-17
Runtime telemetry
Runtime telemetry emits structured tracing events for challenges, paid delivery, settlement, upstream errors, channel activity, and accepted value. Hosts can also receive completed exchange records and live inference usage through PaymentState. OpenTelemetry can turn these events into metrics, but payment enforcement does not require a collector.
References: rust/…/lib.rs• L114-198 rust/…/telemetry.rs• L1-35 rust/…/telemetry.rs• L233-380
TLS trust
TLS trust protects the runtime's outbound HTTPS connections, including the HTTP path used by payment services. The core test boundary checks that the inherited rustls-webpki and webpki-roots policy rejects known-compromised certificate chains and removed trust anchors while accepting a valid chain through an explicitly trusted root.
References: rust/…/Cargo.toml• L74-75 rust/…/Cargo.toml• L115-120 rust/…/tls_distrust_tests.rs• L1-10 rust/…/tls_distrust_tests.rs• L78-142
Change checklist
When these files or sections are changed, remember to consider these:
- Keep scheme support aligned across server challenge generation, gate verification, client selection, seller pricing, and discovery.
- Keep payment-attempt identity aligned with method, URL, body, payer, network, and offer terms.
- Keep subscription plan terms, proof binding, resource boundaries, and replay stores aligned.
- Keep metering variant selection, tier selection, usage extraction, and base-unit conversion aligned.
- Keep request-body preparation aligned with the bytes sent to the provider.
- Keep stream watermarks, capacity leases, completion signals, and settlement callbacks aligned.
- Keep payout manifests, plans, one-approval ceilings, journal events, and resume actions aligned.
- Treat receipt fields and raw amount strings as public wire contracts.
- Keep channel-store schema, lifecycle ownership, Redis keys, and worker assumptions aligned.
- Keep mint, decimal, and token-program data aligned across balances, signing, metering, and settlement.
- Keep signer roles distinct between payer, payee, fee payer, and settlement worker.
- Keep remote provider records, secrets, wallet IDs, and cached addresses aligned.
- Keep seller pricing, generated API specs, usage paths, and Pay Connect records aligned.
- Keep deployment policy identity, expiry, allocations, and session binding aligned.
- Keep payment-header stripping shared by the in-process and standalone proxy paths.
- Keep body-dependent upstream signing tied to body buffering.
- Keep TLS trust-bundle and
rustls/webpkiversions aligned with the certificate distrust checks. - Keep optional workspace features aligned with their callers.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| No payment backend can serve an accepted scheme | Paid traffic fails instead of serving free | payment_backend_unconfigured from the gate (rust/…/gate.rs• L1202-1211) |
| Forced client protocol differs from the server offer | The client refuses to switch silently and reports a rejection | ProtocolPreference in the runner (rust/…/runner.rs• L925-950, rust/…/runner.rs• L1301-1320) |
| Forced client network differs from the challenge | The client refuses to sign | Client network and Surfpool checks (rust/…/mpp.rs• L780-830, rust/…/x402.rs• L266-270) |
| An x402 sign-in challenge names another origin | The client does not sign a proof for that origin | Resource-origin binding (rust/…/x402.rs• L47-85) |
| Retry follows an unresolved paid request | A second payment could be created | Scoped PaymentAttempt reuse (rust/…/attempt.rs• L132-193) |
| A batch channel changes payer or channel terms | Escrow or vouchers could be used for the wrong offer | Payer-aware cache and channel key (rust/…/batch.rs• L38-59, rust/…/batch.rs• L186-203) |
| Batch funding is submitted but not confirmed | A second open or top-up could double-fund the channel | Pending-funding state and public-key-only recovery (rust/…/batch.rs• L231-271, rust/…/x402.rs• L932-981) |
| Stream ends without completion | Partial output is not charged as complete | Completion ownership and release (rust/…/completion_stream.rs• L203-261) |
| Chargeable stream bytes lack a durable commit | Bytes remain withheld or time out | Commit wait before release (rust/…/session_stream.rs• L691-744, rust/…/session_stream.rs• L896-919) |
| A metered request body is compressed | Model or input pricing does not match the forwarded content | Identity-encoding guard (rust/…/metered_body.rs• L145-181) |
| Policy data is missing or stale | Deployment admission is blocked | Per-admission policy validation (rust/…/gate.rs• L592-641) |
| Payment or internal identity headers reach an upstream | Provider may see a client credential | Shared strip list (rust/…/proxy.rs• L37-93) |
| Hosted HTTP targets a private address | A hosted caller could reach internal services | Public URL and DNS checks (rust/…/fetch.rs• L45-147) |
| A certificate chain uses a distrusted intermediate or removed root | Outbound HTTPS verification fails instead of trusting the chain | Rustls/webpki distrust regression tests (rust/…/tls_distrust_tests.rs• L70-107) |
Key files
| File | Why to read it |
|---|---|
| rust/…/Cargo.toml | Shows optional features and deployment boundaries. |
| rust/…/lib.rs | Shows the public runtime and host contract. |
| rust/…/gate.rs | Shows challenge, verification, routing, and settlement decisions. |
| rust/…/payment.rs | Shows the Axum adapter and internal trust boundary. |
| rust/…/proxy.rs | Shows upstream routing, auth, body signing, and header stripping. |
| rust/…/metered_body.rs | Shows shared request-body rules for metered forwards. |
| rust/…/completion_stream.rs | Shows completion-gated settlement. |
| rust/…/lib.rs | Shows the standalone HTTP data plane. |
| rust/…/attempt.rs | Shows payment retry identity. |
| rust/…/fetch.rs | Shows replayable HTTP transport and hosted restrictions. |
| rust/…/runner.rs | Shows 402 classification, protocol preference, and tool retries. |
| rust/…/mpp.rs | Shows MPP selection, network checks, and cross-protocol choice. |
| rust/…/x402.rs | Shows x402 exact, usage, sign-in, and batch payment behavior. |
| rust/…/session.rs | Shows session vouchers and close actions. |
| rust/…/subscription.rs | Shows subscription activation and persistence. |
| rust/…/batch.rs | Shows batch channel cache, authorization budgets, and receipt reconciliation. |
| rust/…/session.rs | Shows channel lifecycle, leases, watermark settlement, and payout. |
| rust/…/metering.rs | Shows price and usage resolution. |
| rust/…/session_stream.rs | Shows stream backpressure and metering. |
| rust/…/subscription.rs | Shows server subscription contracts. |
| rust/…/sell_inference.rs | Shows seller pricing, scheme selection, and API generation. |
| rust/…/accounts.rs | Shows network-aware wallet and subscription state. |
| rust/…/signer.rs | Shows local, hardware, ephemeral, and remote signer resolution. |
| rust/…/mod.rs | Shows provider catalog and lazy endpoint discovery. |
| rust/…/probe.rs | Shows payment-aware endpoint probing. |
| rust/…/test_rpc.rs | Shows the loopback-only payment test boundary. |
| rust/…/rpc.rs | Shows the chain-read boundary. |
| rust/…/receipt.rs | Shows protocol-aware receipts. |
| rust/…/settle_sessions.rs | Shows session reconciliation. |
| rust/…/close_channels.rs | Shows channel close and distribution. |
| rust/…/auth.rs | Shows user approval intents. |
| rust/…/metering.rs | Defines endpoint and payment contracts. |
| rust/…/lib.rs | Defines shared stablecoin rules. |
| rust/…/tls_distrust_tests.rs | Shows the outbound TLS trust boundary and distrust regression checks. |
rust/bench | Shows the benchmark boundary. |