> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ana.fi/llms.txt
> Use this file to discover all available pages before exploring further.

# ERC20Allow account

> Classify a plain address, approve the tokens that a rule document spends, set caps, stage, and commit with plain transactions.

After this page, you can take a plain address to a committed rule document that runs through `AnafiDelegationAdapterERC20Allow`. You know which tokens the address must approve, how caps and the block switch work, each prompt, each refusal, and how to resume.

## When to use it

Use the ERC20Allow kind (`erc20_allow`) when the funds stay in the address of the owner, and the rules move only ERC-20 tokens. The account is the owner address itself. Each owner act is a plain transaction that the address sends and pays for. Anafi never relays it.

Use the [Safe account](https://docs.ana.fi/flows/safe-account.md) for the native coin, for `off_ramp`, or when the funds live in a Safe.

## Preconditions

| Condition | How to check | What refuses it |
| - | - | - |
| The client config has `delegationAdapters.erc20_allow` | your config | `Error`: `... is not this chain's configured ERC20Allow adapter` |
| `AnafiRegistry.delegationAdapters()` lists that adapter | `classifyErc20AllowAccount` returns a class other than `leg_not_live` | `Error`: `... is not the live configured erc20_allow adapter` |
| The address has no code, or an EIP-7702 pointer | `classifyErc20AllowAccount(account)` | `Error`: `... is not an address the ERC20Allow leg serves` |
| The address holds the native coin for gas | `publicClient.getBalance` | the wallet refuses the transaction |
| The wallet is connected to the account | your app | each transaction comes from the connected address |

Today, the Anafi API hosts answer CORS only for `https://app.ana.fi`. Run the calls that use the Anafi API from a server, a script, or your own same-origin proxy. Approvals, caps, the block switch, the commit and the revoke are chain transactions, so this limit does not apply to them.

## Classification

`classifyErc20AllowAccount(account, options?)` reads at one block and returns one value:

| Value | Meaning | What to do |
| - | - | - |
| `no_code` | A plain address. | Served. |
| `eip7702_pointer` | The code is exactly an EIP-7702 delegation pointer: `0xef0100` and a 20-byte address. | Served. |
| `contract_code` | Other contract code, such as a Safe or another smart account. | Not served. For a Safe, use the Safe kind. |
| `leg_not_live` | The network has no `erc20_allow` adapter in the config, or the registry does not list it. | The kind is not available on this network now. |

## Tokens that the document spends

The SDK reads tokens(D), the list of tokens that the engine can pull for the document, in this order:

1. each token of a `send_one` value and of each `send_batch` row, and each `in` token of an `exchange`, in document order, each one time;
2. the token of `global.fees_method`, when it is not in the list yet.

A send value names its token in one of two forms: a literal `"<amount> <TOKEN>"`, or `trigger.value` (with an optional `* <n>%`) under an `incoming_tx` or `outgoing_tx` trigger whose `value` range ends in a token. A bought token (`out` of an `exchange`) needs no approval, unless it is also a spent token or the fee token.

Each token of tokens(D) must have a row in the `erc20s` table of the client config.

### What the document may not contain

The SDK refuses these before any request, in this order. The first cause that holds decides.

| Cause | Error |
| - | - |
| The SDK cannot read the document | `Erc20AllowSpentTokenUnnamedError` with `rule: null` |
| A send value or an `exchange` input names no token (for example a sum, or `trigger.value` under a trigger with no token range) | `Erc20AllowSpentTokenUnnamedError` with the rule name |
| An `exchange` sells the native coin | `Erc20AllowNativeSwapTokenError` with `side: "sold"` |
| An `exchange` buys the native coin | `Erc20AllowNativeSwapTokenError` with `side: "bought"` |
| An `exchange` buys a token with no row in `erc20s` | `Error`: `rule ... buys ...` |
| A send of the native coin | `Error`: `... has no ERC-20 contract on this chain` |
| No `global.fees_method` | `Error`: `an ERC20Allow document needs global.fees_method` |
| A token of tokens(D) with no row in `erc20s` | `Error`: `... has no ERC-20 contract on this chain` |
| An `exchange`, and the adapter has no swap executor | `Erc20AllowSwapsNotServedError` |
| An `exchange`, and the read of `swapExecutor()` failed | `Erc20AllowSwapSupportUnreadError`. Retry. |

The engine also refuses an `off_ramp` for this kind, and a fee token that is not an ERC-20. These refusals come back as `DslStageRefusedError`.

You can run the same check with no request: `findErc20AllowDocumentRefusal(yaml, { native, erc20s, swapSupport })` returns the first cause or `null`. See [ERC20Allow methods](https://docs.ana.fi/sdk/erc20-allow.md).

### Swap support

`readErc20AllowSwapSupport()` reads `swapExecutor()` on the adapter and returns `"served"` (an executor is set) or `"not_served"` (zero address, or the call reverted).

`"served"` does not prove that a swap can run. The adapter also checks the router of each swap (see [Swap executor](https://docs.ana.fi/contracts/swap-executor.md)), and the engine must have a swap route on the network. On `polygon-amoy`, the engine refuses each `exchange` today.

A swap leg pulls exactly `amountIn` of the sold token from the account to `AnafiSwapExecutor`. The executor calls an allowed router and pays the output and the unused input back to the account. When the output at the account is below the signed `minAmountOut`, the legs of the payment fail with `SwapOutputBelowMinimum`. See [Swap executor](https://docs.ana.fi/contracts/swap-executor.md).

## Approvals, caps and the block switch

The adapter pulls tokens with `transferFrom`. Three facts of the account decide what it can pull.

| Control | Contract call | Effect | SDK |
| - | - | - | - |
| Allowance | `approve(adapter, amount)` on the token | The adapter can pull at most the allowance. The SDK approves `2^256 - 1` and reads any allowance of at least `2^255` as unlimited. | `approveErc20AllowTokens`, inside `commitStagedErc20AllowDsl` |
| Cap | `setCaps(CapEntry[])` on the adapter, `CapEntry = { token, limit, periodSeconds }` | At most `limit` base units of `token` in each window of `periodSeconds`. | `setErc20AllowCaps`, `clearErc20AllowCaps` |
| Block switch | `setBlocked(bool)` on the adapter | `true` refuses each pull of each token. The allowances stay. | `setErc20AllowBlocked` |

Rules of the cap:

* `periodSeconds` must be at least 3600 (`MIN_CAP_PERIOD_SECONDS`). A shorter window reverts `CapPeriodTooShort`, and the SDK refuses it first.
* The windows are fixed: window number `block.timestamp / periodSeconds`. A window does not start when you call `setCaps`.
* A new `setCaps` with the same `periodSeconds`, in the same window, keeps the amount spent. Any other change starts the count at zero.
* Each pull counts: each payment leg, each Anafi fee leg, each swap input, and the reserved gas charge (`maxCharge`) in its token. The part of `maxCharge` that the adapter returns is taken off the count again.
* A pull above the room left fails with `CapExceeded(owner, token)`. For the reserved gas charge, the whole redeem reverts. For a leg, the legs of the payment fail.

Read all three at one block with `readErc20AllowDelegation({ account, adapter, tokens })`. It returns `{ blocked, tokens: [{ token, allowance, cap }], block }`. `cap` is `null` when no cap is set, else `{ limit, periodSeconds, spentInPeriod }`.

See [ERC20Allow adapter](https://docs.ana.fi/contracts/erc20-allow-adapter.md) for each function, event and error of the adapter.

## Sequence

```mermaid theme={null}
sequenceDiagram
    autonumber
    participant W as Owner wallet (the account)
    participant A as Your app (SDK)
    participant API as Anafi API
    participant E as Anafi engine (black box)
    participant C as Chain
    A->>A: Read tokens(D), refuse unsupported documents
    A->>C: swapExecutor() (only when the document swaps)
    A->>C: Registry list, account code, isBlocked, allowance and capOf per token
    A->>C: AnafiRegistry.engineEncKey()
    A->>API: POST /api/wallets/{account}/dsl/commit/stage (sealed)
    API->>E: Relay sealed document
    E-->>A: commitment, engineSig, attestationValidUntil, sealed findings
    opt Optional cap
        W->>C: Transaction: adapter.setCaps([...])
    end
    A->>C: allowance per token, at one block
    loop Each token with allowance 0
        W->>C: Transaction: token.approve(adapter, max)
    end
    W->>C: Transaction: AnafiDslRegistry.commitDsl(hash, validUntil, engineSig, adapter)
```

## Steps

**1. Stage the document**

Call `stageErc20AllowDsl({ account, adapter, yaml, salt, parent, plannedCap? })`. Use a new random 32-byte `salt`. Set `parent` to `await readDslCommitment(account)`.

The SDK, in this order:

1. refuses an adapter that is not the `erc20_allow` row of the config;
2. applies the document refusals of the table above, and reads `swapExecutor()` when the document swaps;
3. at one tip block, classifies the account and reads its block switch, and the allowance and cap of each token of tokens(D). It refuses `leg_not_live` and an account class that is not served. It then counts each allowance of 0 as approved (the commit approves it), and the cap of `plannedCap.token` as the cap after that `setCaps`. It throws `Erc20AllowNotLiveError` when the owner is blocked (`reason.kind: "blocked"`) or when a cap has no room left (`"cap_exhausted"`);
4. seals the document and sends `POST /api/wallets/{account}/dsl/commit/stage`;
5. checks the reply as for a Safe: the adapter echo, `commitment = keccak256(salt ‖ yaml)`, and a deadline in the future and at most 1 hour away.

No wallet prompt. The result is a `StagedErc20AllowDsl`: `account`, `adapter`, `yaml`, `salt`, `commitment`, `engineSig`, `attestationValidUntilUnixSeconds`, `warnings`, `tokens` (tokens(D) with addresses) and `approvals` (the tokens whose allowance was 0 at the stage).

Show `staged.warnings` and `staged.approvals` to the owner. The approvals tell the owner how many prompts follow.

**2. Set a cap (optional)**

When you passed `plannedCap` to the stage, send that cap before the commit:

```ts theme={null}
await anafi.setErc20AllowCaps({ account, adapter, entries: [plannedCap] });
```

One transaction prompt: `setCaps(entries)` on the adapter. You can also set a cap at any later time.

**3. Commit**

Call `commitStagedErc20AllowDsl({ staged, onStep, onSigned, onConfirmed })`.

1. The SDK refuses an adapter that is not the `erc20_allow` row of the config, and a lapsed attestation.
2. It refuses a staged value whose `commitment` is not `keccak256(salt ‖ yaml)` of its own text, or whose `tokens` are not tokens(D) of that text (`Erc20AllowStagedDocumentMismatchError`). It applies the document refusals again, and reads `swapExecutor()` again for a document that swaps.
3. It reads the allowance of each token of `staged.tokens` again, at one tip block. A token that the owner revoked after the stage needs an approval that `staged.approvals` does not list.
4. For each token with allowance 0, in order: `onStep({ kind: "approve", token })`, then one transaction prompt `token.approve(adapter, 2^256 - 1)`. The SDK waits for each receipt before the next prompt. `onConfirmed(block)` runs after each receipt.
5. It checks the attestation deadline again.
6. `onStep({ kind: "commit" })`, then one transaction prompt: `AnafiDslRegistry.commitDsl(commitment, validUntil, engineSig, adapter)` from the account. `onSigned` runs when the wallet returns the hash. The SDK waits for the receipt.

The result is `{ txHash, kind: "committed", confirmedBlock }`. A reverted receipt throws `owner transaction ... reverted`.

## What can refuse

| Where | Refusal | Meaning and what to do |
| - | - | - |
| SDK | `Erc20AllowNotLiveError` | `reason.kind` is `blocked` (call `setErc20AllowBlocked` with `false`), `cap_exhausted` (wait for the next window, or raise the cap), or `allowance_zero`. |
| SDK | `Erc20AllowStagedDocumentMismatchError` | The staged value does not match its own text. Stage again. |
| SDK | attestation lapsed | Stage again with a new salt. |
| Stage route | `DslStaleParentError` (`409`) | Another document landed. Rebuild on `error.current`. |
| Stage route | `NotificationEmailNotVerifiedError` (`422`) | Verify the inbox first. |
| Stage route | `DslStageRefusedError` (`422`) | Show `error.refusal`. Fix the document. |
| Stage route | `BackendRequestError` (`422`, `429`, `502`, `null`) | As for a Safe. See [Safe account](https://docs.ana.fi/flows/safe-account.md#at-the-stage). |
| Wallet | user rejection | The approvals that landed before stay on chain. |
| Token | `approve` reverts | Some tokens refuse a change from one nonzero allowance to another. The commit approves only a token whose allowance is 0. `approveErc20AllowTokens` first sets a nonzero allowance below the unlimited bound to 0, then approves the maximum. |
| `commitDsl` | `AttestationExpired()` | Stage again. |
| `commitDsl` | `InvalidEngineSignature()` | A commit landed after the stage, so the next version changed. Stage again on the new parent. |

## Resume after a failure or a reload

| State | How to see it | What to do |
| - | - | - |
| Some approvals landed, then a failure | `readErc20AllowDelegation` shows nonzero allowances | Call `commitStagedErc20AllowDsl` again with the same `staged`. It asks only for the approvals still needed. |
| The attestation lapsed | `Date.now() / 1000` is past `attestationValidUntilUnixSeconds` | Stage again. The approvals that landed stay valid. |
| The commit was sent, the result is unknown | `readDslCommitment(account)` | When `hash` equals `staged.commitment`, the commit landed. Else stage or commit again. |

## End state on chain

| Fact | Read it with |
| - | - |
| Allowance of each token to the adapter | `readErc20AllowDelegation`, or the token `allowance(account, adapter)` |
| Block switch and caps | `readErc20AllowDelegation`, or the adapter `isBlocked(account)` and `capOf(account, token)` |
| The commitment | `readDslCommitment(account)`. The registry emits `DslCommitted(aaWallet, commitment, version, adapter)`. |
| The adapter events | `BlockedSet(owner, blocked)`, `CapSet(owner, token, limit, periodSeconds)`, `CapCleared(owner, token)` |

## Example

This example uses the client of the [Quickstart](https://docs.ana.fi/quickstart.md). It stages, sets a daily cap, and commits.

```ts theme={null}
import {
  Erc20AllowNotLiveError,
  type AnafiClient,
  type Erc20AllowCapEntry,
  type Hex,
} from "@anafi-cc/anafi-sdk";
import { bytesToHex } from "viem";

export async function commitErc20Allow(
  anafi: AnafiClient,
  account: Hex,
  adapter: Hex,
  usdc: Hex,
  yaml: string,
) {
  const accountClass = await anafi.classifyErc20AllowAccount(account);
  if (accountClass !== "no_code" && accountClass !== "eip7702_pointer") {
    throw new Error(`ERC20Allow does not serve this address: ${accountClass}`);
  }

  // At most 50 USDC (6 decimals) in each window of one day.
  const cap: Erc20AllowCapEntry = { token: usdc, limit: 50_000_000n, periodSeconds: 86_400 };

  let staged;
  try {
    staged = await anafi.stageErc20AllowDsl({
      account,
      adapter,
      yaml,
      salt: bytesToHex(crypto.getRandomValues(new Uint8Array(32))),
      parent: await anafi.readDslCommitment(account),
      plannedCap: cap,
    });
  } catch (error) {
    if (error instanceof Erc20AllowNotLiveError) console.log("not live:", error.reason);
    throw error;
  }
  console.log("findings:", staged.warnings);
  console.log("approvals to sign:", staged.approvals.map(({ symbol }) => symbol));

  await anafi.setErc20AllowCaps({ account, adapter, entries: [cap] });

  const result = await anafi.commitStagedErc20AllowDsl({
    staged,
    onStep: (step) => console.log(step.kind === "approve" ? `approve ${step.token}` : "commit"),
    onConfirmed: (block) => console.log("confirmed at block", block),
  });

  const delegation = await anafi.readErc20AllowDelegation({
    account,
    adapter,
    tokens: staged.tokens.map(({ address }) => address),
  });
  console.log(result.txHash, delegation.blocked, delegation.tokens);
  return staged;
}
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.