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

# Confidential channel

> Seal rule documents and requests to the engine key, open the sealed replies, read back the active rule document with recover, and render the sign-in messages.

After you read this page, you can seal data that only the engine can read, open a reply that only you can read, read back the committed rule document of an account, and check that the engine signed the reply.

The engine is a black box here. The SDK seals each request to the public key that `AnafiRegistry.engineEncKey()` publishes on chain. The Anafi API carries the sealed bytes and cannot read them. See [security](https://docs.ana.fi/concepts/security.md) and [sealed requests](https://docs.ana.fi/api-reference/sealed-requests.md).

## Cipher suite

```ts theme={null}
const suite: CipherSuite; // from @hpke/core
```

HPKE (RFC 9180) in base mode with:

| Part | Value |
| - | - |
| KEM | DHKEM(X25519, HKDF-SHA256) |
| KDF | HKDF-SHA256 |
| AEAD | ChaCha20-Poly1305 |

The engine uses the same suite. A change of any part makes every envelope unreadable.

## One-way seal

### `seal`

```ts theme={null}
function seal(enginePubkey: Uint8Array, info: Uint8Array, payload: Uint8Array): Promise<SealedEnvelope>;

interface SealedEnvelope {
  kem_pk: number[]; // the ephemeral X25519 public key of the sender, as byte integers
  ct: number[];     // the AEAD ciphertext and tag, as byte integers
}
```

Seals `payload` to the engine key under `info`. Each call uses a new ephemeral key, so two seals of one payload differ. `enginePubkey` must be 32 bytes, else it throws `Error("enginePubkey must be 32 bytes, got N")`.

Both fields are JSON arrays of numbers, not hex strings. The key name is `kem_pk` in snake case.

### `dslSealInfo`

```ts theme={null}
function dslSealInfo(network: Network, aa: Hex): Uint8Array;
```

The HPKE `info` of a rule document: the UTF-8 text `anafi/dsl-seal/<network>/`, then the 20 raw bytes of the account address. The engine derives the same `info` from the account in the request path. So a document sealed for one account and network does not open for another account or network. It throws for an unknown network or an invalid address.

```ts theme={null}
// "anafi/dsl-seal/polygon-amoy/" followed by the 20 bytes of the account
dslSealInfo("polygon-amoy", "0x2222222222222222222222222222222222222222");
```

## Request and response channel

A seal alone gives the engine no private way to answer. The channel keeps the HPKE context of the request and exports a 32-byte response key from it. The engine derives the same key and seals its reply with it. Only the caller that sealed the request can open the reply.

### `sealRequest`

```ts theme={null}
function sealRequest(
  enginePubkey: Uint8Array,
  info: Uint8Array,
  payload: Uint8Array,
): Promise<{ sealed: SealedEnvelope; secret: ResponseSecret }>;

interface ResponseSecret {
  responseKey: ArrayBuffer;
}
```

Seals the request as `seal` does, and keeps the response key, exported with the context `anafi/confidential-call/resp/v1`. The envelope has the same wire form as a `seal` envelope. Keep `secret` in memory only, and only until you open the reply.

### `openResponse`

```ts theme={null}
function openResponse(secret: ResponseSecret, response: SealedResponse): Promise<Uint8Array>;

interface SealedResponse {
  nonce: number[]; // the random 12-byte AEAD nonce
  ct: number[];    // the ciphertext and tag
}
```

Opens a sealed reply with ChaCha20-Poly1305, the exported key, and an empty additional data. A reply for another request fails to open and rejects.

### Request tags

| Request | `info` | Route |
| - | - | - |
| Stage of a rule document | `dslSealInfo(network, aa)` | `POST /api/wallets/:aa/dsl/commit/stage` |
| Read-back | `CONFIDENTIAL_CALL_REQUEST_INFO` = UTF-8 `anafi/confidential-call/req/v1` | `POST /api/wallets/:aa/recover` |
| Notification code request | `notificationEmailSealInfo("request_code", network, aa)` | `POST /api/wallets/:aa/notification_email/request_code` |
| Notification code check | `notificationEmailSealInfo("verify_code", network, aa)` | `POST /api/wallets/:aa/notification_email/verify_code` |

Each route takes the body `{ "sealed": SealedEnvelope }`. A sealed reply has the form `SealedResponse`.

```ts theme={null}
import { CONFIDENTIAL_CALL_REQUEST_INFO, openResponse, sealRequest } from "@anafi-cc/anafi-sdk";

const key = await anafi.readEngineEncKey();
const { sealed, secret } = await sealRequest(key, CONFIDENTIAL_CALL_REQUEST_INFO, new TextEncoder().encode(json));
// POST { sealed } to the route, read the JSON reply as a SealedResponse, then:
const plaintext = await openResponse(secret, reply);
```

## `recover`

```ts theme={null}
recover(params: { aa: Hex; eoa: Hex }): Promise<RecoveredUserState>;
```

Reads back the state of an account from the engine: the committed rule document in plain text, the status of the account, and the verified notification inbox. The chain holds only the salted commitment, so this is the only way to read the text of a committed document.

| Parameter | Meaning |
| - | - |
| `aa` | The account. |
| `eoa` | The owner. The owner signs the sign-in. |

### Steps

1. Make a 16-byte random nonce, as 32 hex characters with no `0x`.
2. Render the sign-in with `renderSiweMessage`: the domain `siweDomain` (or `window.location.host`), the address `eoa`, the statement `Sign in to Anafi to recover your wallet state.`, the URI `https://<domain>`, the `chainId`, the nonce and `Issued At`. No expiry line.
3. **Prompt:** `walletClient.signMessage({ account: eoa, message })`.
4. Read `engineEncKey()` and seal `{ "aa", "siwe_message", "signature" }` with `CONFIDENTIAL_CALL_REQUEST_INFO`.
5. `POST /api/wallets/:aa/recover` with `{ sealed }`.
6. Open the reply, and parse it as `RecoverResponsePayload`.
7. Read `AnafiRegistry.engineSigKey()`. Check that `engine_sig` recovers to that address over `recoverResponseDigest(nonce, state)`. Else throw.
8. Check the `tenant` field (`assertRecoveredTenantValid`). Else throw.
9. Return `state`.

The sign-in message:

```text theme={null}
app.ana.fi wants you to sign in with your Ethereum account:
0x1111111111111111111111111111111111111111

Sign in to Anafi to recover your wallet state.

URI: https://app.ana.fi
Version: 1
Chain ID: 80002
Nonce: 3f9c0a7d5e2b4c1a8f6e0d9b7a5c3e1f
Issued At: 2026-12-03T10:00:00.000Z
```

> [!WARNING]
>
> The Anafi API accepts this sign-in only when the message names the domain of the Anafi dapp, `app.ana.fi`. It refuses a sign-in for another domain with status `422`. An integration on another domain cannot complete `recover` today.

Throws: `BackendRequestError` for a failed request (for example `422` for a refused sign-in), an `Error` for a reply that does not open, a bad signature, or a bad `tenant`, and the error of the wallet when the owner rejects the prompt.

### `RecoveredUserState`

```ts theme={null}
interface RecoveredUserState {
  dsl: RecoveredDsl | null;
  grant_hash?: string | null;
  grant_json?: unknown;
  tenant?: TenantStatus;
  verified_notification_email?: string | null;
}

interface RecoveredDsl {
  status: RecoveredDslStatus; // "active" | "retired"
  yaml: string;
  version: number | null;
  commitment: string | null;
}

interface TenantStatus {
  state: TenantLifecycle;        // "none" | "active" | "parked"
  adapter: string | null;
  since_block: number | null;
  reason: ParkedReason | null;
  parked_token?: string;
}
```

The field names are in snake case, as the engine writes them.

| Field | Meaning |
| - | - |
| `dsl` | The document of the account, or `null` when the engine has no document to return. A first commit that the engine did not admit can also give `null`. |
| `dsl.status` | `active`: the engine runs this document. A document with no rules is also `active`. `retired`: no document runs. |
| `dsl.yaml` | The plain text of the document. |
| `dsl.version` | The registry version of this document, or `null`. Do not match a document to the chain by the version. |
| `dsl.commitment` | The commitment of the document. Compare it with `readDslCommitment(aa).hash` before you trust the text as the live document. |
| `grant_hash`, `grant_json` | A pair that only some engines send, always together. For a Safe, `grant_hash` is `null`: the grant of a Safe is its module list. `grant_json` is opaque. |
| `tenant` | Where the account stands with the engine. Absent means that the engine said nothing about it. It never means `none`. |
| `verified_notification_email` | The verified inbox of the account in canonical form, or `null` when none is verified. Absent means that the engine said nothing about it. |

### `TenantLifecycle`

| `state` | Meaning | `adapter`, `since_block` | `reason` |
| - | - | - | - |
| `none` | No commit has admitted the account. | `null` | `null` |
| `active` | The engine can serve the permission through the adapter of the last admitted commit. It says nothing about whether a rule fires. | set; `since_block` is the block of the last admitted commit | `null` |
| `parked` | The engine stopped its service of the account. A new admitted commit resumes it. | set; `since_block` is the block of the stop | set |

### `ParkedReason`

| Value | Kind | Meaning | What to do |
| - | - | - | - |
| `commit_refused` | any | A later commit failed the checks of the engine at its block. | Stage and commit a valid document. |
| `adapter_removed` | any | The registry no longer lists the adapter that the commit named. | Commit again through the live adapter. |
| `safe_module_disabled` | `safe_module` | The Safe disabled the adapter. | Enable the adapter and commit, or leave it revoked. |
| `safe_reported_disable` | `safe_module` | A payment found the module of the Safe off, and the engine confirmed it. | As above. |
| `safe_module_guard_set` | `safe_module` | The Safe set a module guard after the admission. | Remove the guard, then commit again. |
| `dsl_unloadable_at_boot` | any | The committed document no longer loads under the current engine. | Stage and commit a new document. |
| `erc20_allow_delegation_blocked` | `erc20_allow` | The owner set the block on the adapter. | `setErc20AllowBlocked({ blocked: false })`, then commit again. |
| `erc20_allow_allowance_revoked` | `erc20_allow` | The allowance of one document token is 0. | Approve the token, then commit again. |
| `erc20_allow_allowance_too_low` | `erc20_allow` | A payment needs more allowance of one token than the adapter holds. | Approve the token, then commit again. |
| `erc20_allow_cap_exhausted` | `erc20_allow` | The cap of one document token has no room left in its window. | Raise or clear the cap, or wait for the next window, then commit again. |
| `erc20_allow_cap_exceeded` | `erc20_allow` | A payment moves more of one token than its cap leaves. | Raise the cap, then commit again. |

`parked_token` names the token that caused the stop, when one token did. It is present only on a `parked` account.

### Example reply

```json theme={null}
{
  "dsl": {
    "status": "active",
    "yaml": "rules:\n  pay_rent:\n    trigger:\n ...",
    "version": 3,
    "commitment": "0xc1c235032e0996270b456797d8954becf561b97dd7f422a6e04b6ee84a1d1111"
  },
  "tenant": {
    "state": "active",
    "adapter": "0x425fe0a554299d33589edc51387254175478ee0e",
    "since_block": 29871234,
    "reason": null
  },
  "verified_notification_email": "ada@example.com"
}
```

```ts theme={null}
const state = await anafi.recover({ aa: safe, eoa: owner });
const onChain = await anafi.readDslCommitment(safe);
if (state.dsl && onChain && state.dsl.commitment?.toLowerCase() === onChain.hash.toLowerCase()) {
  editor.setValue(state.dsl.yaml);
}
```

## The engine signature check

```ts theme={null}
interface RecoverResponsePayload {
  state: RecoveredUserState;
  engine_sig: Hex; // 65 bytes r ‖ s ‖ v
}

function recoverResponseDigest(nonce: string, state: RecoveredUserState): Hex;
function assertRecoverResponseSignedByEngine(params: {
  nonce: string;
  state: RecoveredUserState;
  engineSig: Hex;
  engineSigKey: Hex;
}): Promise<void>;
function assertRecoveredTenantValid(state: RecoveredUserState): void;
```

The channel proves that only the engine key holder could make the reply. The signature proves that the engine signing key, which the registry publishes as `engineSigKey()`, wrote this exact state for this exact request.

`recoverResponseDigest(nonce, state)` is `keccak256(utf8(nonce + canonicalStateJson))`:

* `nonce` is the nonce of the sign-in. It binds the reply to this request, so an old reply cannot answer a new prompt.
* The state JSON is compact, with no spaces. The fields come in this order: `dsl` (with `status`, `yaml`, `version`, `commitment`), then `grant_hash` and `grant_json` when present, then `tenant` (with `state`, `adapter`, `since_block`, `reason`, then `parked_token` when present), then `verified_notification_email` when present. Keys of any map inside `grant_json` are sorted by code point.
* An absent field is left out. A `null` field prints `null`.
* A non-integer number makes the function throw.

`assertRecoverResponseSignedByEngine` checks that `engineSig` is 65 bytes of hex, recovers the signer of the raw digest (no EIP-191 prefix), and throws unless the signer is `engineSigKey`.

`assertRecoveredTenantValid` checks the `tenant` field after the signature check: a known `state`; `parked_token` only on a `parked` account and only as an address; for `none`, all of `adapter`, `since_block`, `reason` are `null`; for `active` and `parked`, an address and a block of 0 or more; for `active`, a `null` reason; for `parked`, a known reason. An absent `tenant` passes.

## Sign-in messages

### `renderSiweMessage`

```ts theme={null}
function renderSiweMessage(fields: SiweMessageFields): string;

interface SiweMessageFields {
  domain: string;
  address: Hex;
  statement: string;
  uri: string;
  chainId: number;
  nonce: string;
  issuedAt: string;              // RFC 3339, copied as given
  expiresAt?: string;            // RFC 3339; omit for no expiry line
  resources?: readonly string[]; // omit for no Resources block
}
```

Renders an EIP-4361 message. The lines are joined with `\n`, and the address is checksummed:

```text theme={null}
<domain> wants you to sign in with your Ethereum account:
<checksummed address>

<statement>

URI: <uri>
Version: 1
Chain ID: <chainId>
Nonce: <nonce>
Issued At: <issuedAt>
Expiration Time: <expiresAt>      (only with expiresAt)
Resources:                        (only with resources)
- <resource>
```

### The sign-ins of the SDK

| Flow | Statement | Expiry | Resources |
| - | - | - | - |
| `recover` | `Sign in to Anafi to recover your wallet state.` | none | none |
| `requestNotificationEmailCode` | `Verify <email> to receive notifications from wallet <account, lowercase>.` | 300 seconds after `Issued At` | `urn:anafi:notification-email-code:<account, lowercase>:<keccak256 of the email>` |
| `generateDsl` (`siweSessionMessage`) | `Sign in to Anafi to write rules from a description.` | none | none |

The notification-email sign-in is on [notification email](https://docs.ana.fi/sdk/notification-email.md). The rule generation sign-in is on [rule builders](https://docs.ana.fi/sdk/rule-builders.md#generate-a-document-from-text).


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