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

# AnafiRegistry

> Reference of the registry that publishes the engine keys, records the heartbeat, lists the live adapters and holds the admin role.

After you read this page, you can read the engine keys and the adapter list from the chain, check a heartbeat, and decode each registry event and error.

`AnafiRegistry` is the root contract of each network. It runs behind an ERC-1967 proxy with UUPS upgrades. Use the proxy address from [Deployments](https://docs.ana.fi/contracts/deployments.md).

The registry does four things:

* It publishes the engine identity: the signer address `engineSigKey`, the encryption key `engineEncKey`, the `composeHash`, and a commitment to the attestation evidence.
* It records the signed heartbeat of the engine.
* It lists the delegation adapters that this deployment trusts.
* Its `owner()` is the admin and the upgrade authority of every Anafi proxy on the network.

## Functions for anyone

### attestHeartbeat

```solidity theme={null}
function attestHeartbeat(uint64 attestedBlock, uint64 attestedTick, bytes calldata engineSignature) external
```

Records a heartbeat that the engine key signed. Any address can submit it, because the signature is the authorization.

| Parameter | Type | Description |
| - | - | - |
| `attestedBlock` | `uint64` | The block number that the engine signs. It must be more than `lastHeartbeatBlock()` and not more than `block.number`. |
| `attestedTick` | `uint64` | A Unix time in seconds that the engine signs with the block. |
| `engineSignature` | `bytes` | A 65-byte ECDSA signature of the engine key over the raw digest below. |

The digest has no EIP-191 prefix and no EIP-712 domain:

```solidity theme={null}
bytes32 HEARTBEAT_DOMAIN = keccak256("ANAFI_HEARTBEAT_V1");
// = 0x105f735a105b76a7036617b0ac969848a03f7e39bbc2a54745492c2975e6de60

bytes32 digest = keccak256(abi.encode(HEARTBEAT_DOMAIN, block.chainid, address(registry), attestedBlock, attestedTick));
```

The checks run in this order:

1. `attestedBlock > block.number` reverts `HeartbeatAheadOfChain()`.
2. `attestedBlock <= lastHeartbeatBlock()` reverts `HeartbeatNotNewer()`. This check is the replay guard.
3. A malformed signature reverts with an OpenZeppelin `ECDSA` error. A signer other than `engineSigKey()` reverts `InvalidEngineSignature()`.

Effects: sets `lastHeartbeatBlock` and `lastHeartbeatTick`, and emits `HeartbeatAttested(attestedBlock, attestedTick)`.

`attestedTick` has no bound. The next accepted heartbeat replaces it.

## Functions of the registry owner

Each function in this section reverts `OwnableUnauthorizedAccount(address account)` when the caller is not `owner()`.

### setEngineIdentity

```solidity theme={null}
function setEngineIdentity(
    address sigKey,
    bytes32 encKey,
    bytes32 composeHash_,
    bytes calldata tlsCertDer,
    bytes calldata quote,
    bytes calldata eventLog
) external
```

Replaces the whole engine identity in one call: both keys, the compose hash and the attestation evidence.

| Parameter | Type | Description |
| - | - | - |
| `sigKey` | `address` | The new engine signer address. It must not be zero. |
| `encKey` | `bytes32` | The new X25519 public key of the engine, 32 raw bytes. It must not be zero. |
| `composeHash_` | `bytes32` | The new measurement of the engine application. |
| `tlsCertDer` | `bytes` | The TLS certificate of the engine, DER form. Empty for an unattested identity. |
| `quote` | `bytes` | The Intel TDX quote that binds the certificate and both keys. Empty for an unattested identity. |
| `eventLog` | `bytes` | The event log that goes with the quote. Empty for an unattested identity. |

Effects:

* Stores `sigKey`, `encKey` and `composeHash_`.
* Sets `engineEvidenceHash` to `keccak256(abi.encode(tlsCertDer, quote, eventLog))`. When all three are empty, it sets `bytes32(0)`.
* Adds 1 to `version`.
* Emits `EngineIdentitySet` with the three evidence blobs as event data.

Reverts: `ZeroEngineSigKey()`, `ZeroEngineEncKey()`, `OwnableUnauthorizedAccount(address)`.

The registry does not check the quote. A reader checks it off chain. See [Verification](https://docs.ana.fi/contracts/verification.md).

### addDelegationAdapter

```solidity theme={null}
function addDelegationAdapter(address adapter) external
```

Appends `adapter` to the list and emits `DelegationAdapterAdded(adapter)`.

| Condition | Revert |
| - | - |
| The list holds `adapter` already | `DelegationAdapterAlreadyListed(address adapter)` |
| `adapter` has no code | `DelegationAdapterNotBoundToThisRegistry(address adapter)` |
| `adapter.anafiRegistry()` is not this registry | `DelegationAdapterNotBoundToThisRegistry(address adapter)` |
| `adapter.anafiRegistry()` reverts or returns bad data | The call reverts |

### removeDelegationAdapter

```solidity theme={null}
function removeDelegationAdapter(address adapter) external
```

Removes `adapter` from the list and emits `DelegationAdapterRemoved(adapter)`. Each later entry moves down one place, so the other entries keep their order. Reverts `DelegationAdapterNotListed(address adapter)` when the list does not hold `adapter`.

After this call, the removed adapter refuses each redeem with `AdapterNotAllowed()`. The call does not touch the grant of any account.

### Ownership and upgrade

These functions come from OpenZeppelin `Ownable2StepUpgradeable` and `UUPSUpgradeable` version 5.

```solidity theme={null}
function transferOwnership(address newOwner) public;            // owner only
function acceptOwnership() public;                               // the proposed owner only
function renounceOwnership() public pure;                        // always reverts
function upgradeToAndCall(address newImplementation, bytes memory data) public payable; // owner only
```

| Function | Effect | Reverts |
| - | - | - |
| `transferOwnership` | Sets `pendingOwner()` to `newOwner` and emits `OwnershipTransferStarted`. The owner does not change yet. A zero `newOwner` clears the proposal. | `OwnableUnauthorizedAccount` |
| `acceptOwnership` | Makes the caller the owner, clears `pendingOwner()`, and emits `OwnershipTransferred`. | `OwnableUnauthorizedAccount` when the caller is not `pendingOwner()` |
| `renounceOwnership` | None. | Always `OwnershipNotRenounceable()` |
| `upgradeToAndCall` | Points the proxy to `newImplementation`, emits `Upgraded`, and calls `data` on it when `data` is not empty. | `OwnableUnauthorizedAccount`, `UUPSUnauthorizedCallContext`, `UUPSUnsupportedProxiableUUID`, `ERC1967InvalidImplementation`, `ERC1967NonPayable` |

## Initialization

```solidity theme={null}
function initialize(address initialEngineSigKey, bytes32 initialEngineEncKey, bytes32 composeHash_, address initialOwner)
    external
```

The deployment calls `initialize` once, in the transaction that creates the proxy. A second call reverts `InvalidInitialization()`. The implementation contract locks its own initializer in its constructor.

It reverts `ZeroEngineSigKey()` or `ZeroEngineEncKey()` for a zero key, and `OwnableInvalidOwner(address(0))` for a zero owner. After it, `version()` is 0 and the adapter list is empty.

## Views

| Function | Returns | Description |
| - | - | - |
| `engineSigKey()` | `address` | The engine signer. Each adapter redeem, each `commitDsl` attestation and each heartbeat must recover to it. |
| `engineEncKey()` | `bytes32` | The X25519 public key of the engine. The SDK seals rule documents to it. No contract uses it. |
| `composeHash()` | `bytes32` | The measurement of the engine application that the published keys belong to. |
| `engineEvidenceHash()` | `bytes32` | `keccak256(abi.encode(tlsCertDer, quote, eventLog))` of the last `EngineIdentitySet`, or zero for an identity with no evidence. |
| `version()` | `uint64` | The number of identity changes since deployment. |
| `lastHeartbeatBlock()` | `uint64` | The block of the last accepted heartbeat, or 0 before the first. |
| `lastHeartbeatTick()` | `uint64` | The Unix time of the last accepted heartbeat, or 0 before the first. |
| `delegationAdapters()` | `address[]` | The listed adapters, in list order. |
| `isDelegationAdapter(address adapter)` | `bool` | Whether the list holds `adapter`. |
| `owner()` | `address` | The admin of the contract set. |
| `pendingOwner()` | `address` | The proposed new owner, or zero. |
| `UPGRADE_INTERFACE_VERSION()` | `string` | `"5.0.0"`. |
| `proxiableUUID()` | `bytes32` | The ERC-1967 slot. Reverts `UUPSUnauthorizedCallContext()` through the proxy, so call it on an implementation. |

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

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

const [engineSigKey, engineEncKey, adapters] = await Promise.all([
  publicClient.readContract({ address: registry, abi: ANAFI_REGISTRY_ABI, functionName: "engineSigKey" }),
  publicClient.readContract({ address: registry, abi: ANAFI_REGISTRY_ABI, functionName: "engineEncKey" }),
  publicClient.readContract({ address: registry, abi: ANAFI_REGISTRY_ABI, functionName: "delegationAdapters" }),
]);
```

`ANAFI_REGISTRY_ABI` holds only `engineEncKey`, `engineSigKey` and `delegationAdapters`. For the other views, use `parseAbi` from viem with the signatures in the table.

## Events

```solidity theme={null}
event EngineIdentitySet(
    address indexed newSigKey,
    bytes32 newEncKey,
    bytes32 newCompose,
    uint64 indexed newVersion,
    bytes tlsCertDer,
    bytes quote,
    bytes eventLog
);
event HeartbeatAttested(uint64 indexed attestedBlock, uint64 attestedTick);
event DelegationAdapterAdded(address indexed adapter);
event DelegationAdapterRemoved(address indexed adapter);

// OpenZeppelin
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event Upgraded(address indexed implementation);
event Initialized(uint64 version);
```

| Event | Emitted by | Fields |
| - | - | - |
| `EngineIdentitySet` | `setEngineIdentity` | The new signer, the new encryption key, the new compose hash, the version after the change, and the three evidence blobs. The blobs are empty for an unattested identity. |
| `HeartbeatAttested` | `attestHeartbeat` | The attested block and the attested Unix time. The block time of the transaction shows when the heartbeat landed. |
| `DelegationAdapterAdded` | `addDelegationAdapter` | The adapter that the list now holds. |
| `DelegationAdapterRemoved` | `removeDelegationAdapter` | The adapter that the list no longer holds. |
| `OwnershipTransferStarted` | `transferOwnership` | The current owner and the proposed owner. |
| `OwnershipTransferred` | `initialize`, `acceptOwnership` | The old owner and the new owner. |
| `Upgraded` | `upgradeToAndCall` | The new implementation. |
| `Initialized` | `initialize` | The initializer version, 1. |

## Errors

| Error | Raised by | Cause |
| - | - | - |
| `InvalidEngineSignature()` | `attestHeartbeat` | The signature recovers to an address other than `engineSigKey()`. |
| `ZeroEngineSigKey()` | `initialize`, `setEngineIdentity` | The signer key is the zero address. |
| `ZeroEngineEncKey()` | `initialize`, `setEngineIdentity` | The encryption key is zero. |
| `OwnershipNotRenounceable()` | `renounceOwnership` | Always. |
| `HeartbeatNotNewer()` | `attestHeartbeat` | `attestedBlock` is not more than `lastHeartbeatBlock()`. |
| `HeartbeatAheadOfChain()` | `attestHeartbeat` | `attestedBlock` is more than `block.number`. |
| `DelegationAdapterAlreadyListed(address adapter)` | `addDelegationAdapter` | The list holds the adapter already. |
| `DelegationAdapterNotListed(address adapter)` | `removeDelegationAdapter` | The list does not hold the adapter. |
| `DelegationAdapterNotBoundToThisRegistry(address adapter)` | `addDelegationAdapter` | The address has no code, or its `anafiRegistry()` is another address. |
| `OwnableUnauthorizedAccount(address account)` | owner functions, `acceptOwnership` | The caller has no right to call the function. |
| `OwnableInvalidOwner(address owner)` | `initialize` | The initial owner is zero. |
| `InvalidInitialization()` | `initialize` | The proxy is already initialized. |
| `NotInitializing()` | none in practice | OpenZeppelin guard. |
| `UUPSUnauthorizedCallContext()` | `upgradeToAndCall`, `proxiableUUID` | The call context is wrong for a UUPS call. |
| `UUPSUnsupportedProxiableUUID(bytes32 slot)` | `upgradeToAndCall` | The new implementation returns another slot. |
| `ERC1967InvalidImplementation(address implementation)` | `upgradeToAndCall` | The new implementation has no code. |
| `ERC1967NonPayable()` | `upgradeToAndCall` | Value was sent with an empty `data`. |
| `ECDSAInvalidSignature()`, `ECDSAInvalidSignatureLength(uint256 length)`, `ECDSAInvalidSignatureS(bytes32 s)` | `attestHeartbeat` | The signature is malformed. |

## Invariants

* `owner()` is never the zero address after initialization.
* `version()` goes up by exactly 1 on each `setEngineIdentity`, and never goes down.
* `lastHeartbeatBlock()` only goes up, and is never more than the block number of the transaction that set it.
* `engineEvidenceHash()` is zero exactly when the last identity change had three empty blobs, or when no change happened after initialization.
* `delegationAdapters()` holds no duplicate. Each entry has code, and its `anafiRegistry()` returned this registry when the owner added it.
* `isDelegationAdapter(a)` is true exactly when `delegationAdapters()` holds `a`.

## Storage

All mutable state is in one ERC-7201 namespace, `anafi.storage.AnafiRegistry`, at slot `0xb5c5947aaa61057d86d25588a7fdf9a60e4e6b2511d9c0ad72aa5d6069a5a400`. Use the view functions to read it.


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