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

# Redeem

> How the chain authorizes and executes one Anafi payment, for each account kind.

After you read this page, you can decode a redeem transaction, check its engine signature yourself, compute its gas charge, and tell from the receipt why it reverted or why its legs failed.

A redeem is one call of `redeemAsEngine` on an adapter. It carries a payload of legs, the gas terms, a nonce, a deadline and an engine signature. This page describes only what the contracts check and do.

```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)
```

Both adapters have this function with the same signature and the same `GasTerms` struct. The payload has a different shape for each adapter.

## The flow of one redeem

```mermaid theme={null}
sequenceDiagram
    participant S as Any sender
    participant A as Adapter
    participant R as AnafiRegistry
    participant W as Account
    participant L as Inner leg call
    S->>A: redeemAsEngine(payload, gasTerms, nonce, validUntil, engineSignature)
    A->>R: isDelegationAdapter(adapter)
    A->>A: check validUntil
    A->>R: engineSigKey()
    A->>A: recover the signer of the digest, check the nonce, spend the nonce
    A->>W: check the account
    A->>W: collect maxCharge, when it is above zero
    A->>A: check the gas left
    A->>L: executeLegsAsSelf(payload), with exactly legsGasLimit gas
    L-->>A: success, or revert data
    A->>A: compute the charge
    A->>W: refund maxCharge minus the charge
    A->>A: emit EngineRedeemed or EngineRedeemFailed, then GasCharged
```

Any address can submit a redeem. The engine signature is the whole authorization. In practice, Anafi submits the transaction.

## The signed digest

The adapter does not use EIP-712 or EIP-191. The engine key signs a raw `keccak256` digest of `abi.encode` of 13 values:

```solidity theme={null}
bytes32 ROUTE_TAG = keccak256("ANAFI_ADAPTER_REDEEM_WITH_GAS");
// = 0x31747694805ea00e26185495e79555aa0fd8bc5ed92dee2440234ea76be46373

bytes32 digest = keccak256(abi.encode(
    ROUTE_TAG,
    block.chainid,
    address(adapter),
    payload,                         // bytes
    gasTerms.token,
    gasTerms.maxCharge,
    gasTerms.tokenUnitsPerNativeCoin,
    gasTerms.baseGas,
    gasTerms.floorGas,
    gasTerms.legsGasLimit,
    gasTerms.receiver,
    nonce,
    validUntil
));
```

| Field | Type | Description |
| - | - | - |
| `ROUTE_TAG` | `bytes32` | The same tag on both adapters. It keeps a redeem signature apart from other signatures of the engine key. |
| `block.chainid` | `uint256` | The chain of the redeem. |
| `adapter` | `address` | The adapter proxy that gets the call. |
| `payload` | `bytes` | The legs, in the shape of that adapter. |
| `token` | `address` | The gas token. The zero address is the native coin, on the Safe adapter only. |
| `maxCharge` | `uint256` | The most that the account pays, in units of `token`. Zero is a sponsored redeem. |
| `tokenUnitsPerNativeCoin` | `uint256` | The units of `token` that 10^18 wei cost. Zero for the native coin. |
| `baseGas` | `uint256` | The base and calldata gas of the transaction, which the adapter cannot measure. |
| `floorGas` | `uint256` | The least gas that the charge bills, or zero. |
| `legsGasLimit` | `uint256` | The exact gas of the inner call of the legs. |
| `receiver` | `address` | The address that gets the charge. |
| `nonce` | `uint256` | The replay key. |
| `validUntil` | `uint256` | The Unix deadline. |

The chain id and the adapter address are in the digest, so one signature is valid at one adapter on one chain. Every field of `GasTerms` and the deadline are in the digest, so a sender cannot change them.

### Check a redeem signature yourself

```ts theme={null}
import { encodeAbiParameters, keccak256, recoverAddress, toHex } from "viem";

const ROUTE_TAG = keccak256(toHex("ANAFI_ADAPTER_REDEEM_WITH_GAS"));

function redeemDigest(chainId: bigint, adapter: `0x${string}`, payload: `0x${string}`, gasTerms: {
  token: `0x${string}`; maxCharge: bigint; tokenUnitsPerNativeCoin: bigint; baseGas: bigint;
  floorGas: bigint; legsGasLimit: bigint; receiver: `0x${string}`;
}, nonce: bigint, validUntil: bigint) {
  return keccak256(
    encodeAbiParameters(
      [
        { type: "bytes32" }, { type: "uint256" }, { type: "address" }, { type: "bytes" },
        { type: "address" }, { type: "uint256" }, { type: "uint256" }, { type: "uint256" },
        { type: "uint256" }, { type: "uint256" }, { type: "address" }, { type: "uint256" },
        { type: "uint256" },
      ],
      [
        ROUTE_TAG, chainId, adapter, payload,
        gasTerms.token, gasTerms.maxCharge, gasTerms.tokenUnitsPerNativeCoin, gasTerms.baseGas,
        gasTerms.floorGas, gasTerms.legsGasLimit, gasTerms.receiver, nonce,
        validUntil,
      ],
    ),
  );
}

// Compare the signer with AnafiRegistry.engineSigKey() at the block of the redeem.
const signer = await recoverAddress({ hash: redeemDigest(/* ... */), signature: engineSignature });
```

Test vector: with the values below, the digest is `0x04e7a47e8fe1ff58013d96c937f5c85e4bdc2b70205b3daeaa3c5512e2873a16`.

| Input | Value |
| - | - |
| `chainId` | `137` |
| `adapter` | `0x3333333333333333333333333333333333333333` |
| `payload` | `0xabcdef00010203` |
| `token` | `0x4444444444444444444444444444444444444444` |
| `maxCharge` | `25000000` |
| `tokenUnitsPerNativeCoin` | `1700123456` |
| `baseGas` | `61234` |
| `floorGas` | `130000` |
| `legsGasLimit` | `1200000` |
| `receiver` | `0x5555555555555555555555555555555555555555` |
| `nonce` | `12345678901234567890` |
| `validUntil` | `1893456000` |

## Who signs

The signer must be `AnafiRegistry.engineSigKey()` at the time of the call. The adapter reads the key on each redeem. After a key change at the registry, a redeem that the old key signed fails with `InvalidEngineSignature()`.

The signature is 65 bytes. A malformed signature reverts with an OpenZeppelin `ECDSA` error: `ECDSAInvalidSignature()`, `ECDSAInvalidSignatureLength(uint256)` or `ECDSAInvalidSignatureS(bytes32)`.

## Nonce and deadline

| Rule | Detail |
| - | - |
| Scope | Each adapter has its own nonce set. A nonce is not tied to an account. |
| Value | Any `uint256`. The contract does not require an order. |
| Single use | A redeem that does not revert spends its nonce, also when its legs fail. A second redeem with the same nonce reverts `NonceAlreadyUsed()`, even with another digest. |
| Refusal | A redeem that reverts does not spend its nonce. |
| Read | `usedNonces(nonce)` on the Safe adapter. `isNonceUsed(nonce)` on the ERC20Allow adapter. |
| Deadline | `block.timestamp > validUntil` reverts `RedeemWindowExpired()`. A redeem at exactly `validUntil` passes. |

A revocation does not cancel a signed redeem. If the owner grants the permission again before `validUntil`, a signed redeem that did not land can land. Only `validUntil` bounds it.

## The order of checks

Each step that fails reverts the whole transaction. Then the adapter spends no nonce, takes no charge and runs no leg.

| Step | Safe adapter | ERC20Allow adapter |
| - | - | - |
| 1 | Reads `gasleft()` to start the gas measurement. Takes the redeem lock, else `RedeemReentered()`. | Same. |
| 2 | `AnafiRegistry.isDelegationAdapter(adapter)`, else `AdapterNotAllowed()`. | Same. |
| 3 | `block.timestamp <= validUntil`, else `RedeemWindowExpired()`. | Same. |
| 4 | The digest recovers to `engineSigKey()`, else `InvalidEngineSignature()`. | Same. |
| 5 | The nonce is not spent, else `NonceAlreadyUsed()`. The adapter spends it. | Same. |
| 6 | Decodes the payload. The avatar must be an admitted Safe, else `SafeNotAdmitted(account)`. It must have no module guard, else `SafeHasModuleGuard(account)`. | Decodes the payload. The block switch of the account must be off, else `OwnerBlocked(account)`. |
| 7 | When `maxCharge` is above zero: the token must have a gas overhead, else `GasTokenNotSupported(token)`. The Safe pays `maxCharge` into the adapter, else `GasChargeCollectionFailed()`. | When `maxCharge` is above zero: the token must not be zero and must have a gas overhead, else `GasTokenNotSupported(token)`. `maxCharge` counts against the cap of the token, else `CapExceeded(account, token)`. The account pays `maxCharge` into the adapter, else `GasChargeCollectionFailed()`. |
| 8 | `gasleft() >= legsGasLimit * 64 / 63 + 300000`, else `GasForLegsTooLow(gasLeft, gasNeeded)`. | Same. |
| 9 | Runs the legs in an inner call. A failure undoes the legs only. | Same, and the block switch is read again at the start of the legs. |
| 10 | Computes the charge, pays it, and refunds the rest. | Same, and subtracts the unused reservation from the cap. |
| 11 | Emits `EngineRedeemed` or `EngineRedeemFailed`, then `GasCharged`, and frees the lock. | Same. |

## The payload and its legs

### Safe adapter

```solidity theme={null}
payload = abi.encode(address avatar, bytes32[] modes, bytes[] callDatas);
callDatas[i] = abi.encodePacked(address target, uint256 value, bytes data);
modes[i] = bytes32(0); // the ERC-7579 single-call mode
```

The adapter calls `avatar.execTransactionFromModule(target, value, data, 0)` for each leg, in order. A leg that returns `false` fails all legs with `AvatarExecutionFailed(legIndex)`. The Safe adapter has no leg types: each leg is a plain call from the Safe.

### ERC20Allow adapter

```solidity theme={null}
payload = abi.encode(address account, Leg[] legs);  // Leg = (uint8 kind, bytes args)
// kind 0, transfer: args = abi.encode(address token, address to, uint256 amount)
// kind 1, swap:     args = abi.encode(address tokenIn, uint256 amountIn, address tokenOut,
//                                     uint256 minAmountOut, address router, address spender, bytes routerData)
```

The adapter runs the legs in order. Each leg counts against the cap of its pulled token. A transfer leg calls `token.transferFrom(account, to, amount)`. A swap leg goes through [AnafiSwapExecutor](https://docs.ana.fi/contracts/swap-executor.md) and pays the output to the account.

### Kinds of payment

| Payment | Safe account | ERC20Allow account |
| - | - | - |
| Send to one payee | One leg. For a token: `target` is the token, `value` is 0, and `data` is `transfer(to, amount)`. For the native coin: `target` is the payee, `value` is the amount, and `data` is empty. | One transfer leg. The native coin is not possible. |
| Send to many payees | One leg for each payee in one payload. | One transfer leg for each payee in one payload. |
| Swap | The Safe adapter has no swap leg. A swap is plain calls that the Safe executes. The adapter checks no minimum output. | One swap leg. The adapter checks the router pair, the exact debit, and the minimum output at the account. |
| Bank payout | Not a leg. The Safe answers the signature check of the provider through the [off-ramp handler](https://docs.ana.fi/contracts/off-ramp-handler.md), under the policy of the Safe. | The adapter has no off-ramp path. |
| Fee | The adapters have no fee field. A leg that pays a fee is a plain leg of the payload, and the adapter treats it like each other leg. See [Fees](https://docs.ana.fi/concepts/fees.md). | Same. |

All legs of one payload succeed together or fail together. One engine signature covers the whole array.

For the full list of the ERC20Allow pull rules, the caps and the block switch, see [AnafiDelegationAdapterERC20Allow](https://docs.ana.fi/contracts/erc20-allow-adapter.md).

## The gas charge

Each redeem charges the account the gas of the whole transaction, also when the legs fail. A `maxCharge` of zero is a sponsored redeem: no gas token moves and `GasCharged` shows a zero charge.

### Collection before the legs

| | Safe adapter | ERC20Allow adapter |
| - | - | - |
| Gas token | The native coin, with `token = address(0)`, or an ERC-20 token. | An ERC-20 token only. |
| How | One module call of the Safe with 150,000 gas: a value send to the adapter for the native coin, or `token.transfer(adapter, maxCharge)` for a token. | `maxCharge` counts against the cap of the token. Then `token.transferFrom(account, adapter, maxCharge)` with 150,000 gas. The call must return nothing or `true`. |
| Check | The adapter balance must grow by exactly `maxCharge`. | The adapter balance must grow by exactly `maxCharge`. |

The registry owner admits a gas token with `setGasOverhead(token, overhead)` on each adapter. Read `gasOverhead(token)`: zero means the adapter refuses a charge in that token.

### The charge formula

```text theme={null}
gasUsed  = gasleft() at the start of redeemAsEngine  -  gasleft() after the legs
billed   = max(gasUsed + baseGas + gasOverhead(token), floorGas)
cost     = billed * tx.gasprice                                   (wei)
charge   = cost                                                   (native coin)
charge   = ceil(cost * tokenUnitsPerNativeCoin / 10^18)           (ERC-20 token)
charge   = min(charge, maxCharge)
charge   = 0                                                      (when maxCharge is 0)
```

Example, from the test vectors of the contracts: `gasUsed = 123456`, `baseGas = 54321`, overhead `98765`, `floorGas = 0`, gas price `1500000000` wei, `tokenUnitsPerNativeCoin = 1700123456`, `maxCharge = 25000000`. The billed gas is 276,542, the cost is 414,813,000,000,000 wei, and the charge is `705234` token units.

### Payment after the legs

1. The adapter pays `charge` to `receiver`, with 100,000 gas.
2. The adapter pays `maxCharge - charge` back to the account, with 100,000 gas.
3. On the ERC20Allow adapter, it subtracts `maxCharge - charge` from the cap of the gas token. It does this only when the same cap still holds the reservation.

A payment never reverts the redeem. A failed payment becomes a credit of its payee, and the adapter emits `GasCreditKept(payee, token, amount)`. The payee claims the credit with `claimGasCredit(token, to)`. The claim needs no grant.

A token payment passes only when the call did not revert and returned no data, or exactly one 32-byte word equal to 1. Each other result is a failed payment.

On the Safe adapter, a native refund runs code of the Safe. So the adapter checks the Safe again before it sends a native refund: the code hash and the singleton must still be admitted. When the check fails, the refund becomes a credit of the Safe, and the adapter sends no native coin to the Safe.

## Revert or failed legs

A redeem ends in one of three ways.

| Outcome | What the chain shows | Nonce | Gas charge | Legs |
| - | - | - | - | - |
| Success | `EngineRedeemed`, then `GasCharged`. `legsSucceeded = true`. | Spent | Paid | Done |
| Legs failed | `EngineRedeemFailed`, then `GasCharged`. `legsSucceeded = false`. `legsRevertData` holds the first 256 bytes of the inner revert. | Spent | Paid | Undone |
| Revert | The transaction reverts with a custom error of the adapter. | Not spent | None | None |

These causes revert the whole transaction:

* `RedeemReentered()`, `AdapterNotAllowed()`, `RedeemWindowExpired()`, `InvalidEngineSignature()`, the `ECDSA` errors, `NonceAlreadyUsed()`.
* A payload that does not decode.
* Safe adapter: `SafeNotAdmitted(address)`, `SafeHasModuleGuard(address)`.
* ERC20Allow adapter: `OwnerBlocked(address)`, and `CapExceeded(address,address)` for the gas reservation.
* `GasTokenNotSupported(address)`, `GasChargeCollectionFailed()`, `GasForLegsTooLow(uint256,uint256)`.
* An arithmetic overflow in the charge formula.

These causes make the legs fail, with the error in `legsRevertData`:

* Safe adapter: `UnsupportedMode(bytes32)`, `AvatarExecutionFailed(uint256)`, a Safe error such as `GS104` when the module is not enabled and `maxCharge` is zero, a malformed leg, or the inner call out of gas.
* ERC20Allow adapter: `UnsupportedLegKind(uint8)`, `CapExceeded(address,address)` for a leg, the error of a token for a low allowance or balance, `SafeERC20FailedOperation(address)`, the swap errors `SwapExecutorNotSet()`, `SwapRouterNotAllowed(address,address)`, `SwapLegNotValid()`, `SwapInputNotReceived(address,uint256,uint256)`, `SwapInputDebitNotExact(address,uint256,uint256)`, `SwapOutputBelowMinimum(address,uint256,uint256)`, the executor errors `RouterCallFailed(bytes)` and `SwapReentered()`, or the inner call out of gas.

On the Safe adapter, a Safe that did not enable the module reverts at the collection step with `GasChargeCollectionFailed()` when `maxCharge` is above zero. When `maxCharge` is zero, the legs fail with `GS104`.

## Watch redeems

```ts theme={null}
import { createPublicClient, http, parseAbi } from "viem";
import { polygonAmoy } from "viem/chains";

const publicClient = createPublicClient({ chain: polygonAmoy, transport: http() });
const REDEEM_EVENTS = parseAbi([
  "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)",
]);

const logs = await publicClient.getLogs({
  address: "0x425FE0A554299D33589edc51387254175478Ee0e", // polygon-amoy Safe adapter
  events: REDEEM_EVENTS,
  fromBlock,
  toBlock,
});
```

The redeem events do not name the account. Decode the `payload` from the transaction input to get it: the first ABI word of the payload is the account on both adapters. The ERC-20 `Transfer` events of the same receipt show the moved funds.

For the status of a payment as the Anafi API reports it, see [Execution](https://docs.ana.fi/flows/execution.md).


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