Dev.to AI 🤖 Ai 👁 0 📖 6 min read

Your AI agent's per-payment limit won't save its wallet

Most agent payment setups have one guardrail: a per-payment limit. "Never pay more than $50." That stops one big mistake. It does nothing about fifty small ones. An agent that pays for APIs with x402 signs a USDC autho

Most agent payment setups have one guardrail: a per-payment limit. "Never pay more than $50."

That stops one big mistake. It does nothing about fifty small ones.

An agent that pays for APIs with x402 signs a USDC authorization per request. If a server keeps asking, or a prompt injection keeps the agent looping, each payment is under the limit and every one of them goes through. Stablecoin payments are final, so there is nothing to claw back afterwards.

In October the Cloud Security Alliance wrote up 25 flaws in the x402 SDKs. One of them: the default client paid whatever the server asked, up to the wallet's balance. Their advice is worth reading in full, but the short version is: per-payment and cumulative budgets, enforced outside the model, where the agent cannot override them, and the payer's policy decides what is paid, not the payee's request.

This post adds exactly that to an agent in about five minutes, with sra-riskgate, an open-source Python library of payment checks (Apache 2.0). Version 1.8.0 adds four things:

  1. Rolling budgets per agent wallet and per payee
  2. Anomaly holds for unusual spending rates and amounts
  3. Signed receipts for every decision
  4. One policy file for all of it
pip install "sra-riskgate>=1.8.0"

1. A budget that counts across payments

from sra_riskgate import ActionDecision, SpendGuard, SpendLedger, check_payment

AGENT = "0x1111111111111111111111111111111111111111"
API = "0x2222222222222222222222222222222222222222"

guard = SpendGuard(
    SpendLedger("~/.sra-riskgate/ledger.jsonl"),  # local JSON Lines file; omit the path for memory only
    total_limit=5.00,          # at most $5 per agent wallet...
    per_payee_limit=2.00,      # ...and $2 to any one payee...
    window_seconds=86_400,     # ...in any 24 hours
)

for i in range(1, 6):
    r = check_payment(chain_id=8453, sender=AGENT, recipient=API, amount=0.50,
                      peg_deviation_pct=0.0, spend_guard=guard)
    print(i, r.decision.value, r.flags)
1 approve []
2 approve []
3 approve []
4 approve []
5 hold ['PAYEE_BUDGET_EXCEEDED']

Four payments of $0.50 fit the $2 per-payee budget. The fifth would make it $2.50, so it is held, with a reason the agent can show a human:

2 has been approved to this payee in the last 24 h; 0.5 more would exceed the per-payee budget of 2.

A few details that matter in practice:

  • A payment counts when it is approved. Checks made one after another all count, so the agent cannot get ten approvals before paying any of them. If an approved payment is never sent, pass payment_id="inv-42" when checking and call guard.release("inv-42") to remove it.
  • Only approvals count. A payment that was held or rejected for another reason (a look-alike payee, a self-vouching invoice) does not use up the budget.
  • It holds, it never rejects. A budget being hit does not mean the payment is fraud. It means a person should look.
  • A corrupt or unreadable ledger holds every payment. A broken file never lets one through.

2. Holding what doesn't look like this wallet

Budgets catch volume. Two more limits catch patterns:

guard = SpendGuard(
    max_payments_per_hour=60,   # RATE_SPIKE: a sudden burst of payments
    amount_spike_factor=5,      # AMOUNT_SPIKE: 5x this wallet's usual payment to this payee
)

AMOUNT_SPIKE compares the amount with the median of the wallet's last payments to that same payee. An agent that pays a search API $0.002 a call will have a $5 request to that API held, while a new payee is not judged by it at all (pass known_recipients for that: unknown payees are held as NEW_COUNTERPARTY).

3. It works on the exact thing the agent signs

Agents rarely call a "pay" function. They sign a transaction, an x402 authorization, or a smart-account UserOperation. The same guard works with every check in the library:

from sra_riskgate import check_authorization, check_transaction, check_user_operation

check_transaction(tx, spend_guard=guard)                         # raw transaction or ERC-20 transfer
check_authorization(typed_data, sender=AGENT, spend_guard=guard)  # x402 / EIP-3009 signature
check_user_operation(user_op, chain_id=8453, spend_guard=guard)  # ERC-4337 smart account

Smart-account batches get one extra rule. A batch is checked call by call and as a whole, and it is counted once. Two calls of $1.20 each to the same payee each fit a $2 per-payee budget; the batch does not:

hold ['BATCH_TOTAL', 'PAYEE_BUDGET_EXCEEDED']

Splitting a payment across calls is one of the oldest ways around a per-transaction limit, so this matters.

4. A receipt for every decision

When an agent pays on its own, "what did the gate decide, and why?" becomes an audit question. A log line can be edited. A signed receipt cannot, at least not without breaking it:

from sra_riskgate import ReceiptSigner, issue_receipt, verify_receipt

secret = bytes.fromhex("11" * 32)          # keep it in a secret manager, not in code
payment = {"chain_id": 8453, "sender": AGENT, "recipient": API, "amount": 0.50}
r = check_payment(**payment, peg_deviation_pct=0.0)

receipt = issue_receipt(r, ReceiptSigner.hmac(secret), payment=payment)
print(verify_receipt(receipt, key=secret))      # True

receipt["decision"] = "reject"
print(verify_receipt(receipt, key=secret))      # False: any edit breaks it

The receipt covers the decision, flags, explanation, the payment, the policy's hash, the time and the library version.

With an HMAC key, anyone holding the secret could also make receipts, so it proves integrity to you. For receipts an auditor or counterparty can check without the secret, sign with an Ethereum key instead (pip install "sra-riskgate[receipts]"). They then verify against your address, and nobody without the key can forge one:

signer = ReceiptSigner.ethereum(receipts_only_private_key)   # a key that holds no funds
receipt = issue_receipt(r, signer, payment=payment)
verify_receipt(receipt, expected_signer="0xYourReceiptAddress")

One honest caveat: a receipt proves what the gate decided. It does not prove the payment was sent. The library's verify_settlement() checks that from the chain.

5. One policy file instead of rules in every agent

Rules scattered across agent code drift apart. Put them in one file your team reviews like code:

{
  "version": 1,
  "name": "api-buying-agents",
  "max_amount": 25,
  "known_recipients": ["0x2222222222222222222222222222222222222222"],
  "blocked_addresses": [],
  "screening": {
    "providers": [{"type": "chainalysis", "api_key_env": "CHAINALYSIS_API_KEY"}, {"type": "trm"}]
  },
  "budgets": {"window_hours": 24, "total": 50, "per_payee": 20},
  "anomalies": {"max_payments_per_hour": 60, "amount_spike_factor": 5},
  "ledger": "~/.sra-riskgate/ledger.jsonl"
}
from sra_riskgate import load_policy

policy = load_policy("payment-policy.json")     # .yaml works too, with PyYAML
r = check_payment(chain_id=8453, sender=AGENT, recipient=API, amount=0.50,
                  **policy.check_kwargs())
receipt = issue_receipt(r, signer, payment=payment, policy=policy)  # records policy.sha256

Two rules keep the file safe to commit:

  • API keys never go in it. api_key_env names the environment variable that holds the key. A literal api_key field is refused.
  • Unknown keys are refused. A typo like "max_ammount" raises an error instead of silently dropping your limit.

Using it from Claude Desktop or Cursor

The same checks ship as an MCP server. Budgets, receipts and the policy file are environment variables:

{
  "mcpServers": {
    "sra-riskgate": {
      "command": "uvx",
      "args": ["sra-riskgate-mcp"],
      "env": {
        "SRA_BUDGET_TOTAL": "50",
        "SRA_BUDGET_PER_PAYEE": "20",
        "SRA_MAX_PAYMENTS_PER_HOUR": "60",
        "SRA_LEDGER_FILE": "~/.sra-riskgate/ledger.jsonl",
        "SRA_RECEIPT_KEY": "<64 hex characters>"
      }
    }
  }
}

Every payment decision then carries a receipt, and a verify_receipt tool checks one later. Or set SRA_POLICY_FILE to the file above. If a rule is set both in the file and as its own variable, that is a configuration error, never a silent override.

What this does not do (yet)

  • The ledger is per machine. Two checks at the same instant can both pass before either is recorded. For hard limits, check payments from one process, one at a time. A shared ledger across machines is the obvious next step.
  • Budgets are in dollars, not per token. Every supported stablecoin (USDC, USDT, USDB, USDG) is dollar-pegged, so totals add up across them.
  • It is a gate, not a wallet. It never holds funds or signs anything. Your agent should only sign when the decision is approve.

Try it

If you run agents that pay, I'd love to hear which limit you'd want next. And if you find a way past these checks, please open an issue; that is the most useful feedback there is.

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.