r/ethdev • • 23d ago

My Project We deployed an on-chain Spend Policy & Circuit Breaker on Polygon to prevent AI agents from draining wallets ($5k/tx hard cap, verified contract)

Hey r/ethdev,

Over the past few months, we've been building infrastructure for autonomous AI agents (ElizaOS, LangChain) that interact with smart contracts.

The biggest security hole we observed is that **most teams pass raw private keys or unconstrained session keys to LLMs**. If an agent encounters a prompt injection or hallucinates an input parameter, it can drain an entire contract or treasury in a single block.

To solve this, we deployed and verified **`SecurityGateOMSPolicy.sol`** on Polygon Mainnet to act as an on-chain economic circuit breaker.

### πŸ› οΈ Architecture Highlights:

  1. **Hard Spend Caps at Contract Level:**

    * Single Transaction Max: $5,000 USDC

    * 24-Hour Velocity Cap: $25,000 USDC

    * Any call violating these thresholds automatically reverts, completely bypassing whatever the LLM decided.

  2. **EIP-712 Dual-Attestation:** All agent deliverables and truth oracle attestations require deterministic EIP-712 structured data signatures before releasing escrow funds.

  3. **Pre-Sign AST Analysis (<5ms):** Before an agent signs an EVM transaction, its generated payload undergoes deterministic AST parsing off-chain to detect code injection or malicious parameters.

### πŸ“œ Verified Contracts:

* **Polygon Mainnet Policy:** [`0x4A28F9A2E6D0DcB69791980560FC8364A514f205`](https://polygonscan.com/address/0x4A28F9A2E6D0DcB69791980560FC8364A514f205)

* **Universal Escrow Core:** `0x4Dbd77F4799816859a595f24a57A786516D2EAa8`

We’d love to get feedback from other smart contract engineers on how you're handling agentic wallet permissions and multi-sig fail-safes!

*(Open-source repos, packages, and architecture docs are in the first comment)*

2 Upvotes

12 comments sorted by

1

u/EstablishmentTough18 23d ago

Open-source resources and contract links:

πŸ“œ **Polygonscan Verified Code:**

https://polygonscan.com/address/0x4A28F9A2E6D0DcB69791980560FC8364A514f205#code

🌐 **Live Gateway & Hub:**

https://agent-security-gate-x402-212942243360.asia-northeast3.run.app/hub/

πŸ“¦ **NPM Package:** https://www.npmjs.com/package/security-gate-x402

🐍 **PyPI Package:** https://pypi.org/project/security-gate-x402/

Looking forward to your thoughts and constructive feedback on our on-chain spend policy!

1

u/EstablishmentTough18 22d ago

### 🚨 Today's Keplr / Web3Auth breach (44,041 wallets, $6M exposed) is the textbook proof of why on-chain spend circuit-breakers are mandatory.

Just hours ago, a major vulnerability in Web3Auth's social-login mapping exposed over 44,000 Keplr wallets across 7 chains.

The most alarming part? **There were zero on-chain velocity limits or spend caps.** The only way the core team could save user funds was to perform an emergency, manual white-hat sweep racing against the hackers to drain their own users' accounts before the attackers did.

This exact nightmare is why we designed **A.GRID Security Gate & Escrow**:

  1. **Never trust the auth layer alone:** Even if a Google/Apple OAuth session, MPC key-share, or agent private key is completely compromised, the smart contract must enforce an on-chain ceiling ($5k single-tx, $25k daily rolling window).
  2. **Deterministic Pre-Sign Inspection (<2.8ms):** Rogue automated sweeps triggering abnormal velocity spikes get quarantined before transactions can be broadcast.

Convenience without on-chain circuit breakers is an economic catastrophe waiting to happen. How is your team implementing hard spend limits on user and agent wallets today?

1

u/Tritan-Devillalba47 22d ago

Hard caps in the contract are the backstop most of agent wallet builders end up wanting it.

1

u/EstablishmentTough18 22d ago

100%. That was the exact architectural journey our team went through.

Most teams usually start with soft client-side guardrails or ephemeral session keysβ€”until an adversarial prompt injection or a compromised key-share (like today's Keplr/Web3Auth incident) bypasses the off-chain checks entirely.

When that happens, the only thing that stands between an intact treasury and zero balance is the contract reverting the transaction directly on-chain.

Are you seeing teams prefer rolling 24h velocity windows or epoch-based resets for the limits? In `SecurityGateOMSPolicy.sol`, we settled on a rolling window paired with a single-tx hard cap to prevent burst exploits at epoch boundaries.

1

u/0xfone 16d ago

After your allowance update, I'm curious about approvals that remain unused for more than 24 hours. When the spender eventually calls transferFrom, does that allowance still reserve headroom, or has it aged out of the daily budget ?

I'd test a delayed spender alongside a fresh approval after the window moves on. Is the 24-hour cap meant to bound newly granted authorization, or all token outflow in that window??

1

u/EstablishmentTough18 16d ago

Really sharp catch β€” you nailed a classic ERC-20 allowance edge case.

To answer honestly based on our current architecture:

  1. **On-chain (`SecurityGateOMSPolicy.sol`):**

    `checkUserOpPolicy` enforces a **session-lifetime ceiling** (`cfg.currentSpent + effectiveSpend <= cfg.maxSpendLimit` until `expiresAt`), not a resetting 24h bucket, and restricts `spender` to `cfg.allowedTarget` (e.g., the Escrow contract). So within a session, an unused `approve` still consumes session headroom and cannot go to an arbitrary EOA.

  2. **Off-chain 24h Sliding-Window Velocity Cap (`$25k / 24h`):**

    Right now, the 24h sliding window bounds **newly authorized spend/approvals** in that rolling window. Because an external spender calling `transferFrom()` directly on the token contract doesn't route back through `UserOp` validation, a stale approval sitting past 24h would indeed fall outside a pure authorization-window counter.

**How we're closing that gap cleanly:**

- Bounding **all token outflow** requires either (a) never leaving lingering allowances open (using Permit2 / EIP-2612 `permit` with tight `deadline` or resetting `allowance` to `0` post-call), or (b) counting **active unconsumed allowances + observed on-chain `Transfer` outflows** in the 24h tracker rather than aging approvals out after 24h.

Adding your delayed-`transferFrom` + fresh-approval test case to our simulation suite β€” appreciate the thoughtful review!

1

u/rayQuGR 18d ago

This is an interesting approach because it puts spending restrictions outside the LLM's decision-making process. That's an important distinction. An AI agent should never be the final authority over how much it can spend.

I'd also be interested in how the policy handles token price changes, cumulative spending across multiple wallets, and attempts to bypass limits through several smaller transactions. A per-transaction cap is useful, but the velocity limit and authorization model are just as important.

There's also an interesting connection to confidential computing. With Oasis Sapphire, sensitive agent logic and transaction-related state can be handled in a confidential EVM environment, while ROFL can support verifiable off-chain policy evaluation. That could complement an on-chain circuit breaker, especially when an agent needs access to private strategy data without exposing everything publicly.

The key principle, in my view, is that the agent should propose actions, but independent policy enforcement should decide whether those actions are allowed. Prompt injection defenses are useful, but spending limits, authorization checks, and fail-safe mechanisms need to hold even when the model behaves unexpectedly.

0

u/[deleted] 20d ago

[removed] β€” view removed comment

1

u/EstablishmentTough18 19d ago

Spot-on catch β€” thank you! Relying only on native `value` or direct `transfer` leaves the `approve` -> spender-initiated `transferFrom` (and EIP-2612 `permit`) path wide open since the subsequent `transferFrom` executes directly on the token contract outside the wallet's guard.

We just updated both `SecurityGateOMSPolicy.sol` and our pre-sign policy engine to decode calldata selectors (`0x095ea7b3` approve, `0x39509351` increaseAllowance, `0xd505accf` permit, `0xa9059cbb` transfer, and `0x23b872dd` transferFrom) so that:

  1. Any allowance grant is counted immediately toward `effectiveSpend` against `maxSpendLimit` at approval time.
  2. `spender` is strictly checked against the whitelisted `allowedTarget` (reverting with `UnauthorizedSpender` otherwise).

Really appreciate the sharp review!

0

u/[deleted] 12d ago

[removed] β€” view removed comment

1

u/EstablishmentTough18 12d ago

Great questions β€” you're hitting the exact distinction between a dumb spending limit and a real policy engine. Here is how our current contract (`SecurityGateOMSPolicy.sol`) and OMS adapter handle both:

### 1. What happens when the cap trips mid-task?

It **never** silently splits or retries smaller to route around the per-tx cap (an agent turning a $6k payout into two $3k calls would defeat the control).

* **On-chain:** `checkUserOpPolicy` deterministically reverts with `BudgetExceeded(uint256 attempted, uint256 remaining)`.

* **Mid-task flow:** The settlement leg halts and returns a structured rejection receipt containing `sessionKey`, `attemptedAmount`, `remaining24hAllowance`, `target`, and `payloadHash`. From there, a human operator can either bump the scoped session allowance on-chain (`registerSession`) or explicitly authorize a partial milestone escrow split (`alpha`-split) if the counterparty agrees to staged delivery.

### 2. What does the EIP-712 attestation actually bind to?

It binds **much more than just "amount < cap."**

In `SecurityGateOMSPolicy.sol`, the EIP-712 struct is:

`SecurityAttestation(bytes32 payloadHash, uint8 riskScore, string verdict, uint256 expiresAt)`

* **What was delivered/audited:** `payloadHash` is the Keccak-256 digest of the exact audited deliverable/request payload that passed the <10ms AST/injection/NLI gate (`riskScore <= 30`, not expired).

* **Who & Where:** `checkUserOpPolicy` binds that execution to a specific `sessionKey` and whitelisted `target` (e.g., the Escrow Hub), and decodes ERC-20 `transfer` / `approve` / `transferFrom` / `permit` selectors directly in Solidity so an agent can't smuggle an arbitrary spender or recipient inside calldata.

*(Fair nuance: right now `sessionKey` + `target` are enforced at the `checkUserOpPolicy` boundary while `payloadHash` lives inside the signed struct β€” pulling an explicit `requester` and `nonce` directly into `ATTESTATION_TYPEHASH` for strict 1:1 request-to-settlement binding is a clean v2 hardening step.)*