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

# Safe account

> Predict or choose a 1-of-1 Safe, stage a rule document, and commit it with the module grant in one owner prompt.

After this page, you can take an owner address to a Safe that runs a committed rule document through `AnafiDelegationAdapterSafe`. You know each prompt, each HTTP route, each contract call, each refusal, and how to resume.

## When to use it

Use the Safe kind (`safe_module`) when:

* the rules must move the native coin, or a token that the ERC20Allow kind cannot serve;
* the rules use `off_ramp` (bank payouts, `polygon-amoy` only);
* the owner wants the funds in a Safe, and one module grant in place of token approvals.

Use the [ERC20Allow account](https://docs.ana.fi/flows/erc20-account.md) when the funds stay in a plain address.

## Preconditions

| Condition | How to check | What refuses it |
| - | - | - |
| The client config has `delegationAdapters.safe` and `addresses.safe` (singleton, `singletonL2`, `toL2Setup`, `proxyFactory`, `multiSend`) | your config | `Error`: `this deployment configures no Safe singleton, proxy factory or MultiSend`, or `... is not this chain's configured Safe adapter` |
| `AnafiRegistry.delegationAdapters()` lists the Safe adapter | `readLiveDelegationAdapters()` | `Error`: `... is not the live configured safe_module adapter` |
| The Safe proxy code hash and its singleton are admitted by the adapter | `readAccountAdapter(safe)` returns the Safe adapter | `Error`: `... is not a Safe admitted by adapter ...` |
| The Safe has threshold 1, and the owner address is an owner | Safe `getThreshold()`, `isOwner(eoa)` | `Error`: `Safe ... has threshold N; this client can submit only single-owner Safe transactions`, or `... is not an owner of Safe ...` |
| The Safe has no module guard | Safe storage | `redeemAsEngine` reverts `SafeHasModuleGuard(account)` at each payment. The SDK does not check this. |
| Owner gas, when Anafi does not relay | `fetchWalletSponsorship(safe)` | the wallet refuses the transaction |

Today, the Anafi API hosts answer CORS only for `https://app.ana.fi`. Run the calls that use the Anafi API from a server, a script, or your own same-origin proxy.

### Admitted Safes

`AnafiDelegationAdapterSafe` serves a Safe only when two facts hold. Read both on the adapter:

* `admittedSafeProxyCodehashes(keccak256(code of the Safe))` is `true`;
* `admittedSafeSingletons(masterCopy())` is `true`.

The deployment records of `polygon` and `polygon-amoy` list the singletons of Safe 1.3.0, 1.4.1 and 1.5.0. The Safe that the SDK provisions runs Safe 1.5.0 on `SafeL2`. Always read the adapter on chain, because the admitted sets can change. See [Safe adapter](https://docs.ana.fi/contracts/safe-adapter.md) and [Deployments](https://docs.ana.fi/contracts/deployments.md).

## Sequence

```mermaid theme={null}
sequenceDiagram
    autonumber
    participant W as Owner wallet
    participant A as Your app (SDK)
    participant API as Anafi API
    participant E as Anafi engine (black box)
    participant C as Chain
    A->>C: SafeProxyFactory.proxyCreationCode() (predictSafe)
    A->>API: GET /api/wallets/{safe}/sponsorship
    alt Relayed deploy
        A->>API: POST /api/wallets/provision
        API->>C: createProxyWithNonce (Anafi pays)
    else Owner-sent deploy
        W->>C: Transaction: SafeProxyFactory.createProxyWithNonce
    end
    A->>C: Read registry list, Safe code, singleton, threshold, isOwner, isModuleEnabled
    A->>C: AnafiRegistry.engineEncKey()
    A->>API: POST /api/wallets/{safe}/dsl/commit/stage (sealed)
    API->>E: Relay sealed document
    E-->>A: commitment, engineSig, attestationValidUntil, sealed findings
    A->>C: Safe.nonce()
    alt Relayed commit
        W-->>A: EIP-712 SafeTx signature
        A->>API: POST /api/wallets/{safe}/safe/sponsor_exec
        API->>C: Safe.execTransaction (Anafi pays)
    else Owner-sent commit
        W->>C: Transaction: Safe.execTransaction
    end
    Note over C: MultiSend: Safe.enableModule(adapter), then AnafiDslRegistry.commitDsl
```

## Steps

**1. Find the Safe**

Two ways:

* **Predict.** `predictSafe(eoa)` reads `proxyCreationCode()` from the Safe proxy factory and computes the CREATE2 address of a Safe with one owner (`eoa`), threshold 1, a setup call `setupToL2(singletonL2)` on `toL2Setup`, and the salt nonce `uint256(keccak256(eoa))`. No prompt. No HTTP call. The result is the same before and after the deploy.
* **Discover.** `discoverAccounts(eoa)` calls `GET /api/accounts/discover?eoa=...`. Each suggestion has `address`, `kind`, `source` (`predicted_safe`, `safe_transaction_service`, `connected_address`) and `deployed`. A suggestion authorizes nothing. Check `completeness`: only `every_source_consulted` means the list is complete. See [Accounts](https://docs.ana.fi/concepts/accounts.md).

For a Safe that already exists, call `readAccountAdapter(safe)`. It returns the Safe adapter when the adapter admits the Safe, else the ERC20Allow adapter when that kind serves the address, else `null`.

**2. Decide who pays**

The SDK reads `GET /api/wallets/{safe}/sponsorship` before each owner operation. Anafi relays when `feesOn` is `false` or `sponsored` is `true`. In each other case, the owner address sends the transaction and pays the gas. You can read the same answer with `fetchWalletSponsorship(safe)` to tell the owner in advance.

**3. Stage the document for arm**

Call `stageDsl({ safe, eoa, adapter, yaml, salt, parent, write: "arm" })`. Use a new random 32-byte `salt` for each commit. Set `parent` to `await readDslCommitment(safe)`: `null` for a first document.

**a. Provision, only when the Safe has no code.** The SDK calls `provisionPredictedSafe({ safe, eoa })`:

| Path | Prompt | Call |
| - | - | - |
| Relayed | none | `POST /api/wallets/provision` with `{ "eoa": "0x...", "kind": "safe_1of1" }`. The reply is `{ aa, accountKind: "safe_module", kind: "deployed" or "already_deployed", txHash? }`. The SDK waits up to 60 seconds for its own RPC to return the receipt. |
| Owner-sent | transaction | `SafeProxyFactory.createProxyWithNonce(singleton, initializer, saltNonce)` from `eoa`. The SDK waits for the receipt, then checks that the Safe has code at that block. |

The SDK refuses a `safe` that is not `predictSafe(eoa)`, and a relayed reply that names another address. `onProvisioned(confirmedBlock)` runs once after the provision, also when a later part of the stage fails. The Safe stays deployed in all cases.

**b. Checks.** The SDK checks the adapter, the admission of the Safe, the threshold, the owner, and `isModuleEnabled(adapter)`. After a provision, it reads at or above the block of the provision. For `write: "arm"`, `enableAdapter` is `true` when the module is not enabled yet.

**c. Seal and send.** The SDK reads `AnafiRegistry.engineEncKey()` and encrypts the adapter, the parent, the salt and the text to the engine. It sends `POST /api/wallets/{safe}/dsl/commit/stage` with `{ "sealed": ... }`. The Anafi API cannot read the document. See [Sealed requests](https://docs.ana.fi/api-reference/sealed-requests.md).

**d. Check the reply.** The reply holds `adapter`, `commitment`, `engineSig`, `dslVersion`, `attestationValidUntil` and optional `sealedWarnings`. The SDK refuses a reply when the adapter is not the requested one, when `commitment` is not `keccak256(salt ‖ yaml)`, when the deadline has passed, or when the deadline is more than 1 hour away. It decrypts the findings into `staged.warnings`.

The stage shows no wallet prompt, except the deploy transaction of step a.

**4. Show the findings**

`staged.warnings` holds the findings of the engine, verbatim and in order. An empty list means a clean document. Show each finding to the owner before the commit. See [Validation](https://docs.ana.fi/rules/validation.md) for the findings that the rule language defines.

**5. Commit in one prompt**

Call `commitStagedDsl({ staged, onStep, onSigned })`.

1. The SDK refuses a staged value whose attestation deadline has passed: `commitStagedDsl: the engine's attestation over this staged document has lapsed; stage it again`.
2. It builds the call `AnafiDslRegistry.commitDsl(commitment, attestationValidUntil, engineSig, adapter)`.
3. When `staged.enableAdapter` is `true`, it puts two calls in one `MultiSend` batch (a delegatecall from the Safe): first `Safe.enableModule(adapter)`, then `commitDsl`. Else it sends `commitDsl` as one plain call.
4. It reads the Safe nonce (at or above `staged.minReadBlock`) and the sponsorship.
5. It calls `onStep("safe")`, then asks the wallet for one prompt:

| Path | Prompt | What the SDK sends |
| - | - | - |
| Relayed | EIP-712 typed data: `SafeTx` with domain `{ chainId, verifyingContract: safe }`, `gasPrice` and `safeTxGas` set to 0 | `POST /api/wallets/{safe}/safe/sponsor_exec` with `{ network, account, execTransactionCalldata }`. The reply is `{ txHash, success }`. The SDK waits up to 60 seconds for its own RPC to return the receipt. |
| Owner-sent | transaction: `Safe.execTransaction(...)` from `eoa`, with the Safe pre-validated signature of `eoa` | nothing to the Anafi API. The SDK waits for the receipt. |

6. `onSigned` runs after the wallet answers, before the relay request or the receipt wait.

The result is `{ txHash, kind, confirmedBlock }`. `kind` is `"committed"`, or `"inner_reverted"` when the Safe reports that its inner call failed. `confirmedBlock` is `null` when a relayed receipt did not arrive in time.

`armSafe(...)` runs `stageDsl` with `write: "arm"` and then `commitStagedDsl` in one call. Use the two calls when you want to show the findings before the prompt.

## What can refuse

### At the stage

| Error | HTTP | Meaning | What to do |
| - | - | - | - |
| `DslStaleParentError` | `409` | The chain holds another document than `parent`. `error.current` is the current `{ hash, version }`, or `null`. | Rebuild the document on `error.current` and stage again. See [Update, pause, revoke](https://docs.ana.fi/flows/update-pause-revoke.md). |
| `NotificationEmailNotVerifiedError` | `422` | `global.notification_email` is not the verified inbox of the account. | Verify the inbox first. See [Notification email](https://docs.ana.fi/flows/notification-email.md). |
| `DslStageRefusedError` | `422` | The engine refused the document. `error.refusal` is its reason as text. | Show `error.refusal` to the author, fix the document. |
| `BackendRequestError` | `422` | The engine could not open the request, or it does not serve the adapter. | Check the network, the adapter and the account. |
| `BackendRequestError` | `429` | Too many staged documents wait for a commit. | Commit, or wait and stage again. |
| `BackendRequestError` | `502`, `null` | The engine or the Anafi API did not answer. `status: null` means no answer at all. | Retry later. |
| `BackendRequestError` | `403` | Relayed provision refused: `{"code":"account_not_sponsored"}` when fees are on and the Safe has no sponsor. | Read the sponsorship again. The owner sends the deploy. |
| `BackendRequestError` | `503`, `502` | Relayed provision: the network serves no Safe leg, the engine did not answer, or the deploy did not finish in time. A deploy that was sent can still land. | Call `isWalletDeployed(safe)` before a retry. |

See [Errors](https://docs.ana.fi/sdk/errors.md) and [API errors](https://docs.ana.fi/api-reference/errors.md).

### At the commit

| Where | Refusal | Meaning |
| - | - | - |
| SDK | attestation lapsed | Stage again. |
| Wallet | user rejection | Nothing was sent. Call `commitStagedDsl` again while the attestation is valid. |
| `sponsor_exec` | `400` | The body does not name this network or this Safe, or the calldata is not a Safe transaction that Anafi can read. |
| `sponsor_exec` | `403` | Fees are on and the Safe has no sponsor (`account_not_sponsored`), the call is not one that Anafi relays, or the transaction reverts in a simulation. Anafi relays only the enable or disable of the configured Safe adapter, `commitDsl` or `commitDslDirect` that names that adapter, the off-ramp setup calls, and `MultiSend` batches of these calls. |
| `sponsor_exec` | `429` | Another relayed transaction of this Safe is in flight. Wait and retry. |
| `sponsor_exec` | `502`, `503` | The chain or the engine did not answer. |
| `sponsor_exec` | `504` | The transaction may have been sent and can still be mined. Do not send the same bytes again. Read the Safe nonce and `readDslCommitment(safe)` first. |
| Safe | `GS` error codes | The Safe refused the signature or the nonce. With `gasPrice` and `safeTxGas` at 0, a failed inner call reverts the whole `execTransaction`. |
| `AnafiDslRegistry.commitDsl` | `AttestationExpired()` | `block.timestamp` is after `validUntil`. Stage again. |
| `AnafiDslRegistry.commitDsl` | `InvalidEngineSignature()` | The engine signed a digest over the chain id, the registry, the Safe, the next version, the hash, `validUntil` and the adapter. A commit that landed after the stage changes the next version, so the old attestation no longer matches. Stage again on the new parent. |

## Resume after a failure or a reload

| State | How to see it | What to do |
| - | - | - |
| The Safe was deployed, the stage failed | `isWalletDeployed(safe)` is `true`, `readDslCommitment(safe)` is unchanged | Call `stageDsl` again. It does not deploy again. |
| The stage succeeded, no prompt yet | You hold `staged` | Call `commitStagedDsl({ staged })` before `attestationValidUntilUnixSeconds`. After the deadline, stage again with a new salt. |
| The commit was sent, the result is unknown (reload, `504`, timeout) | `readDslCommitment(safe)` | When `hash` equals `staged.commitment`, the commit landed. Else, when the Safe nonce did not move, commit again. When the nonce moved and the hash differs, stage again on the new parent. |
| `kind` is `"inner_reverted"` | result | The Safe nonce moved and nothing was committed. Stage again. |

The `staged` value is plain data. You can store it and pass it to `commitStagedDsl` after a reload, until its deadline.

## End state on chain

| Fact | Read it with |
| - | - |
| The module is enabled | `readSafeModuleEnabled(safe, adapter)`, or Safe `isModuleEnabled(adapter)`. The Safe emits `EnabledModule(adapter)`. |
| The document commitment | `readDslCommitment(safe)` returns `{ hash, version }`. `AnafiDslRegistry` emits `DslCommitted(aaWallet, commitment, version, adapter)`. |
| The account kind | `readAccountAdapter(safe)` returns the Safe adapter. |

The chain holds only the salted hash. To read the plaintext and the state that the engine holds, see [Read-back](https://docs.ana.fi/flows/read-back.md).

## Other Safe calls

| Method | Use |
| - | - |
| `enableSafeModule({ safe, eoa, adapter })` | Enable the adapter with no commit. Requires the adapter to be live. One prompt, relayed or owner-sent. |
| `commitDslFromSafe({ ... })` | `stageDsl` with `write: "update"`, then `commitStagedDsl`. The module must be enabled already. |
| `disableSafeModule({ safe, eoa, adapter })` | Revoke. See [Update, pause, revoke](https://docs.ana.fi/flows/update-pause-revoke.md). |
| `executeSafeOwnerCalls({ safe, eoa, legs, ownerSent? })` | Any other Safe owner calls, as one call or one `MultiSend` batch. Set `ownerSent: true` for a call that Anafi does not relay. |

See [Safe methods](https://docs.ana.fi/sdk/safe.md) for each signature.

## Example

This example uses the client of the [Quickstart](https://docs.ana.fi/quickstart.md). It runs on a server or in a script.

```ts theme={null}
import {
  BackendRequestError,
  DslStageRefusedError,
  DslStaleParentError,
  NotificationEmailNotVerifiedError,
  type AnafiClient,
  type Hex,
} from "@anafi-cc/anafi-sdk";
import { bytesToHex } from "viem";

export async function armSafe(anafi: AnafiClient, eoa: Hex, adapter: Hex, yaml: string) {
  const safe = await anafi.predictSafe(eoa);
  const sponsorship = await anafi.fetchWalletSponsorship(safe);
  const relayed = !sponsorship.feesOn || sponsorship.sponsored;
  console.log(relayed ? "Anafi pays the gas" : "the owner pays the gas");

  const salt = bytesToHex(crypto.getRandomValues(new Uint8Array(32)));
  const parent = await anafi.readDslCommitment(safe);

  let staged;
  try {
    staged = await anafi.stageDsl({
      safe,
      eoa,
      adapter,
      yaml,
      salt,
      parent,
      write: "arm",
      onProvisioned: (block) => console.log("Safe deployed at block", block),
    });
  } catch (error) {
    if (error instanceof DslStaleParentError) {
      console.log("another document landed:", error.current);
    } else if (error instanceof NotificationEmailNotVerifiedError) {
      console.log("verify the notification inbox first");
    } else if (error instanceof DslStageRefusedError) {
      console.log("the engine refused the document:", error.refusal);
    } else if (error instanceof BackendRequestError) {
      console.log("the Anafi API answered", error.status, error.responseText);
    }
    throw error;
  }

  for (const finding of staged.warnings) console.log("finding:", finding);

  const result = await anafi.commitStagedDsl({
    staged,
    onStep: () => console.log("approve the Safe transaction in the wallet"),
    onSigned: () => console.log("signed"),
  });
  if (result.kind !== "committed") throw new Error(`the Safe transaction failed: ${result.txHash}`);

  const onChain = await anafi.readDslCommitment(safe);
  console.log("committed:", onChain?.hash === staged.commitment, "version", onChain?.version);
  console.log("module enabled:", await anafi.readSafeModuleEnabled(safe, adapter));
  return { safe, staged, result };
}
```


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