CLI payment operations
The Pay CLI gives a wallet a common way to view funds, add funds, move stablecoins, and call paid HTTP services. It also lets agent tools use the same payment path through subscriptions, receipts, and a local payer proxy. For the wider command map, see Payment CLI; account setup is covered by CLI account management, agent provider setup by CLI skills and catalog, and gateway and inference work by CLI server and inference.
Payment operation model
Account and network context
The CLI resolves each payment against an account and a Solana network. A named --account choice takes priority. Otherwise, the CLI uses the active account for the selected network. mainnet is the normal default; --sandbox and --local select localnet and use an ephemeral or local sandbox wallet.
The same network choice must reach the balance lookup, signer, RPC service, and payment challenge. This keeps a request from showing one wallet while signing on another network. Sandbox payment paths can fund their temporary wallet through the sandbox service before signing.
References: rust/…/main.rs• L41-60 rust/…/main.rs• L163-214 rust/…/mpp.rs• L45-63
Payment challenge cycle
Paid HTTP services first return HTTP 402, which means that payment is required. The CLI reads the advertised challenge, asks the selected wallet to approve and sign it, then retries the same request with a payment credential.
The cycle supports MPP (Machine Payments Protocol) and x402. The client chooses a supported, fundable offer when the service gives more than one choice. A successful retry returns the service response and may include a receipt that identifies the settlement.
The following diagram shows the normal request path.
flowchart LR
A[CLI request] --> B[Paid service]
B -->|free response| C[Return response]
B -->|402 challenge| D[Choose protocol and network]
D --> E[Approve and sign with wallet]
E --> F[Retry original request]
F --> G[Service response and receipt]
F -->|payment rejected| H[Show error or pass through 402]
References: rust/…/mod.rs• L309-375 rust/…/mod.rs• L393-475 rust/…/runner.rs• L1
Balance and funding flows
Balance views
pay whoami shows the operating-system user, the resolved Pay account, and that account's stablecoin balances. pay account list shows all configured accounts grouped by network. These views help an engineer confirm which wallet will fund the next request.
SOL balance data comes from the selected Solana RPC service. Stablecoin data comes from the Pay API stablecoin service. If that service is unavailable, the CLI marks the token balance as unavailable instead of treating it as zero. A mainnet account with no visible stablecoins receives a top-up hint.
References: rust/…/whoami.rs• L24-115 rust/…/list.rs• L13-31 rust/…/balance.rs• L235-305
Top-up flow
pay topup funds the account used for later paid requests. It targets mainnet by default. The --sandbox form targets the local sandbox account instead. The --account option can select a configured account on the chosen network, a named remote account available on mainnet, or a raw Solana address. Without the option, the command uses the network's default account.
The interactive screen offers two funding paths:
- Buy stablecoins opens an on-ramp in a browser. The user can choose PayPal, Venmo, or Apple Pay.
- Transfer from a mobile wallet shows a Solana Pay QR code for a USDC transfer.
The CLI watches for an increase in stablecoin balance. It reports success when funds arrive, or returns a clear aborted result when the user closes the flow. A non-terminal environment prints static instructions instead of opening the interactive screen.
References: rust/…/topup.rs• L3-56 rust/…/topup.rs• L224-365 rust/…/topup.rs• L379-452
Stablecoin transfer flows
Direct transfer requests
pay send moves a supported stablecoin to a Solana address or a configured account name on the selected network. The command accepts a positive decimal amount or max (also *) for the selected coin's full available balance. A memo can use plain text or hex-encoded UTF-8 text, but the two memo forms cannot be used together. Memo text must fit the on-chain limit. --fee-within makes the requested amount include the fee refund rather than adding it on top. The max form implies this fee behavior.
The command uses a fee-payer-backed service. The service first describes the charge in a 402 response. The wallet signs that charge, then the service co-signs and broadcasts the transfer. The CLI reports the recipient amount, any fee amount, and a receipt link after settlement. A confidential transfer can be requested when the selected Token-2022 mint supports that feature.
References: rust/…/send.rs• L22-124 rust/…/send.rs• L155-225 rust/…/send.rs• L131-274
Batch fanout payouts
pay fanout sends one stablecoin from a selected account to many recipients listed in an RFC 4180 CSV file with recipient,amount headers. It is intended for high-volume payouts rather than one-off transfers. The command uses the selected network and mint, then checks the source balance and the SOL needed for account setup and transaction fees before it broadcasts.
The command records the payout plan and each run result in a durable JSONL journal. It groups recipients into transactions, signs the batch under one authorization, and confirms transactions concurrently. A run with failed chunks returns an error while keeping the journal as the source for later review.
The following diagram shows the batch payout path.
flowchart LR
A[CSV payout manifest] --> B[Validate network and mint]
B --> C[Check token and SOL funds]
C --> D[Plan transaction chunks]
D --> E[Authorize batch]
E --> F[Broadcast and confirm]
F --> G[Write journal and report result]
References: rust/…/fanout.rs• L37-66 rust/…/fanout.rs• L68-179 rust/…/fanout.rs• L191-255 rust/…/mod.rs• L75-83
Transfer selection rules
When no currency is given, the CLI checks the sender's known stablecoin balances. It uses a single eligible coin without asking a question. If several coins can cover the amount, an interactive terminal asks the user to choose; a non-interactive caller must provide --currency. An amount request must be covered by one coin; balances are not combined.
An explicit currency uses the wallet's known mint when the balance service can provide it. If the wallet is offline, does not hold that coin, or the balance service does not list it, the CLI falls back to its local stablecoin registry. Without a configured mainnet account, a normal amount defaults to USDC; max instead requires an account so the CLI can learn the coin and its full amount. On a non-mainnet network, the CLI can use an ephemeral account and fund it through the sandbox before reading balances.
This rule makes pay send safe for a human with several funded coins while keeping automation deterministic.
References: rust/…/send.rs• L270-347 rust/…/send.rs• L350-413 rust/…/send.rs• L162-179
HTTP request flows
External request wrappers
pay curl wraps the installed curl program and passes its request arguments through. pay wget and pay http provide the same payment-aware pattern for downloads and HTTPie requests. These commands keep the normal tool experience while Pay handles a 402 response and retries the request after payment approval.
HTTP tools auto-pay by design. A free response passes through unchanged. A paid response starts the challenge cycle described above. The original exit status still represents the final HTTP result, so scripts can treat a failed paid request as a failure.
References: rust/…/curl.rs• L3-12 rust/…/wget.rs• L3-12 rust/…/http.rs• L3-12 rust/…/main.rs• L274-281
Built-in fetch requests
pay fetch performs an HTTP request without an external binary. It defaults to GET without a body and POST with a body. It accepts headers, an inline body, a file body, or multipart fields. Only one body source is allowed.
The built-in client owns the request bytes before the first send. This lets a paid retry use the exact same body. File-backed and multipart requests do not follow redirects after sending the body; the CLI asks the caller to use the final URL instead. This prevents a body intended for one destination from being sent to another destination without a new decision.
References: rust/…/fetch.rs• L6-53 rust/…/fetch.rs• L55-159 rust/…/fetch.rs• L32-72 rust/…/fetch.rs• L414-456
Receipt handling
A receipt is the service's proof that a paid request settled. MPP places it in Payment-Receipt; x402 uses Payment-Response or its versioned form. The CLI accepts the supported encodings and extracts the best transaction reference when one exists.
Human-readable output links to the Pay receipt page or shows the transaction reference. Machine-oriented output keeps the response body and status separate from payment details. A receipt is not required for a free response, and a payment failure does not become a successful response merely because the service returned a challenge.
References: rust/…/receipt.rs• L35-65 rust/…/mod.rs• L841-859 rust/…/link.rs• L42-54
Subscription flows
Subscription activation
An MPP subscription challenge authorizes recurring access to a service plan. It names the plan, token, recipient, puller, period, and charge. The normal paid HTTP path validates the challenge, asks for approval, signs the activation transaction, and retries the request.
After a successful activation, the CLI records the subscription under the signing account. The subscription ID is the on-chain delegation identifier. The service performs later renewals on-chain, so renewal payments do not repeat the HTTP activation flow.
The explicit pay subscriptions new command currently validates its plan, mint, puller, recipient, amount, and period inputs but does not activate a subscription in this build. Activation is therefore normally reached through a service's subscription challenge.
References: rust/…/subscription.rs• L86-182 rust/…/subscription.rs• L185-221 rust/…/subscription.rs• L431-535 rust/…/new.rs• L1-10
Subscription records
pay subscriptions list is the account-facing view of tracked delegations. It can filter by account or network and can emit stable JSON for scripts. pay subscriptions status <subscription-id> gives one record's plan, amount, period, parties, timestamps, and activation transaction.
The local record links wallet context to on-chain subscription state. It also stores the resource URL and description when the activation challenge provides them. A cancelled subscription remains active until the end of its already-paid period, then the list view removes the expired local tombstone.
References: rust/…/mod.rs• L17-30 rust/…/list.rs• L24-85 rust/…/status.rs• L21-104
Subscription cancellation
pay subscriptions cancel <subscription-id> ends future subscription periods. The command first checks the subscriber's SOL balance. It broadcasts directly when the wallet can pay the network fee; when SOL is low, or when --via-gateway <url> is set, it uses a pay-api gateway that sponsors the fee for a small stablecoin charge.
The gateway path first discovers the charge and fee payer through a 402 response. The CLI uses that information to show the real fee in the approval prompt, then signs the charge and submits the partially signed cancellation transaction for gateway co-signing and broadcast. The gateway URL can use the built-in default or PAY_API_URL; --gateway-fee-payer and PAY_API_FEE_PAYER are optional overrides.
Both network paths update the local record only after cancellation settles. The current paid period remains active until its end. If the record lacks an expiry, the CLI can derive it from the activation time and the day or week period. --local-only skips the network operation and only marks a subscription that was cancelled elsewhere.
References: rust/…/cancel.rs• L41-79 rust/…/cancel.rs• L81-213 rust/…/cancel.rs• L263-341 rust/…/cancel.rs• L395-587 rust/…/cancel.rs• L607-623
Subscription record refresh
pay subscriptions refresh repairs local records that have no activation transaction reference. It asks the subscription's network for the oldest transaction touching the delegation identifier and stores the result. This covers receipt or indexer gaps after an otherwise successful activation.
A missing result is kept as a failure for that entry rather than guessed. Running the command again lets a later RPC or indexer update fill the gap.
References: rust/…/refresh.rs• L16-31 rust/…/refresh.rs• L33-112 rust/…/subscription.rs• L557-649
Payer-proxy usage
Agent request mediation
The payer proxy gives an agent CLI a local HTTP endpoint that can pay upstream 402 challenges. It is used when an agent process cannot handle payment itself, such as alternate provider routes started by pay claude, pay codex, or pay goose.
The proxy forwards the request to the selected upstream and buffers the body so it can replay the request once after signing. It streams the final response back to the agent. For compatible providers, it can translate the agent's API shape before payment and translate the successful response back afterward.
The proxy listens on loopback only. It is a child-process support service, not a general network service.
References: rust/…/payer_proxy.rs• L1-34 rust/…/payer_proxy.rs• L57-73 rust/…/payer_proxy.rs• L312-405 rust/…/mod.rs• L137-257
Session reuse and payment boundaries
The proxy supports an automatic payment mode and a session-only mode. Automatic mode prefers reusable or metered payment offers before one-shot payment. Session-only provider routes open one delegated MPP session and reuse its authorization for later requests from the same agent process.
The proxy keeps the session lock while a request is metered. It replaces a cached session only after a new paid retry succeeds. If payment cannot be built, the upstream is unreachable, or a hosted route returns success without its required payment challenge, the proxy fails closed or passes through the original 402 rather than hiding the payment problem.
References: rust/…/payer_proxy.rs• L75-111 rust/…/payer_proxy.rs• L355-405 rust/…/payer_proxy.rs• L484-655 rust/…/mod.rs• L460-519
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the network slug mapping aligned across CLI flags, RPC selection, Pay API balance requests, and receipt links.
localnetis the CLI name while balance and on-ramp services may usesandbox. - Keep the 402 challenge parsers aligned with the authorization header and receipt header emitted by each supported protocol. A request can pay successfully while losing its receipt link if only one side changes.
- Preserve one owned request body across the first HTTP call and the paid retry. File and multipart requests must keep their redirect and size rules.
- When subscription receipt fields or PDA derivation change, update local record creation and the refresh lookup together. The list and status views depend on the same subscription ID.
- Keep subscription cancellation discovery, fee display, gateway fee-payer selection, signed transaction shape, and post-settlement local status changes aligned. A mismatch can charge the user without a valid cancellation or show a cancelled record before the chain confirms it.
- When an agent provider changes API dialect or endpoint paths, update provider compatibility, proxy translation, and the launcher's selected base path as one contract.
- Keep the
tokens_unavailabledistinction through balance, top-up, and currency-selection flows. An API outage must not look like an empty wallet. - Keep the
pay sendinput contract aligned with recipient-name lookup, memo decoding and length limits, currency resolution, fee handling, and the transfer client. A change in one path can make a valid transfer fail before signing or change its reported amount. - Keep the fanout CSV schema, manifest hash, selected mint, token program, transaction plan, batch authorization, and journal events aligned. A mismatch can make a payout look valid in planning but unsafe to broadcast or hard to review afterward.
- Keep fanout preflight funding estimates consistent with the accounts that receive missing token accounts and with the executor's transaction count. Underestimating SOL can stop a batch after it has been authorized.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| The selected account has no stablecoin balance | pay send cannot choose a currency, and a paid request cannot sign a usable offer | Show balances first with pay whoami or pay account list; use pay topup before paid work |
| Stablecoin balance service is unreachable | Token data is unavailable, not zero; automatic currency choice and top-up detection may stop | Render the unavailable state and retry after the service recovers |
| No default account exists for the selected top-up network | pay topup stops before the funding flow starts | Run pay setup or pass a configured account name or valid Solana address |
| A forced network does not match the server challenge | The CLI refuses to sign the payment | Remove the forced network flag or use a service on the intended network |
A pay send recipient is neither a valid Solana address nor a configured account name | The transfer stops before the payment request | Use the recipient's address or configure the account on the selected network |
A pay send memo uses both forms, invalid hex, non-UTF-8 bytes, or too many bytes | The transfer stops before signing | Pass one valid text or hex memo within the on-chain limit |
| No single stablecoin covers the requested amount | Currency selection stops, even if several balances could add up to the amount | Fund one coin enough to cover the amount or select a coin with --currency |
| A file-backed fetch request receives a redirect | The body is not forwarded to the new destination | Re-run pay fetch against the final URL |
| A paid retry is rejected | The CLI returns the rejection or the proxy passes the original 402 through | Check the challenge, account funds, network, and protocol choice |
| Subscription activation succeeds but local persistence or indexer lookup fails | The service works, but the local list can miss the activation transaction or record | Run pay subscriptions refresh and then inspect status |
| A subscription cancellation gateway probe lacks a valid 402 challenge or fee-payer | The CLI cannot show a trusted charge or build the gateway transaction | Check the gateway URL and its payment response; use the direct path when the account has enough SOL |
| A subscription cancellation transaction fails after approval | The local record stays unchanged, so the subscription is not falsely shown as cancelled | Check the RPC or gateway error, then retry after the account and network recover |
| The payer proxy cannot pay a hosted route | The agent receives the original 402 instead of an unmetered success | Fund the selected account and verify the provider's advertised protocol and network |
| A fanout CSV is malformed or names an unsupported network or mint | The batch stops before signing and no payout is broadcast | Use the required recipient,amount headers and match the currency to the selected network |
| A fanout source lacks stablecoins or enough SOL for token accounts and fees | The batch stops during preflight instead of producing a partial payout | Fund the source token account and fee payer before starting the run |
| One or more fanout chunks fail to confirm | The command returns an error and the journal records a partial result | Use the journal to review confirmed and failed chunks before taking follow-up action |
Key files
| File | Why to read it |
|---|---|
| rust/…/main.rs | Defines global network, account, payment, sandbox, and automation behavior before commands run. |
| rust/…/mod.rs | Connects HTTP outcomes to challenge handling, paid retries, receipt display, and the payment command map. |
| rust/…/whoami.rs | Shows how the CLI resolves an account and presents its balances. |
| rust/…/topup.rs | Defines top-up destination selection and completion output. |
| rust/…/topup.rs | Explains the user funding choices and balance polling model. |
| rust/…/send.rs | Defines stablecoin transfer input, recipient resolution, memo validation, currency selection, fee handling, and transfer output. |
| rust/…/send.rs | Shows the service-backed transfer and fee-payer payment lifecycle. |
| rust/…/fanout.rs | Shows the CSV payout flow from preflight and batch authorization to concurrent confirmation and durable journal output. |
| rust/…/fetch.rs | Defines the built-in HTTP request shapes and body rules. |
| rust/…/fetch.rs | Defines replayable request bodies, redirects, and raw HTTP outcomes. |
| rust/…/receipt.rs | Provides the common view of MPP and x402 payment receipts. |
| rust/…/subscription.rs | Connects subscription challenges, activation records, and on-chain lookup. |
| rust/…/cancel.rs | Shows direct and gateway-assisted cancellation paths, charge discovery, approval, and expiry-aware local state. |
| rust/…/payer_proxy.rs | Defines local agent payment mediation, retry behavior, and session reuse. |
| rust/…/mod.rs | Maps selected agent providers to payer-proxy routes and payment protocols. |