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

# The client

> Create an Anafi client with createAnafiClient, fill each field of its config, and connect your viem public and wallet clients.

After you read this page, you can create a client for `polygon-amoy` or `polygon`, give it the right addresses and tokens, and connect a wallet that the client can use.

## `createAnafiClient`

```ts theme={null}
function createAnafiClient(cfg: AnafiClientConfig): AnafiClient;
```

`createAnafiClient` returns a client bound to one chain. It does no I/O. It checks one thing: `network` must be one of `NETWORKS`, and `NETWORK_CHAIN_IDS[network]` must equal `chainId`. If not, it throws an `Error`:

```text theme={null}
network must be one of anvil, ethereum-sepolia, ethereum, xlayer, xlayer-testnet, polygon, polygon-amoy, got "x-layer"
network polygon is chain 137, not the configured chainId 80002
```

The client does not check the other fields at creation. A wrong address shows up later as a refusal or a failed read. Use the addresses on this page or on [deployments](https://docs.ana.fi/contracts/deployments.md).

> [!WARNING]
>
> Call the Anafi API from a server, a script, or your own same-origin proxy. The Anafi API hosts answer CORS (`Access-Control-Allow-Origin`) only for `https://app.ana.fi` today. A browser page on another origin cannot call the API directly. Chain reads and owner-sent transactions do not go through the API, and this limit does not affect them.

## `AnafiClientConfig`

```ts theme={null}
interface AnafiClientConfig {
  backendUrl: string;
  chainId: number;
  network: Network;
  siweDomain?: string;
  addresses: AnafiClientAddresses;
  delegationAdapters: DelegationAdapters;
  native: RoutingToken;
  erc20s: readonly Erc20Token[];
  publicClient: AnafiPublicClient;
  walletClient: AnafiWalletClient;
  fetchImpl?: typeof fetch;
}
```

| Field | Type | Required | Meaning |
| - | - | - | - |
| `backendUrl` | `string` | yes | The base URL of the Anafi API for this network, with no final `/`. The client appends paths such as `/api/fees`. Production hosts are `https://api.polygon.ana.fi`, `https://api.xlayer.ana.fi` and `https://api.polygon-amoy.ana.fi`. A relative URL of your own same-origin proxy also works in a browser. |
| `chainId` | `number` | yes | The EVM chain id. It must equal `NETWORK_CHAIN_IDS[network]`. The client also puts it in each sign-in message, in the Safe EIP-712 domain, and in the wallet chain check of the payment methods. |
| `network` | `Network` | yes | The network token, for example `"polygon-amoy"`. The seal of a rule document binds this token. A wrong token gives an envelope that no engine can open. |
| `siweDomain` | `string` | no | The domain that each sign-in message names. The default is `window.location.host`. In Node.js you must set it, because Node.js has no `window`. See [sign-in limits](#sign-in-limits). |
| `addresses` | `AnafiClientAddresses` | yes | The registry addresses, and the Safe framework addresses for the Safe leg. |
| `delegationAdapters` | `DelegationAdapters` | yes | The adapter of each account kind on this network. Leave a row out to switch off that leg in this client. |
| `native` | `RoutingToken` | yes | The native coin of the chain: `"POL"` on `polygon` and `polygon-amoy`, `"OKB"` on `xlayer`. An ERC20Allow document cannot send, sell or buy it. |
| `erc20s` | `readonly Erc20Token[]` | yes | The ERC-20 table of the chain: each symbol that a document can name, with its contract. The ERC20Allow leg maps the tokens of a document to contracts through this table. `revokeErc20Allowances` revokes every token of this table. |
| `publicClient` | `AnafiPublicClient` | yes | Your viem public client for this chain. Every chain read goes through it. |
| `walletClient` | `AnafiWalletClient` | yes | The wallet of the owner. Every signature and every owner transaction goes through it. |
| `fetchImpl` | `typeof fetch` | no | The `fetch` that the client uses for the Anafi API. The default is the global `fetch`. |

### `AnafiClientAddresses`

```ts theme={null}
interface AnafiClientAddresses {
  anafiRegistry: Hex;
  dslRegistry: Hex;
  safe?: SafeLegAddresses;
}

interface SafeLegAddresses {
  singleton: Hex;
  singletonL2: Hex;
  toL2Setup: Hex;
  proxyFactory: Hex;
  multiSend: Hex;
}
```

| Field | Meaning |
| - | - |
| `anafiRegistry` | `AnafiRegistry`. The client reads `engineEncKey()`, `engineSigKey()` and `delegationAdapters()` from it. See [the registry](https://docs.ana.fi/contracts/registry.md). |
| `dslRegistry` | `AnafiDslRegistry`. The client reads `commitments(aa)` and sends `commitDsl(...)` to it. See [the DSL registry](https://docs.ana.fi/contracts/dsl-registry.md). |
| `safe.singleton` | The base Safe singleton that a provisioned Safe is created against. |
| `safe.singletonL2` | The `SafeL2` singleton that a provisioned Safe runs on, on every chain except chain id 1. |
| `safe.toL2Setup` | The `SafeToL2Setup` contract. The `setup` of a provisioned Safe calls it with `delegatecall` to move the Safe to `singletonL2`. |
| `safe.proxyFactory` | `SafeProxyFactory`. The client reads `proxyCreationCode()` from it and calls `createProxyWithNonce` on it. |
| `safe.multiSend` | `MultiSend`. A Safe transaction with 2 or more calls runs through it. |

`safe` is optional. Without it, `predictSafe`, `provisionPredictedSafe`, an `arm` of a Safe with no code, a commit that enables the adapter, and a call to `executeSafeOwnerCalls` with 2 or more calls throw `Error("this deployment configures no Safe singleton, proxy factory or MultiSend")`. All three networks use the same Safe v1.5.0 framework addresses.

### `DelegationAdapters`

```ts theme={null}
interface DelegationAdapters {
  safe?: Hex;        // the adapter of the safe_module kind
  erc20_allow?: Hex; // the adapter of the erc20_allow kind
}
```

The client checks each adapter that you pass to a method against this table. A Safe method refuses an adapter that is not `delegationAdapters.safe`. An ERC20Allow method refuses an adapter that is not `delegationAdapters.erc20_allow`. Many methods also read `AnafiRegistry.delegationAdapters()` to check that the registry still lists the adapter ("live").

## The viem clients

### `AnafiPublicClient`

```ts theme={null}
interface AnafiPublicClient extends AdapterPublicClient {
  waitForTransactionReceipt(args: {
    hash: Hex;
    timeout?: number;
    checkReplacement?: boolean;
    onReplaced?: (replacement: unknown) => void;
  }): Promise<unknown>;
  getBalance(args: { address: Hex }): Promise<bigint>;
  getTransactionReceipt?(args: { hash: Hex }): Promise<unknown>;
  getTransaction?(args: { hash: Hex }): Promise<unknown>;
  getLogs?(args: {
    address: Hex;
    event: typeof ERC20_TRANSFER_EVENT_ABI;
    args: { from: Hex; to: Hex };
    fromBlock: bigint;
    toBlock: bigint;
  }): Promise<unknown[]>;
}

interface AdapterPublicClient {
  readContract(args: {
    address: Hex;
    abi: readonly unknown[];
    functionName: string;
    args?: readonly unknown[];
    blockNumber?: bigint;
  }): Promise<unknown>;
  getCode(args: { address: Hex; blockNumber?: bigint }): Promise<Hex | null | undefined>;
  getBlockNumber(args?: { cacheTime?: number }): Promise<bigint>;
}
```

A viem `PublicClient` from `createPublicClient` has every method. The table says which methods need the optional ones.

| Method of the public client | Used by |
| - | - |
| `readContract`, `getCode`, `getBlockNumber` | every read |
| `waitForTransactionReceipt` | every write. An owner-sent transaction waits up to 180 seconds. A relayed transaction waits up to 60 seconds. |
| `getBalance` | `disableSafeModule`, when the sponsorship read fails |
| `getTransactionReceipt` | `readErc20PaymentTransactionState`, and the payment proof of `setUpErc20AllowSubscriptionInBatch` and `readErc20AllowSubscriptionBatchResult` |
| `getTransaction` | `readErc20PaymentTransactionState` |
| `getLogs` | `scanErc20PaymentTransfers` |

A method that needs an absent optional method throws an `Error` that says so.

### `AnafiWalletClient`

```ts theme={null}
interface AnafiWalletClient {
  signTypedData(data: unknown): Promise<Hex>;
  signMessage(args: { account: Hex; message: string }): Promise<Hex>;
  sendTransaction(args: { account: Hex; to: Hex; data: Hex }, options?: { signal?: AbortSignal }): Promise<Hex>;
  getAddresses?(): Promise<Hex[]>;
  getChainId?(): Promise<number>;
  getCapabilities?(args: { account: Hex; chainId: number }): Promise<unknown>;
  sendCalls?(
    args: { account: Hex; calls: readonly { to: Hex; data: Hex }[]; id: string; forceAtomic: true },
    options?: { signal?: AbortSignal },
  ): Promise<unknown>;
  getCallsStatus?(args: { id: string }): Promise<unknown>;
}
```

| Method of the wallet client | What the client sends | Used by |
| - | - | - |
| `signTypedData` | The EIP-712 `SafeTx` of `safeTxTypedData`, with no `account` field | every relayed Safe operation |
| `signMessage` | An EIP-4361 sign-in text, with `account` set to the owner | `recover`, `requestNotificationEmailCode` |
| `sendTransaction` | `{ account, to, data }` with no value. The second argument carries `{ signal }` only for the payment methods. | every owner-sent operation |
| `getAddresses`, `getChainId` | none | `sendErc20Payment`, `setUpErc20AllowSubscription`, `setUpErc20AllowSubscriptionInBatch`. These methods check that the wallet is on `chainId` and that its first address is the payer. |
| `getCapabilities` | `{ account, chainId }` | `readWalletAtomicBatchSupport` |
| `sendCalls`, `getCallsStatus` | an EIP-5792 batch with `forceAtomic: true` | `setUpErc20AllowSubscriptionInBatch`, `readErc20AllowSubscriptionBatchResult` |

`signTypedData` gets no `account` field. Your wallet client must know the owner account. With viem, create the wallet client with `account` set:

* For a browser wallet (EIP-1193), pass the owner address as `account`. viem sends each request to the wallet.
* For a local private key, wrap the viem client. The SDK passes `account` as an address string. viem treats an address string as a JSON-RPC account and asks the RPC node to sign, and a public node cannot sign. The wrapper below drops that field, so viem signs with the local key.

A wallet client may throw `OwnerRequestCancelledError` when it sees the `signal` of a payment method abort before it asks the wallet. The payment methods then answer `stopped_before_request`. See [payments](https://docs.ana.fi/sdk/payments.md).

## Complete config for `polygon-amoy`

This script runs in Node.js with a local test key. All addresses come from the `polygon-amoy` deployment.

> [!WARNING]
>
> Use a test key only. Never put a key that holds real funds in a script or an environment variable.

```ts theme={null}
import { createAnafiClient, type AnafiWalletClient, type Hex } from "@anafi-cc/anafi-sdk";
import { createPublicClient, createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { polygonAmoy } from "viem/chains";

const owner = privateKeyToAccount(process.env.ANAFI_TEST_KEY as Hex);
const viemWallet = createWalletClient({ account: owner, chain: polygonAmoy, transport: http() });

// The SDK passes the owner address as `account`. A local account signs only
// when viem gets no `account` field, so this wrapper drops it.
const walletClient: AnafiWalletClient = {
  signTypedData: (data) => viemWallet.signTypedData(data as Parameters<typeof viemWallet.signTypedData>[0]),
  signMessage: ({ message }) => viemWallet.signMessage({ message }),
  sendTransaction: ({ to, data }) => viemWallet.sendTransaction({ to, data }),
  getAddresses: async () => [owner.address],
  getChainId: async () => polygonAmoy.id,
};

export const anafi = createAnafiClient({
  chainId: 80002,
  network: "polygon-amoy",
  backendUrl: "https://api.polygon-amoy.ana.fi",
  addresses: {
    anafiRegistry: "0x100B1e2d05dac3DdF6774b6668BCE07c9BEc8018",
    dslRegistry: "0xa60904ABC7e96B06005234EACF02217afA02d5C3",
    safe: {
      singleton: "0xFf51A5898e281Db6DfC7855790607438dF2ca44b",
      singletonL2: "0xEdd160fEBBD92E350D4D398fb636302fccd67C7e",
      toL2Setup: "0x900C7589200010D6C6eCaaE5B06EBe653bc2D82a",
      proxyFactory: "0x14F2982D601c9458F93bd70B218933A6f8165e7b",
      multiSend: "0x218543288004CD07832472D464648173c77D7eB7",
    },
  },
  delegationAdapters: {
    safe: "0x425FE0A554299D33589edc51387254175478Ee0e",
    erc20_allow: "0x3C58b31704Bbb13D32b38FFf1427799D6ce900e7",
  },
  native: "POL",
  erc20s: [
    { symbol: "USDC", address: "0x41E94Eb019C0762f9Bfcf9Fb1E58725BfB0e7582" },
    { symbol: "EURe", address: "0xeD5D0B6C5BEFfDd607639094397C223536B0Bae7" },
  ],
  publicClient: createPublicClient({ chain: polygonAmoy, transport: http() }),
  walletClient,
});

console.log(await anafi.predictSafe(owner.address));
```

This script sets no `siweDomain`, so a call of `recover` or `requestNotificationEmailCode` from it throws. Read [sign-in limits](#sign-in-limits) before you use these two methods.

## Complete config for `polygon`

This config uses a browser wallet. In a browser on your own origin, set `backendUrl` to your own same-origin proxy of the Anafi API, because of the CORS limit above. The chain reads and the owner-sent transactions go from the page to the chain directly.

```ts theme={null}
import { createAnafiClient, type Hex } from "@anafi-cc/anafi-sdk";
import { createPublicClient, createWalletClient, custom, http, type EIP1193Provider } from "viem";
import { polygon } from "viem/chains";

declare const provider: EIP1193Provider; // for example window.ethereum
const [owner] = (await provider.request({ method: "eth_requestAccounts" })) as Hex[];

const anafi = createAnafiClient({
  chainId: 137,
  network: "polygon",
  backendUrl: "https://api.polygon.ana.fi", // or the path of your same-origin proxy
  addresses: {
    anafiRegistry: "0x943Fb1925acc758c87F7672eCAF7041b25DE8506",
    dslRegistry: "0xadAC71d7060d99E530a52f61599Abb653dc349F4",
    safe: {
      singleton: "0xFf51A5898e281Db6DfC7855790607438dF2ca44b",
      singletonL2: "0xEdd160fEBBD92E350D4D398fb636302fccd67C7e",
      toL2Setup: "0x900C7589200010D6C6eCaaE5B06EBe653bc2D82a",
      proxyFactory: "0x14F2982D601c9458F93bd70B218933A6f8165e7b",
      multiSend: "0x218543288004CD07832472D464648173c77D7eB7",
    },
  },
  delegationAdapters: {
    safe: "0xA5E5cE761CD9a5E49be6adD95d1b67d57cb23D78",
    erc20_allow: "0x1A8368bD76eb24CfC3bF5E483be0e3390728484d",
  },
  native: "POL",
  erc20s: [
    { symbol: "USDC", address: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359" },
    { symbol: "USDC.e", address: "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174" },
    { symbol: "USDT0", address: "0xc2132D05D31c914a87C6611C10748AEb04B58e8F" },
    { symbol: "WETH", address: "0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619" },
    { symbol: "WBTC", address: "0x1BFD67037B42Cf73acF2047067bd4F2C47D9BfD6" },
    { symbol: "LINK", address: "0x53E0bca35eC356BD5ddDFebbD1Fc0fD03FaBad39" },
    { symbol: "AAVE", address: "0xD6DF932A45C0f255f85145f286eA0b292B21C90B" },
    { symbol: "EURe", address: "0xE0aEa583266584DafBB3f9C3211d5588c73fEa8d" },
  ],
  publicClient: createPublicClient({ chain: polygon, transport: http() }),
  walletClient: createWalletClient({ account: owner, chain: polygon, transport: custom(provider) }),
});
```

On `polygon`, `USDC` is the native Circle contract and `USDC.e` is the older bridged one. They are two tokens, and a rule never mixes them. For the token table of every network, see [networks](https://docs.ana.fi/networks.md).

### Addresses per network

| Field | `polygon` (137) | `polygon-amoy` (80002) | `xlayer` (196) |
| - | - | - | - |
| `addresses.anafiRegistry` | `0x943Fb1925acc758c87F7672eCAF7041b25DE8506` | `0x100B1e2d05dac3DdF6774b6668BCE07c9BEc8018` | `0xe4Fe05AbAe4e3bC6a6f2256A6383114e6fbc1BF8` |
| `addresses.dslRegistry` | `0xadAC71d7060d99E530a52f61599Abb653dc349F4` | `0xa60904ABC7e96B06005234EACF02217afA02d5C3` | `0x2ec9910e7BEBaa23B3622E9E08C6bffD057BA5C6` |
| `delegationAdapters.safe` | `0xA5E5cE761CD9a5E49be6adD95d1b67d57cb23D78` | `0x425FE0A554299D33589edc51387254175478Ee0e` | `0xe1379422D97a017e9BB19A5045ac937086075F8F` |
| `delegationAdapters.erc20_allow` | `0x1A8368bD76eb24CfC3bF5E483be0e3390728484d` | `0x3C58b31704Bbb13D32b38FFf1427799D6ce900e7` | `0xc9e5D2f9CD199e324aC9035aab922da6bF03f4f1` |
| `native` | `"POL"` | `"POL"` | `"OKB"` |
| `addresses.safe` | Safe v1.5.0, the values above | the same | the same |

These are the deployed values when this page was written. The registry can list a new adapter later. Read `readLiveDelegationAdapters()` to see the live list, and see [deployments](https://docs.ana.fi/contracts/deployments.md).

## Sign-in limits

The two sign-in (EIP-4361) flows, `recover` and the notification-email code request (`requestNotificationEmailCode`), are accepted only when the sign-in message names the domain of the Anafi dapp, `app.ana.fi`. The Anafi API refuses a sign-in for another domain with status `422`. An integration on another domain cannot complete these two flows today.

## Network and token vocabulary

### `Hex`

```ts theme={null}
type Hex = `0x${string}`;
```

### `NETWORK_CHAIN_IDS`, `Network`, `NETWORKS`

```ts theme={null}
const NETWORK_CHAIN_IDS = {
  anvil: 31337,
  "ethereum-sepolia": 11155111,
  ethereum: 1,
  xlayer: 196,
  "xlayer-testnet": 1952,
  polygon: 137,
  "polygon-amoy": 80002,
} as const;

type Network = keyof typeof NETWORK_CHAIN_IDS;
const NETWORKS: readonly Network[]; // the keys above, in this order
```

The type names every network token that the SDK knows. Anafi has a deployment only on `polygon`, `xlayer` and `polygon-amoy`. The other tokens name no deployment of Anafi. See [networks](https://docs.ana.fi/networks.md).

### `RoutingToken`, `ROUTING_TOKENS`, `TOKEN_DECIMALS`

```ts theme={null}
type RoutingToken =
  | "ETH" | "WBTC" | "xSOL" | "USDC" | "USDT" | "OKB" | "LINK" | "USDe" | "USDG" | "PYUSD"
  | "sUSDe" | "rsETH" | "uniBTC" | "frxUSD" | "POL" | "AAVE" | "USDC.e" | "USDT0" | "WETH"
  | "xETH" | "xBTC" | "wSPYx" | "wNVDAx" | "PAXGy" | "EURe";

const ROUTING_TOKENS: readonly RoutingToken[]; // every value above, as an array
const TOKEN_DECIMALS: Record<RoutingToken, number>;
```

`RoutingToken` is the set of token symbols that the SDK can write in a rule document. The spelling is exact and case-sensitive: `USDC.e` is bridged USDC, `USDT0` is the ASCII name of the `USD₮0` contract, and `ETH`, `WETH` and `xETH` are three different assets. The type does not say which token a network has. Use `erc20s` and `native` for that.

| Decimals | Symbols |
| - | - |
| 18 | `ETH`, `WETH`, `xETH`, `OKB`, `POL`, `LINK`, `USDe`, `sUSDe`, `rsETH`, `frxUSD`, `AAVE`, `wSPYx`, `wNVDAx`, `PAXGy`, `EURe` |
| 9 | `xSOL` |
| 8 | `WBTC`, `xBTC`, `uniBTC` |
| 6 | `USDC`, `USDC.e`, `USDT`, `USDT0`, `USDG`, `PYUSD` |

### `Erc20Token`

```ts theme={null}
interface Erc20Token {
  symbol: RoutingToken;
  address: Hex;
}
```

One row of the `erc20s` table: the symbol that a document names, and its contract.

### `OnChainDsl`

```ts theme={null}
interface OnChainDsl {
  hash: Hex;      // the commitment of the committed document
  version: number; // the registry version, 1 or more; it rises by 1 per commit
}
```

The identity of the committed document of an account, as `AnafiDslRegistry.commitments(aa)` holds it. The registry pair for "nothing committed" (version 0, zero hash) is never an `OnChainDsl`. Each reader maps it to `null`. You pass an `OnChainDsl` as the `parent` of a stage.

### `OnChainDslAtBlock`

```ts theme={null}
interface OnChainDslAtBlock {
  dsl: OnChainDsl | null;
  block: bigint;
}
```

A registry identity together with the block that it was read at. No client method returns it. Use it to keep a read of `readDslCommitmentAtBlock` together with its block.

### `AccountKind`

```ts theme={null}
type AccountKind = "safe_module" | "erc20_allow";
```

| Value | Account | Adapter row |
| - | - | - |
| `safe_module` | A Safe that enables the Safe adapter as a module | `delegationAdapters.safe` |
| `erc20_allow` | A plain address (no code, or an EIP-7702 pointer) that approves ERC-20 allowances to the ERC20Allow adapter | `delegationAdapters.erc20_allow` |

See [accounts](https://docs.ana.fi/concepts/accounts.md).

### Other token constants

| Export | Value | Meaning |
| - | - | - |
| `ANY_WATCHED_TOKEN` | `"any"` | The answer of `watchedTokenOf` for an `incoming_tx` trigger with no range. Such a trigger watches the native coin and every registered token. |
| `WatchedAsset` | `RoutingToken` or `"any"` | The asset that a trigger watches. |
| `OFF_RAMP_PROVIDER` | `"monerium"` | The provider that an `off_ramp` action names. |
| `OFF_RAMP_TOKEN` | `"EURe"` | The token that an `off_ramp` action pays out. |
| `SWAP_PIVOT_TOKEN` | `"USDG"` | The quote token of the swap forms on `xlayer`. |

## `AnafiClient`

`AnafiClient` is the interface of the object that `createAnafiClient` returns. The [overview](https://docs.ana.fi/sdk/overview.md#client-methods) lists every method with a link to its entry.


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