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

# Update, pause, revoke

> Replace a committed rule document, stop payments for a time, and remove the permission, with or without Anafi.

After this page, you can replace the rule document of an account, resolve a stale parent, stop payments, and remove the permission of the adapter. You also know what the activity feed and the read-back show for a payment that is in flight at that time.

## Replace the rule document

A commit replaces the whole document. To change one rule, change it inside the full document and commit the full document again. `splitDocument` and `assembleDocument` take a document apart by rule and put it together again. See [Documents](https://docs.ana.fi/sdk/documents.md).

### The parent identity

The DSL registry holds, for each account, the pair `commitments(account) = (hash, version)`. `version` is 0 before the first commit and goes up by 1 at each commit. The SDK reads the pair as an `OnChainDsl` (`{ hash, version }`), or `null` for version 0.

Each stage names the identity that the new document was built on: the `parent`. The engine refuses the stage when the chain no longer holds that parent. The attestation of the engine also binds the next version, so a commit that lands between your stage and your commit makes your attestation invalid on chain.

```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: AnafiDslRegistry.commitments(account) = parent
    A->>API: POST /api/wallets/{account}/dsl/commit/stage (parent inside the sealed request)
    API->>E: Relay
    alt Parent is current
        E-->>A: commitment, engineSig, deadline
        W->>C: commitDsl (Safe transaction, or plain transaction)
    else Another commit landed
        E-->>A: 409, sealed refusal with current_document
        A->>A: DslStaleParentError(current)
    end
```

### Steps

**1. Read the parent**

`const parent = await anafi.readDslCommitment(account)`. Get the plaintext of that document from your own store, or with [`recover`](https://docs.ana.fi/flows/read-back).

**2. Stage the new document**

* Safe: `stageDsl({ ..., parent, write: "update" })`. `update` requires the module to be enabled already, else the SDK throws `Safe ... has not enabled adapter ...`. `write: "arm"` also works on an armed Safe: it then enables nothing.
* ERC20Allow: `stageErc20AllowDsl({ ..., parent })`. There is no `write` field. A new token in the document adds an approval prompt at the commit.

Use a new salt for each commit. The same salt and the same text give the same commitment, which links the two commits.

**3. Commit**

* Safe: `commitStagedDsl({ staged })`, one prompt. Or call `commitDslFromSafe(...)` for the stage and the commit in one call.
* ERC20Allow: `commitStagedErc20AllowDsl({ staged })`.

### Stale parent: `409` and how to rebase

| Signal | Where | What it means |
| - | - | - |
| `DslStaleParentError` | stage, HTTP `409` | The chain holds another document. `error.current` is `{ hash, version }` of the chain, or `null` when nothing is committed. |
| `InvalidEngineSignature()` | `commitDsl` reverts | A commit landed after your stage. |
| `commitments(account)` changed | your own read | Another app, tab or device committed. |

To rebase:

1. Read the document that the chain holds now: compare `error.current.hash` with the commitment of a document that you stored, or read it with `recover`.
2. Apply your change again on top of that document. Do not overwrite the newer document with your old copy.
3. Stage with `parent: error.current` and a new salt.
4. Commit.

## Pause

| Way | Kind | Effect | Calls |
| - | - | - | - |
| `enabled: false` on a rule | both | The rule stays in the document and does not fire. | stage and commit a new document |
| `rules: {}` | both | The engine runs no rule. The permission stays. | stage and commit a new document |
| `expiry` and `start` on a rule | both | The rule fires only inside the window. | stage and commit a new document |
| Block switch | ERC20Allow | The adapter refuses each pull of each token. The document and the allowances stay. | `setErc20AllowBlocked({ account, adapter, blocked: true })`, one transaction `setBlocked(true)` |
| Cap | ERC20Allow | Limits the amount in each window. | `setErc20AllowCaps`, `clearErc20AllowCaps` |

The block switch acts on chain at once and does not need the engine. `setBlocked(false)` ends the block on chain. When the engine sees the block, or a cap with no room, it parks the account, so commit the document again after you clear the cause. See the parked reasons in [Read-back](https://docs.ana.fi/flows/read-back.md#parked-reasons). See [Rule language: document](https://docs.ana.fi/rules/document.md) for `enabled`, `start` and `expiry`.

## Revoke

### Safe

`disableSafeModule({ safe, eoa, adapter })`:

1. Checks that `adapter` is the Safe adapter of the config and that it admits the Safe. It does not require the adapter to be listed in the registry for an owner-sent revoke.
2. Reads `GET /api/wallets/{safe}/sponsorship`. When the read fails, it selects the owner-sent path, and refuses only when the owner address holds no gas.
3. For a relayed revoke, requires the adapter to be listed in the registry, else it throws and names the owner-sent path.
4. Checks threshold 1 and the owner.
5. Reads the module list with `getModulesPaginated` and finds the module before the adapter in the list (`0x0000000000000000000000000000000000000001` when the adapter is first). It throws when the adapter is not enabled.
6. Builds `Safe.disableModule(prevModule, adapter)` and lands it as one Safe transaction: an EIP-712 `SafeTx` prompt with `POST /api/wallets/{safe}/safe/sponsor_exec`, or one transaction prompt from the owner address.

The result is `{ txHash, success, confirmedBlock }`. `success: false` means the Safe refused the transaction, and the module is still enabled.

### ERC20Allow

`revokeErc20Allowances({ account, adapter, onStep?, onConfirmed? })`:

1. Reads, at one tip block, the allowance to the adapter of each token in the `erc20s` table of the config.
2. Sends `token.approve(adapter, 0)` for each token with an allowance above 0, in table order. Each is one transaction prompt. Each waits for its receipt.

It uses no Anafi API. With no allowance to remove, it sends nothing and `txHashes` is empty. A token that is not in your `erc20s` table is not covered: remove that allowance with a plain `approve(adapter, 0)`.

For a stop in one transaction, call `setErc20AllowBlocked({ ..., blocked: true })`. It keeps the allowances.

### Revoke without Anafi

The owner can revoke from any wallet, with no Anafi service. These are plain contract calls.

| Kind | Call | Notes |
| - | - | - |
| Safe | `Safe.disableModule(prevModule, adapter)`, sent through the Safe (`execTransaction`) by its owners | Find `prevModule` with `getModulesPaginated(0x0000000000000000000000000000000000000001, n)`. Any Safe interface that can disable a module works. |
| ERC20Allow | `token.approve(adapter, 0)` for each token | From the account itself. |
| ERC20Allow | `AnafiDelegationAdapterERC20Allow.setBlocked(true)` | From the account itself. Stops each pull of each token. |

## Payments in flight

A payment that the engine signed before your change carries a firing nonce and a deadline, `validUntil`. See [Redeem](https://docs.ana.fi/contracts/redeem.md) for what the contracts do with such a payment after each change, and [Redeem: nonce and deadline](https://docs.ana.fi/contracts/redeem.md#nonce-and-deadline) for the deadline.

What the public statuses show:

| Value | Where | Meaning |
| - | - | - |
| `withdrawn` | activity `status` | The engine closed the payment: a new document removed its rule, or the account was parked. |
| `grant_inactive_pending` | activity `waitReason` | The Safe module reads as disabled. The payment waits. |
| `grant_inactive` | activity `failureReason` | The payment closed because the module was disabled. Nothing was paid. |
| `adapter_delisted_pending` | activity `waitReason` | The registry does not list the adapter now. The payment waits. |
| `parked` with `safe_module_disabled`, `erc20_allow_delegation_blocked`, `erc20_allow_allowance_revoked`, `erc20_allow_allowance_too_low`, `erc20_allow_cap_exhausted`, `erc20_allow_cap_exceeded` | `recover` → `tenant` | The engine stopped the account and names the cause. |

To start again after a revoke, grant the permission and commit a document. For a Safe, `stageDsl` with `write: "arm"` does both in one transaction. See [Activity](https://docs.ana.fi/concepts/activity.md) and [Read-back](https://docs.ana.fi/flows/read-back.md).

## Example

This example uses the client of the [Quickstart](https://docs.ana.fi/quickstart.md).

```ts theme={null}
import {
  DslStaleParentError,
  type AnafiClient,
  type Hex,
  type OnChainDsl,
} from "@anafi-cc/anafi-sdk";
import { bytesToHex, encodeFunctionData, erc20Abi, type WalletClient } from "viem";

const newSalt = () => bytesToHex(crypto.getRandomValues(new Uint8Array(32)));

// Replace the document of an ERC20Allow account. `rebuild` applies your change
// on top of the document that the chain holds (null: no document yet).
export async function updateErc20Allow(
  anafi: AnafiClient,
  account: Hex,
  adapter: Hex,
  rebuild: (parent: OnChainDsl | null) => Promise<string>,
) {
  let parent = await anafi.readDslCommitment(account);
  for (let attempt = 0; attempt < 3; attempt++) {
    try {
      const staged = await anafi.stageErc20AllowDsl({
        account,
        adapter,
        yaml: await rebuild(parent),
        salt: newSalt(),
        parent,
      });
      return await anafi.commitStagedErc20AllowDsl({ staged });
    } catch (error) {
      if (!(error instanceof DslStaleParentError)) throw error;
      parent = error.current; // rebase on the document that the chain holds
    }
  }
  throw new Error("the document changed three times; try again later");
}

// Revoke with the SDK.
export async function revoke(anafi: AnafiClient, kind: "safe" | "erc20", account: Hex, eoa: Hex, adapter: Hex) {
  if (kind === "safe") {
    const result = await anafi.disableSafeModule({ safe: account, eoa, adapter });
    if (!result.success) throw new Error(`the Safe refused ${result.txHash}`);
    return [result.txHash];
  }
  return (await anafi.revokeErc20Allowances({ account, adapter })).txHashes;
}

// Revoke one token allowance with viem only, from the account itself.
export async function revokeWithoutAnafi(wallet: WalletClient, token: Hex, adapter: Hex) {
  const [account] = await wallet.getAddresses();
  return wallet.sendTransaction({
    account,
    chain: wallet.chain,
    to: token,
    data: encodeFunctionData({ abi: erc20Abi, functionName: "approve", args: [adapter, 0n] }),
  });
}
```


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