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

# AnafiDelegationAdapterSafe

> Reference of the Safe module that executes engine-signed calls for `safe_module` accounts.

After you read this page, you know what a Safe grants when it enables the Anafi module, what the module checks, and every function, event and error of the contract.

`AnafiDelegationAdapterSafe` is the adapter of the `safe_module` 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 grant is one Safe call, and the revocation is one Safe call. The adapter keeps no record of either.

| Step | Call on the Safe | Effect |
| - | - | - |
| Grant | `enableModule(safeAdapter)` | The Safe accepts `execTransactionFromModule` from the adapter. |
| Revoke | `disableModule(prevModule, safeAdapter)` | The Safe refuses each module call from the adapter. Each later leg fails inside the Safe with the Safe error `GS104`. |

The Safe owners send both calls through a Safe transaction. See [Safe account flow](https://docs.ana.fi/flows/safe-account.md) and [Safe](https://docs.ana.fi/sdk/safe.md) for how the SDK builds them.

The adapter executes each engine-signed leg as a plain call from the Safe, with the target, the value and the call data of the leg. It never sends a delegatecall. Its checks are the registry list, the deadline, the engine signature, the nonce and the account. It sets no limit on the target, the value or the call data of a leg. A leg can call any contract, the Safe itself included.

## Which Safes the adapter accepts

`redeemAsEngine` accepts an account only when all three checks pass:

1. The `EXTCODEHASH` of the account is in `admittedSafeProxyCodehashes`. Each proxy of one Safe release has the same runtime code, so one entry covers one release.
2. The account answers `masterCopy()` (selector `0xa619486e`) with a singleton in `admittedSafeSingletons`. The call gets 30,000 gas.
3. The module guard slot of the Safe, `0xb104e0b93118902c651344349b610029d694cfdec91c589c91ebafbcd0289947`, holds zero. The adapter reads it with the Safe function `getStorageAt(slot, 1)` and 30,000 gas.

Check 1 fails or check 2 fails: `SafeNotAdmitted(account)`. Check 3 fails, or its read fails: `SafeHasModuleGuard(account)`. Both reverts come before the gas charge.

You can run the same checks before you enable the module:

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

const publicClient = createPublicClient({ chain: polygonAmoy, transport: http() });
const safeAdapter = "0x425FE0A554299D33589edc51387254175478Ee0e"; // polygon-amoy
const MODULE_GUARD_SLOT = "0xb104e0b93118902c651344349b610029d694cfdec91c589c91ebafbcd0289947";

const code = await publicClient.getCode({ address: safe });
const codehashAdmitted = await publicClient.readContract({
  address: safeAdapter,
  abi: ANAFI_SAFE_ADAPTER_ABI,
  functionName: "admittedSafeProxyCodehashes",
  args: [keccak256(code!)],
});
const singleton = await publicClient.readContract({
  address: safe,
  abi: parseAbi(["function masterCopy() view returns (address)"]),
  functionName: "masterCopy",
});
const singletonAdmitted = await publicClient.readContract({
  address: safeAdapter,
  abi: ANAFI_SAFE_ADAPTER_ABI,
  functionName: "admittedSafeSingletons",
  args: [singleton],
});
const guardWord = await publicClient.getStorageAt({ address: safe, slot: MODULE_GUARD_SLOT });
const noModuleGuard = BigInt(guardWord ?? "0x0") === 0n;
```

[Deployments](https://docs.ana.fi/contracts/deployments.md) lists the code hashes and singletons that each deployment admitted. The getters give the live sets.

## Functions for anyone

### redeemAsEngine

```solidity theme={null}
struct GasTerms {
    address token;                    // the gas token; address(0) is the native coin
    uint256 maxCharge;                // the most the Safe pays, in units of token; 0 charges nothing
    uint256 tokenUnitsPerNativeCoin;  // units of token that 10^18 wei cost; 0 for the native coin
    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
}

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 legs of an engine-signed payload as the Safe, and charges the Safe the gas of the whole call. Any address can submit it.

The payload is:

```solidity theme={null}
abi.encode(address avatar, bytes32[] modes, bytes[] callDatas)
```

| Field | Rule |
| - | - |
| `avatar` | The Safe that executes the legs and pays the gas. It must pass the admission checks above. |
| `modes[i]` | The ERC-7579 mode of leg `i`. It must be the single-call mode, `bytes32(0)`. Another value reverts the legs with `UnsupportedMode(bytes32 mode)`. |
| `callDatas[i]` | One packed execution: `abi.encodePacked(address target, uint256 value, bytes data)`. The first 20 bytes are the target, the next 32 bytes are the value, and the rest is the call data. |

The adapter calls `avatar.execTransactionFromModule(target, value, data, 0)` for each leg, in order. A native coin send has the recipient as `target`, the amount as `value`, and empty `data`. An ERC-20 send has the token as `target`, zero `value`, and `transfer(to, amount)` as `data`.

Returns:

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

### 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 module grant, so a Safe that disabled the adapter can still claim. The zero address as `token` is the native coin.

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)`. The payment gets 100,000 gas.

A Safe claims in a Safe transaction, because the Safe must be `msg.sender`. The SDK exports `readGasCredit` and `buildClaimGasCreditCalldata`.

`readGasCredit` takes `publicClient` as the viem `PublicClient` type of the viem version that the SDK pins (`2.55.10`). With another viem version in your project, TypeScript can refuse your client. Install `viem@2.55.10` in your project, or cast the client to the parameter type as below. The cast type-checks with both versions.

```ts theme={null}
import { buildClaimGasCreditCalldata, readGasCredit } from "@anafi-cc/anafi-sdk";

type GasCreditClient = Parameters<typeof readGasCredit>[0]["publicClient"];

const credit = await readGasCredit({
  publicClient: publicClient as unknown as GasCreditClient,
  adapter: safeAdapter,
  payee: safe,
  token,
});
const data = buildClaimGasCreditCalldata(token, recipient); // send from the Safe to safeAdapter
```

### receive

```solidity theme={null}
receive() external payable
```

Accepts the native coin. The adapter collects a native gas charge from the Safe through it.

## 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()`.

## Functions of the registry owner

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

| Function | Effect | Event |
| - | - | - |
| `setSafeProxyCodehashAdmitted(bytes32 codehash, bool admitted)` | Admits or withdraws a Safe proxy runtime code hash. | `SafeProxyCodehashAdmittedSet(codehash, admitted)` |
| `setSafeSingletonAdmitted(address singleton, bool admitted)` | Admits or withdraws a Safe singleton. | `SafeSingletonAdmittedSet(singleton, admitted)` |
| `setGasOverhead(address token, uint256 overhead)` | Sets the gas overhead of a gas token. The zero address is the native coin. A zero overhead stops charges in that token. | `GasOverheadSet(token, overhead)` |
| `upgradeToAndCall(address newImplementation, bytes memory data)` | Upgrades the proxy. Payable. | `Upgraded(newImplementation)` |

`initialize(address anafiRegistry_)` ran once at deployment. It reverts `RegistryNotUsable(address registry)` when the registry has no code or its `owner()` is zero, and `InvalidInitialization()` on a second call.

## 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. |
| `usedNonces(uint256 nonce)` | `bool` | Whether a redeem spent `nonce` on this adapter. |
| `admittedSafeProxyCodehashes(bytes32 codehash)` | `bool` | Whether the registry owner admitted the proxy code hash. |
| `admittedSafeSingletons(address singleton)` | `bool` | Whether the registry owner admitted the singleton. Read the code hash set first: only a real Safe proxy answers `masterCopy()` from its own code. |
| `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`. |
| `UPGRADE_INTERFACE_VERSION()` | `string` | `"5.0.0"`. |
| `proxiableUUID()` | `bytes32` | The ERC-1967 slot. Reverts through the proxy. |

| Constant | Value | Description |
| - | - | - |
| `ROUTE_TAG` | `keccak256("ANAFI_ADAPTER_REDEEM_WITH_GAS")` = `0x31747694805ea00e26185495e79555aa0fd8bc5ed92dee2440234ea76be46373` | The tag at the start of each redeem digest. |
| `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 module call that collects `maxCharge` from the Safe. |
| `PAYMENT_GAS` | `100000` | The gas of each payment: a charge, a refund or a claimed credit. |
| `ACCOUNT_CHECK_GAS` | `30000` | The gas of each read of the account check. |
| `MAX_LEGS_REVERT_DATA_BYTES` | `256` | The most revert bytes that `redeemAsEngine` returns. |

## 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 SafeProxyCodehashAdmittedSet(bytes32 indexed codehash, bool admitted);
event SafeSingletonAdmittedSet(address indexed singleton, bool admitted);

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

| 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, or a native refund went to a Safe that is no longer admitted. 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. |
| `SafeProxyCodehashAdmittedSet` | The registry owner changed the code hash set. |
| `SafeSingletonAdmittedSet` | The registry owner changed the singleton set. |

## Errors

| Error | Raised by | Cause | Nonce spent |
| - | - | - | - |
| `RedeemReentered()` | `redeemAsEngine` | A call entered `redeemAsEngine` inside a redeem that is not complete. | No |
| `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 |
| `SafeNotAdmitted(address account)` | `redeemAsEngine` | The code hash or the singleton of the account is not admitted. | No |
| `SafeHasModuleGuard(address account)` | `redeemAsEngine` | The Safe has a module guard, or the guard read failed. | No |
| `GasTokenNotSupported(address token)` | `redeemAsEngine` | `maxCharge` is above zero and the token has no gas overhead. | No |
| `GasChargeCollectionFailed()` | `redeemAsEngine` | The module call that collects `maxCharge` reverted, or the adapter balance did not grow by exactly `maxCharge`. A Safe that did not enable the module also gives this error when `maxCharge` is above zero. | No |
| `GasForLegsTooLow(uint256 gasLeft, uint256 gasNeeded)` | `redeemAsEngine` | The gas left is below `legsGasLimit * 64 / 63 + 300000`. | No |
| `UnsupportedMode(bytes32 mode)` | inner leg call | A mode is not the single-call mode. | Yes, legs fail |
| `AvatarExecutionFailed(uint256 legIndex)` | inner leg call | The Safe returned `false` for leg `legIndex`. | Yes, legs fail |
| `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 code or no owner. | 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()` | initializer and upgrade | OpenZeppelin guards. | Not a redeem |

A leg that the Safe refuses because the module is not enabled fails inside the Safe. `legsRevertData` then holds `Error("GS104")`. A payload that does not decode as `(address, bytes32[], bytes[])` reverts the whole call, so no nonce is spent. A leg shorter than 52 bytes, or a `modes` array shorter than `callDatas`, makes the inner call fail with a panic.

## Invariants

* The adapter never sends a delegatecall as the Safe.
* A nonce is spent at most once on this adapter. It is spent exactly when `redeemAsEngine` does not revert.
* Each redeem that does not revert emits exactly one of `EngineRedeemed` and `EngineRedeemFailed`, and then one `GasCharged`.
* The charge is never more than `maxCharge`. The Safe 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.
* Revocation does not cancel a signed redeem. If the Safe enables the module again, an unexpired redeem that was signed before can land. Only `validUntil` bounds it.

## Storage

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


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