> ## 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.

# AnafiDelegationAdapterERC20Allow

> Reference of the adapter that pulls engine-signed ERC-20 transfers and swaps from an address that approved it.

After you read this page, you know what an `erc20_allow` account grants, how caps and the block switch work, how a swap leg moves funds, and every function, event and error of the contract.

`AnafiDelegationAdapterERC20Allow` is the adapter of the `erc20_allow` account kind. It runs behind an ERC-1967 proxy with UUPS upgrades. It has no owner of its own. Its admin is `AnafiRegistry.owner()`.

## The permission

The account grants the permission token by token, with the ERC-20 allowance of the token. The adapter keeps no grant record.

| Step | Call | Sent by | Effect |
| - | - | - | - |
| Grant | `approve(erc20AllowAdapter, amount)` on each token | The account | The adapter can pull up to `amount` of that token: for transfer legs, for swap legs, and for the gas charge. |
| Revoke | `approve(erc20AllowAdapter, 0)` on each token | The account | Each later pull of that token fails in the token. |
| Pause | `setBlocked(true)` on the adapter | The account | Each later redeem for the account reverts `OwnerBlocked(account)`. |
| Limit | `setCaps(entries)` on the adapter | The account | Each pull counts against a cap for each token and fixed time window. |

See [ERC-20 account flow](https://docs.ana.fi/flows/erc20-account.md) and [ERC20Allow](https://docs.ana.fi/sdk/erc20-allow.md) for the SDK calls.

The adapter cannot move the native coin. It has no native leg, and it refuses the native coin as a gas token. It does not check the code at the account address.

> [!NOTE]
>
> The allowance is state of the token. The block switch and the caps are state of the adapter. Only the account can set its own allowance with `approve`.

## Types

```solidity theme={null}
struct Leg {
    uint8 kind;   // 0 = transfer, 1 = swap
    bytes args;   // the ABI-encoded arguments of that kind
}

struct CapEntry {
    address token;
    uint256 limit;
    uint32 periodSeconds;
}

struct SwapRouterPair {
    address router;
    address spender;
}

enum RedeemRefusal {
    None,                 // 0
    OwnerBlocked,         // 1
    CapExceeded,          // 2
    AllowanceTooLow,      // 3
    BalanceTooLow,        // 4
    UnsupportedLegKind,   // 5
    SwapRouterNotAllowed  // 6
}

struct GasTerms {
    address token;                    // an ERC-20 gas token; address(0) is refused
    uint256 maxCharge;                // the most the account pays, in units of token; 0 charges nothing
    uint256 tokenUnitsPerNativeCoin;  // units of token that 10^18 wei cost
    uint256 baseGas;                  // base and calldata gas of the transaction
    uint256 floorGas;                 // the least gas that the charge bills, or 0
    uint256 legsGasLimit;             // the exact gas of the inner call of the legs
    address receiver;                 // the address that gets the charge
}
```

The payload of a redeem is `abi.encode(address account, Leg[] legs)`.

| Kind | Constant | `args` | What the leg does |
| - | - | - | - |
| Transfer | `LEG_KIND_TRANSFER = 0` | `abi.encode(address token, address to, uint256 amount)` | Counts `amount` against the cap of `token`, then calls `token.transferFrom(account, to, amount)` through OpenZeppelin `SafeERC20`. |
| Swap | `LEG_KIND_SWAP = 1` | `abi.encode(address tokenIn, uint256 amountIn, address tokenOut, uint256 minAmountOut, address router, address spender, bytes routerData)` | Sells exactly `amountIn` of `tokenIn` through an allowed router and requires the account to receive at least `minAmountOut` of `tokenOut`. See [Swap legs](#swap-legs). |

Any other `kind` makes the legs fail with `UnsupportedLegKind(uint8 kind)`.

## Functions for the account

### setBlocked

```solidity theme={null}
function setBlocked(bool blocked) external
```

Sets the block switch of `msg.sender` and emits `BlockedSet(msg.sender, blocked)`. While the switch is on, `redeemAsEngine` reverts `OwnerBlocked(account)` before it collects a gas charge, so the redeem spends no nonce.

The adapter reads the switch at the start of a redeem and again at the start of the legs. A switch that a token callback sets during the legs stops the next redeem, not the later legs of the current one.

### setCaps

```solidity theme={null}
function setCaps(CapEntry[] calldata entries) external
```

Sets one cap for each entry, in order, for `msg.sender`. It emits `CapSet(msg.sender, token, limit, periodSeconds)` for each entry.

* An entry with `periodSeconds` below `MIN_CAP_PERIOD_SECONDS` (3600) reverts the whole call with `CapPeriodTooShort(uint32 periodSeconds)`.
* The window of a cap is `block.timestamp / periodSeconds`. Windows are fixed. They start at multiples of `periodSeconds` after the Unix epoch, not at the time of the call.
* An entry for a cap that is set, with the same `periodSeconds`, in the current window, keeps the amount spent in that window. Each other entry starts the counter at zero.
* A `limit` of zero lets only zero-amount pulls pass.

### clearCaps

```solidity theme={null}
function clearCaps(address[] calldata tokens) external
```

Removes the cap of each token for `msg.sender` and emits `CapCleared(msg.sender, token)` for each token, also for a token that had no cap.

### claimGasCredit

```solidity theme={null}
function claimGasCredit(address token, address to) external
```

Pays the whole credit of `msg.sender` in `token` to `to`. A credit comes from a failed payment of a charge or a refund. The call needs no allowance and works while the switch is on. The adapter clears the credit before it pays. A failed payment reverts `GasCreditClaimFailed()` and keeps the credit. A zero credit reverts `NoGasCredit()`. On success, it emits `GasCreditClaimed(msg.sender, token, to, amount)`.

### How a cap counts

A cap counts each pull of its token from the account:

| Pull | Amount that counts |
| - | - |
| Transfer leg | `amount` |
| Swap leg | `amountIn`, also when the router returns part of it |
| Gas reservation, when `maxCharge` is above zero | `maxCharge`, before the legs |
| Gas settlement | Subtracts `maxCharge - charge` after the legs, but only when the same cap still holds the reservation |

A pull fails with `CapExceeded(owner, token)` when the spent amount is more than the limit, or when the pull is more than `limit - spent`. The counter starts at zero when a new window starts. When `clearCaps` removes the cap during the legs, or `setCaps` starts a new counter during the legs, the adapter does not subtract the unused reservation, so the new cap keeps the spend. A `setCaps` with the same `periodSeconds` in the same window keeps the counter, and the adapter subtracts the unused reservation from it.

```ts theme={null}
import { createPublicClient, http } from "viem";
import { polygonAmoy } from "viem/chains";
import { ANAFI_ERC20_ALLOW_ADAPTER_ABI } from "@anafi-cc/anafi-sdk";

const publicClient = createPublicClient({ chain: polygonAmoy, transport: http() });
const erc20AllowAdapter = "0x3C58b31704Bbb13D32b38FFf1427799D6ce900e7"; // polygon-amoy

const [isSet, limit, periodSeconds, spentInPeriod] = await publicClient.readContract({
  address: erc20AllowAdapter,
  abi: ANAFI_ERC20_ALLOW_ADAPTER_ABI,
  functionName: "capOf",
  args: [account, token],
});
const blocked = await publicClient.readContract({
  address: erc20AllowAdapter,
  abi: ANAFI_ERC20_ALLOW_ADAPTER_ABI,
  functionName: "isBlocked",
  args: [account],
});
```

## Functions for anyone

### redeemAsEngine

```solidity theme={null}
function redeemAsEngine(
    bytes calldata payload,
    GasTerms calldata gasTerms,
    uint256 nonce,
    uint256 validUntil,
    bytes calldata engineSignature
) external returns (bool legsSucceeded, uint256 charge, bytes memory legsRevertData)
```

Executes the transfer and swap legs of an engine-signed payload, and charges the account the gas of the whole call in an ERC-20 token. Any address can submit it.

| Return | Description |
| - | - |
| `legsSucceeded` | `true` when every leg succeeded. |
| `charge` | The gas charge, in units of `gasTerms.token`. |
| `legsRevertData` | The first 256 bytes of the revert data of the inner call when the legs failed. Empty on success. |

[Redeem](https://docs.ana.fi/contracts/redeem.md) gives the digest, the order of checks, the gas formula, and the full list of revert and failure causes.

### redeemRefusal and redeemRefusalWithGas

```solidity theme={null}
function redeemRefusal(address account, Leg[] calldata legs)
    external view returns (RedeemRefusal reason, uint256 legIndex);

function redeemRefusalWithGas(address account, Leg[] calldata legs, address gasToken, uint256 maxCharge)
    external view returns (RedeemRefusal refusal, uint256 legIndex);
```

Returns the first reason why the adapter or a token refuses `legs` now, or `None`. Use it to show the owner what to fix, for example an allowance that is too low.

The checks run in this order:

1. The block switch. A blocked account returns `(OwnerBlocked, 0)`.
2. Only `redeemRefusalWithGas` with `maxCharge` above zero: the gas token. A zero `gasToken`, or one with no gas overhead, reverts `GasTokenNotSupported(gasToken)`. Then the reservation of `maxCharge` counts against the cap and the allowance of `gasToken`. A refusal of the reservation returns the index `legs.length`.
3. Each leg in order: the leg kind, then the cap of the pulled token, then the allowance of the pulled token. Each leg uses the room that the earlier pulls of the same token left.
4. The first swap leg whose router and spender pair is not allowed: `SwapRouterNotAllowed`.
5. The balance of each pulled token. A swap leg adds its `minAmountOut` to the balance room of `tokenOut` for the later legs. A refusal of the reservation returns the index `legs.length`.

A sum of amounts that does not fit in `uint256` gives a refusal, not a revert. The views do not check the nonce, the deadline, the signature, the registry list, the swap executor, the shape of a swap leg, the exact debit of a swap leg, or the swap output.

```ts theme={null}
import { parseAbi } from "viem";

const REFUSAL_ABI = parseAbi([
  "function redeemRefusalWithGas(address account, (uint8 kind, bytes args)[] legs, address gasToken, uint256 maxCharge) view returns (uint8 refusal, uint256 legIndex)",
]);

const [refusal, legIndex] = await publicClient.readContract({
  address: erc20AllowAdapter,
  abi: REFUSAL_ABI,
  functionName: "redeemRefusalWithGas",
  args: [account, legs, gasToken, maxCharge],
});
```

## Swap legs

A swap leg runs these steps, in this order, inside the legs of the redeem:

1. `swapExecutor()` must be set. Else: `SwapExecutorNotSet()`.
2. The pair `(router, spender)` must be allowed. Else: `SwapRouterNotAllowed(router, spender)`.
3. `tokenIn` must differ from `tokenOut`, and `amountIn` and `minAmountOut` must be above zero. Else: `SwapLegNotValid()`.
4. `amountIn` counts against the cap of `tokenIn`. Else: `CapExceeded(owner, token)`.
5. The adapter reads the `tokenOut` balance of the account.
6. The adapter calls `tokenIn.transferFrom(account, swapExecutor, amountIn)`. The executor balance must grow by exactly `amountIn`. Else: `SwapInputNotReceived(tokenIn, amountReceived, amountIn)`. Then the account balance must fall by exactly `amountIn`. Else: `SwapInputDebitNotExact(tokenIn, amountDebited, amountIn)`.
7. The adapter calls `swapExecutor.swap(tokenIn, amountIn, tokenOut, router, spender, routerData, account)`. The executor pays the output and the unused input to the account. See [AnafiSwapExecutor](https://docs.ana.fi/contracts/swap-executor.md).
8. The `tokenOut` balance of the account must have grown by at least `minAmountOut`. Else: `SwapOutputBelowMinimum(tokenOut, amountOut, minAmountOut)`.

Limits of the swap leg:

* It sells and buys ERC-20 tokens only. It moves no native coin.
* A token with a transfer tax cannot be the sold token, because step 6 requires an exact amount.
* The adapter checks the exact debit for a swap leg only. A transfer leg of a token that takes a tax from the sender can debit the account more than the leg amount.
* The registry owner controls the pair list. A pair that the registry owner removes stops each swap leg that names it, also a leg that the engine signed before the removal.

## Functions of the registry owner

Each function reverts `CallerNotRegistryOwner()` when the caller is not `AnafiRegistry.owner()`.

| Function | Effect | Event |
| - | - | - |
| `initializeSwaps(address swapExecutor_, SwapRouterPair[] calldata allowedPairs)` | Records the swap executor and allows the first pairs. It runs one time only. The executor must have code, and its `adapter()` must return this proxy. Else: `SwapExecutorNotUsable(address swapExecutor)`. A second call reverts `InvalidInitialization()`. | `SwapRouterAllowedSet` for each pair, `Initialized(2)` |
| `setSwapRouterAllowed(address router, address spender, bool allowed)` | Adds or removes one pair. | `SwapRouterAllowedSet(router, spender, allowed)` |
| `setGasOverhead(address token, uint256 overhead)` | Sets the gas overhead of a gas token. A zero overhead stops charges in that token. The zero address reverts `GasTokenNotSupported(address(0))`. | `GasOverheadSet(token, overhead)` |
| `upgradeToAndCall(address newImplementation, bytes memory data)` | Upgrades the proxy. Payable. | `Upgraded(newImplementation)` |

When `swapExecutor()` returns a non-zero address, `initializeSwaps` ran already and the executor cannot change.

`initialize(address anafiRegistry_)` ran once at deployment. It reverts `RegistryNotUsable(address registry)` when the registry has no code, or when its `owner()` reverts, returns other than one address word, or returns zero.

## Functions that only the adapter calls

```solidity theme={null}
function executeLegsAsSelf(bytes calldata payload) external
```

The inner call of the legs. `redeemAsEngine` calls it on the adapter itself with exactly `legsGasLimit` gas. Any other caller gets `CallerNotSelf()`.

## Views and constants

| Function | Returns | Description |
| - | - | - |
| `anafiRegistry()` | `address` | The registry that the adapter reads. It never changes. |
| `owner()` | `address` | `AnafiRegistry.owner()`, read at the time of the call. |
| `swapExecutor()` | `address` | The swap executor, or zero before `initializeSwaps`. |
| `isSwapRouterAllowed(address router, address spender)` | `bool` | Whether a swap leg can name this pair. |
| `isNonceUsed(uint256 nonce)` | `bool` | Whether a redeem spent `nonce` on this adapter. |
| `isBlocked(address account)` | `bool` | The block switch of the account. |
| `capOf(address account, address token)` | `(bool isSet, uint256 limit, uint32 periodSeconds, uint256 spentInPeriod)` | The cap of the account for the token. `spentInPeriod` is 0 when a new window started after the last pull. |
| `gasOverhead(address token)` | `uint256` | The gas overhead of the gas token. Zero means the adapter does not charge in it. |
| `gasCredit(address payee, address token)` | `uint256` | The credit that the adapter keeps for `payee` in `token`. |
| `redeemRefusal`, `redeemRefusalWithGas` | `(RedeemRefusal, uint256)` | See above. |
| `UPGRADE_INTERFACE_VERSION()` | `string` | `"5.0.0"`. |
| `proxiableUUID()` | `bytes32` | The ERC-1967 slot. Reverts through the proxy. |

| Constant | Value | Description |
| - | - | - |
| `ROUTE_TAG` | `0x31747694805ea00e26185495e79555aa0fd8bc5ed92dee2440234ea76be46373` | `keccak256("ANAFI_ADAPTER_REDEEM_WITH_GAS")`, the same tag as the Safe adapter. |
| `SETTLEMENT_RESERVE_GAS` | `300000` | The gas above the 64/63 share of `legsGasLimit` that must be left before the legs start. |
| `COLLECTION_GAS` | `150000` | The gas of the `transferFrom` call that collects `maxCharge`. |
| `PAYMENT_GAS` | `100000` | The gas of each payment: a charge, a refund or a claimed credit. |
| `MAX_LEGS_REVERT_DATA_BYTES` | `256` | The most revert bytes that `redeemAsEngine` returns. |
| `LEG_KIND_TRANSFER` | `0` | The transfer leg kind. |
| `LEG_KIND_SWAP` | `1` | The swap leg kind. |
| `MIN_CAP_PERIOD_SECONDS` | `3600` | The shortest cap period. |

## Events

```solidity theme={null}
event EngineRedeemed(uint256 indexed nonce, bytes32 indexed digest);
event EngineRedeemFailed(uint256 indexed nonce, bytes32 indexed digest);
event GasCharged(uint256 indexed nonce, bytes32 indexed digest, address token, uint256 charge);
event GasCreditKept(address indexed payee, address indexed token, uint256 amount);
event GasCreditClaimed(address indexed payee, address indexed token, address to, uint256 amount);
event GasOverheadSet(address indexed token, uint256 overhead);
event BlockedSet(address indexed owner, bool blocked);
event CapSet(address indexed owner, address indexed token, uint256 limit, uint32 periodSeconds);
event CapCleared(address indexed owner, address indexed token);
event SwapRouterAllowedSet(address indexed router, address indexed spender, bool allowed);

// OpenZeppelin
event Upgraded(address indexed implementation);
event Initialized(uint64 version);
```

In `BlockedSet`, `CapSet` and `CapCleared`, the field `owner` is the account that called the function.

| Event | When |
| - | - |
| `EngineRedeemed` | Once per redeem whose legs succeeded. |
| `EngineRedeemFailed` | Once per redeem whose legs failed. The nonce stays spent and the charge is paid. |
| `GasCharged` | Once per redeem, after the result event, also for a zero charge. |
| `GasCreditKept` | A payment of a charge or a refund failed. The adapter keeps `amount` as a credit of `payee`. |
| `GasCreditClaimed` | A payee claimed its whole credit in one token. |
| `GasOverheadSet` | The registry owner set a gas overhead. |
| `BlockedSet` | An account changed its block switch. |
| `CapSet` | An account set a cap. One event per entry, in the order of the entries. |
| `CapCleared` | An account cleared a cap. One event per token. |
| `SwapRouterAllowedSet` | The registry owner added or removed a router and spender pair. |

## Errors

| Error | Raised by | Cause | Nonce spent |
| - | - | - | - |
| `RedeemReentered()` | `redeemAsEngine` | A token or router callback entered `redeemAsEngine` inside a redeem that is not complete. In the legs, this makes the legs fail. | No, or legs fail |
| `AdapterNotAllowed()` | `redeemAsEngine` | The registry does not list this adapter. | No |
| `RedeemWindowExpired()` | `redeemAsEngine` | `block.timestamp` is more than `validUntil`. | No |
| `InvalidEngineSignature()` | `redeemAsEngine` | The signature recovers to an address other than `engineSigKey()`. | No |
| `NonceAlreadyUsed()` | `redeemAsEngine` | A redeem spent this nonce before. | No |
| `OwnerBlocked(address owner)` | `redeemAsEngine` | The block switch of the account is on. | No |
| `GasTokenNotSupported(address token)` | `redeemAsEngine`, `redeemRefusalWithGas`, `setGasOverhead` | The gas token is the zero address, or has no gas overhead. | No |
| `CapExceeded(address owner, address token)` | `redeemAsEngine` | The gas reservation has no room in the cap of the gas token. | No |
| `GasChargeCollectionFailed()` | `redeemAsEngine` | The `transferFrom` of `maxCharge` failed, returned other than nothing or `true`, or the adapter balance did not grow by exactly `maxCharge`. | No |
| `GasForLegsTooLow(uint256 gasLeft, uint256 gasNeeded)` | `redeemAsEngine` | The gas left is below `legsGasLimit * 64 / 63 + 300000`. | No |
| `CapExceeded(address owner, address token)` | inner leg call | A leg has no room in the cap of its token. | Yes, legs fail |
| `UnsupportedLegKind(uint8 kind)` | inner leg call | A leg kind is not 0 or 1. | Yes, legs fail |
| `SwapExecutorNotSet()` | inner leg call | A swap leg came before `initializeSwaps`. | Yes, legs fail |
| `SwapRouterNotAllowed(address router, address spender)` | inner leg call | The pair of a swap leg is not allowed. | Yes, legs fail |
| `SwapLegNotValid()` | inner leg call | The swap leg sells the token that it buys, sells zero, or names a zero minimum. | Yes, legs fail |
| `SwapInputNotReceived(address tokenIn, uint256 amountReceived, uint256 amountIn)` | inner leg call | The executor did not receive exactly `amountIn`. | Yes, legs fail |
| `SwapInputDebitNotExact(address tokenIn, uint256 amountDebited, uint256 amountIn)` | inner leg call | The account balance did not fall by exactly `amountIn`. | Yes, legs fail |
| `SwapOutputBelowMinimum(address tokenOut, uint256 amountOut, uint256 minAmountOut)` | inner leg call | The account received less than `minAmountOut`. | Yes, legs fail |
| `SafeERC20FailedOperation(address token)` | inner leg call | A `transferFrom` of a leg returned `false`. A token that reverts gives its own error, for example for a low allowance or balance. | Yes, legs fail |
| `CapPeriodTooShort(uint32 periodSeconds)` | `setCaps` | A period is below 3600 seconds. | Not a redeem |
| `CallerNotSelf()` | `executeLegsAsSelf` | The caller is not the adapter. | Not a redeem |
| `CallerNotRegistryOwner()` | admin functions, `upgradeToAndCall` | The caller is not `AnafiRegistry.owner()`. | Not a redeem |
| `RegistryNotUsable(address registry)` | `initialize` | The registry has no usable `owner()`. | Not a redeem |
| `SwapExecutorNotUsable(address swapExecutor)` | `initializeSwaps` | The executor has no code, or its `adapter()` is not this proxy. | Not a redeem |
| `NoGasCredit()` | `claimGasCredit` | The caller has no credit in the token. | Not a redeem |
| `GasCreditClaimFailed()` | `claimGasCredit` | The payment of the credit failed. The credit stays. | Not a redeem |
| `ECDSAInvalidSignature()`, `ECDSAInvalidSignatureLength(uint256 length)`, `ECDSAInvalidSignatureS(bytes32 s)` | `redeemAsEngine` | The signature is malformed. | No |
| `InvalidInitialization()`, `NotInitializing()`, `UUPSUnauthorizedCallContext()`, `UUPSUnsupportedProxiableUUID(bytes32 slot)`, `ERC1967InvalidImplementation(address implementation)`, `ERC1967NonPayable()` | initializers and upgrade | OpenZeppelin guards. | Not a redeem |

A payload that does not decode as `(address, Leg[])` reverts the whole call, so no nonce is spent.

## Invariants

* The adapter executes no call data from the payload, except the `routerData` that the swap executor sends to an allowed router.
* Each pull comes from the account of the payload. A transfer leg pays `to`. A swap leg pays its output and its unused input to the account.
* A nonce is spent at most once on this adapter. It is spent exactly when `redeemAsEngine` does not revert.
* The charge is never more than `maxCharge`. The account gets back `maxCharge - charge`, or a credit of that amount.
* Outside a redeem, the adapter holds only gas credits and funds that someone sent to it directly.
* A zero allowance stops every pull of that token until the account approves the adapter again.
* Revocation does not cancel a signed redeem. A new approval, `setBlocked(false)`, a cleared or raised cap, a changed period, or the next window can admit an unexpired redeem that was signed before. Only `validUntil` bounds it. A redeem that the adapter refused before its legs left its nonce unspent.

## Storage

All state is in one ERC-7201 namespace, `anafi.storage.AnafiDelegationAdapterERC20Allow`, at slot `0x48349d960e8d331c8299c530b4e2a7d3a045c0e55fb8c6b6beb7c663738c7300`.


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