# Automatic payments, spending limits and mandates

This page is for two readers: the **human** who wants an agent to spend money
without asking every time, and the **integrator** whose platform runs the agent.
It describes exactly what AIPAY enforces, what it does not, and who carries
which risk.

Everything here is **local**. AIPAY holds no keys, signs nothing on a user's
behalf, and has no "payout API" for somebody else's agent. That is a product
boundary, not a missing feature: it is the reason an attacker who reaches our
servers still cannot move a user's money.

The machine-readable versions are [`/llms.txt`](../llms.txt) and
[`/agent.json`](../../agent.json); this page is the prose version of the same
rules.

## What "automatic payment" means here

The agent surface (`agent/mcp-server.mjs`, `agent/cli.mjs`) is a local process
with its **own** wallet. It can already:

- create a payment request (a static link + QR payload) and reconcile it,
- **pay out** — `aipay_pay` signs with the agent's own key and broadcasts,
  on 8 EVM mainnets, Solana and Tron,
- watch for incoming payments with its own RPC quota (`aipay watch`).

What it may spend is decided by **two independent gates**, and a payment must
pass **both**:

| Gate | What it is | Signed by | Where it lives |
|---|---|---|---|
| **capability** | What the human granted: chains, assets, recipients/merchants, per-payment / per-window / lifetime budget, expiry, approval mode | the human's approval key (over every field) | the local state store |
| **mandate** | The user's own limit on *automatic* spending: scope, per-payment / per-window / total / daily caps, expiry, anti-replay nonce | the user's own key (the "authorization key") | the local state store |

A mandate can only **narrow** what the capability allows. It can never widen
it, and no server can widen either one. Without a capability, nothing is paid
at all — a mandate is an additional limit, never a licence.

Both gates are **signed**, and the engine refuses what it cannot check: a
capability with no signature, or one signed by a key this machine does not
trust, is not a capability (the payment is denied with `capability_unsigned` /
`capability_untrusted`). A capability is created and signed by the human:

```bash
aipay-agent approval keygen            # the human's approval key (its own passphrase!)
aipay-agent capabilities grant \
  --chain base --asset USDC --to 0x…merchant \
  --per-payment 25 --per-window 100 --window-seconds 86400 --total 500 \
  --expiry 2026-12-31T00:00:00Z
# → the issuer is that key's address, and the command signs it
```

The agent cannot do this: it holds no approval key. A capability made before
signing existed can be signed once with `aipay-agent capabilities sign --id <id>`
— look at it first, because you are signing what is stored.

Use a passphrase for the approval key that the agent process does **not** have:
`AIPAY_AGENT_APPROVAL_PASSPHRASE` (or `--passphrase`). The agent reads
`AIPAY_AGENT_PASSPHRASE` for the wallet, and `approval keygen` refuses to create
an approval key with that one.

**Delegation shares the allowance.** A capability may name a `holder`, and that
holder may hand on a narrower child (`aipay_capability_delegate`). The child is
signed by the holder, keeps the human as the approval authority, and may only be
narrower in every dimension — scope, expiry, budgets, the rolling-window
length, the approval mode, the timelock and the stream ceiling. What the
children spend counts against the **parent**, and a revoked or expired parent
withdraws the delegation. The engine re-checks all of it on every payment, not
only when the child is imported.

## The mandate object — `aipay-mandate-v1`

```jsonc
{
  "v": 1,
  "id": "mandate_…",                 // local id, unpredictable
  "issuer": "0x…",                   // the key that signed it (the user)
  "audience": "aipay-agent",         // which runtime may act on it
  "scope": {
    "chains": ["bsc"],                // allowed chains (chain keys)
    "assets": ["USDT"],               // allowed assets
    "operations": ["pay"],            // "pay" and/or "refund" — never both
    "merchants": ["0x…"],             // allowed merchants; [] means "any"
    "maxPerPayment": { "USDT": "25.00" },
    "maxPerWindow": { "window": "1h", "USDT": "100.00" },
    "maxTotal": { "USDT": "500.00" },
    "dailyCap": { "USDT": "200.00" }
  },
  "windowStart": 1763000000,          // start of the accounting window
  "expiresAt": 1763003600,            // hard expiry (unix seconds)
  "nonce": "…",                       // consumed once, at registration
  "issuedAt": 1763000000,
  "riskAccepted": true,               // the user said yes; there is no default
  "signature": "0x…"                  // EIP-191 personal_sign over everything above
}
```

Field notes:

- `issuer` **is** the signing key's address. It cannot be set to somebody else.
- `riskAccepted` must be `true`. Automation is never enabled by omission.
- `operations` may not contain both `pay` and `refund`: a refund is a separate
  decision with smaller caps (see *Refunds* below).
- `maxPerPayment` and `maxTotal` are **required for every asset in `assets`**.
  `maxPerWindow` and `dailyCap` are optional (without them, only the per-payment
  and total caps bound the spend).
- `maxPerWindow.window` is a duration: `30m`, `1h`, `7d`, `3600s`. `dailyCap` is
  a rolling 24 hours.

## The bytes that get signed

The signature covers **every field**, including the scope and the caps: change
one byte and verification fails. The signed message is

```
aipay-mandate-v1\n{"schema":"aipay-mandate-v1","v":1,…}
```

where the JSON is built with fixed key order and canonicalised values:

| Field | Canonical form |
|---|---|
| `chains` | trimmed, lower-cased, de-duplicated, sorted |
| `assets` | trimmed, **upper-cased**, de-duplicated, sorted |
| `operations` | trimmed, lower-cased, de-duplicated, sorted |
| `merchants` | trimmed, de-duplicated, sorted (case preserved) |
| `maxPerPayment`, `maxTotal`, `dailyCap` | keys trimmed + upper-cased, values trimmed, sorted by key |
| `maxPerWindow` | `{ "window": <trimmed>, …the same amount map, minus the "window" key… }` |
| everything else | as written (numbers, ids, addresses, the nonce) |

`signature` is a 65-byte EIP-191 `personal_sign` — the same scheme any EVM
wallet can produce, so the user can sign a mandate with the wallet they already
have (or with a hardware signer), not only with our CLI.

### A verifier you can copy

This checks authenticity and expiry. The limit checks are the rules below.

```js
import { verifyMessage } from 'ethers';

const SCHEMA = 'aipay-mandate-v1';

function canonical(m) {
  const upper = (s) => s.trim().toUpperCase();
  const sorted = (list) => [...new Set(list.map((x) => x.trim()))].sort();
  const amounts = (map) =>
    Object.fromEntries(
      Object.entries(map ?? {})
        .map(([k, v]) => [upper(k), String(v).trim()])
        .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),
    );
  const windowAmounts = Object.fromEntries(
    Object.entries(m.scope.maxPerWindow ?? {}).filter(
      ([k]) => k.trim().toLowerCase() !== 'window',
    ),
  );
  return JSON.stringify({
    schema: SCHEMA,
    v: m.v,
    id: m.id,
    issuer: m.issuer,
    audience: m.audience,
    scope: {
      chains: sorted(m.scope.chains.map((c) => c.toLowerCase())),
      assets: sorted(m.scope.assets.map((a) => upper(a))),
      operations: sorted(m.scope.operations.map((o) => o.toLowerCase())),
      merchants: sorted(m.scope.merchants),
      maxPerPayment: amounts(m.scope.maxPerPayment),
      maxTotal: amounts(m.scope.maxTotal),
      ...(m.scope.maxPerWindow
        ? {
            maxPerWindow: {
              window: String(m.scope.maxPerWindow.window).trim(),
              ...amounts(windowAmounts),
            },
          }
        : {}),
      ...(m.scope.dailyCap ? { dailyCap: amounts(m.scope.dailyCap) } : {}),
    },
    windowStart: m.windowStart,
    expiresAt: m.expiresAt,
    nonce: m.nonce,
    issuedAt: m.issuedAt,
    riskAccepted: m.riskAccepted,
  });
}

export function verifyMandate(mandate, { now, issuer } = {}) {
  if (!mandate || mandate.v !== 1 || mandate.riskAccepted !== true) {
    return { ok: false, reason: 'mandate_malformed' };
  }
  let recovered;
  try {
    recovered = verifyMessage(`${SCHEMA}\n${canonical(mandate)}`, mandate.signature);
  } catch {
    return { ok: false, reason: 'mandate_signature_invalid' };
  }
  if (recovered.toLowerCase() !== mandate.issuer.toLowerCase()) {
    return { ok: false, reason: 'mandate_issuer_mismatch' };
  }
  if (issuer && issuer.toLowerCase() !== mandate.issuer.toLowerCase()) {
    return { ok: false, reason: 'mandate_issuer_mismatch' };
  }
  if (now !== undefined && now >= mandate.expiresAt) {
    return { ok: false, reason: 'mandate_expired' };
  }
  return { ok: true };
}
```

## The rules a mandate must enforce

1. **Signature first.** An unverifiable mandate is not a mandate. Nothing about
   scope or budget is even looked at before the signature checks out.
2. **Expiry is judged against chain time as well as the local clock.** The later
   of the two wins, and the chain timestamp is remembered — so rewinding the
   local clock cannot extend a window or resurrect an expired mandate. Moving
   the clock *forward* is always conservative. The agent's payment path reads
   the chain's own clock (the latest block timestamp) once per payment when a
   mandate is in force; on EVM and Solana that is one read-only RPC call. On
   chains without such a call yet (Tron, MSG) the last timestamp seen is kept —
   the floor never moves backwards.
3. **Spend is reserved, then settled.** The amount is held before the payment is
   signed, turned into a spend when the money moved, and released when the
   payment failed. Two concurrent payments cannot spend the same allowance.
4. **The limits are per operation.** A payment is checked against every mandate
   that authorizes that operation; the strictest one wins.
5. **Out of limits ⇒ a human, not a refusal and not a pass.** Exceeding the
   per-payment, window, total or daily cap, using another chain, asset or
   merchant, or a mandate that is not yet active all produce
   `needs-human`: the request is handed back to the person, who signs a
   single-use approval for **that one payment**.
6. **A revoked or expired mandate is still a gate.** A revoked mandate refuses
   automatic payments (the unused allowance does not survive the revocation); an
   expired one means every payment needs a human until a new mandate is issued.
   A human's one-off approval is a separate authority and still works.
7. **Refunds need their own mandate**, with caps of at most **20 %** of the
   payment mandate it refunds. A refund mandate cannot be registered before
   the payment mandate it refunds exists, and registering one above that
   ratio is refused.
8. **The verdict never leaks the quota.** It carries stable reason codes and
   nothing else — no remaining budget, no "you are short by X".

### Reason codes

`within_mandate`, `mandate_malformed`, `mandate_signature_invalid`,
`mandate_issuer_mismatch`, `mandate_unknown`, `mandate_revoked`,
`mandate_expired`, `mandate_not_active`, `operation_unknown`,
`operation_not_allowed`, `chain_not_allowed`, `asset_not_allowed`,
`merchant_not_allowed`, `per_payment_cap_exceeded`, `window_cap_exceeded`,
`total_cap_exceeded`, `daily_cap_exceeded`, `amount_invalid`,
`request_conflict`.

Branch on these, never on prose.

## Who carries which risk

| Step | Who signs | If it is breached |
|---|---|---|
| Private key | only the user's device (optionally a hardware signer) | the user's own funds are at risk — AIPAY never had them |
| Authorization (the mandate) | the user, on their own machine | the user's limit can be exceeded **by their own agent**, not by AIPAY |
| A single payment | the agent's key, inside the limits | the user's funds move — that is what they authorized |
| A refund | a separate, smaller mandate | same, with a smaller ceiling |
| Order status | AIPAY's server | the server can lie about a confirmation; the money still moves on-chain |
| The mandate itself | nobody but the user | AIPAY stores nothing, so there is nothing to steal |
| A *capability record* | the human's approval key, over every field | an unsigned or foreign-signed capability is refused by the engine (`capability_unsigned` / `capability_untrusted`), so the agent cannot widen its own limits |
| The trust anchor and the spend ledger | nobody — they are local state on the agent's machine | whoever can rewrite the agent's home directory can move the anchor or delete a recorded spend; keep the approval key's passphrase different from the wallet's |

Concretely: **a compromise of AIPAY's servers cannot spend a user's money, mint
an authorization, or widen a limit.** The limits live on the user's machine,
signed by the user's key.

## What AIPAY deliberately does not do

- no custody, no server-side signing, no "one switch to enable automatic
  spending";
- no unlimited switch, and no using our server as the quota ledger (that would
  make us a critical path for every payment);
- no deriving a refund permission from a payment permission;
- no way for support or operations to widen a user's limit;
- no quota details in an error message shown to anyone but the user.

## Using this in your own agent

You do not need our runtime to use a mandate — it is a document, and the format
is public. The reference implementation lives in the project checkout
(`src/lib/core/policy/mandate.ts`, with the ledger next to it), and the CLI
wraps it:

```bash
# The human signs a mandate (needs the approval key; the agent cannot do this)
node agent/cli.mjs mandate create --chain bsc --asset USDT --merchant 0xMerchant \
  --per-payment 25 --total 500 --per-window 100 --window 1h --expires-in 2592000

node agent/cli.mjs mandate list            # what the agent may spend automatically
node agent/cli.mjs mandate show --id <id>  # one mandate, with what is left
node agent/cli.mjs mandate revoke --id <id>
```

If your platform runs the agent, the flow is:

1. the user signs a mandate on their machine and hands you the object;
2. you verify it (the snippet above) and **store it locally** — it is the
   user's limit, so it belongs on the user's side, not on yours;
3. before every payment you check the limits yourself, keep your own reserved /
   settled ledger, and when a limit is exceeded you ask the human (do not pay
   and reconcile later);
4. you can optionally publish the mandate's **hash** to AIPAY so a merchant can
   audit afterwards. That is an audit trail, not an execution path: our server
   never widens a limit because of it.

The MCP server also exposes a read-only view of the limits in force
(`aipay_mandate_list`), so an agent can see its own budget before it asks.

## Related

- [Agent surface](./agent.md) — install, tools, capabilities, the audit trail.
- [Security model](./security.md) — what protects the money, and the residual
  risks we do not hide.
- [Provider assessment answers](./provider-assessment-answers.md) — the
  point-by-point answers a third-party review asks for.
