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

> Provision, arm, update and revoke a Safe account with the SDK: every method, its prompts in order, its routes and contract calls, and every refusal.

After you read this page, you can deploy the 1-of-1 Safe of an owner, commit its first rule document, replace the document, and enable or disable the Safe adapter.

A Safe account (kind `safe_module`) grants its permission when the Safe enables the Safe adapter as a module. The owner revokes the permission with `disableModule`. See [the Safe adapter](https://docs.ana.fi/contracts/safe-adapter.md) and the [Safe account flow](https://docs.ana.fi/flows/safe-account.md).

## Relayed and owner-sent execution

Each owner operation of a Safe is one Safe transaction. The client sends it in one of two ways.

| Way | When | Wallet prompt | Who sends and pays | Route |
| - | - | - | - | - |
| Relayed | `GET /api/wallets/:aa/sponsorship` answers `feesOn: false`, or `sponsored: true` | 1 EIP-712 `SafeTx` signature (`signTypedData`) | Anafi | `POST /api/wallets/:aa/safe/sponsor_exec` |
| Owner-sent | all other cases | 1 transaction (`sendTransaction`) from the owner to the Safe | the owner | none |

The client reads the sponsorship before each operation. It never assumes it. A failed sponsorship read rejects the operation, with one exception: `disableSafeModule` falls back to the owner-sent way (see below).

In the relayed way, the owner signs the `SafeTx` typed data (`safeTxTypedData`). The client then posts `{ network, account, execTransactionCalldata }`. After the relay answers, the client waits up to 60 seconds for its own RPC to return the receipt (`waitForRelayedTransaction`). If the receipt does not arrive, `confirmedBlock` is `null`, and the method still resolves.

In the owner-sent way, the owner sends `execTransaction` to the Safe with the pre-validated signature (`buildSafePreValidatedSignature`). The Safe accepts it only because `msg.sender` is the owner, so there is no typed-data prompt. The client waits up to 180 seconds for the receipt. A reverted receipt rejects with `Error("owner transaction <hash> reverted")`.

Anafi relays only Safe transactions whose calls are on its list. The list has `enableModule` and `disableModule` of the configured Safe adapter at the Safe, and `commitDsl` and `commitDslDirect` at the DSL registry that name that adapter. On a network with an off-ramp handler, the list also has the off-ramp setup calls of the Safe. The calls can be alone or in a MultiSend. Each transaction must have `value`, `gasPrice` and `safeTxGas` at 0, as the client builds them. The Anafi API refuses other calls. For another call, use `executeSafeOwnerCalls` with `ownerSent: true`. See the [API reference](https://docs.ana.fi/api-reference/introduction.md) for the status codes of the route.

## Single-owner limits

The client signs and sends Safe transactions for a Safe with threshold 1 only. Before an owner operation it reads `getThreshold()` and `isOwner(eoa)`. It throws:

* `Error("Safe <safe> has threshold <n>; this client can submit only single-owner Safe transactions")` when the threshold is not 1.
* `Error("<eoa> is not an owner of Safe <safe>")` when `eoa` is not an owner.

A Safe with more owners and threshold 1 works. A Safe with threshold 2 or more does not work with these methods.

## The arm flow

```mermaid theme={null}
sequenceDiagram
  participant App
  participant SDK
  participant Wallet as Owner wallet
  participant API as Anafi API
  participant Chain
  App->>SDK: armSafe({ safe, eoa, adapter, yaml, salt, parent })
  SDK->>Chain: getCode(safe)
  alt Safe has no code
    SDK->>API: GET /api/wallets/:safe/sponsorship
    alt relayed
      SDK->>API: POST /api/wallets/provision
    else owner-sent
      SDK->>Wallet: sendTransaction(createProxyWithNonce)
    end
  end
  SDK->>Chain: adapter checks, threshold, isOwner, isModuleEnabled
  SDK->>Chain: engineEncKey()
  SDK->>API: POST /api/wallets/:safe/dsl/commit/stage (sealed)
  API-->>SDK: commitment, engineSig, attestationValidUntil, sealed warnings
  SDK->>Chain: nonce()
  SDK->>API: GET /api/wallets/:safe/sponsorship
  alt relayed
    SDK->>Wallet: signTypedData(SafeTx)
    SDK->>API: POST /api/wallets/:safe/safe/sponsor_exec
  else owner-sent
    SDK->>Wallet: sendTransaction(execTransaction)
  end
  SDK-->>App: { txHash, kind, confirmedBlock }
```

## `provisionPredictedSafe`

```ts theme={null}
provisionPredictedSafe(params: { safe: Hex; eoa: Hex }): Promise<ProvisionWalletResult>;

interface ProvisionWalletResult {
  aa: Hex;
  accountKind: AccountKind;            // always "safe_module"
  kind: "deployed" | "already_deployed";
  txHash?: Hex;
  confirmedBlock: bigint | null;
}
```

Deploys the predicted 1-of-1 Safe of `eoa`, or returns the Safe that exists.

| Step | What happens |
| - | - |
| 1 | `predictSafe(eoa)`. The method throws `Error("requested Safe <safe> is not predicted Safe <predicted>")` when `safe` differs. |
| 2 | `GET /api/wallets/:safe/sponsorship`. |
| 3a, relayed | `POST /api/wallets/provision` with `{ eoa, kind: "safe_1of1" }`. The client throws `Error("provisioning returned <aa>, not predicted Safe <predicted>")` when the reply names another Safe. When the reply has a `txHash`, the client waits for its receipt. |
| 3b, owner-sent | If the Safe has code, the method returns `already_deployed` with no prompt. Else the owner sends `SafeProxyFactory.createProxyWithNonce(singleton, initializer, keccak256(eoa))`. After the receipt, the client checks the code at the receipt block, under the retry rule. It throws `Error("owner transaction <hash> did not deploy Safe <safe>")` when there is no code. |

| Field | Meaning |
| - | - |
| `kind` | `deployed`: this call deployed the Safe. `already_deployed`: the Safe had code. |
| `txHash` | The deploy transaction, when this call deployed the Safe. |
| `confirmedBlock` | The block of the deploy receipt. `null` when nothing was sent, or when the receipt of a relayed deploy did not arrive in 60 seconds. |

Prompts: relayed 0, owner-sent 1 transaction (or 0 for `already_deployed`).

```ts theme={null}
const safe = await anafi.predictSafe(owner);
const provisioned = await anafi.provisionPredictedSafe({ safe, eoa: owner });
```

## `stageDsl`

```ts theme={null}
stageDsl(params: StageDslParams): Promise<StagedSafeDsl>;

type DslWrite = "arm" | "update";

type StageDslParams = {
  safe: Hex;
  eoa: Hex;
  adapter: Hex;
  yaml: string;
  salt: Hex;
  parent: OnChainDsl | null;
  write: DslWrite;
  onProvisioned?: (confirmedBlock: bigint | null) => void;
};
```

Sends the rule document to the engine for a stage, checks the reply, and returns everything that the commit needs. The owner signs nothing in the stage itself. The engine checks the document and signs an attestation for this exact commitment and adapter. A staged document commits only through `commitStagedDsl`.

| Parameter | Meaning |
| - | - |
| `safe` | The Safe account. |
| `eoa` | The owner. It authorizes the commit. It sends the transactions when Anafi does not pay. |
| `adapter` | The Safe adapter. It must be `delegationAdapters.safe`. |
| `yaml` | The rule document. The commitment covers these exact bytes. See [documents](https://docs.ana.fi/sdk/documents.md). |
| `salt` | A random 32-byte hex value. It goes into the commitment `keccak256(salt ‖ yaml)`. Make a new salt for each document, for example `toHex(crypto.getRandomValues(new Uint8Array(32)))`. |
| `parent` | The registry identity that you built the document on: `readDslCommitment(safe)`, or `null` for the first document. The engine refuses a stale parent. |
| `write` | `arm` for the setup of the account. `update` for a new document over an adapter that the Safe has enabled. |
| `onProvisioned` | Called once after an `arm` provisions the Safe, with the block of the provision (or `null`), whether the stage then succeeds or not. |

### What `write` changes

| `write` | Safe with no code | Adapter not enabled | Adapter enabled |
| - | - | - | - |
| `arm` | The client provisions the Safe first (`provisionPredictedSafe`). | `enableAdapter: true`: the commit also enables the adapter. | `enableAdapter: false`. |
| `update` | The checks fail: the Safe is not admitted. | Throws `Error("Safe <safe> has not enabled adapter <adapter>")`. | `enableAdapter: false`. |

### Order of work

1. For `arm` of a Safe with no code: `provisionPredictedSafe`, then `onProvisioned`. The later checks read at or above the provision block.
2. These checks, and the seal of the document, run at the same time:
   * `adapter` must equal `delegationAdapters.safe`, else `Error("<adapter> is not this chain's configured Safe adapter")`.
   * The registry must list `adapter`, else `Error("<adapter> is not the live configured safe_module adapter")`.
   * The adapter must admit the Safe (code hash and singleton), else `Error("<safe> is not a Safe admitted by adapter <adapter>")`.
   * Threshold 1, and `eoa` is an owner (see [single-owner limits](#single-owner-limits)).
   * `isModuleEnabled(adapter)` decides `enableAdapter`.
   * The seal reads `engineEncKey()` and seals `0x02 ‖ adapter ‖ parent ‖ salt ‖ yaml` to the engine under `dslSealInfo(network, safe)`.
3. `POST /api/wallets/:safe/dsl/commit/stage` with `{ sealed }`.
4. The client checks the reply. The echoed adapter must equal `adapter`. The echoed commitment must equal `dslCommitment(salt, yaml)`. `attestationValidUntil` must be in the future and at most 3600 seconds away. Each failed check throws an `Error` that starts with `stageDsl:`.
5. The client opens the sealed warnings of the engine. If they cannot be opened, `warnings` is empty.

### Return value: `StagedSafeDsl`

```ts theme={null}
interface StagedSafeDsl {
  safe: Hex;
  eoa: Hex;
  adapter: Hex;
  yaml: string;
  salt: Hex;
  commitment: Hex;                         // keccak256(salt ‖ yaml)
  engineSig: Hex;                          // the engine signature over the commit attestation
  attestationValidUntilUnixSeconds: number; // the commit deadline
  enableAdapter: boolean;
  warnings: string[];                      // sanity findings of the engine, in its order
  minReadBlock: bigint | null;             // the provision block, or null
}
```

`warnings` holds findings that do not stop the commit, for example a rule that can never fire. Show them to the owner before the commit.

### Throws

| Error | When |
| - | - |
| `DslStaleParentError` | The registry no longer holds `parent`. `error.current` is the identity that the chain holds now. Rebuild the document on `current`, and stage again. |
| `NotificationEmailNotVerifiedError` | The document names a `global.notification_email` that is not the verified inbox of the account. |
| `DslStageRefusedError` | Any other refusal of the engine. `error.refusal` is the reason, for the author of the document. |
| `BackendRequestError` | Any other failed request. |
| `Error` | A failed check above, or a failed provision. |

Prompts: 0, or the prompt of the provision for `arm` of a Safe with no code when Anafi does not pay.

```ts theme={null}
import { toHex } from "viem";

const parent = await anafi.readDslCommitment(safe);
const staged = await anafi.stageDsl({
  safe,
  eoa: owner,
  adapter: config.delegationAdapters.safe!,
  yaml,
  salt: toHex(crypto.getRandomValues(new Uint8Array(32))),
  parent,
  write: parent === null ? "arm" : "update",
});
for (const warning of staged.warnings) console.warn(warning);
```

## `commitStagedDsl`

```ts theme={null}
commitStagedDsl(params: {
  staged: StagedSafeDsl;
  onStep?: (step: "safe") => void;
  onSigned?: () => void;
}): Promise<DslCommitSubmitResult>;

interface DslCommitSubmitResult {
  txHash: Hex;
  kind: "committed" | "inner_reverted";
  confirmedBlock: bigint | null;
}
```

Commits a staged document with one Safe transaction.

1. Throws `Error("commitStagedDsl: the engine's attestation over this staged document has lapsed; stage it again")` when `attestationValidUntilUnixSeconds` is now or earlier.
2. Builds the call `AnafiDslRegistry.commitDsl(commitment, validUntil, engineSig, adapter)`.
3. Reads the Safe `nonce()`, at or above `staged.minReadBlock`, and reads the sponsorship.
4. Builds the Safe transaction. With `enableAdapter: true`, it is a MultiSend `delegatecall` of 2 calls: `Safe.enableModule(adapter)`, then `commitDsl`. Else it is one plain call of `commitDsl`.
5. Calls `onStep("safe")` before the wallet prompt.
6. Relayed: the owner signs the `SafeTx`, then `onSigned()`, then `POST /api/wallets/:safe/safe/sponsor_exec`. Owner-sent: the owner sends `execTransaction`, and `onSigned()` runs when the wallet returns the hash.

| Field | Meaning |
| - | - |
| `kind` | `committed`: the Safe reports that its inner call succeeded. `inner_reverted`: the Safe transaction landed but its inner call failed, so nothing was committed. Stage again. |
| `confirmedBlock` | The receipt block. `null` when the receipt of a relayed transaction did not arrive in 60 seconds. |

The `commitDsl` call reverts when the attestation deadline passes before inclusion, or when another commit landed since the stage. See [the DSL registry](https://docs.ana.fi/contracts/dsl-registry.md).

```ts theme={null}
const result = await anafi.commitStagedDsl({
  staged,
  onStep: () => showStatus("Confirm in your wallet"),
  onSigned: () => showStatus("Sent"),
});
if (result.kind === "inner_reverted") showError("The commit failed in the Safe. Stage the document again.");
```

## `armSafe`

```ts theme={null}
armSafe(params: {
  safe: Hex;
  eoa: Hex;
  adapter: Hex;
  yaml: string;
  salt: Hex;
  parent: OnChainDsl | null;
  onStep?: (step: "safe") => void;
  onSigned?: () => void;
}): Promise<DslCommitSubmitResult>;
```

`stageDsl` with `write: "arm"`, then `commitStagedDsl`. Use it for the first document of an account. The warnings of the stage are not returned. To show them before the commit, call the two methods yourself.

Prompts in order, worst case (Anafi does not pay): 1 deploy transaction, then 1 `execTransaction`. Best case (Anafi pays): 1 typed-data signature.

## `commitDslFromSafe`

```ts theme={null}
commitDslFromSafe(params: {
  safe: Hex;
  eoa: Hex;
  adapter: Hex;
  yaml: string;
  salt: Hex;
  parent: OnChainDsl | null;
  onStep?: (step: "safe") => void;
  onSigned?: () => void;
}): Promise<DslCommitSubmitResult>;
```

`stageDsl` with `write: "update"`, then `commitStagedDsl`. The Safe must have enabled the adapter. Prompts: 1.

To pause all rules, commit a document with no rules (`rules: {}`). See [update, pause and revoke](https://docs.ana.fi/flows/update-pause-revoke.md).

## `readSafeModuleEnabled`

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

Reads `Safe.isModuleEnabled(adapter)`. With `options`, the read is pinned under the [retry rule](https://docs.ana.fi/sdk/reads.md#block-pinned-reads).

## `enableSafeModule`

```ts theme={null}
enableSafeModule(params: { safe: Hex; eoa: Hex; adapter: Hex }): Promise<SafeOwnerExecResult>;

interface SafeOwnerExecResult {
  txHash: Hex;
  success: boolean;               // the verdict of the Safe on its inner call
  confirmedBlock: bigint | null;
}
```

Enables the adapter as a module with one Safe transaction: `Safe.enableModule(adapter)`, sent to the Safe itself. It commits no document. Use it to restore the permission after a `disableSafeModule`, with the same committed document.

Checks: `adapter` is `delegationAdapters.safe`, the registry lists it, the adapter admits the Safe, threshold 1, and `eoa` is an owner. Prompts: 1.

## `disableSafeModule`

```ts theme={null}
disableSafeModule(params: { safe: Hex; eoa: Hex; adapter: Hex }): Promise<SafeOwnerExecResult>;
```

Revokes the permission: one Safe transaction that calls `Safe.disableModule(prevModule, adapter)`. After it lands, the adapter is no longer a module of the Safe. See [the Safe adapter](https://docs.ana.fi/contracts/safe-adapter.md).

1. Checks that `adapter` is `delegationAdapters.safe` and that the adapter admits the Safe. It does not need the adapter to be live for an owner-sent revoke.
2. Reads the sponsorship. If that read fails, the client chooses the owner-sent way, so the revoke does not depend on the Anafi API. It then reads the native balance of `eoa`:
   * If the balance read fails, it throws an `Error` that says so.
   * If the balance is 0, it throws `Error("This deployment could not say whether it pays for the revoke, and owner <eoa> holds no gas to send it. Use the self-funded path instead: disable the module from the Safe itself, for example in its own wallet UI.")`.
3. For a relayed revoke, the registry must list the adapter. Else it throws `Error("This deployment will not pay for the revoke because Safe adapter <adapter> is not live. Use the self-funded path instead: ...")`.
4. Checks threshold 1 and that `eoa` is an owner.
5. Reads the module list with `getModulesPaginated` (pages of 50, at most 20 pages) and finds the module before `adapter`. Throws `Error("<safe> does not have adapter <adapter> enabled")` when the adapter is not in the list.
6. Sends the Safe transaction.

Prompts: 1. You can also revoke without Anafi and without this SDK: call `disableModule` from the Safe in any Safe wallet.

```ts theme={null}
const revoked = await anafi.disableSafeModule({ safe, eoa: owner, adapter: config.delegationAdapters.safe! });
console.log(revoked.success, revoked.txHash);
```

## `executeSafeOwnerCalls`

```ts theme={null}
executeSafeOwnerCalls(params: {
  safe: Hex;
  eoa: Hex;
  legs: readonly SafeBatchLeg[];
  onSigned?: () => void;
  minReadBlock?: bigint | null;
  ownerSent?: boolean;
}): Promise<SafeOwnerExecResult>;

interface SafeBatchLeg {
  target: Hex;
  calldata: Hex;
}
```

Has the owner authorize your calls as one Safe transaction. One leg is a plain call. Two or more legs are a MultiSend batch of zero-value calls.

| Parameter | Meaning |
| - | - |
| `legs` | The calls. Throws `Error("a Safe owner operation needs at least one call")` when empty. |
| `onSigned` | Runs when the wallet answers its prompt. |
| `minReadBlock` | The block of an earlier write on the Safe, for example the provision. The owner checks and the nonce read happen at or above it. |
| `ownerSent` | `true`: the owner sends and pays, and the client reads no sponsorship and asks for no relay. Use it for any call that Anafi does not relay, for example a call to an adapter. |

The method resolves with the verdict of the Safe in `success`. It rejects on a reverted receipt of an owner-sent transaction. It does not check `adapter` or any other target: you are responsible for the calls.

```ts theme={null}
import { buildSafeEnableModuleLeg } from "@anafi-cc/anafi-sdk";

await anafi.executeSafeOwnerCalls({
  safe,
  eoa: owner,
  legs: [buildSafeEnableModuleLeg(safe, config.delegationAdapters.safe!)],
});
```

## `waitForRelayedTransaction`

```ts theme={null}
function waitForRelayedTransaction(publicClient: AnafiPublicClient, txHash: Hex): Promise<bigint | null>;
```

Waits up to 60 seconds for your RPC to return the receipt of a transaction that the relay reported. It returns the receipt block, or `null` when the receipt did not arrive or had no valid block. It never rejects. The relay can read a node that is ahead of yours, so a read right after its answer can miss the write. This wait closes that gap. The client calls it after each relayed write.

## Sponsorship

`fetchWalletSponsorship(aa)` returns `{ feesOn, sponsored }`. The client relays an owner operation of a Safe when `!feesOn || sponsored`. See [activity and fees](https://docs.ana.fi/sdk/activity-and-fees.md#fetchwalletsponsorship).


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