{"slug": "spending-mandates-for-agents-the-wallet-can-never-raise-its-own-limit", "title": "Spending mandates for agents: the wallet can never raise its own limit", "summary": "A developer built Turnstile, a paid-lane system for onchain data agents that enforces spending mandates so the key that spends can never raise its own limit. The design splits authority across a 2-of-2 board quorum that sets the cap, a 1-of-2 operations quorum that funds the agent within it, a Privy server wallet for the buyer organization, and an agent wallet on Arc that can only spend, never deposit or widen limits. The agent pays through Circle Gateway by signing EIP-3009 authorizations offchain, so it holds no gas and cannot submit transactions, bounding losses to what was deposited.", "body_md": "*Part 7 of 9 in the [Turnstile series](https://ignaciopastorsanchez.com/blog/series/turnstile): building a paid lane for onchain data agents.*\n\nAs part of Turnstile we built an agent that buys answers over paid HTTP (x402-style). An agent that pays needs a spending limit, and the limit is worthless unless one rule holds:\n\n**The key that spends can never raise its own limit.**\n\nA limit exists for the day the agent misbehaves: a prompt injection, a bad dependency, a leaked key. Whoever controls the agent's key can then do anything that key can do. If raising the limit is one of those things, they raise it first and spend second.\n\nThis is how we made that true without writing the enforcement ourselves.\n\n`PATCH`.` 401`) and accepts it with two.\nThe code is at [github.com/IpastorSan/turnstile](https://github.com/IpastorSan/turnstile), and the `/mandate` page is on camera in the [demo video](https://github.com/IpastorSan/turnstile/blob/main/docs/demo/turnstile-demo.mp4). Everything below runs on testnet.\n\nThe usual first design for a paying agent goes like this. The agent has a wallet. Some config says \"max $1 per day\". The agent's code checks the config before paying. The problem is that the thing enforcing the limit and the thing being limited share a process. A prompt injection, a bad dependency or a leaked `.env` defeats both at once, because whoever can spend can also edit the check.\n\nIn Turnstile, the limits a buyer gives its agent are a **mandate**: a total spend cap, a ceiling per query and a list of sellers it may pay. The agent's code checks the mandate before every payment, but that check is exactly the one a compromised agent skips.\n\nThe agent can only spend what is in its wallet, and the only way money gets in is a deposit from the buyer organization's wallet. Cap that deposit and a compromised agent can't overspend: it runs out of money instead.\n\nSo we set a stricter goal. Assume our server is fully compromised, app secret included. What should still hold?\n\nThe agent never asks for money. An operator tops it up by hand, one deposit at a time (`scripts/arc-setup.ts`), and the agent spends what it holds; inside that balance, only its own checks stop it. So the mandate doesn't make a compromised agent behave. It bounds the loss to what was deposited.\n\nTopping up by hand is fine for a testnet demo, but it does not scale. Automating it means a job that holds an operations key, and if that job runs on our server, a compromised server can approve capped deposits as often as it likes. At that point the cap has to cover the running total, not just each deposit.\n\nOn the buyer side, authority runs one way: from the humans who set the rules, through the wallet that funds the agent, down to the agent that spends. Each layer may authorize less than the one above it.\n\n| Layer | What it is | May authorize | \n|---|---|---|\n| **Board quorum** | Two operators, 2-of-2, owning the mandate policy | Raising the cap | \n| **Operations quorum** | Two operators, 1-of-2, owning the org wallet | Funding the agent, within the cap | \n| **Org wallet** | A **Privy server wallet** for the buyer organization | Deposits to the agent, and only what the policy allows | \n| **Agent wallet** | The buyer agent's wallet on Arc | Nothing. It spends inside the mandate | \n\nThe seller side has the same split: its hot key can change the price but not the payout address (see [The offer is the name: ENSv2 records and a key split the chain enforces](https://ignaciopastorsanchez.com/blog/ensv2-agent-offer-records-hot-cold-keys)).\n\nThe agent wallet is the interesting one. The agent pays through Circle Gateway by signing EIP-3009 authorizations offchain, and the batcher submits them. The agent never submits a transaction, so it has no gas and no way to deposit, withdraw or widen anything.\n\nThat leaves one tap that fills the agent's balance, and the agent doesn't control it. The org wallet calls `depositFor(token, agent, value)` on Circle's GatewayWallet contract: the org wallet sends the transaction and pays the gas, and the balance is credited to the agent. Cap that call and the mandate is capped at its source.\n\nThe org wallet is a Privy server wallet: Privy holds its private key, and we ask Privy to sign with it. A deposit goes like this: our code builds the `depositFor` transaction and sends it, unsigned, to Privy's API, together with an operator's signature approving the request. Privy checks that signature against the wallet's owners, checks the transaction against the wallet's policy, and only if both pass does it sign. We get back a signed transaction and broadcast it to Arc ourselves.\n\nThree things follow from that.\n\n`.env` gives nobody the power to spend.\nThe policy is two ALLOW rules and nothing else:\n\n```\nreturn [\n  {\n    name: 'Fund the agent, within the mandate',\n    method: 'eth_signTransaction',\n    conditions: [\n      { field_source: 'ethereum_transaction', field: 'to', operator: 'eq', value: gateway },\n      { field_source: 'ethereum_calldata', field: 'depositFor.depositor', abi: DEPOSIT_FOR_ABI, operator: 'eq', value: agent },\n      { field_source: 'ethereum_calldata', field: 'depositFor.value', abi: DEPOSIT_FOR_ABI, operator: 'lte', value: cap },\n    ],\n    action: 'ALLOW',\n  },\n  // ...a second rule caps approve(spender = GatewayWallet, value <= cap)\n];\n```\n\n*Trimmed from [`buyer/mandate/policy.ts`](https://github.com/IpastorSan/turnstile/blob/main/buyer/mandate/policy.ts)*\n\nThree conditions do the work:\n\n`depositor` argument must be this agent, so the org wallet cannot fund some other address inside its cap.`value` must be at or below the cap, written as hex USDC atomic units and rounded down, because rounding a ceiling up authorizes more than the operators approved.\nA single quorum cannot express the control we wanted. If the wallet needed 2-of-N, funding the agent would need a meeting. If the policy needed 1-of-N, one compromised operator key could raise the cap and then spend against it.\n\nSo the org wallet and the policy have different owners:\n\n| Quorum | Threshold | Owns | So this needs | \n|---|---|---|---|\n| operations | 1 of 2 | the org wallet | any one operator, for routine funding | \n| board | 2 of 2 | the mandate policy | both operators, to widen what the agent may spend | \n\nThe setup script creates both quorums from the same two operators and hands each one a different resource:\n\n``` js\nconst ops = await createKeyQuorum(privy, { displayName: 'Turnstile operations', members: operators, threshold: 1 });\nconst board = await createKeyQuorum(privy, { displayName: 'Turnstile board', members: operators, threshold: 2 });\n\nconst policy = await createMandatePolicy(privy, { mandate, agentAddress, ownerQuorumId: board.id });\nconst wallet = await createOrgWallet(privy, { ownerQuorumId: ops.id, policyId: policy.id, displayName: 'Turnstile buyer org' });\n```\n\n*From [`scripts/privy-org-setup.ts`](https://github.com/IpastorSan/turnstile/blob/main/scripts/privy-org-setup.ts)*\n\nThe wallet is created with its owner and policy already set. A wallet created bare and patched later has no owner and no policy for a moment, and we did not want that moment to exist on something holding a treasury. `createKeyQuorum` also refuses a threshold above the member count, because that quorum could never approve anything, and you only find out when you need it.\n\nEvery request to change something a quorum owns needs two kinds of proof. Our app secret proves the request comes from Turnstile. The operators' signatures prove who approved it. Each signature covers that exact request, so it cannot be reused to approve a different one. Stealing the app secret gets an attacker the first proof, never the second, so it cannot raise the cap. The two-person rule is enforced by Privy, not by an approval screen in our app that an attacker could go around by calling the API directly.\n\n`npm run privy:mandate` plays the whole story against the live API. This is the part of the transcript that matters:\n\n```\n3 & 4. THE ORG WALLET FUNDS THE AGENT: PRIVY DECIDES, NOT US\nfund $0.25, at the cap, alice approves        SIGNED  0x02f8d2834cef5280830f4240…\nfund $1, over the cap, alice approves         REFUSED 400 policy_violation\nfund $0.25, nobody approves                   REFUSED 401 Missing `privy-authorization-signature` header\n\n5. RAISING THE CAP NEEDS A QUORUM\nalice (CFO) proposes raising the cap $0.25 → $1\n\nalice alone      REFUSED 401 Number of signatures in `privy-authorization-signature` header\n                 does not match the wallet's authorization threshold.\n\nbob (Head of Research) approves.\n\nalice + bob      RAISED → Turnstile mandate, $1 cap\nfund $1, the same request as beat 4           SIGNED  0x02f8d2834cef5280830f4240…\n```\n\n*From [`docs/privy-mandate.md`](https://github.com/IpastorSan/turnstile/blob/main/docs/privy-mandate.md), punctuation lightly edited*\n\nThe three failures are different, and we keep them apart in code. `400 policy_violation` is the organization saying no. `401` with a missing header means nobody asked. `401` with a threshold mismatch means someone asked and not enough people agreed. The error text says \"wallet's\" even though the resource being patched is a policy.\n\nThe raise itself is an ordinary `PATCH /v1/policies/{id}` with new rules. `raiseSpendCap` has no force flag and no admin override, and could not have a useful one: the threshold check runs on Privy's side, so an override in our code would be a 401 with extra steps. It also refuses to lower a cap. Lowering carries different risk and should not slip through the raise path.\n\nThen the money moved. The org wallet signed `approve` and `depositFor` with one operator's approval, inside the policy, and we broadcast both ourselves. Privy does not route RPC for Arc testnet, and it doesn't need to: `eth_signTransaction` only needs a `chain_id` to produce an EIP-155 signature. Both transactions are on [ArcScan](https://testnet.arcscan.app/address/0x3De96375140717193f52c220Df5Ec460971cbE84), sent from the org wallet four seconds apart. The agent's Gateway balance went from 0.1055 to 0.3555 USDC, and its nonce stayed at 0.\n\nOperator keys are P-256 keys, the kind Privy accepts in a quorum. On `/mandate/new` the browser generates them and sends us only the public half, so our database, logs and environment never hold anyone's approval key.\n\nThat protection is not perfect. The private key is shown on the page and the operator copies it into a `.env` file, so it ends up as plain text on their laptop. And our server serves the page's code: a compromised server could ship a version that copies the key as it is made.\n\nIf we built it again, we would not hand out raw keys. Privy accepts two better kinds of quorum member:\n\n**Multisig and threshold approval.** A key quorum is an m-of-n approval, like a Safe. The difference is where it runs: a Safe checks signatures on chain and pays gas to do it. A Privy quorum is checked by Privy's API and enclave before a signature exists, so nothing reaches the chain unless the policy and threshold both pass. You gain speed and any-chain signing, but you trust Privy's infrastructure instead of a contract you can read. For an org wallet that funds an agent a few times a day, that trade is fine. For a cold treasury we would still want something on chain.\n\n**Account abstraction session keys.** A session key is a scoped signer on a smart account (targets, a spend limit, an expiry) enforced by a validator module. Same idea of bounded delegation, but the limit lives next to the account. Our setup has no smart account: the agent is a plain EOA that never transacts, and the limit sits one level up, on the tap that fills its balance. What session keys do not give you out of the box is the asymmetry: one approval to operate, two to change the rules.\n\n**x402 buyers.** An x402 buyer is where this matters most, because the agent reads a `402` challenge and decides to sign a payment on its own. Turnstile enforces the mandate twice. First, the agent's own code checks each offer against the seller allowlist, the per-query ceiling and what is left of the cap, and refuses before signing. Then Privy refuses to hand the agent money beyond the cap at all. The first check is the agent being well behaved. The second holds even when it is not.\n\nFive come from Turnstile itself.\n\n`{ method: '*', action: 'DENY' }` blocks everything`to` then fails to match. Run every address through `getAddress()`.` policy_violation` has no detail.`gas_limit` and the fee fields take a JSON number or a `0x` string. `bigint.toString()` produces exactly the rejected form, and Arc fee values overflow a safe integer, so we send hex everywhere.`GET /v1/policies` and `GET /v1/key_quorums` return 405\nTurnstile's Privy cap is **per deposit**, not cumulative. The running total is tracked by the agent's own ledger. We reused the same Privy app in our next project, Sente, where you hire an AI agent to trade on Monad, and tried to close that gap with a stateful policy. That work added three more findings.\n\n`chain_id` accepted hex. The typed-data domain `chainId` condition and the timestamp needed decimal. Typed-data requests carry no transaction chain id at all, so the chain has to be pinned through the EIP-712 domain.`docs/privy-mandate.md` holds the live transcript and rough edges, `docs/EVIDENCE.md` the evidence table.`approve` from the org wallet, success.`depositFor` from the org wallet to the GatewayWallet, success.`privy-authorization-signature` header.`PATCH /v1/policies/<id>`, owner signature required.` eth_signTransaction` signs without broadcasting.\n**Next in the series:** [Sell the answer, keep the method: Chainlink CRE Confidential Workflows](https://ignaciopastorsanchez.com/blog/chainlink-cre-confidential-workflows-sell-the-answer), part 8 of 9.", "url": "https://wpnews.pro/news/spending-mandates-for-agents-the-wallet-can-never-raise-its-own-limit", "canonical_source": "https://dev.to/ignacio_pastor/spending-mandates-for-agents-the-wallet-can-never-raise-its-own-limit-4lfk", "published_at": "2026-12-02 11:37:05+00:00", "updated_at": "2026-12-02 11:44:47.598973+00:00", "lang": "en", "topics": ["ai-agents", "ai-safety", "agent-protocols"], "entities": ["Turnstile", "Arc", "Circle Gateway", "Privy", "GatewayWallet", "Ignacio Pastor Sanchez"], "also_reported_by": [], "takeaway": "Enforce agent spending limits outside the agent's process by giving the agent a wallet it can only spend from and funding it via capped deposits from a separately controlled org wallet, so a compromised agent runs out of money instead of raising its own cap.", "recommendation": {"advice": "Keep the spending key unable to raise its own limit: fund the agent wallet only through capped deposits from an org wallet controlled by a separate quorum, and have the agent sign offchain payment authorizations so it holds no gas or withdrawal rights.", "playbook": "agent-security", "playbook_url": "https://wpnews.pro/playbooks/agent-security"}, "alternates": {"html": "https://wpnews.pro/news/spending-mandates-for-agents-the-wallet-can-never-raise-its-own-limit", "markdown": "https://wpnews.pro/news/spending-mandates-for-agents-the-wallet-can-never-raise-its-own-limit.md", "text": "https://wpnews.pro/news/spending-mandates-for-agents-the-wallet-can-never-raise-its-own-limit.txt", "jsonld": "https://wpnews.pro/news/spending-mandates-for-agents-the-wallet-can-never-raise-its-own-limit.jsonld"}}