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

# Documents

> Normalize, split, assemble and inspect rule documents with the SDK, set the fee token and the notification inbox, and compute the commitment.

After you read this page, you can change any rule document to one normal text, edit one rule of a document with many rules, read which tokens and addresses a document names, and compute its on-chain commitment.

## The normal layout

The SDK writes one text for a document, whatever layout its author typed. Two documents are the same document when their normal texts are equal. Comments, blank lines, indent width, quote style, flow style, and the key order inside a rule make no difference to the normal text. The engine also reads a rule by its parsed content, not by its bytes.

The commitment covers the exact bytes that you commit. Normalize a document before you stage it, so the text that you show, compare, store and commit is one text.

The normal layout:

* prints maps in block style, and lists of scalars in flow style (`[mon, tue]`);
* prints the keys inside a rule in this order: `type`, `trigger`, `actions`, `account`, `to`, `value`, `recipients`, `in`, `out`, `channel`, `message`, `timestamps`, `day_of_week`, `day_of_month`, `time_of_day`, `timezone`, `start`, `expiry`, then any other key in document order;
* keeps the top-level keys, and the keys outside rules, in document order;
* prints a string plain when it is an identifier that the engine reads as a string, and in double quotes in all other cases;
* prints a number from its source text, a null as `null`, and a boolean as `true` or `false`;
* has no comments.

### `normalizeDocument`

```ts theme={null}
function normalizeDocument(text: string): DocumentNormalization;

type DocumentNormalization = { ok: true; text: string } | { ok: false; reason: string };
```

Returns the normal text, or the reason why the text has none. `reason` is a sentence for the author. The function never throws for a bad document.

It refuses:

* YAML with any parser error or warning: a duplicate key, a tab in an indent, an unknown tag, two documents in one text;
* a raw U+000D with no U+000A after it, and a raw U+0085, U+2028 or U+2029, anywhere;
* a raw U+FEFF anywhere except as the first character;
* a `%YAML` version other than 1.2, and a `%TAG` directive;
* an anchor or an alias;
* any tag except `!!str`;
* a double-quoted value that escapes a line break;
* a `|` or `>` block value with no `-` in its header and no line break after its last line;
* a `|` or `>` block value with an indent digit in its header;
* a top level that is not a map, and a `rules` value that is not a map;
* a rule name that is not a string or a 64-bit integer, and two rules with one name.

The engine refuses almost all of these too. The SDK refuses the rest because its YAML reader and the engine reader read them differently.

```ts theme={null}
const messy = `# my rule
rules:
  r1:
    actions:
      - {type: send_one, value: "5 USDC", to: '0x1111111111111111111111111111111111111111'}
    trigger: {type: incoming_tx, value: "1.. USDC"}
global: {fees_method: {token: USDC, type: fixed_token}}
`;
const normal = normalizeDocument(messy);
if (normal.ok) console.log(normal.text);
```

```yaml theme={null}
rules:
  r1:
    trigger:
      type: incoming_tx
      value: "1.. USDC"
    actions:
      - type: send_one
        to: "0x1111111111111111111111111111111111111111"
        value: "5 USDC"
global:
  fees_method:
    token: USDC
    type: fixed_token
```

```ts theme={null}
normalizeDocument("rules:\n  a: &x {type: notify}\n");
// { ok: false, reason: "The document uses a YAML anchor; write each value out in full." }
```

### `printRuleDocument`

```ts theme={null}
function printRuleDocument(name: string, rule: DslMap, global?: DslMap): string;

type DslValue = string | number | DslNumberText | readonly DslValue[] | DslMap;
interface DslMap {
  readonly [key: string]: DslValue;
}
class DslNumberText {
  constructor(readonly numberText: string) {}
}
```

Prints a one-rule document in the normal layout, with an optional `global:` map before `rules:`. Every builder of [rule builders](https://docs.ana.fi/sdk/rule-builders.md) prints through it.

| Value | Prints as |
| - | - |
| `string` | plain or double-quoted, by the string rule |
| `number` | the number as JavaScript writes it; use safe integers only |
| `DslNumberText` | its `numberText` as a plain number. The printer throws when the engine would not read the text as an integer or a float. Use it for a decimal such as `0.25`. |
| array | a list; flow style when every item is a scalar |
| `DslMap` | a map, with the keys inside the rule in the normal key order |

```ts theme={null}
printRuleDocument("hello", {
  trigger: { type: "incoming_tx", value: "0.. USDC" },
  actions: [{ type: "notify", channel: "email", message: "USDC arrived." }],
});
```

### `PlainScalarKind`

```ts theme={null}
type PlainScalarKind = "null" | "bool" | "int" | "float" | "string";
```

How the engine reads a plain (unquoted) scalar. The normal layout uses it to decide which strings need quotes.

### `normalTextWithGlobalMap`

```ts theme={null}
function normalTextWithGlobalMap(text: string, key: string, value: DslMap | null): string;
```

Returns the text in the normal layout with the map `value` under `global.<key>`. A `null` value removes the key, and removes `global:` when it becomes empty. A document with no `global:` gets one as its first key. It throws an `Error` with the refusal reason for a text with no normal layout, and for a `global` that is not a map.

## Split and assemble

A document can hold many rules. The functions below let an editor own one rule at a time and still commit one document. The non-rule parts of the document survive: the preamble (the top-level keys above `rules`, such as `global:`) and the trailer (the top-level keys after it).

### `splitDocument`

```ts theme={null}
function splitDocument(yaml: string): SplitDocument | null;

interface SplitDocument {
  preamble: string;     // the top-level keys above rules, as normal text
  rules: DocumentRule[];
  trailer: string;      // the top-level keys after rules, as normal text
  hasRulesKey: boolean;
}

interface DocumentRule {
  name: string; // the rule name as the engine reads it
  body: string; // the rule lines, the "  name:" line first, each line ending in \n
}
```

Returns `null` for a text that `normalizeDocument` refuses. For a document with no `rules` key, `rules` is empty and `hasRulesKey` is `false`.

```ts theme={null}
splitDocument(`global:
  fees_method:
    type: fixed_token
    token: USDC
rules:
  a:
    trigger:
      type: incoming_tx
    actions:
      - type: notify
        channel: email
        message: hi
  b:
    trigger:
      type: incoming_tx
    actions:
      - type: notify
        channel: email
        message: ho
`);
```

```json theme={null}
{
  "preamble": "global:\n  fees_method:\n    type: fixed_token\n    token: USDC\n",
  "rules": [
    { "name": "a", "body": "  a:\n    trigger:\n      type: incoming_tx\n    actions:\n      - type: notify\n        channel: email\n        message: hi\n" },
    { "name": "b", "body": "  b:\n    trigger:\n      type: incoming_tx\n    actions:\n      - type: notify\n        channel: email\n        message: ho\n" }
  ],
  "trailer": "",
  "hasRulesKey": true
}
```

### `assembleDocument`

```ts theme={null}
function assembleDocument(doc: SplitDocument): string;
```

The inverse of `splitDocument`: the preamble, then `rules:` and the rule bodies, then the trailer. With no rules and `hasRulesKey: true`, it prints `rules: {}`, a valid document with nothing to run. With nothing at all, it prints `{}`.

```ts theme={null}
// Replace rule "b" with a rule from a builder, and keep the rest.
const doc = splitDocument(current)!;
const newBody = ruleBodyOfBuilt(buildRoutingDsl(form));
const next = assembleDocument({
  ...doc,
  rules: doc.rules.map((rule) => (rule.name === "b" ? { name: form.ruleName, body: newBody } : rule)),
});
```

### Single-rule helpers

```ts theme={null}
function singleRuleDocument(rule: DocumentRule): string;
function ruleBodyOfBuilt(yaml: string): string;
function singleRuleDocumentOfBuilt(yaml: string): string;
function documentHasNoRules(yaml: string): boolean;
```

| Function | Returns |
| - | - |
| `singleRuleDocument` | `"rules:\n" + rule.body`: the one-rule document that the readers of [rule builders](https://docs.ana.fi/sdk/rule-builders.md) accept. |
| `ruleBodyOfBuilt` | The body of the one rule of a builder output, without its `global:` map. Throws `Error("not a built single-rule document")` unless the text has exactly one rule. |
| `singleRuleDocumentOfBuilt` | `"rules:\n"` and that body: the builder output without `global:`. |
| `documentHasNoRules` | `true` when the document defines zero rules: a `rules` map that is empty, or no `rules` key beside an `agent_envelope` key. `false` for text that does not parse, a bare `rules:`, and a document with neither key. |

## Fee token

### `readFeesMethod`

```ts theme={null}
function readFeesMethod(yaml: string): FeesMethod | null;
```

Returns `global.fees_method` when it is exactly `{ type: fixed_token, token: <RoutingToken> }`. Returns `null` for no fee method, any other shape, an unknown token, and text with no normal layout.

### `documentWithFeesMethod`

```ts theme={null}
function documentWithFeesMethod(yaml: string, method: FeesMethod | null): string;
```

Returns the normal text with `global.fees_method` set to `method`, or removed for `null`. It throws for text with no normal layout.

```ts theme={null}
documentWithFeesMethod(yaml, { type: "fixed_token", token: "USDC" });
```

```yaml theme={null}
global:
  fees_method:
    type: fixed_token
    token: USDC
rules:
  forward_usdc:
    # ... the rule, unchanged
```

## What a document names

### `documentActionTokens`

```ts theme={null}
function documentActionTokens(yaml: string): DocumentActionTokens;

type DocumentActionTokens =
  | { kind: "named"; feeToken: RoutingToken | null; spentTokens: RoutingToken[]; swaps: DocumentSwapTokens[] }
  | { kind: "unnamed"; rule: string; actionKind: "send" | "exchange" }
  | { kind: "unreadable" };

interface DocumentSwapTokens {
  rule: string;
  sold: RoutingToken;
  bought: RoutingToken | null; // null when `out` is not a RoutingToken
}
```

Reads the tokens that the actions spend, rule by rule in document order. It reads the `value` of each `send_one`, the `value` of each `send_batch` row, and the `in` of each `exchange`:

* A literal `"AMOUNT TOKEN"` names `TOKEN`.
* `"trigger.value"` and `"trigger.value * N%"` name the token at the end of the `value` range of the `incoming_tx` or `outgoing_tx` trigger of the rule.
* Any other value names no token, and the answer is `unnamed` with the rule and the action kind.

Other action types are not read. `spentTokens` holds each token one time, in first-seen order. `feeToken` is the token of `global.fees_method`, or `null`. The ERC20Allow leg computes tokens(D) from this answer (see [ERC20Allow](https://docs.ana.fi/sdk/erc20-allow.md)).

For the Builder example of [rule builders](https://docs.ana.fi/sdk/rule-builders.md#builder):

```json theme={null}
{
  "kind": "named",
  "feeToken": "USDC",
  "spentTokens": ["USDC"],
  "swaps": [{ "rule": "split_and_swap", "sold": "USDC", "bought": "WETH" }]
}
```

For a Routing rule with an `anyTx` condition and a percent payee, the trigger has no range, so the share names no token:

```json theme={null}
{ "kind": "unnamed", "rule": "forward_usdc", "actionKind": "send" }
```

### `documentDestinations`

```ts theme={null}
function documentDestinations(yaml: string): string[] | null;
```

Returns each address value of a `to` key inside the `actions` of each rule: the `to` of a `send_one` and of each `send_batch` row. The bank details of an `off_ramp` are a map, not an address, and are not listed. The `to` filter of an `outgoing_tx` trigger is not listed: it pays nothing. A `to:` inside a string is text and is not listed. A number is listed as its decimal text. Returns `null` for text with no normal layout. Use it to check every payee before the owner signs.

### `documentTransferFilterAddresses`

```ts theme={null}
function documentTransferFilterAddresses(yaml: string): TransferFilterAddress[] | null;

type TransferFilterKey = "account" | "from" | "to";
interface TransferFilterAddress {
  key: TransferFilterKey;
  address: string; // an address or a $name reference, as written
}
```

Returns each address filter of the transfer triggers, in document order: the `account` and `from` of an `incoming_tx`, and the `account` and `to` of an `outgoing_tx`. Returns `null` for text with no normal layout.

### `documentHasOffRampAction`

```ts theme={null}
function documentHasOffRampAction(yaml: string): boolean;
```

`true` when any rule has an `off_ramp` action. `false` for text with no normal layout.

### `documentNotificationEmail` and `documentWithNotificationEmail`

```ts theme={null}
function documentNotificationEmail(yaml: string): string | null;
function documentWithNotificationEmail(yaml: string, canonicalEmail: string): string;
```

`documentNotificationEmail` returns `global.notification_email` as the document spells it, or `null`.

`documentWithNotificationEmail` returns the normal text with `global.notification_email` set. `canonicalEmail` must already be canonical (`canonicalNotificationEmail`), else it throws `Error("notification email must already be canonical")`. A document whose email has the same canonical form keeps its own spelling. It throws an `Error` with the refusal reason for text with no normal layout.

```yaml theme={null}
global:
  fees_method:
    type: fixed_token
    token: USDC
  notification_email: "ada@example.com"
rules:
  # ...
```

The engine refuses a stage of a document whose `notification_email` is not the verified inbox of the account. See [notification email](https://docs.ana.fi/sdk/notification-email.md).

## Commitment

### `dslCommitment`

```ts theme={null}
function dslCommitment(salt: Hex, yaml: string): Hex; // keccak256(salt ‖ utf8(yaml))
```

The on-chain commitment of a document. `salt` must be exactly `0x` and 64 hex characters, else it throws. `AnafiDslRegistry.commitments(aa).hash` holds this value after a commit. The stage and the commit methods check the engine echo against it.

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

const onChain = await anafi.readDslCommitment(account);
const same = onChain !== null && onChain.hash.toLowerCase() === dslCommitment(salt, yaml).toLowerCase();
```

The framing of the sealed stage payload (`dslUploadPayload`, `dslStagePayload`) is on [low-level helpers](https://docs.ana.fi/sdk/low-level.md#stage-payload).


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