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

# Sealed requests

> How to seal a request to the Anafi engine, the exact HPKE suite and domain tags, the envelope format, and how to open and check the reply.

After you read this page, you can call the four sealed routes of the Anafi API without the SDK. You can seal a payload to the engine, open the reply, and check the engine signature.

The four sealed routes:

| Route | What the sealed payload holds |
| - | - |
| `POST /api/wallets/{aa}/dsl/commit/stage` | The rule document, its salt, the adapter and the parent document |
| `POST /api/wallets/{aa}/recover` | A sign-in of the owner |
| `POST /api/wallets/{aa}/notification_email/request_code` | An email address and a sign-in of the owner |
| `POST /api/wallets/{aa}/notification_email/verify_code` | A code token and the code from the email |

The Anafi API passes each envelope to the engine without change and cannot read it. Only the engine can open it. The reply is sealed to the caller with a key that only the caller and the engine know.

> [!WARNING]
>
> Do not plan an integration on another domain that uses `recover` or the notification-email code request. These two sign-in (EIP-4361) flows are accepted only when the sign-in message names the domain of the Anafi dapp, `app.ana.fi`. A sign-in for another domain is refused with `422`. An integration on another domain cannot complete these two flows today. The stage route and the verify route take no sign-in.

## The steps

```mermaid theme={null}
sequenceDiagram
    participant C as Caller
    participant R as AnafiRegistry (chain)
    participant A as Anafi API
    participant E as Engine
    C->>R: engineEncKey()
    R-->>C: bytes32 X25519 public key
    C->>C: HPKE seal(payload, info) and export response key
    C->>A: POST route with sealed envelope
    A->>E: same envelope, unchanged
    E-->>A: sealed reply
    A-->>C: sealed reply, unchanged
    C->>C: open reply with response key
    C->>R: engineSigKey() (recover only)
    C->>C: check engine_sig (recover only)
```

**1. Read the engine key**

Call `engineEncKey()` on the `AnafiRegistry` of the network. It returns a `bytes32`. These 32 bytes are the raw X25519 public key of the engine. The registry address of each network is on [Deployments](https://docs.ana.fi/contracts/deployments.md). The key can change, so read it before each seal. See [Registry](https://docs.ana.fi/contracts/registry.md).

**2. Build the plaintext**

Build the payload of the route, as the sections below show.

**3. Seal and export**

Seal the payload with HPKE under the `info` tag of the route. Then export the 32-byte response key from the same HPKE context. Keep the response key in memory. It is the only key that opens the reply.

**4. Send the envelope**

Send `{"sealed": {"kem_pk": [...], "ct": [...]}}` to the route, with `Content-Type: application/json`.

**5. Open the reply**

Open `{"nonce": [...], "ct": [...]}` with ChaCha20-Poly1305 under the response key. For `recover`, check the engine signature in the opened payload.

## HPKE suite

The engine accepts only this suite. A change of any part makes the envelope unopenable.

| Part | Value | RFC 9180 id |
| - | - | - |
| Mode | Base (no PSK, no sender key) | `0x00` |
| KEM | DHKEM(X25519, HKDF-SHA256) | `0x0020` |
| KDF | HKDF-SHA256 | `0x0001` |
| AEAD | ChaCha20-Poly1305 | `0x0003` |

* Seal once per context (single-shot), with an empty AAD.
* Use a new ephemeral key for each seal. Two seals of one payload give different envelopes.
* The engine public key must be exactly 32 bytes.

## Info tags

The `info` tag binds the envelope to its purpose. For three routes it also binds the network and the account. An envelope sealed for one account or one network does not open for another one. The engine derives the tag from the `aa` path segment and from its own network, so a relay cannot move an envelope to another account.

| Route | `info` bytes |
| - | - |
| `stage` | UTF-8 of `anafi/dsl-seal/` + network token + `/`, then the 20 raw bytes of `aa` |
| `recover` | UTF-8 of `anafi/confidential-call/req/v1` |
| `notification_email/request_code` | UTF-8 of `anafi/notification-email/request-code/` + network token + `/`, then the 20 raw bytes of `aa` |
| `notification_email/verify_code` | UTF-8 of `anafi/notification-email/verify-code/` + network token + `/`, then the 20 raw bytes of `aa` |

The network token is `polygon`, `xlayer` or `polygon-amoy`, with no other spelling. The address bytes are the raw 20 bytes, not hex text.

Example: the `stage` tag for account `0xf9836de53d455019ed985896fce8af80be66b7f9` on `polygon-amoy` is 48 bytes:

```text theme={null}
"anafi/dsl-seal/polygon-amoy/"  (28 bytes of UTF-8)
f9 83 6d e5 3d 45 50 19 ed 98 58 96 fc e8 af 80 be 66 b7 f9  (20 bytes)
```

The SDK builds these tags with `dslSealInfo(network, aa)`, `notificationEmailSealInfo(route, network, aa)` and the constant `CONFIDENTIAL_CALL_REQUEST_INFO`.

## Response key

After the seal, export a secret from the same HPKE sender context:

| Parameter | Value |
| - | - |
| Exporter context | UTF-8 of `anafi/confidential-call/resp/v1` |
| Length | 32 bytes |

All four routes use this exporter context. The `info` tag already separates the routes.

## Envelope format

The request body of each sealed route:

```json theme={null}
{
  "sealed": {
    "kem_pk": [131, 22, 7, 240, 18, 77, 5, 199, 61, 3, 88, 140, 211, 9, 47, 100, 12, 250, 33, 64, 17, 92, 180, 6, 71, 39, 145, 201, 8, 55, 160, 26],
    "ct": [17, 204, 93, 6, 145, 220, 61, 2, 118, 33, 9, 250, 4, 77, 18, 160, 5, 66, 201]
  }
}
```

| Field | Content |
| - | - |
| `kem_pk` | The encapsulated key (`enc`) of HPKE: the 32-byte ephemeral X25519 public key of the sender |
| `ct` | The ciphertext: the sealed payload and the 16-byte AEAD tag |

* Each field is a JSON array of integers from 0 to 255. A hex string is refused with `422`.
* The keys are snake\_case: `kem_pk`, not `kemPk`.
* The body of the stage route, the recover route and the email routes is at most 512 KiB. Each byte of an array takes up to 4 characters of JSON.

## Reply format

A sealed reply has no encapsulated key. It uses the response key that you exported.

```json theme={null}
{
  "nonce": [12, 201, 4, 77, 150, 3, 88, 9, 61, 240, 18, 33],
  "ct": [201, 14, 90, 3, 66, 129, 4, 250, 17, 8, 61, 92, 140, 7, 33, 2, 99]
}
```

| Field | Content |
| - | - |
| `nonce` | The 12-byte AEAD nonce. The engine draws a new random nonce for each reply. |
| `ct` | The ciphertext and the 16-byte tag |

Open it with ChaCha20-Poly1305: key = the response key, nonce = `nonce`, AAD = empty. The plaintext is UTF-8 JSON.

The sealed reply comes as the whole `200` body of `recover` and of the email routes. The stage route puts sealed replies in `sealedWarnings` (on `200`) and in `sealed_error` (on `409` and `422`).

Only the holder of the engine private key can derive your response key. So a reply that opens came from the engine and answers your request. If the reply does not open, discard it.

## Stage a rule document

### Plaintext

The stage plaintext is a binary frame, not JSON:

```text theme={null}
0x02 ‖ adapter[20] ‖ parent_version[8, big-endian u64] ‖ parent_hash[32] ‖ salt[32] ‖ yaml (UTF-8)
```

| Part | Content |
| - | - |
| `0x02` | The frame tag. |
| `adapter` | The 20 bytes of the adapter that the commit will name. It must be the live adapter of the account kind on this network. |
| `parent_version`, `parent_hash` | The on-chain document that you built on: `AnafiDslRegistry.commitments(aa)`. For the first document of an account, version `0` and 32 zero bytes. |
| `salt` | 32 random bytes. Keep them. You need them to compute the commitment. |
| `yaml` | The rule document. See [Rule language](https://docs.ana.fi/rules/overview.md) and [Limits](https://docs.ana.fi/rules/limits.md). |

The commitment is `keccak256(salt ‖ yaml)`. The adapter and the parent are not part of the commitment.

### Reply

A `200` reply is plain JSON, with one sealed field. See the operation "Stage a rule document" in this reference. Before the owner signs `commitDsl`, check:

1. `commitment` equals your own `keccak256(salt ‖ yaml)`.
2. `adapter` equals the adapter in your frame.
3. `attestationValidUntil` is in the future.

Open `sealedWarnings` with the response key. The plaintext is:

```json theme={null}
{ "messages": ["Rule ai_weekly_buy_eth_3f9a1c: ..."] }
```

The list is empty for a clean document. The findings are advice. They do not stop the commit.

### Open a staging refusal

A `409` or a `422` with this body is a refusal of the document:

```json theme={null}
{ "error": "invalid_dsl", "sealed_error": { "nonce": [...], "ct": [...] } }
```

Open `sealed_error` with the response key. The plaintext is:

```json theme={null}
{
  "message": "...",
  "reason": "stale_parent",
  "current_document": { "version": 3, "hash": "0x3c6e0b8a024d5c2f1b7e9a4d6c8f0e2a4b6c8d0e2f4a6b8c0d2e4f6a8b0c2d4e" }
}
```

| Field | Presence | Meaning |
| - | - | - |
| `message` | Always | The reason of the engine, for the author of the document. |
| `reason` | Optional | `stale_parent` (with `409`): another commit landed. `notification_email_not_verified` (with `422`): the document names an email that the account has not verified. Absent for other refusals. |
| `current_document` | Only with `stale_parent` | The on-chain document now: `version` and `hash`. Version `0` with a zero hash means that the account has no commit. Rebuild your document on it. |

### Engine signature

`engineSig` in the stage reply is the attestation of the engine for the commit. You do not check it off chain. `AnafiDslRegistry.commitDsl` checks it on chain against `engineSigKey` of the registry. See [DSL registry](https://docs.ana.fi/contracts/dsl-registry.md).

### Example

This example stages a document with SDK exports and `fetch`, without the SDK client.

```ts theme={null}
import { bytesToHex, createPublicClient, hexToBytes, http, type Hex } from "viem";
import { polygonAmoy } from "viem/chains";
import {
  ANAFI_REGISTRY_ABI,
  dslCommitment,
  dslSealInfo,
  dslStagePayload,
  openResponse,
  sealRequest,
  type OnChainDsl,
} from "@anafi-cc/anafi-sdk";

const API = "https://api.polygon-amoy.ana.fi";
const registry: Hex = "0x..."; // AnafiRegistry of polygon-amoy, from /contracts/deployments
const account: Hex = "0x..."; // the account
const adapter: Hex = "0x..."; // the live adapter of the account kind
const parent: OnChainDsl | null = null; // the current on-chain document, or null for the first one
const yaml = "..."; // the rule document

const publicClient = createPublicClient({ chain: polygonAmoy, transport: http() });
const engineKey = hexToBytes(
  (await publicClient.readContract({ address: registry, abi: ANAFI_REGISTRY_ABI, functionName: "engineEncKey" })) as Hex,
);

const salt = bytesToHex(crypto.getRandomValues(new Uint8Array(32)));
const { sealed, secret } = await sealRequest(
  engineKey,
  dslSealInfo("polygon-amoy", account),
  dslStagePayload(adapter, salt, yaml, parent),
);

const response = await fetch(`${API}/api/wallets/${account}/dsl/commit/stage`, {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify({ sealed }),
});
if (!response.ok) throw new Error(`${response.status} ${await response.text()}`);
const staged = await response.json();

if (staged.commitment.toLowerCase() !== dslCommitment(salt, yaml).toLowerCase()) {
  throw new Error("the commitment in the reply is not the commitment of this document");
}
const warnings = JSON.parse(new TextDecoder().decode(await openResponse(secret, staged.sealedWarnings)));
console.log(warnings.messages);
// Next: the owner calls AnafiDslRegistry.commitDsl(staged.commitment,
// staged.attestationValidUntil, staged.engineSig, staged.adapter).
```

## Read back the account state

### Plaintext

```json theme={null}
{
  "aa": "0xf9836de53d455019ed985896fce8af80be66b7f9",
  "siwe_message": "app.ana.fi wants you to sign in with your Ethereum account:\n0x...",
  "signature": "0x..."
}
```

| Field | Content |
| - | - |
| `aa` | The account. It must equal the `aa` path segment. |
| `siwe_message` | The EIP-4361 message that the owner signed, byte for byte. |
| `signature` | The 65-byte `personal_sign` signature over `siwe_message`, as `0x` hex. |

The engine checks the sign-in in this order. A failure gives `422`.

1. The signature recovers to the address in the message.
2. The domain is `app.ana.fi` and the `Chain ID` is the chain of the host.
3. The time is inside `Not Before` and `Expiration Time`, when the message has them.
4. The message has no `Resources` list.
5. The `Issued At` is at most 5 minutes old and at most 60 seconds in the future, and the address has not used the nonce before. The nonce is used up from this step on.
6. If the engine accepted a commit of this account before, the signer must be a signer of the account: an owner of the Safe for a `safe_module` account, or the address itself for an `erc20_allow` account. Another signer gets `422`. If the engine never accepted a commit of this account, the reply holds the empty state: `dsl` is `null` and `tenant.state` is `none`.

The SDK signs this statement: `Sign in to Anafi to recover your wallet state.` The message format is the EIP-4361 format that `renderSiweMessage` writes.

### Reply plaintext

```json theme={null}
{
  "state": {
    "dsl": {
      "status": "active",
      "yaml": "rules:\n  ...",
      "version": 3,
      "commitment": "0x3c6e0b8a024d5c2f1b7e9a4d6c8f0e2a4b6c8d0e2f4a6b8c0d2e4f6a8b0c2d4e"
    },
    "tenant": {
      "state": "active",
      "adapter": "0x5f3c0e1b2a4d6e8f0a1b2c3d4e5f60718293a4b5",
      "since_block": 28411907,
      "reason": null
    },
    "verified_notification_email": "owner@example.com"
  },
  "engine_sig": "0x..."
}
```

| Field | Meaning |
| - | - |
| `state.dsl` | The document of the account, or `null` when the engine has none to return. |
| `state.dsl.status` | `active`: the engine runs this document. `retired`: no document runs, and this is the last one. |
| `state.dsl.yaml` | The rule document in plain text. |
| `state.dsl.version` | The registry version of the document, or `null`. |
| `state.dsl.commitment` | The commitment of the document. Compare it with `AnafiDslRegistry.commitments(aa)` before you trust the text. |
| `state.grant_hash`, `state.grant_json` | Optional, always together. An opaque record of the permission. `null` for a Safe. |
| `state.tenant` | The account state that the engine reports. Optional: absent means that the engine said nothing about it, not `none`. |
| `state.verified_notification_email` | The verified notification email, or `null`. Optional. |
| `engine_sig` | The 65-byte signature of the engine (`r ‖ s ‖ v`), as `0x` hex. |

Account states in `state.tenant.state`:

| Value | Meaning | What to do |
| - | - | - |
| `none` | No commit of this account was accepted. `adapter`, `since_block` and `reason` are `null`. | Commit a document to start. |
| `active` | The engine serves the account through `adapter`, since block `since_block`. A document with no rules is also `active`. | Nothing. |
| `parked` | The engine stopped the account. `reason` says why. `parked_token` names the token when one token caused it. | Fix the cause, then commit a document again. A new accepted commit makes the account `active`. |

Reasons in `state.tenant.reason` for a `parked` account:

| Value | Meaning | What to do |
| - | - | - |
| `commit_refused` | The engine did not accept the last commit. | Stage and commit a valid document. |
| `adapter_removed` | The registry no longer lists the adapter that the commit named. | Move to the current adapter of the network and commit again. |
| `safe_module_disabled` | The Safe disabled the Safe adapter as a module. | Enable the module again and commit. |
| `safe_reported_disable` | A payment found the module disabled, and the engine confirmed it on chain. | Enable the module again and commit. |
| `safe_module_guard_set` | The Safe set a module guard after the account started. | Remove the module guard and commit again. |
| `dsl_unloadable_at_boot` | The committed document no longer loads in the engine. | Commit a new valid document. |
| `erc20_allow_delegation_blocked` | The owner blocked the `erc20_allow` adapter. | Unblock the adapter and commit again. |
| `erc20_allow_allowance_revoked` | The allowance of one token to the adapter is 0. | Approve the token again and commit again. |
| `erc20_allow_allowance_too_low` | A payment needs more allowance of one token than the adapter has. | Raise the allowance and commit again. |
| `erc20_allow_cap_exhausted` | The cap of one token has no room left in its period. | Raise the cap, or wait for the next period, and commit again. |
| `erc20_allow_cap_exceeded` | A payment moves more of one token than its cap allows. | Raise the cap and commit again. |

See [ERC-20 allowance adapter](https://docs.ana.fi/contracts/erc20-allow-adapter.md) and [Safe adapter](https://docs.ana.fi/contracts/safe-adapter.md).

### Check the engine signature

The engine signs each `recover` reply. Check the signature before you show the document or act on the state.

1. Compute `digest = keccak256(UTF-8(nonce) ‖ UTF-8(canonical JSON of state))`. `nonce` is the `Nonce` value of your sign-in message, as text.
2. Recover the signer from `digest` and `engine_sig` with plain `ecrecover`, without an EIP-191 prefix.
3. Compare the signer with `engineSigKey()` of the `AnafiRegistry`. They must be equal.

The canonical JSON of `state` is compact, with no spaces, and has its keys in this order:

| Object | Key order |
| - | - |
| `state` | `dsl`, `grant_hash`, `grant_json`, `tenant`, `verified_notification_email`. Leave out a key that the reply does not have. |
| `dsl` | `status`, `yaml`, `version`, `commitment` |
| `tenant` | `state`, `adapter`, `since_block`, `reason`, then `parked_token` only when the reply has it |
| Objects inside `grant_json` | Keys sorted by Unicode code point |

Strings use the escapes of `JSON.stringify`. Numbers are integers.

The nonce in the digest binds the reply to your request. An old reply to another sign-in does not verify.

The SDK exports `recoverResponseDigest(nonce, state)` and `assertRecoverResponseSignedByEngine({ nonce, state, engineSig, engineSigKey })` for this check.

## Verify a notification email

### Code request plaintext

```json theme={null}
{
  "adapter": "0x5f3c0e1b2a4d6e8f0a1b2c3d4e5f60718293a4b5",
  "email": "Owner@Example.com",
  "siwe_message": "app.ana.fi wants you to sign in with your Ethereum account:\n0x...",
  "signature": "0x..."
}
```

| Field | Content |
| - | - |
| `adapter` | The live adapter of the account kind on this network. |
| `email` | The email address as the user typed it. |
| `siwe_message` | The EIP-4361 message that the owner signed, byte for byte. |
| `signature` | The 65-byte `personal_sign` signature, as `0x` hex. |

The canonical email is the `email` value with ASCII white space removed at both ends, in lowercase. An address with a non-ASCII character, white space inside, or one of the characters `<`, `>`, `,`, `;`, `"` has no canonical form.

The sign-in must pass the checks 1, 2, 3 and 5 of the `recover` sign-in, and the signer must be a signer of the account. In place of check 4, its `Resources` list must hold exactly one entry:

```text theme={null}
urn:anafi:notification-email-code:<aa in lowercase hex>:<keccak256 of the UTF-8 canonical email, as 0x hex>
```

The SDK signs the statement `Verify <canonical email> to receive notifications from wallet <aa in lowercase hex>.` and an `Expiration Time` 5 minutes after `Issued At`. The SDK function `notificationEmailCodeSiweMessage` writes this message.

### Code request reply plaintext

```json theme={null}
{
  "aa": "0xf9836de53d455019ed985896fce8af80be66b7f9",
  "email": "owner@example.com",
  "outcome": { "kind": "code_issued", "code_token": "0x9f1c2a3b4c5d6e7f8091a2b3c4d5e6f7", "delivery": "sent" }
}
```

| `outcome.kind` | Other fields | Meaning | What to do |
| - | - | - | - |
| `code_issued` | `code_token`, `delivery` | The engine made a code and tried to mail it. `code_token` is `0x` and 32 lowercase hex digits. `delivery` is `sent` or `failed`. | Keep `code_token`. Ask the user for the 6-digit code. If `delivery` is `failed`, request a new code later. |
| `already_verified` | none | This email is already the verified email of the account. No mail was sent. | Nothing. |
| `invalid_email` | none | The email has no canonical form or cannot receive mail. `email` is `null`. | Ask for another address. |
| `retry_after` | `seconds` | Too many code requests now. | Wait `seconds`, then sign a new request. |
| `mail_not_configured` | none | This network sends no email. | Notification email is not available on this network. |

Check that `aa` equals your account.

### Verify plaintext and reply

```json theme={null}
{ "code_token": "0x9f1c2a3b4c5d6e7f8091a2b3c4d5e6f7", "code": "482913" }
```

The reply plaintext has `aa`, `email` and `outcome`:

| `outcome.kind` | Other fields | Meaning | What to do |
| - | - | - | - |
| `verified` | none | The email is now the verified notification email of the account. | A rule document can now name this email. |
| `wrong_code` | `attempts_left` | The code is wrong. | Ask again, at most `attempts_left` more times. |
| `code_token_invalid` | none | The token is unknown, expired after 15 minutes, for another account, or has no attempts left. `email` is `null`. | Request a new code. |

The email replies carry no engine signature. The response key proves that the engine made them. Check that `aa` equals your account.

See [Notification email flow](https://docs.ana.fi/flows/notification-email.md) and [SDK notification email](https://docs.ana.fi/sdk/notification-email.md).

## Engine signatures

| Reply | Signature | Who checks it |
| - | - | - |
| `stage` | `engineSig`, over the commit digest | `AnafiDslRegistry.commitDsl` on chain |
| `recover` | `engine_sig`, over the nonce and the state | You, off chain, against `engineSigKey()` |
| `notification_email/*` | None | The response key proves the origin. |

See [Security](https://docs.ana.fi/concepts/security.md) for the trust model and [SDK confidential channel](https://docs.ana.fi/sdk/confidential-channel.md) for the SDK functions.


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