> ## 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, stage, commit, block, cap, approve and revoke an ERC20Allow account with the SDK, with every refusal and error class.

After you read this page, you can run a plain address as an Anafi account: check that the leg serves it, commit a rule document with the right approvals, set caps, block the adapter, and revoke.

An ERC20Allow account (kind `erc20_allow`) is a plain address: a key with no code, or an address with an EIP-7702 pointer. The account grants its permission with ERC-20 allowances to `AnafiDelegationAdapterERC20Allow`. It can also set a block switch and caps on the adapter. See [the ERC20Allow adapter](https://docs.ana.fi/contracts/erc20-allow-adapter.md) and the [ERC20Allow account flow](https://docs.ana.fi/flows/erc20-account.md).

## Rules of this leg

* **Every write is a plain transaction from the account.** The account sends it and pays the gas. The client never asks for a relay and never reads the sponsorship for this leg.
* **One transaction at a time.** Each transaction waits for its receipt (up to 180 seconds) before the next prompt. A reverted receipt rejects with `Error("owner transaction <hash> reverted")`. The transactions that landed before stay on chain.
* **The adapter must be the configured row.** Each method throws `Error("<adapter> is not this chain's configured ERC20Allow adapter")` when `adapter` is not `delegationAdapters.erc20_allow`.
* **Only ERC-20 tokens.** The adapter cannot pull the native coin. A document of this leg cannot send, sell or buy `native`.
* **A fee token is required.** A document of this leg must set `global.fees_method`. See [fees](https://docs.ana.fi/concepts/fees.md).
* **The client copies your input.** The stage and the commit read their parameters one time, when you call them. A later change to your object, also from a callback, changes nothing.

### tokens(D)

tokens(D) is the list of tokens that the engine can pull for a document D. The client computes it from the text:

1. each token that a `send_one` or a `send_batch` row spends, and each token that an `exchange` sells, in document order, each one time;
2. then the fee token of `global.fees_method`, when no action spends it.

The token that an `exchange` buys is not in tokens(D), unless an action also spends it or it is the fee token. The account must approve each token of tokens(D) to the adapter.

## `classifyErc20AllowAccount`

```ts theme={null}
classifyErc20AllowAccount(account: Hex, options?: BlockReadOptions): Promise<Erc20AllowAccountClass>;

type Erc20AllowAccountClass = "no_code" | "eip7702_pointer" | "contract_code" | "leg_not_live";
```

Classifies `account` for this leg. Every read is at one block: `options.block`, or the uncached tip. With no `erc20_allow` row in the config, it answers `leg_not_live` and reads nothing.

| Class | Meaning | What to do |
| - | - | - |
| `no_code` | A plain key. The leg serves it. | Continue. |
| `eip7702_pointer` | An EIP-7702 account. The leg serves it. | Continue. |
| `contract_code` | A contract, for example a Safe. The leg does not serve it. | Use the [Safe leg](https://docs.ana.fi/sdk/safe.md) for a Safe. |
| `leg_not_live` | The registry does not list the ERC20Allow adapter, or the config has none. | The leg is not available on this network now. |

## `readErc20AllowDelegation`

```ts theme={null}
readErc20AllowDelegation(params: {
  account: Hex;
  adapter: Hex;
  tokens: readonly Hex[];
  options?: BlockReadOptions;
}): Promise<Erc20AllowDelegation>;

interface Erc20AllowDelegation {
  blocked: boolean;
  tokens: Erc20AllowTokenDelegation[]; // one row per token, in the order asked
  block: bigint;                       // the block of every read
}

interface Erc20AllowTokenDelegation {
  token: Hex;
  allowance: bigint;          // token.allowance(account, adapter)
  cap: Erc20AllowCap | null;  // null when no cap is set
}

interface Erc20AllowCap {
  limit: bigint;          // base units per window
  periodSeconds: number;  // the window length
  spentInPeriod: bigint;  // 0 once the stored window has ended
}
```

Reads the whole permission of one account at one block: `adapter.isBlocked(account)`, and for each token `token.allowance(account, adapter)` and `adapter.capOf(account, token)`. An answer of the wrong type throws.

```ts theme={null}
const usdc = "0x41E94Eb019C0762f9Bfcf9Fb1E58725BfB0e7582";
const delegation = await anafi.readErc20AllowDelegation({
  account,
  adapter: config.delegationAdapters.erc20_allow!,
  tokens: [usdc],
});
console.log(delegation.blocked, delegation.tokens[0].allowance, delegation.tokens[0].cap);
```

The package also exports the functions behind it:

```ts theme={null}
function readErc20AllowDelegation(params: {
  publicClient: AdapterPublicClient;
  adapter: Hex;
  account: Hex;
  tokens: readonly Hex[];
  at: bigint | BlockReadOptions;
}): Promise<Erc20AllowDelegation>;

function readErc20AllowAllowances(params: {
  publicClient: AdapterPublicClient;
  adapter: Hex;
  account: Hex;
  tokens: readonly Hex[];
  at: bigint | BlockReadOptions;
}): Promise<bigint[]>; // the allowance of each token, in the order asked
```

## `readErc20AllowSwapSupport`

```ts theme={null}
readErc20AllowSwapSupport(): Promise<Erc20AllowSwapSupport>;

type Erc20AllowSwapSupport = "served" | "not_served";
```

Reads `swapExecutor()` of the configured ERC20Allow adapter at the latest block.

| Answer | When |
| - | - |
| `served` | The executor is a non-zero address. |
| `not_served` | The executor is the zero address, the call reverts, or the config has no `erc20_allow` row (no read). |

Any other failure throws `Erc20AllowSwapSupportUnreadError`. A failure never reads as `not_served`.

`served` does not promise that a swap can run. The adapter can permit no router pair yet. The engine also refuses every `exchange` action on `polygon-amoy`, where no swap aggregator is available.

The function behind it:

```ts theme={null}
function readErc20AllowSwapSupport(params: { publicClient: AdapterPublicClient; adapter: Hex }): Promise<Erc20AllowSwapSupport>;
```

## `stageErc20AllowDsl`

```ts theme={null}
stageErc20AllowDsl(params: StageErc20AllowDslParams): Promise<StagedErc20AllowDsl>;

interface StageErc20AllowDslParams {
  account: Hex;
  adapter: Hex;
  yaml: string;
  salt: Hex;                    // 32 random bytes
  parent: OnChainDsl | null;    // readDslCommitment(account), or null
  plannedCap?: Erc20AllowCapEntry;
}
```

Sends the document to the engine for a stage. Nothing prompts the wallet.

| Parameter | Meaning |
| - | - |
| `account` | The plain address that will commit. |
| `adapter` | `delegationAdapters.erc20_allow`. |
| `yaml` | The rule document. It must set `global.fees_method`. |
| `salt` | 32 random bytes in hex. |
| `parent` | The registry identity that you built the document on, or `null`. |
| `plannedCap` | A cap that the owner will set with `setCaps` before the commit. The cap check uses it in place of the cap on chain (`erc20AllowCapAfterSetCaps`). |

### Checks, in order

The method stops at the first check that fails.

| # | Check | Error |
| - | - | - |
| 1 | `adapter` is the configured `erc20_allow` row. | `Error` |
| 2 | The SDK can read the text and name each token that a send or a swap spends. A value `trigger.value` names the token of the trigger range. A trigger with no range names no token. | `Erc20AllowSpentTokenUnnamedError` |
| 3 | No swap sells `native`. | `Erc20AllowNativeSwapTokenError` with `side: "sold"` |
| 4 | No swap buys `native`. | `Erc20AllowNativeSwapTokenError` with `side: "bought"` |
| 5 | Each bought token has a row in `erc20s`. | `Error("rule <r> buys <T>, which has no ERC-20 contract on this chain")` |
| 6 | No send spends `native`. | `Error("<T> has no ERC-20 contract on this chain")` |
| 7 | The document sets `global.fees_method`. | `Error("an ERC20Allow document needs global.fees_method")` |
| 8 | Each token of tokens(D) has a row in `erc20s`. | `Error("<T> has no ERC-20 contract on this chain")` |
| 9 | For a document with a swap: `swapExecutor()` is non-zero. | `Erc20AllowSwapsNotServedError` (zero or revert), `Erc20AllowSwapSupportUnreadError` (other failure) |
| 10 | At one tip block: the registry lists the adapter. | `Error("<adapter> is not the live configured erc20_allow adapter")` |
| 11 | The same block: the account class is `no_code` or `eip7702_pointer`. | `Error("<account> is not an address the ERC20Allow leg serves")` |
| 12 | The same block: the account has not blocked the adapter. | `Erc20AllowNotLiveError` with `reason.kind: "blocked"` |
| 13 | The same block: no cap of a token of tokens(D) is full. With `plannedCap`, its token uses the planned cap. | `Erc20AllowNotLiveError` with `reason.kind: "cap_exhausted"` |
| 14 | `POST /api/wallets/:account/dsl/commit/stage`, then the echo checks of the reply (adapter, commitment, deadline within 3600 seconds). | `DslStaleParentError`, `NotificationEmailNotVerifiedError`, `DslStageRefusedError`, `BackendRequestError`, `Error` |

An allowance of 0 does not stop the stage. The token goes to `approvals`, and the commit approves it.

### Return value: `StagedErc20AllowDsl`

```ts theme={null}
interface StagedErc20AllowDsl {
  account: Hex;
  adapter: Hex;
  yaml: string;
  salt: Hex;
  commitment: Hex;                          // keccak256(salt ‖ yaml)
  engineSig: Hex;
  attestationValidUntilUnixSeconds: number;
  warnings: string[];                       // sanity findings of the engine
  tokens: Erc20Token[];                     // tokens(D), in order
  approvals: Erc20Token[];                  // the tokens of `tokens` with allowance 0 at the stage
}
```

```ts theme={null}
const staged = await anafi.stageErc20AllowDsl({
  account,
  adapter: config.delegationAdapters.erc20_allow!,
  yaml,
  salt: toHex(crypto.getRandomValues(new Uint8Array(32))),
  parent: await anafi.readDslCommitment(account),
});
console.log(staged.approvals.map((t) => t.symbol)); // the approve prompts of the commit
```

## `commitStagedErc20AllowDsl`

```ts theme={null}
commitStagedErc20AllowDsl(params: {
  staged: StagedErc20AllowDsl;
  onStep?: (step: Erc20AllowCommitStep) => void;
  onSigned?: () => void;
  onConfirmed?: (confirmedBlock: bigint) => void;
}): Promise<DslCommitSubmitResult>;

type Erc20AllowCommitStep = { kind: "approve"; token: Hex } | { kind: "commit" };
```

Commits a staged document from the account with plain transactions.

1. Checks that `staged.adapter` is the configured row.
2. Throws `Error("commitStagedErc20AllowDsl: the engine's attestation over this staged document has lapsed; stage it again")` when the deadline has passed.
3. Checks that `staged.commitment` is `dslCommitment(staged.salt, staged.yaml)`, and that `staged.tokens` is tokens(D) of `staged.yaml` in order. Else it throws `Erc20AllowStagedDocumentMismatchError`.
4. Applies to `staged.yaml` the token checks 2 to 9 of the stage, with a new read of `swapExecutor()` for a document with a swap.
5. Reads the allowance of each token of `staged.tokens` again, at one tip block. The owner can have revoked or approved in the meantime, so the list can differ from `staged.approvals`.
6. Checks the deadline again.
7. For each token with allowance 0, in order: `onStep({ kind: "approve", token })`, then the prompt for `token.approve(adapter, 2^256 - 1)`, then the receipt, then `onConfirmed(block)`.
8. Checks the deadline again.
9. `onStep({ kind: "commit" })`, then the prompt for `AnafiDslRegistry.commitDsl(commitment, validUntil, engineSig, adapter)` from the account. `onSigned()` runs when the wallet returns the hash. Then the receipt and `onConfirmed(block)`.

It returns `{ txHash, kind: "committed", confirmedBlock }`. A reverted receipt rejects. Prompts: one per token with allowance 0, then one.

The commit does not check the block switch or the caps again. The engine reports a later problem of the permission, such as a block or a full cap, in the `tenant` field of [`recover`](https://docs.ana.fi/sdk/confidential-channel#recover).

```ts theme={null}
const result = await anafi.commitStagedErc20AllowDsl({
  staged,
  onStep: (step) => showStatus(step.kind === "approve" ? `Approve ${step.token}` : "Commit the rules"),
  onConfirmed: (block) => console.log("landed in", block),
});
```

## `setErc20AllowBlocked`

```ts theme={null}
setErc20AllowBlocked(params: {
  account: Hex;
  adapter: Hex;
  blocked: boolean;
  onConfirmed?: (confirmedBlock: bigint) => void;
}): Promise<Erc20AllowOwnerTransactionsResult>;

interface Erc20AllowOwnerTransactionsResult {
  txHashes: Hex[];
  confirmedBlock: bigint | null; // the block of the last receipt; null when nothing was sent
}
```

Sends `adapter.setBlocked(blocked)` from the account. With `true`, the adapter refuses each pull of every token of this account. The allowances stay. With `false`, the pulls work again. Prompts: 1.

This is the fastest stop of this leg: one transaction pauses all payments, and one transaction resumes them.

## `setErc20AllowCaps`

```ts theme={null}
setErc20AllowCaps(params: {
  account: Hex;
  adapter: Hex;
  entries: readonly Erc20AllowCapEntry[];
  onConfirmed?: (confirmedBlock: bigint) => void;
}): Promise<Erc20AllowOwnerTransactionsResult>;

interface Erc20AllowCapEntry {
  token: Hex;
  limit: bigint;        // base units in each window
  periodSeconds: number; // the window length in seconds
}

const ERC20_ALLOW_MIN_CAP_PERIOD_SECONDS = 3600;
```

Sends one `adapter.setCaps(entries)` from the account. Each entry lets the adapter pull at most `limit` base units of `token` in each window of `periodSeconds`. Prompts: 1.

Throws `Error("setCaps needs at least one cap")` for an empty list. Throws an `Error` when a window is under `ERC20_ALLOW_MIN_CAP_PERIOD_SECONDS` (3600 seconds), because `setCaps` reverts on it.

When the window length stays the same, the adapter keeps the amount spent in the window. A new cap, or a new window length, starts with nothing spent. `erc20AllowCapAfterSetCaps` computes this.

## `clearErc20AllowCaps`

```ts theme={null}
clearErc20AllowCaps(params: {
  account: Hex;
  adapter: Hex;
  tokens: readonly Hex[];
  onConfirmed?: (confirmedBlock: bigint) => void;
}): Promise<Erc20AllowOwnerTransactionsResult>;
```

Sends one `adapter.clearCaps(tokens)` from the account. Throws `Error("clearCaps needs at least one token")` for an empty list. Prompts: 1.

## `approveErc20AllowTokens`

```ts theme={null}
approveErc20AllowTokens(params: {
  account: Hex;
  adapter: Hex;
  tokens: readonly Hex[];
  onStep?: (token: Hex) => void;
  onConfirmed?: (confirmedBlock: bigint) => void;
}): Promise<Erc20AllowOwnerTransactionsResult>;
```

Reads the allowance of each token at one tip block, then raises each allowance to the unlimited amount, in order.

| Allowance now | Transactions |
| - | - |
| unlimited (`isUnlimitedErc20Allowance`) | none |
| 0 | `approve(adapter, max)` |
| finite and above 0 | `approve(adapter, 0)`, then `approve(adapter, max)`. Some tokens, such as USDT, refuse a change from one nonzero allowance to another. |

`onStep(token)` runs before each prompt. `onConfirmed` gets the block of each receipt, also when a later transaction fails. With no token to change, it sends nothing and returns `{ txHashes: [], confirmedBlock: null }`.

## `revokeErc20Allowances`

```ts theme={null}
revokeErc20Allowances(params: {
  account: Hex;
  adapter: Hex;
  onStep?: (token: Hex) => void;
  onConfirmed?: (confirmedBlock: bigint) => void;
}): Promise<Erc20AllowOwnerTransactionsResult>;
```

Revokes the permission. It reads the allowance of the account to the adapter on each token of `erc20s`, at one tip block. Then it sends `approve(adapter, 0)` to each token whose allowance is above 0, in table order. `onStep(token)` runs before each prompt. It needs no Anafi API. Prompts: one per token with an allowance.

A token that is not in your `erc20s` table is not revoked. Revoke such a token yourself with `buildErc20ApproveCalldata(adapter, 0n)`.

```ts theme={null}
const revoked = await anafi.revokeErc20Allowances({
  account,
  adapter: config.delegationAdapters.erc20_allow!,
  onStep: (token) => showStatus(`Revoke ${token}`),
});
console.log(revoked.txHashes.length, "transactions");
```

## Helpers of this leg

### Allowance and cap helpers

```ts theme={null}
const ERC20_ALLOW_UNLIMITED_ALLOWANCE: bigint; // 2^256 - 1
function isUnlimitedErc20Allowance(allowance: bigint): boolean; // allowance >= 2^255
function erc20AllowCapAfterSetCaps(current: Erc20AllowCap | null, entry: Erc20AllowCapEntry): Erc20AllowCap;
function isErc20AllowCapAtLeast(cap: Erc20AllowCap | null, entry: Erc20AllowCapEntry): boolean;
```

| Export | Meaning |
| - | - |
| `ERC20_ALLOW_UNLIMITED_ALLOWANCE` | The amount of each approval that the SDK sends. |
| `isUnlimitedErc20Allowance` | `true` at 2^255 or more. Some tokens, such as USDC, lower even a maximum allowance on each pull, so the floor is half the maximum. |
| `erc20AllowCapAfterSetCaps` | The cap after `setCaps([entry])` over `current`. The spent amount stays only when the window length stays. |
| `isErc20AllowCapAtLeast` | `true` when `cap` has the window length of `entry` and a limit of at least `entry.limit`. `false` with no cap. |

### Live check

```ts theme={null}
type Erc20AllowNotLiveReason =
  | { kind: "blocked" }
  | { kind: "allowance_zero"; token: Hex }
  | { kind: "cap_exhausted"; token: Hex };

function erc20AllowNotLiveReason(delegation: Erc20AllowDelegation, tokens: readonly Hex[]): Erc20AllowNotLiveReason | null;
```

Answers why the permission cannot serve `tokens`, or `null` when it can. The block switch comes first. Then, for each token in order: an allowance of 0 (or no row) answers `allowance_zero`, and a cap with `spentInPeriod >= limit` answers `cap_exhausted`.

### Document refusal

```ts theme={null}
interface Erc20AllowChainTokens {
  native: RoutingToken;
  erc20s: readonly Erc20Token[];
}
interface Erc20AllowChainFacts extends Erc20AllowChainTokens {
  swapSupport: Erc20AllowSwapSupport | null; // null when not read
}

type Erc20AllowDocumentRefusal =
  | { kind: "unreadable" }
  | { kind: "unnamed_send_token"; rule: string }
  | { kind: "unnamed_sold_token"; rule: string }
  | { kind: "native_sold_token"; rule: string; token: RoutingToken }
  | { kind: "native_bought_token"; rule: string; token: RoutingToken }
  | { kind: "bought_token_not_configured"; rule: string; token: RoutingToken | null }
  | { kind: "native_send_token"; token: RoutingToken }
  | { kind: "swaps_not_served"; rule: string }
  | { kind: "swap_support_unread"; rule: string };

function findErc20AllowDocumentRefusal(yaml: string, chain: Erc20AllowChainFacts): Erc20AllowDocumentRefusal | null;
function findErc20AllowDocumentRefusalFromActions(
  actionTokens: DocumentActionTokens,
  chain: Erc20AllowChainFacts,
): Erc20AllowDocumentRefusal | null;
```

Answers why the tokens or the swaps of a document stop it on this leg, or `null`. It throws nothing. Use it to show a refusal in an editor before any request. The causes are weighed in this order, and the first that holds answers:

| # | `kind` | Meaning | What to do |
| - | - | - | - |
| 1 | `unreadable` | `normalizeDocument` refuses the text. | Fix the YAML. |
| 2 | `unnamed_send_token`, `unnamed_sold_token` | A send value or a swap input names no token, for example `trigger.value` under a trigger with no range. | Write a literal amount, or give the trigger a token range. |
| 3 | `native_sold_token` | A swap sells the native coin. | Sell an ERC-20. |
| 4 | `native_bought_token` | A swap buys the native coin. | Buy an ERC-20, for example the wrapped coin. |
| 5 | `bought_token_not_configured` | A swap buys a token with no row in `erc20s`. `token` is `null` when the symbol is not a `RoutingToken`. | Buy a token of this network. |
| 6 | `native_send_token` | A send spends the native coin. | Send an ERC-20. |
| 7 | `swaps_not_served`, `swap_support_unread` | A rule swaps, and `swapSupport` is `not_served` or `null`. A document with no swap skips this cause. | Remove the swap, or read the swap support first. |

`findErc20AllowDocumentRefusalFromActions` takes the result of `documentActionTokens`, so you read the text one time.

```ts theme={null}
const refusal = findErc20AllowDocumentRefusal(yaml, {
  native: "POL",
  erc20s: config.erc20s,
  swapSupport: await anafi.readErc20AllowSwapSupport(),
});
if (refusal !== null) showError(refusal.kind);
```

### tokens(D) readers

```ts theme={null}
function erc20AllowDocumentTokenSymbols(tokens: {
  feeToken: RoutingToken | null;
  spentTokens: readonly RoutingToken[];
}): RoutingToken[];

function readErc20AllowDocumentTokens(yaml: string, native: RoutingToken, erc20s: readonly Erc20Token[]): Erc20Token[];
function readErc20AllowDocumentTokensFromActions(
  actionTokens: DocumentActionTokens,
  native: RoutingToken,
  erc20s: readonly Erc20Token[],
): Erc20Token[];
```

`erc20AllowDocumentTokenSymbols` returns the spent tokens, then the fee token when it is new. `readErc20AllowDocumentTokens` returns tokens(D) with their contracts. It throws the errors of checks 2 to 8 of the stage. It does not read the swap support.

```ts theme={null}
// A document that forwards 10% of incoming EURe and pays fees in USDC:
readErc20AllowDocumentTokens(yaml, "POL", config.erc20s);
// [
//   { symbol: "EURe", address: "0xeD5D0B6C5BEFfDd607639094397C223536B0Bae7" },
//   { symbol: "USDC", address: "0x41E94Eb019C0762f9Bfcf9Fb1E58725BfB0e7582" },
// ]
```

### `Erc20AllowOwnerTransaction` and the calldata builders

```ts theme={null}
interface Erc20AllowOwnerTransaction {
  from: Hex;
  to: Hex;
  data: Hex;
}
```

A plain transaction with no value that the account sends. `buildErc20AllowCommitTransaction` returns one. The calldata builders of this leg are on [low-level helpers](https://docs.ana.fi/sdk/low-level.md#erc20allow-calldata).

## Errors of this leg

| Error | Thrown by | Fields |
| - | - | - |
| `Erc20AllowNotLiveError` | `stageErc20AllowDsl`, the subscription setup | `reason: Erc20AllowNotLiveReason` |
| `Erc20AllowSpentTokenUnnamedError` | stage, commit, subscription setup, `readErc20AllowDocumentTokens` | `rule: string \| null` |
| `Erc20AllowNativeSwapTokenError` | the same | `rule`, `side: "sold" \| "bought"`, `token` |
| `Erc20AllowSwapsNotServedError` | stage, commit, subscription setup | `rule`, `adapter` |
| `Erc20AllowSwapSupportUnreadError` | the same, and `readErc20AllowSwapSupport` | `adapter`, `cause` |
| `Erc20AllowStagedDocumentMismatchError` | commit, subscription setup | `field: "commitment" \| "tokens"` |

See [errors](https://docs.ana.fi/sdk/errors.md) for each class.


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