You’re wiring an agent to take a WURK job, call a paid API, or pay an x402 endpoint, and it can keep going after the useful work ends. A retry loop can drain the wallet balance or keep adding charges to the API account while you’re away. This guide gives you a per-payment ceiling, a shared budget check, and a stop switch that reaches every payment worker.
The practical rule: keep the agent’s funds and credentials separate, check each charge before it happens, reserve the amount against a durable budget, and make every payment path obey the same stop control.
Map every route money can take
With x402, a service can respond to an HTTP request with 402 Payment Required and payment terms that include the scheme, network, amount, asset, and destination. The client signs a payment and retries the request with proof of payment. The exact scheme is for a fixed amount; upto authorizes a maximum and charges for actual usage. (x402 docs: HTTP 402, payment schemes)
An agent can also call an API using credentials tied to a billed provider account, or initiate an on-chain transfer through a wallet. Coinbase says settled exact and upto payments are irreversible, so check the terms before sending the authorization, not only after settlement (Coinbase x402 FAQ).
Inventory every route the agent can use: payment libraries, wallet signers, API keys, scheduled jobs, and retry handlers. If one path bypasses the budget check, the cap does not cover that path.
Isolate the funds and permissions
Give the agent a separate wallet with only the funds needed for its assigned work. Refill it on a schedule you control, or through a separate process with its own strict limit. Don’t give the agent access to the main wallet or the credentials that can refill it. A low balance limits what is exposed at once; it does not limit lifetime spending if the agent can keep topping itself up.
For x402, set a per-payment maximum and a cumulative budget, then restrict approved networks, assets, and payees. Coinbase documents spend controls for its CdpX402Client that do exactly this: a per-payment cap, a cumulative cap over a rolling window, and allow-lists for networks, assets and payees. Spend is reserved before the payment goes out, and if the outcome is unclear the reservation stands (Coinbase x402 FAQ).
Treat a service directory as a way to discover endpoints, not an endorsement. Coinbase says its Bazaar catalog makes no claim about a listing’s uptime, correctness, or response content. Check the endpoint against your own allow-list before paying it (same FAQ).
For API billing, isolate the agent in its own project or workspace where your provider supports it, with its own key and its own limit. Give the agent only the credentials and permissions its task needs.
Reserve the budget before paying
Set a maximum per request and a daily budget. Count pending payments against that budget, not just completed ones. If several workers can spend at once, the budget check must be atomic and shared: two requests must not both read the same remaining balance and spend it.
Parse the payment terms and compare them with your policy before signing. Check the endpoint, route, scheme, payee, network, asset, and amount. Use integer token units rather than floating-point arithmetic, and fail closed if a field is missing or cannot be parsed. The x402 payment requirements include an amount and destination; reject terms outside the limits you configured.
Here is pseudocode for a payment boundary. It assumes a separate ledger budget for the configured asset and network:
async function pay(request, operationId):
if not paymentsEnabled():
stop
quote = parse402(request)
if not allowedRoute(request) or
not allowedPayee(quote.payTo) or
not allowedNetwork(quote.network) or
not allowedAsset(quote.asset) or
not allowedScheme(quote.scheme):
stop
amount = parseIntegerUnits(quote.amount)
if amount <= 0 or amount > PER_CALL_MAX:
stop
reservation = await ledger.reserveNewAtomically(
operationId, amount, DAILY_CAP
)
if not reservation.created:
stop
try:
if not paymentsEnabled():
raise NOT_SUBMITTED
result = await submitOnce(request, quote)
if result.hasConfirmedSettlement:
await ledger.reconcile(reservation.id, result.receipt)
else:
await ledger.keepPending(reservation.id)
return result
catch error:
if error.provesPaymentWasNotSubmitted:
await ledger.release(reservation.id)
else:
await ledger.keepPending(reservation.id)
raise error
The durable ledger must atomically check completed spending plus pending reservations plus the new amount against the cap. It should reject a reused operation ID instead of submitting another payment. Include applicable fees in your budget, and don’t add amounts from different assets as though they were interchangeable.
If a request times out after submission, keep the reservation and investigate before trying again. The x402 docs are explicit that an HTTP timeout or lost response does not prove a payment failed (client/server: timeouts and safe retries), so a blind retry can pay twice.
API calls need a separate guard: reserve a conservative maximum cost based on the request limits and provider pricing, then reconcile against actual usage when available. Route every billed call through that guard too.
Use provider limits as another layer
Set provider-side limits where they exist, but read what each one actually does. Three questions to answer from your provider's billing docs: is it an alert that lets traffic continue, or a hard limit that stops requests? Is enforcement instant, or can recorded spend overshoot a little? Can the limit apply to the agent's own project or workspace, or only to the whole account?
Keep local per-call and daily checks even when a provider has a hard cap. A monthly project cap and a daily job budget protect different scopes. Send alerts for a blocked charge, an approaching budget, and any payment whose outcome remains unresolved.
Make the stop switch reach every payment
Use one control, such as a centrally checked PAYMENTS_ENABLED=false setting or a stop file, and require every worker to check it before signing and again before submitting. Route all payments through the guarded function. An environment variable read once by one process will not stop other workers, scheduled jobs, or code that bypasses the guard.
Keep the switch and spending policy outside the agent’s ability to change them. Know how to disable the API credential or stop the payment service if the agent is stuck. Test the switch before launch, including while a job is running. A stop signal prevents future attempts; it does not cancel a payment already submitted.
Pre-launch checklist
- Separate wallet and API credentials for the agent
- Per-payment maximum and daily budget configured
- Pending payments count against the budget
- Payees, endpoints, networks, assets, and schemes allow-listed
- Provider limit checked for scope, reset period, and enforcement behavior
- Alerts reach you outside the agent process
- Stop switch tested across every worker and payment route
- Timeout behavior preserves reservations until the outcome is known
Optional tool tip (referral links). A payment cap is only half the budget. If a coding agent writes your agent's code, its model usage costs money too, and a flat plan is easier to cap than a per-request meter. You can try ZCode free through this invitation (complete the invitation's onboarding steps and check current eligibility and terms) or check the Z.ai Coding Plan referral discount (the final price and any discount show at checkout). We may receive referral credit. Eligibility, included models and terms are set on the destination pages.
If this helped you avoid a runaway bill, a tip on this post is always appreciated.
Related: Make your AI agent a polite API client: rate limits and Retry-After






Latest comments
0