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

# Reads

> Read the engine key, the predicted Safe, the adapter and kind of an account, the committed document, and pin reads to a block with the SDK.

After you read this page, you can read every chain fact that a flow needs, pin a read to the block of an earlier write, and know which reads can fail.

## The rule for a failed read

A read that fails throws. It never answers `false`, `null` or `0` in place of an answer. For example, `isWalletDeployed` rejects when the node fails, and it does not answer `false`. Catch the error and retry, or show that the state is unknown.

Two client methods are exceptions. `readEngineSyncedHeight` answers `null` on any failure. `readWalletAtomicBatchSupport` answers `false` on any failure. Each entry says so.

## Engine and account reads

### `readEngineEncKey`

```ts theme={null}
readEngineEncKey(): Promise<Uint8Array>;
```

Reads `AnafiRegistry.engineEncKey()` at the latest block and returns the 32 raw bytes of the X25519 public key of the engine. The SDK seals each rule document and each confidential request to this key.

| Item | Value |
| - | - |
| Prompts | none |
| Chain calls | `AnafiRegistry.engineEncKey()` |
| Throws | `Error` when the answer is not 32 bytes of hex. A failed RPC call rejects. |

```ts theme={null}
const key = await anafi.readEngineEncKey();
console.log(key.length); // 32
```

### `predictSafe`

```ts theme={null}
predictSafe(eoa: Hex): Promise<Hex>;
```

Returns the address of the deterministic 1-of-1 Safe of the owner `eoa`. The address follows from the configured Safe framework addresses and the live creation code of the proxy factory. The Safe does not need to exist. `provisionPredictedSafe` deploys the Safe at this address.

| Item | Value |
| - | - |
| Parameters | `eoa`: the owner address |
| Returns | the predicted Safe address (checksummed) |
| Chain calls | `SafeProxyFactory.proxyCreationCode()` |
| Throws | `Error("owner must be an address, got ...")` for an invalid `eoa`. `Error` when `addresses.safe` is absent. `Error` when the factory returns empty creation code. |

The prediction uses `predictSafeAddress` from the [low-level helpers](https://docs.ana.fi/sdk/low-level.md#address-prediction): owners `[eoa]`, threshold 1, a `setup` that moves the Safe to `SafeL2`, and the salt nonce `keccak256(eoa)`.

```ts theme={null}
const safe = await anafi.predictSafe("0x1111111111111111111111111111111111111111");
```

### `isWalletDeployed`

```ts theme={null}
isWalletDeployed(aa: Hex, options?: BlockReadOptions): Promise<boolean>;
```

Answers `true` when the address has code. Code `0x`, `null` and `undefined` count as no code. With `options`, the read is pinned to `options.block` under the [retry rule](#block-pinned-reads).

| Item | Value |
| - | - |
| Chain calls | `eth_getCode` |
| Throws | a failed RPC call rejects |

### `readLiveDelegationAdapters`

```ts theme={null}
readLiveDelegationAdapters(options?: BlockReadOptions): Promise<DelegationAdapters>;
```

Reads `AnafiRegistry.delegationAdapters()` and returns each row of your `delegationAdapters` config that the registry lists. A row that the registry does not list is absent from the result. An adapter that the registry lists but your config does not name is not in the result either.

```ts theme={null}
const live = await anafi.readLiveDelegationAdapters();
if (live.erc20_allow === undefined) console.log("the ERC20Allow leg is not live on this network");
```

### `readAccountAdapter`

```ts theme={null}
readAccountAdapter(aa: Hex, options?: BlockReadOptions): Promise<Hex | null>;
```

Returns the live configured adapter that can serve the account, or `null`. Every read is at one block: `options.block`, or the uncached tip.

The client decides in this order:

1. It reads the live adapters (`readLiveDelegationAdapters`).
2. If the Safe row is live and the account is a Safe that the Safe adapter admits, it returns the Safe adapter. "Admits" means that `admittedSafeProxyCodehashes(keccak256(code))` is `true` and `admittedSafeSingletons(masterCopy())` is `true` on the adapter.
3. Else, if the `erc20_allow` row is live and the account has no code or an EIP-7702 pointer, it returns the ERC20Allow adapter.
4. Else it returns `null`.

The answer is a structural fact. It does not say that the account granted a permission or committed a document. A plain address with no code always gets the ERC20Allow adapter when that leg is live. To know the kind, compare the answer with `delegationAdapters.safe` and `delegationAdapters.erc20_allow`, or use `delegationAdapterOfKind`.

```ts theme={null}
const adapter = await anafi.readAccountAdapter(account);
const kind =
  adapter === null ? null
  : adapter.toLowerCase() === config.delegationAdapters.safe?.toLowerCase() ? "safe_module"
  : "erc20_allow";
```

### `readDslCommitment`

```ts theme={null}
readDslCommitment(aa: Hex): Promise<OnChainDsl | null>;
```

Reads `AnafiDslRegistry.commitments(aa)` at the latest block. Returns `null` when the version is 0 (nothing committed). Pass the answer as the `parent` of your next stage.

### `readDslCommitmentAtBlock`

```ts theme={null}
readDslCommitmentAtBlock(aa: Hex, at: bigint | BlockReadOptions): Promise<OnChainDsl | null>;
```

The same read at a block. With a bare `bigint`, it reads once at that block. With `BlockReadOptions`, it reads under the retry rule. Use it after a commit, with the `confirmedBlock` of the commit, so that a node behind that block cannot answer with the old document.

```ts theme={null}
const result = await anafi.commitStagedDsl({ staged });
if (result.confirmedBlock !== null) {
  const dsl = await anafi.readDslCommitmentAtBlock(staged.safe, {
    block: result.confirmedBlock,
    deadline: Date.now() + 20_000,
  });
  console.log(dsl?.hash === staged.commitment);
}
```

### `readEngineSyncedHeight`

```ts theme={null}
readEngineSyncedHeight(): Promise<bigint | null>;
```

Returns the last block that the engine has processed, or `null`. It never throws.

| Item | Value |
| - | - |
| Parameters | none |
| Returns | the block number as a `bigint`, or `null` |
| Prompts | none |
| What it calls | one unauthenticated GET to the Anafi API's status endpoint |
| Timeout | 10 seconds |
| Throws | never |

It returns `null` in each of these cases:

* No answer arrives, or the request times out.
* The answer has a status that is not 2xx.
* The body is not JSON, or it has no height.
* The height is not a whole number of 0 or more.
* The engine reports no height yet.

Use it to wait until the engine has processed a block before a read-back. After a commit, the engine reads the commit only when it has processed the block of the commit. Poll until the height is at or above the `confirmedBlock` of the commit, and then call `recover`. Treat `null` as "unknown", not as "behind".

```ts theme={null}
async function waitForEngine(block: bigint, timeoutMs = 60_000): Promise<boolean> {
  const end = Date.now() + timeoutMs;
  while (Date.now() < end) {
    const height = await anafi.readEngineSyncedHeight();
    if (height !== null && height >= block) return true;
    await new Promise((resolve) => setTimeout(resolve, 2_000));
  }
  return false;
}

const result = await anafi.commitStagedDsl({ staged });
if (result.confirmedBlock !== null && (await waitForEngine(result.confirmedBlock))) {
  const state = await anafi.recover({ aa: staged.safe, eoa: owner });
}
```

## Account discovery

### `discoverAccounts`

```ts theme={null}
discoverAccounts(eoa: Hex): Promise<DiscoverAccountsResponse>;
```

Calls `GET /api/accounts/discover?eoa=<eoa>` and returns the accounts that this owner key might use. Discovery is advisory. A suggestion authorizes nothing. Each action on a suggested account needs the signature of that account.

| Item | Value |
| - | - |
| HTTP route | `GET /api/accounts/discover?eoa=` |
| Timeout | 15 seconds |
| Throws | `Error("GET <url> failed: <status> <body>")` on a status that is not 2xx. A network failure or a timeout rejects with the `fetch` error. |

The client reads every row. It drops a row with an unknown `kind`, an unknown `source`, a bad address, or a field of the wrong type. It reads at most 64 rows. When it drops or cuts a row, it sets `completeness` to `UNRECOGNIZED_COMPLETENESS`, whatever the API said.

```ts theme={null}
interface DiscoverAccountsResponse {
  suggestions: AccountSuggestion[];
  completeness: DiscoveryCompletenessRead;
}

interface AccountSuggestion {
  network: string;          // the network token, for example "polygon"
  address: Hex;
  kind: AccountKind;        // "safe_module" | "erc20_allow"
  source: AccountSuggestionSource;
  deployed: boolean;        // whether code exists at the address now
}

type AccountSuggestionSource = "predicted_safe" | "safe_transaction_service" | "connected_address";
type DiscoveryCompleteness = "every_source_consulted" | "stopped_at_the_candidate_cap" | "stopped_at_the_deadline";
type DiscoveryCompletenessRead = DiscoveryCompleteness | typeof UNRECOGNIZED_COMPLETENESS;
const UNRECOGNIZED_COMPLETENESS = "unrecognized_completeness";
```

| `source` | Meaning |
| - | - |
| `predicted_safe` | The predicted 1-of-1 Safe of the owner. It can have no code yet (`deployed: false`). |
| `safe_transaction_service` | A Safe that the Safe Transaction Service lists for this owner. |
| `connected_address` | The owner address itself, as an `erc20_allow` account. |

| `completeness` | Meaning | What to show |
| - | - | - |
| `every_source_consulted` | The list is complete. | The list. |
| `stopped_at_the_candidate_cap` | The API stopped at its limit of candidates. | The list, and a note that more accounts can exist. |
| `stopped_at_the_deadline` | The API stopped at its time limit. | The list, and a note that more accounts can exist. Offer a retry. |
| `unrecognized_completeness` | The SDK cannot tell that the list is complete: an unknown value, an absent field, a dropped row, or a cut list. | The list, and a note that it is not complete. |

Never tell the user that an account does not exist when `completeness` is not `every_source_consulted`.

The package also exports the function that the method calls:

```ts theme={null}
function discoverAccounts(backendUrl: string, eoa: Hex, fetchImpl: typeof fetch): Promise<DiscoverAccountsResponse>;
```

## Block-pinned reads

A load-balanced RPC can send two calls to two nodes. A read right after a write can reach a node that has not seen the write. A read pinned at the block of the write cannot take the old state as the answer. A node below the block answers with a JSON-RPC error, and the SDK asks again until a deadline.

### `BlockReadOptions`

```ts theme={null}
interface BlockReadOptions {
  block: bigint;          // every attempt reads at this block
  deadline: number;       // Date.now() milliseconds; no new attempt starts after it
  signal?: AbortSignal;   // stops the retries when it aborts
  targetHasCode?: boolean;
}
```

| Field | Meaning |
| - | - |
| `block` | The block of each attempt. |
| `deadline` | The wall-clock time in `Date.now()` milliseconds. No attempt starts at or after it. |
| `signal` | Aborts the retries. |
| `targetHasCode` | Set it when you know that the target has code at or below `block`, for example a Safe that a write deployed. Only then does an empty answer count as a node behind the block. |

### The retry rule

A read with `BlockReadOptions` follows this rule (`readAtBlock`):

1. The SDK reads at `block`.
2. If the answer is a JSON-RPC error with a numeric code, the node is behind. The SDK waits and asks again.
3. If the answer is empty (a viem zero-data error, or an empty value) and `targetHasCode` is `true`, the node is behind. The SDK waits and asks again.
4. A revert that carries data, an HTTP error, a malformed answer, and any other failure end the read at once with that error.
5. The first wait is 1 second. Each later wait doubles, up to 3 seconds.
6. No attempt starts at or after `deadline` or after `signal` aborts. Then the read throws the last failure, or an `Error("... passed its deadline")`, or the abort reason.

Without `BlockReadOptions`, a read asks once: at the latest block, or at the bare `bigint` block that you give.

The client uses a deadline of 20 seconds for its own reads after its own writes.

### `resolveReadBlock`

```ts theme={null}
// client method
resolveReadBlock(floor: bigint | null, bounds?: Pick<BlockReadOptions, "deadline" | "signal">): Promise<bigint>;

// function
function resolveReadBlock(
  publicClient: Pick<AdapterPublicClient, "getBlockNumber">,
  floor: bigint | null,
  bounds?: Pick<BlockReadOptions, "deadline" | "signal">,
): Promise<bigint>;
```

Chooses the block for a read after a write at `floor`. It reads the tip once, uncached. It returns `floor` when the node that answered is below `floor`, and the tip in all other cases. It does not loop: the reads pinned at `floor` do the wait. With `bounds`, the tip read stops at the deadline or at the abort, and the method throws.

```ts theme={null}
const deadline = Date.now() + 20_000;
const block = await anafi.resolveReadBlock(result.confirmedBlock, { deadline });
const enabled = await anafi.readSafeModuleEnabled(safe, adapter, { block, deadline, targetHasCode: true });
```

### `readAtBlock`

```ts theme={null}
function readAtBlock<Answer>(
  at: bigint | BlockReadOptions | undefined,
  read: (blockNumber: bigint | undefined) => Promise<Answer>,
  isEmptyAnswer?: (answer: Answer) => boolean,
): Promise<Answer>;
```

Runs your `read` under the retry rule. `isEmptyAnswer` tells which answers are empty; they count as "behind" only when `targetHasCode` is `true`.

```ts theme={null}
const code = await readAtBlock(
  { block, deadline: Date.now() + 20_000, targetHasCode: true },
  (blockNumber) => publicClient.getCode({ address: safe, blockNumber }),
  isEmptyCode,
);
```

### `settleWithinBounds`

```ts theme={null}
type SettledWithinBounds<Answer> = { inTime: true; value: Answer } | { inTime: false };

function settleWithinBounds<Answer>(
  work: Promise<Answer>,
  bounds: Pick<BlockReadOptions, "deadline" | "signal">,
): Promise<SettledWithinBounds<Answer>>;
```

Answers `{ inTime: true, value }` when `work` resolves before the deadline and before the abort. Answers `{ inTime: false }` as soon as the deadline or the abort comes first. A rejection before them rejects. The SDK ignores what `work` does later.

## Adapter and account classification helpers

These functions take a public client and do what the client methods do. Use them when you have no client.

### `delegationAdapterOfKind`

```ts theme={null}
function delegationAdapterOfKind(adapters: DelegationAdapters, kind: AccountKind): Hex | undefined;
```

Returns `adapters.safe` for `safe_module` and `adapters.erc20_allow` for `erc20_allow`.

### `isEmptyCode` and `isEip7702DelegationCode`

```ts theme={null}
function isEmptyCode(code: Hex | null | undefined): code is "0x" | null | undefined;
function isEip7702DelegationCode(code: Hex | null | undefined): boolean;
```

`isEmptyCode` answers `true` for `0x`, `null` and `undefined`. `isEip7702DelegationCode` answers `true` only for code of exactly 23 bytes that starts with `0xef0100`: an EIP-7702 delegation pointer.

### `Erc20AllowAccountClass` and `isServedErc20AllowAccountClass`

```ts theme={null}
type Erc20AllowAccountClass = "no_code" | "eip7702_pointer" | "contract_code" | "leg_not_live";
function isServedErc20AllowAccountClass(accountClass: Erc20AllowAccountClass): boolean;
```

| Class | Meaning | Served |
| - | - | - |
| `no_code` | The address has no code: a plain key. | yes |
| `eip7702_pointer` | The address has an EIP-7702 delegation pointer. | yes |
| `contract_code` | The address has other contract code, for example a Safe. | no |
| `leg_not_live` | Your config has no `erc20_allow` row, or the registry does not list it. | no |

### `readLiveConfiguredAdapters`

```ts theme={null}
function readLiveConfiguredAdapters(
  publicClient: AdapterPublicClient,
  registry: Hex,
  configured: DelegationAdapters,
  at?: bigint | BlockReadOptions,
): Promise<DelegationAdapters>;
```

The function behind `readLiveDelegationAdapters`.

### `classifyErc20AllowAccount` (function)

```ts theme={null}
function classifyErc20AllowAccount(params: {
  publicClient: AdapterPublicClient;
  registry: Hex;
  configured: DelegationAdapters;
  account: Hex;
  at: bigint | BlockReadOptions;
}): Promise<Erc20AllowAccountClass>;
```

Answers `leg_not_live` with no read when `configured.erc20_allow` is absent, and after the registry read when the registry does not list it. Else it reads the code of `account` at `at` and classifies it. An empty code is a valid answer here, so the code read never retries on an empty answer. The client method of the same name is on [ERC20Allow](https://docs.ana.fi/sdk/erc20-allow.md#classifyerc20allowaccount).

### `accountMatchesSafeAdapter`

```ts theme={null}
function accountMatchesSafeAdapter(
  publicClient: AdapterPublicClient,
  account: Hex,
  adapter: Hex,
  at: bigint | BlockReadOptions,
): Promise<boolean>;
```

Answers `true` when the account is a Safe that `adapter` admits: its runtime code hash is in `admittedSafeProxyCodehashes`, and its `masterCopy()` is in `admittedSafeSingletons`. Empty code answers `false`, unless `at` sets `targetHasCode`; then the empty code counts as a node behind the block. See [the Safe adapter](https://docs.ana.fi/contracts/safe-adapter.md).

### `readClassifiedAccountAdapter`

```ts theme={null}
function readClassifiedAccountAdapter(params: {
  publicClient: AdapterPublicClient;
  registry: Hex;
  configured: DelegationAdapters;
  account: Hex;
  options?: BlockReadOptions;
}): Promise<Hex | null>;
```

The function behind `readAccountAdapter`, with the same order of checks.


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