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

# Low-level helpers

> Calldata builders, Safe typed data and digests, ABI fragments, address prediction and the stage payload framing, for a caller that needs less than the client.

After you read this page, you can build each transaction and each signed payload of Anafi yourself, for example on a server, in a test, or in a wallet of your own.

These are pure functions with no I/O, unless an entry says otherwise. The client uses each of them. Each calldata builder gives the same bytes as the client.

## ABI fragments

Each constant is a viem ABI (`parseAbi`), for `readContract`, `encodeFunctionData` and `decodeEventLog`.

| Export | Functions and events |
| - | - |
| `ANAFI_REGISTRY_ABI` | `engineEncKey() view returns (bytes32)`, `engineSigKey() view returns (address)`, `delegationAdapters() view returns (address[])` |
| `ANAFI_DSL_REGISTRY_ABI` | `commitDsl(bytes32 hash, uint256 validUntil, bytes engineSig, address adapter)`, `commitments(address aa) view returns (bytes32 hash, uint64 version)` |
| `SAFE_ABI` | `setup(...)`, `execTransaction(...) payable returns (bool success)`, `enableModule(address)`, `disableModule(address prevModule, address module)`, `isModuleEnabled(address) view returns (bool)`, `getModulesPaginated(address start, uint256 pageSize) view returns (address[] array, address next)`, `isOwner(address) view returns (bool)`, `getThreshold() view returns (uint256)`, `masterCopy() view returns (address)`, `nonce() view returns (uint256)` |
| `SAFE_PROXY_FACTORY_ABI` | `proxyCreationCode() view returns (bytes)`, `createProxyWithNonce(address singleton, bytes initializer, uint256 saltNonce) returns (address proxy)` |
| `SAFE_TO_L2_SETUP_ABI` | `setupToL2(address l2Singleton)` |
| `SAFE_MULTI_SEND_ABI` | `multiSend(bytes transactions) payable` |
| `ANAFI_SAFE_ADAPTER_ABI` | `admittedSafeProxyCodehashes(bytes32 codehash) view returns (bool)`, `admittedSafeSingletons(address singleton) view returns (bool)` |
| `ANAFI_ERC20_ALLOW_ADAPTER_ABI` | `setBlocked(bool blocked)`, `setCaps((address token, uint256 limit, uint32 periodSeconds)[] entries)`, `clearCaps(address[] tokens)`, `isBlocked(address account) view returns (bool)`, `capOf(address account, address token) view returns (bool isSet, uint256 limit, uint32 periodSeconds, uint256 spentInPeriod)`, `swapExecutor() view returns (address)` |
| `ANAFI_GAS_CREDIT_ABI` | `gasCredit(address payee, address token) view returns (uint256)`, `claimGasCredit(address token, address to)` |
| `ERC20_APPROVAL_ABI` | `approve(address spender, uint256 amount) returns (bool)`, `allowance(address owner, address spender) view returns (uint256)` |
| `ERC20_TRANSFER_ABI` | `transfer(address to, uint256 amount) returns (bool)`, `event Transfer(address indexed from, address indexed to, uint256 value)` |
| `ERC20_TRANSFER_EVENT_ABI` | the `Transfer` event alone (`parseAbiItem`), for `getLogs` |

These fragments hold only what the SDK uses. For the full interface of each contract, see the [contracts](https://docs.ana.fi/contracts/overview.md).

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

const [hash, version] = await publicClient.readContract({
  address: "0xa60904ABC7e96B06005234EACF02217afA02d5C3",
  abi: ANAFI_DSL_REGISTRY_ABI,
  functionName: "commitments",
  args: [account],
});
```

## DSL registry

### `buildDslCommitCalldata`

```ts theme={null}
function buildDslCommitCalldata(params: {
  adapter: Hex;
  commitment: Hex;
  validUntil: bigint;
  engineSig: Hex;
}): Hex;
```

Encodes `AnafiDslRegistry.commitDsl(commitment, validUntil, engineSig, adapter)`. Every account kind sends this same call; only the way it reaches the registry differs. Take `commitment`, `engineSig`, `attestationValidUntilUnixSeconds` and `adapter` from a staged value. The selector is `0x385971b5`.

## Stage payload

```ts theme={null}
function dslUploadPayload(salt: Hex, yaml: string): Uint8Array;
function dslStagePayload(adapter: Hex, salt: Hex, yaml: string, parent: OnChainDsl | null): Uint8Array;
function assertBytes32Hex(value: unknown, label: string): asserts value is Hex;
```

| Function | Bytes |
| - | - |
| `dslUploadPayload` | `salt[32] ‖ utf8(yaml)` |
| `dslStagePayload` | `0x02 ‖ adapter[20] ‖ parent_version[8, big-endian] ‖ parent_hash[32] ‖ salt[32] ‖ utf8(yaml)` |

`dslStagePayload` is the plaintext that the stage seals under `dslSealInfo(network, account)`. The first byte `0x02` tags a frame that names its parent. A `null` parent is version 0 and the zero hash. The adapter and the parent are framing only: the commitment stays `keccak256(salt ‖ yaml)`. It throws for an invalid adapter, a negative or unsafe parent version, and a parent hash or salt that is not 32 bytes.

`assertBytes32Hex` throws unless `value` is a string of exactly `0x` and 64 hex characters. It checks the text before any decode, so a 63-digit value cannot pass as 32 bytes.

## Safe

### Constants

| Export | Value | Meaning |
| - | - | - |
| `SAFE_OPERATION_CALL` | `0` | The operation byte of a plain call, in a Safe transaction and in a MultiSend record. |
| `SAFE_OPERATION_DELEGATECALL` | `1` | The operation byte of a Safe `delegatecall` into MultiSend. |
| `SAFE_MODULE_LIST_SENTINEL` | `0x0000000000000000000000000000000000000001` | The head and tail of the module list of a Safe. |
| `SAFE_TX_EIP712_TYPES` | `{ SafeTx: [...] }` | The EIP-712 fields of a `SafeTx`, in contract order: `to`, `value`, `data`, `operation`, `safeTxGas`, `baseGas`, `gasPrice`, `gasToken`, `refundReceiver`, `nonce`. |

### `SafeTransaction` and `SafeBatchLeg`

```ts theme={null}
interface SafeTransaction {
  to: Hex;
  value: bigint;          // wei
  data: Hex;
  operation: number;      // 0 call, 1 delegatecall
  safeTxGas: bigint;
  baseGas: bigint;
  gasPrice: bigint;
  gasToken: Hex;          // zero address: native
  refundReceiver: Hex;    // zero address: tx.origin
  nonce: bigint;
}

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

### Address prediction

```ts theme={null}
function safeSetupInitializer(params: { owner: Hex; toL2Setup: Hex; singletonL2: Hex }): Hex;
function safeSaltNonce(owner: Hex): bigint;
function predictSafeAddress(params: {
  proxyFactory: Hex;
  singleton: Hex;
  singletonL2: Hex;
  toL2Setup: Hex;
  proxyCreationCode: Hex;
  owner: Hex;
}): Hex;
```

| Function | Returns |
| - | - |
| `safeSetupInitializer` | `Safe.setup([owner], 1, toL2Setup, setupToL2(singletonL2), 0x0, 0x0, 0, 0x0)`: one owner, threshold 1, and a setup `delegatecall` that moves the Safe to `SafeL2` on every chain except chain id 1. |
| `safeSaltNonce` | `BigInt(keccak256(owner))`, the salt nonce for the factory. |
| `predictSafeAddress` | The CREATE2 address of `createProxyWithNonce(singleton, initializer, saltNonce)`: salt `keccak256(keccak256(initializer) ‖ uint256(saltNonce))`, init code hash `keccak256(proxyCreationCode ‖ uint256(singleton))`. |

`proxyCreationCode` is the answer of `SafeProxyFactory.proxyCreationCode()`. Read it from the chain; `anafi.predictSafe(owner)` does this for you. The deploy call is `createProxyWithNonce(singleton, safeSetupInitializer(...), safeSaltNonce(owner))`.

### Transactions and legs

```ts theme={null}
function buildSafeCallTransaction(to: Hex, calldata: Hex, nonce: bigint): SafeTransaction;
function buildSafeBatchTransaction(multiSend: Hex, legs: readonly SafeBatchLeg[], nonce: bigint): SafeTransaction;
function packMultiSendRecords(legs: readonly SafeBatchLeg[]): Hex;
function multiSendCalldata(legs: readonly SafeBatchLeg[]): Hex;
function buildSafeEnableModuleLeg(safe: Hex, adapter: Hex): SafeBatchLeg;
function buildSafeDisableModuleLeg(safe: Hex, adapter: Hex, prevModule: Hex): SafeBatchLeg;
function buildSafeDslCommitLeg(params: {
  dslRegistry: Hex;
  adapter: Hex;
  commitment: Hex;
  validUntil: bigint;
  engineSig: Hex;
}): SafeBatchLeg;
function previousSafeModule(modules: readonly Hex[], adapter: Hex): Hex | null;
```

| Function | Does |
| - | - |
| `buildSafeCallTransaction` | A plain call (`operation` 0) with value 0 and every gas and refund field 0. |
| `buildSafeBatchTransaction` | A `delegatecall` (`operation` 1) to `multiSend` with `multiSendCalldata(legs)`, value 0, every gas and refund field 0. Throws `Error("Safe MultiSend requires at least two calls")` for fewer than 2 legs. |
| `packMultiSendRecords` | Packs each leg as `uint8(0) ‖ address(target) ‖ uint256(0) ‖ uint256(length) ‖ calldata`, with no separator. |
| `multiSendCalldata` | `multiSend(packMultiSendRecords(legs))`. |
| `buildSafeEnableModuleLeg` | `{ target: safe, calldata: enableModule(adapter) }`. |
| `buildSafeDisableModuleLeg` | `{ target: safe, calldata: disableModule(prevModule, adapter) }`. |
| `buildSafeDslCommitLeg` | `{ target: dslRegistry, calldata: buildDslCommitCalldata(...) }`. |
| `previousSafeModule` | The module before `adapter` in a newest-first module list, `SAFE_MODULE_LIST_SENTINEL` when `adapter` is first, or `null` when it is absent. Pass the list of `getModulesPaginated`. |

With `safeTxGas` and `gasPrice` at 0, a failed inner call reverts the whole Safe transaction.

### Typed data, digest and signatures

```ts theme={null}
function safeTxTypedData(safe: Hex, chainId: number, tx: SafeTransaction): {
  domain: { chainId: number; verifyingContract: Hex };
  types: typeof SAFE_TX_EIP712_TYPES;
  primaryType: "SafeTx";
  message: SafeTransaction;
};
function safeTxSigningHash(safe: Hex, chainId: number, tx: SafeTransaction): Hex;
function buildSafePreValidatedSignature(owner: Hex): Hex;
function execTransactionCalldata(tx: SafeTransaction, signatures: Hex): Hex;
```

| Function | Returns |
| - | - |
| `safeTxTypedData` | The EIP-712 data that a Safe owner signs. Pass it to `signTypedData`. |
| `safeTxSigningHash` | `hashTypedData(safeTxTypedData(...))`, the digest of the `SafeTx`. |
| `buildSafePreValidatedSignature` | 65 bytes: `r` is `owner` left-padded to 32 bytes, `s` is 0, `v` is 1. The Safe accepts it only when `msg.sender` is `owner`, so an owner that sends `execTransaction` itself needs no typed-data signature. |
| `execTransactionCalldata` | `execTransaction(to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, signatures)`. |

```ts theme={null}
buildSafePreValidatedSignature("0x1111111111111111111111111111111111111111");
// 0x0000000000000000000000001111111111111111111111111111111111111111
//   0000000000000000000000000000000000000000000000000000000000000000
//   01
```

Build and send an owner-sent commit without the client:

```ts theme={null}
import {
  buildSafeCallTransaction,
  buildSafeDslCommitLeg,
  buildSafePreValidatedSignature,
  execTransactionCalldata,
  SAFE_ABI,
} from "@anafi-cc/anafi-sdk";

const leg = buildSafeDslCommitLeg({
  dslRegistry: "0xa60904ABC7e96B06005234EACF02217afA02d5C3",
  adapter: staged.adapter,
  commitment: staged.commitment,
  validUntil: BigInt(staged.attestationValidUntilUnixSeconds),
  engineSig: staged.engineSig,
});
const nonce = await publicClient.readContract({ address: safe, abi: SAFE_ABI, functionName: "nonce" });
const tx = buildSafeCallTransaction(leg.target, leg.calldata, nonce);
const data = execTransactionCalldata(tx, buildSafePreValidatedSignature(owner));
await walletClient.sendTransaction({ account: owner, to: safe, data });
```

## ERC20Allow calldata

```ts theme={null}
function buildErc20ApproveCalldata(spender: Hex, amount: bigint): Hex;
function buildErc20AllowSetBlockedCalldata(blocked: boolean): Hex;
function buildErc20AllowSetCapsCalldata(entries: readonly Erc20AllowCapEntry[]): Hex;
function buildErc20AllowClearCapsCalldata(tokens: readonly Hex[]): Hex;
function buildErc20AllowCommitTransaction(params: {
  owner: Hex;
  dslRegistry: Hex;
  commitment: Hex;
  validUntil: bigint;
  engineSig: Hex;
  adapter: Hex;
}): Erc20AllowOwnerTransaction; // { from: owner, to: dslRegistry, data }
```

| Function | Call | Sent to |
| - | - | - |
| `buildErc20ApproveCalldata` | `approve(spender, amount)` | the token |
| `buildErc20AllowSetBlockedCalldata` | `setBlocked(blocked)`: the block switch of the sender | the ERC20Allow adapter |
| `buildErc20AllowSetCapsCalldata` | `setCaps(entries)`: the caps of the sender, in order | the ERC20Allow adapter |
| `buildErc20AllowClearCapsCalldata` | `clearCaps(tokens)` | the ERC20Allow adapter |
| `buildErc20AllowCommitTransaction` | `commitDsl(...)` | the DSL registry, from `owner` |

The account sends each one as a plain transaction with no value.

## ERC-20 transfer

```ts theme={null}
function buildErc20TransferCalldata(to: Hex, amount: bigint): Hex;
```

Encodes `transfer(to, amount)`. Send it to the token from the payer.

```ts theme={null}
buildErc20TransferCalldata("0x2222222222222222222222222222222222222222", 1_000_000n);
// 0xa9059cbb0000000000000000000000002222222222222222222222222222222222222222
//   00000000000000000000000000000000000000000000000000000000000f4240
```

## Gas credit

`readGasCredit` and `buildClaimGasCreditCalldata` are on [activity and fees](https://docs.ana.fi/sdk/activity-and-fees.md#gas-credit).

## Relayed receipts

`waitForRelayedTransaction(publicClient, txHash)` is on [Safe account](https://docs.ana.fi/sdk/safe.md#waitforrelayedtransaction).


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