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

# Rule builders

> Build and read rule documents from typed forms: Routing, Swap, DCA, Limit order, Standing order, Reimburse and Builder, with the exact YAML that each one emits.

After you read this page, you can turn a typed form into a rule document, read a committed document back into its form, and add an email notice or a fee token.

Each form has a builder and a reader:

| Form | Builder | Reader | Trigger | Actions |
| - | - | - | - | - |
| Routing | `buildRoutingDsl` | `parseRoutingDsl` | `incoming_tx` or one `at_fixed_time` | `send_one`, `send_batch`, `off_ramp` |
| Swap | `buildSwapDsl` | `parseSwapDsl` | `incoming_tx` or one `at_fixed_time` | one `exchange` |
| DCA | `buildDcaDsl` | `parseDcaDsl` | `calendar` or one `at_fixed_time` | one `exchange` |
| Limit order | `buildLimitDsl` | `parseLimitDsl` | `price_crossed` | one `exchange` |
| Standing order | `buildStandingOrderDsl` | `parseStandingOrderDsl` | `calendar` | `send_one`, `send_batch`, `off_ramp` |
| Reimburse | `buildReimburseDsl` | `parseReimburseDsl` | `outgoing_tx` | one `send_one` of a share |
| Builder | `buildBuilderDsl` | `parseBuilderDsl` | `incoming_tx`, `outgoing_tx`, `calendar`, `at_fixed_time` or `price_crossed` | any list of send blocks and swap blocks |

For the meaning of each trigger and action, see the [rule language](https://docs.ana.fi/rules/overview.md).

## The contract of every builder and reader

* **One rule per document.** Each builder prints one rule. Combine rules with `splitDocument` and `assembleDocument` (see [documents](https://docs.ana.fi/sdk/documents.md)).
* **Normal layout.** Each builder prints through `printRuleDocument`, so the output is in the normal layout. Each reader reads normal text only. Normalize other text with `normalizeDocument` first.
* **Byte-for-byte readers.** A reader returns a form only when the builder of that form reproduces the input byte for byte from the form. Else it returns `null`. A field that the form cannot show, such as `enabled:` or a `from:` filter in a Routing rule, makes the reader return `null`. So a form never hides a part of a committed rule.
* **Builders refuse nothing.** A builder prints an unfinished form as it is. The engine checks the document at the stage. For example, a share under a fixed-time trigger prints, and the engine refuses it.
* **Fee token.** Each builder takes an optional `feesMethod`. With it, the document starts with `global.fees_method`. An ERC20Allow document needs it. Each reader reads it back with `readFeesMethod` and passes it to the builder for the byte check.
* **Email notice.** With `notifyByEmail: true`, the actions end with `notify` on the `email` channel and the fixed message of the form (`FORM_NOTIFY_MESSAGES`). The document names no inbox. Each `notify` mails `global.notification_email`, which must be the verified inbox of the account. See [notification email](https://docs.ana.fi/sdk/notification-email.md).

### `FeesMethod`

```ts theme={null}
interface FeesMethod {
  type: "fixed_token";
  token: RoutingToken;
}
```

One fixed token for all fees of a document. It prints as:

```yaml theme={null}
global:
  fees_method:
    type: fixed_token
    token: USDC
```

## Routing

```ts theme={null}
function buildRoutingDsl(form: RoutingForm, feesMethod?: FeesMethod): string;
function parseRoutingDsl(yaml: string, native: RoutingToken): RoutingForm | null;
```

### `RoutingForm`

```ts theme={null}
interface RoutingForm {
  ruleName: string;
  token: RoutingToken;
  condition: RoutingTrigger;
  recipients: RoutingRecipient[];
  notifyByEmail: boolean;
}

type RoutingTrigger = RoutingCondition | { kind: "atTime"; timestamp: string };

type RoutingCondition =
  | { kind: "anyTx" }
  | { kind: "any" }
  | { kind: "above"; min: string }
  | { kind: "below"; max: string }
  | { kind: "between"; min: string; max: string };
```

| Field | Meaning |
| - | - |
| `ruleName` | The rule name, a key of `rules:`. Use letters, digits and `_`. |
| `token` | The asset that must arrive for the rule to fire. Under `anyTx` and `atTime` it is ignored, but kept. |
| `condition` | When the rule fires. |
| `recipients` | The payees, in row order. A valid form has at least one. |
| `notifyByEmail` | Adds the email notice `"Your Routing automation fired."`. |

| `condition.kind` | Trigger it prints | Fires on |
| - | - | - |
| `anyTx` | `incoming_tx` with no `value` | any incoming transfer of the native coin or of any registered token |
| `any` | `value: "0.. TOKEN"` | any amount of `token` |
| `above` | `value: "MIN.. TOKEN"` | at least `min` of `token`; `min` must be above 0 |
| `below` | `value: "..MAX TOKEN"` | at most `max` of `token` |
| `between` | `value: "MIN..MAX TOKEN"` | from `min` to `max` of `token` |
| `atTime` | `at_fixed_time` with `timestamps: [timestamp]` | once, at the RFC 3339 instant |

### `RoutingRecipient`

```ts theme={null}
interface RoutingRecipient {
  destination: Hex;
  bank?: BankPayee;
  amount: string;
  amountUnit: RoutingAmountUnit;
}

type RoutingAmountUnit = RoutingToken | "percent";

interface BankPayee {
  iban: string;     // uppercase, no spaces
  holder: BankHolder;
  country: string;  // ISO 3166-1 alpha-2, 2 uppercase letters
  memo: string;     // "" for no memo; else 5 to 140 characters
}

type BankHolder =
  | { kind: "person"; firstName: string; lastName: string }
  | { kind: "company"; companyName: string };
```

| Field | Meaning |
| - | - |
| `destination` | The address to pay. Ignored while `bank` is set. |
| `bank` | Pays a bank account instead, with an `off_ramp` action through `monerium`. The amount must then be in `EURe` or `percent` of an EURe trigger. Today only `polygon-amoy` serves the `off_ramp` action. |
| `amount` | The number as typed. It prints in the `value` text without change. |
| `amountUnit` | A token: a literal `"AMOUNT TOKEN"`. `percent`: a share of the transfer that fired the rule, `"trigger.value * AMOUNT%"`, paid in the token that arrived. |

One on-chain payee prints `send_one`. Two or more on-chain payees print one `send_batch`, which pays all or none. Each bank payee prints one `off_ramp` after the send. The all-or-none rule covers only the on-chain payees.

### Output

```ts theme={null}
buildRoutingDsl(
  {
    ruleName: "forward_usdc",
    token: "USDC",
    condition: { kind: "above", min: "10" },
    recipients: [
      { destination: "0x1111111111111111111111111111111111111111", amount: "20", amountUnit: "percent" },
      { destination: "0x2222222222222222222222222222222222222222", amount: "5", amountUnit: "USDC" },
    ],
    notifyByEmail: true,
  },
  { type: "fixed_token", token: "USDC" },
);
```

```yaml theme={null}
global:
  fees_method:
    type: fixed_token
    token: USDC
rules:
  forward_usdc:
    trigger:
      type: incoming_tx
      value: "10.. USDC"
    actions:
      - type: send_batch
        recipients:
          - to: "0x1111111111111111111111111111111111111111"
            value: "trigger.value * 20%"
          - to: "0x2222222222222222222222222222222222222222"
            value: "5 USDC"
      - type: notify
        channel: email
        message: "Your Routing automation fired."
```

An `anyTx` condition with one payee:

```yaml theme={null}
rules:
  fwd:
    trigger:
      type: incoming_tx
    actions:
      - type: send_one
        to: "0x1111111111111111111111111111111111111111"
        value: "trigger.value * 50%"
```

A bank payee (`holder: { kind: "person", firstName: "Ada", lastName: "Lovelace" }`, `memo: "Rent payment"`):

```yaml theme={null}
rules:
  to_bank:
    trigger:
      type: incoming_tx
      value: "0.. EURe"
    actions:
      - type: off_ramp
        to:
          iban: DE89370400440532013000
          first_name: Ada
          last_name: Lovelace
          country: DE
        value: "trigger.value * 100%"
        provider: monerium
        memo: "Rent payment"
```

A fixed instant:

```yaml theme={null}
rules:
  pay_once:
    trigger:
      type: at_fixed_time
      timestamps: ["2027-01-01T09:00:00Z"]
    actions:
      - type: send_one
        to: "0x1111111111111111111111111111111111111111"
        value: "25 USDC"
```

### Reader

`parseRoutingDsl(yaml, native)` returns the form, or `null`. `native` is the native coin of the network. It fills `token` for `anyTx` and `atTime`, which name no token. On-chain payees come before bank payees in the result. The reader of the first example returns:

```json theme={null}
{
  "ruleName": "forward_usdc",
  "token": "USDC",
  "condition": { "kind": "above", "min": "10" },
  "recipients": [
    { "destination": "0x1111111111111111111111111111111111111111", "amount": "20", "amountUnit": "percent" },
    { "destination": "0x2222222222222222222222222222222222222222", "amount": "5", "amountUnit": "USDC" }
  ],
  "notifyByEmail": true
}
```

## Swap

```ts theme={null}
function buildSwapDsl(form: SwapForm, feesMethod?: FeesMethod): string;
function parseSwapDsl(yaml: string, placeholderWatchedToken: RoutingToken): SwapForm | null;

type SwapTrigger = RoutingTrigger;

interface SwapForm {
  ruleName: string;
  trigger: SwapTrigger;
  watchedToken: RoutingToken;
  amount: string;
  amountUnit: RoutingAmountUnit;
  toToken: RoutingToken;
  notifyByEmail: boolean;
}
```

| Field | Meaning |
| - | - |
| `trigger` | A Routing condition, or `atTime`. |
| `watchedToken` | The token of the trigger range. Ignored under `anyTx` and `atTime`. |
| `amount`, `amountUnit` | What each fire sells: a literal amount of a token, or a share of the transfer that fired the rule. A share under `atTime` prints, and the engine refuses it. |
| `toToken` | The token to buy. It must differ from the token sold. |
| `notifyByEmail` | Adds `"Your Swap automation fired."`. |

The `exchange` action sells at market through the swap aggregator of the network. The engine refuses every `exchange` on `polygon-amoy`, where no aggregator is available.

```yaml theme={null}
rules:
  swap_in:
    trigger:
      type: incoming_tx
      value: "100..1000 USDC"
    actions:
      - type: exchange
        in: "trigger.value * 50%"
        out: WETH
```

`parseSwapDsl` puts `placeholderWatchedToken` in `watchedToken` under `anyTx` and `atTime`. It returns `null` for a share under `at_fixed_time`.

## DCA

```ts theme={null}
function buildDcaDsl(form: DcaForm, feesMethod?: FeesMethod): string;
function parseDcaDsl(yaml: string): DcaForm | null;

type DcaCadence = "once" | "hourly" | "daily" | "weekly" | "monthly";
const DCA_CADENCES: readonly DcaCadence[]; // ["once", "hourly", "daily", "weekly", "monthly"]

interface DcaForm {
  ruleName: string;
  fromToken: RoutingToken;
  toToken: RoutingToken;
  amount: string;
  cadence: DcaCadence;
  startAt: string;
  timezone: string;
  expiresAt: string;
  notifyByEmail: boolean;
}

type DcaSchedule = Pick<DcaForm, "cadence" | "timezone" | "startAt" | "expiresAt">;
```

| Field | Meaning |
| - | - |
| `fromToken`, `amount` | Each fire sells `amount` of `fromToken`. Always a literal: a scheduled fire has no `trigger.value`. |
| `toToken` | The token to buy. It must differ from `fromToken`. |
| `cadence` | How often the rule fires. |
| `startAt` | The first fire, as an RFC 3339 instant. `""` while not picked. |
| `timezone` | The IANA timezone of the schedule, for example `Europe/Berlin`. A `once` document names no zone. |
| `expiresAt` | The end, as an RFC 3339 instant, or `""` for no end. A `once` rule prints no end. |
| `notifyByEmail` | Adds `"Your DCA automation fired."`. |

| `cadence` | Trigger | Day filter | `time_of_day` |
| - | - | - | - |
| `once` | `at_fixed_time` at `startAt` | none | none |
| `hourly` | `calendar` | every day | `"*:MM"`, the minute of `startAt` |
| `daily` | `calendar` | every day | `"HH:MM"` of `startAt` in `timezone` |
| `weekly` | `calendar` | the weekday of `startAt` | `"HH:MM"` |
| `monthly` | `calendar` | the day of month of `startAt` | `"HH:MM"` |

Every calendar cadence also prints the rule field `start:` (the first fire) and, with an end, `expiry:`. Both print in UTC through `toISOString()`. A monthly rule on day 29, 30 or 31 skips the months without that day.

Weekly, from 2027-01-08 09:00 UTC (10:00 in Berlin), to the end of 2027:

```yaml theme={null}
global:
  fees_method:
    type: fixed_token
    token: USDC
rules:
  buy_weth_weekly:
    trigger:
      type: calendar
      day_of_week: [fri]
      time_of_day: "10:00"
      timezone: "Europe/Berlin"
    actions:
      - type: exchange
        in: "25 USDC"
        out: WETH
    start: "2027-01-08T09:00:00.000Z"
    expiry: "2027-12-31T23:00:00.000Z"
```

The same form with `cadence: "hourly"` and no end:

```yaml theme={null}
rules:
  buy_weth_weekly:
    trigger:
      type: calendar
      day_of_week: [mon, tue, wed, thu, fri, sat, sun]
      time_of_day: "*:00"
      timezone: "Europe/Berlin"
    actions:
      - type: exchange
        in: "25 USDC"
        out: WETH
    start: "2027-01-08T09:00:00.000Z"
```

With `cadence: "once"`:

```yaml theme={null}
rules:
  buy_weth_weekly:
    trigger:
      type: at_fixed_time
      timestamps: ["2027-01-08T09:00:00.000Z"]
    actions:
      - type: exchange
        in: "25 USDC"
        out: WETH
```

`parseDcaDsl` returns `null` for a share, for the same token on both sides, for a `time_of_day` that does not agree with `start:`, and for any other change. A `once` rule reads back with `timezone: "UTC"`.

## Limit order

```ts theme={null}
function buildLimitDsl(form: LimitForm, feesMethod?: FeesMethod): string;
function parseLimitDsl(yaml: string): LimitForm | null;

interface LimitForm {
  ruleName: string;
  trigger: PriceTrigger;
  watchedTokenFollows: boolean;
  amount: string;
  fromToken: RoutingToken;
  toToken: RoutingToken;
  expiresAt: string;
  notifyByEmail: boolean;
}
```

| Field | Meaning |
| - | - |
| `trigger` | The `price_crossed` trigger. See [price trigger](#price-trigger). |
| `watchedTokenFollows` | A value of the form only. It never reaches the document. The reader always returns `false`. |
| `amount`, `fromToken` | Each fire sells `amount` of `fromToken`. |
| `toToken` | The token to buy. |
| `expiresAt` | The end (`expiry:`), or `""`. |
| `notifyByEmail` | Adds `"Your Limit order automation fired."`. |

```yaml theme={null}
rules:
  sell_weth_high:
    trigger:
      type: price_crossed
      token: WETH
      direction: above
      price_usd: 4000.5
      hold_seconds: 300
      cooldown_seconds: 3153600000
    actions:
      - type: exchange
        in: "0.5 WETH"
        out: USDC
      - type: notify
        channel: email
        message: "Your Limit order automation fired."
    expiry: "2027-06-30T00:00:00.000Z"
```

The form of this output had `priceUsd: "4,000.50"`. The builder prints the canonical level `4000.5`. A level that `isPriceUsdText` refuses prints as `0`, which the reader also refuses.

## Standing order

```ts theme={null}
function buildStandingOrderDsl(form: StandingOrderForm, feesMethod?: FeesMethod): string;
function parseStandingOrderDsl(yaml: string): StandingOrderForm | null;

type StandingOrderCadence = "daily" | "weekly" | "monthly";
const STANDING_ORDER_CADENCES: readonly StandingOrderCadence[]; // ["daily", "weekly", "monthly"]

interface StandingOrderForm {
  ruleName: string;
  recipients: RoutingRecipient[];
  cadence: StandingOrderCadence;
  startAt: string;
  timezone: string;
  expiresAt: string;
  notifyByEmail: boolean;
}
```

A fixed payment on a schedule. The schedule fields mean what they mean on `DcaForm`. Each payee must have a literal amount: a scheduled fire has no `trigger.value`. The reader returns `null` for a share, a `once` or `hourly` schedule, and any other action. `notifyByEmail` adds `"Your Standing order automation fired."`.

Rent of 1200 USDC on the first of each month at 09:00 in Berlin:

```yaml theme={null}
global:
  fees_method:
    type: fixed_token
    token: USDC
rules:
  pay_rent:
    trigger:
      type: calendar
      day_of_month: [1]
      time_of_day: "09:00"
      timezone: "Europe/Berlin"
    actions:
      - type: send_one
        to: "0x1111111111111111111111111111111111111111"
        value: "1200 USDC"
      - type: notify
        channel: email
        message: "Your Standing order automation fired."
    start: "2027-01-01T08:00:00.000Z"
```

## Reimburse

```ts theme={null}
function buildReimburseDsl(form: ReimburseForm, feesMethod?: FeesMethod): string;
function parseReimburseDsl(yaml: string, native: RoutingToken): ReimburseForm | null;

interface ReimburseForm {
  ruleName: string;
  account: string;
  token: RoutingToken;
  condition: RoutingCondition;
  percent: string;
  notifyByEmail: boolean;
}
```

Each time `account` sends a transfer that `condition` matches, the rule pays `percent` of that transfer back to `account`.

| Field | Meaning |
| - | - |
| `account` | The account whose outgoing transfers count, a 0x address. |
| `token`, `condition` | The range of the outgoing transfer, as on `RoutingForm`. `anyTx` prints no range. |
| `percent` | The share to pay back, as decimal text. |
| `notifyByEmail` | Adds `"Your Reimburse automation fired."`. |

```yaml theme={null}
global:
  fees_method:
    type: fixed_token
    token: USDC
rules:
  cashback:
    trigger:
      type: outgoing_tx
      account: "0x1111111111111111111111111111111111111111"
      value: "50.. USDC"
    actions:
      - type: send_one
        to: "0x1111111111111111111111111111111111111111"
        value: "trigger.value * 2%"
```

## Builder

```ts theme={null}
function buildBuilderDsl(form: BuilderForm, feesMethod?: FeesMethod): string;
function parseBuilderDsl(yaml: string, native: RoutingToken): BuilderForm | null;

interface BuilderForm {
  ruleName: string;
  trigger: BuilderTrigger;
  actions: BuilderAction[];
  notifyByEmail: boolean;
}

type BuilderTriggerSource = "transfer" | "schedule" | "price";
type BuilderTransferDirection = "incoming" | "outgoing";

interface BuilderTrigger {
  source: BuilderTriggerSource;
  transfer: {
    condition: RoutingCondition;
    token: RoutingToken;
    direction: BuilderTransferDirection;
    account: string | null;       // null: this account
    counterparty: string | null;  // null: any address
  };
  schedule: DcaSchedule;
  price: BuilderPriceTrigger;
}

interface BuilderPriceTrigger extends PriceTrigger {
  expiresAt: string; // the rule expiry, or ""
}

type BuilderAction = BuilderSendAction | BuilderSwapAction;
type BuilderActionKind = BuilderAction["kind"]; // "send" | "swap"

interface BuilderSendAction {
  kind: "send";
  recipients: RoutingRecipient[];
}

interface BuilderSwapAction extends Pick<SwapForm, "amount" | "amountUnit" | "toToken"> {
  kind: "swap";
}
```

One trigger, then any number of action blocks in order, then the optional email notice. `trigger.source` chooses which part of `trigger` prints. The other parts are kept, so a switch back restores them.

| `source` | Prints |
| - | - |
| `transfer` | `incoming_tx` or `outgoing_tx` by `direction`. Then `account` unless it is `null`. Then the counterparty as `from` (incoming) or `to` (outgoing) unless it is `null`. Then the `value` range, or none under `anyTx`. |
| `schedule` | The fields of `dcaScheduleRuleFields(schedule)`, as for DCA. |
| `price` | The `price_crossed` trigger, and the rule `expiry:` when `expiresAt` is set. |

| Block | Prints |
| - | - |
| `send` | `payeeActions(recipients)`: one send, then one `off_ramp` per bank payee. |
| `swap` | One `exchange`. |

The engine runs each action on its own, so the actions of a Builder rule are not atomic as a group. `notifyByEmail` adds `"Your Builder automation fired."`.

```yaml theme={null}
global:
  fees_method:
    type: fixed_token
    token: USDC
rules:
  split_and_swap:
    trigger:
      type: incoming_tx
      value: "0.. USDC"
      from: "0x2222222222222222222222222222222222222222"
    actions:
      - type: send_one
        to: "0x1111111111111111111111111111111111111111"
        value: "trigger.value * 10%"
      - type: exchange
        in: "trigger.value * 50%"
        out: WETH
```

`parseBuilderDsl` fills the parts that the rule does not use with placeholders: an incoming transfer on this account with the `any` condition and `native`, a `once` schedule in `UTC` with no instant, and a price trigger on `native` with no level, direction `above`, and the one-shot cooldown. Two adjacent send blocks that print the same bytes as one block read back as one.

## Price trigger

```ts theme={null}
type PriceDirection = "above" | "below";

interface PriceTrigger {
  token: RoutingToken;
  direction: PriceDirection;
  priceUsd: string;
  holdSeconds: number;
  cooldownSeconds: number;
}

const PRICE_TRIGGER_ONE_SHOT_COOLDOWN_SECONDS = 3_153_600_000; // 100 years

function priceUsdCanonicalText(text: string): string;
function isPriceUsdText(text: string): boolean;
function priceCrossedTriggerMap(trigger: PriceTrigger): DslMap;
function parsePriceCrossedTrigger(triggerLines: readonly string[]): PriceTrigger | null;
```

The rule fires when the USD price of `token` crosses `priceUsd` in `direction` and stays on that side for `holdSeconds`. A cross less than `cooldownSeconds` after the last fire starts no hold.

| Field | Meaning |
| - | - |
| `direction` | `above`: on at a price at or over the level. `below`: on at a price at or under it. |
| `priceUsd` | The level in US dollars, as decimal text. |
| `holdSeconds` | Whole seconds past the level before the fire. `0` fires at the cross. |
| `cooldownSeconds` | Whole seconds after a fire when a cross is skipped. `0` skips none. `PRICE_TRIGGER_ONE_SHOT_COOLDOWN_SECONDS` makes the rule fire once. |

`isPriceUsdText(text)` accepts a level of the form `^(0|[1-9]\d*)(\.\d{1,8})?$` with no final zero in the fraction, at most 15 significant digits, and a value from 0.0001 up to, but not including, 1,000,000,000,000.

`priceUsdCanonicalText(text)` makes typed text canonical: it trims, drops leading zeros of the whole part and final zeros of the fraction, and drops commas only where they must be thousands separators.

| Input | Output |
| - | - |
| `"4,000.50"` | `"4000.5"` |
| `"1,250,000"` | `"1250000"` |
| `"1,250"` | `"1,250"` (a decimal comma in many countries; `isPriceUsdText` refuses it) |
| `"007"` | `"7"` |

`priceCrossedTriggerMap` returns the trigger as a `DslMap` for `printRuleDocument`. It prints the canonical level, or `0` when the level is not valid. `parsePriceCrossedTrigger` reads the lines of a rule up to `actions:`. It needs exactly the keys `type`, `token`, `direction`, `price_usd`, `hold_seconds`, `cooldown_seconds`, in that order.

```ts theme={null}
printRuleDocument("pol_alert", {
  trigger: priceCrossedTriggerMap({
    token: "POL", direction: "below", priceUsd: "0.25", holdSeconds: 0, cooldownSeconds: 3600,
  }),
  actions: [emailNotifyAction("POL is below 0.25 USD.")],
});
```

```yaml theme={null}
rules:
  pol_alert:
    trigger:
      type: price_crossed
      token: POL
      direction: below
      price_usd: 0.25
      hold_seconds: 0
      cooldown_seconds: 3600
    actions:
      - type: notify
        channel: email
        message: "POL is below 0.25 USD."
```

## Email notify action

```ts theme={null}
function emailNotifyAction(message: string): DslMap; // { type: "notify", channel: "email", message }

const FORM_NOTIFY_MESSAGES = {
  routing: "Your Routing automation fired.",
  swap: "Your Swap automation fired.",
  dca: "Your DCA automation fired.",
  limit: "Your Limit order automation fired.",
  standing_order: "Your Standing order automation fired.",
  reimburse: "Your Reimburse automation fired.",
  builder: "Your Builder automation fired.",
} as const;

function actionLinesWithoutNotify(actionLines: readonly string[]): { lines: string[]; notifyByEmail: boolean };
```

`actionLinesWithoutNotify` removes the first `- type: notify` item and its lines from the lines under `actions:`. The readers use it to read `notifyByEmail`.

## Form parts

These functions are the parts that the builders and readers share. Use them to build a form of your own on the same normal layout.

| Function | Signature | Does |
| - | - | - |
| `payeeActions` | `(recipients: readonly RoutingRecipient[]) => DslMap[]` | One `send_one` or `send_batch` for the on-chain payees, then one `off_ramp` per bank payee. |
| `tokenAmountOrShareText` | `(amount: string, unit: RoutingToken \| "percent") => string` | `"5 USDC"` or `"trigger.value * 5%"`. |
| `parseTokenAmountOrShareText` | `(text: string) => Pick<RoutingRecipient, "amount" \| "amountUnit"> \| null` | The inverse. |
| `valueRangeText` | `(c: RoutingCondition, token: RoutingToken) => string` | `"0.. USDC"`, `"10.. USDC"`, `"..10 USDC"`, `"1..10 USDC"`. Throws for `anyTx`. |
| `parseValueRangeText` | `(text: string) => { condition: RoutingCondition; token: RoutingToken } \| null` | The inverse. `null` for an exact value, a `$variable`, or an unknown token. |
| `parseRoutingTrigger` | `(triggerLines: string[], native: RoutingToken) => { condition: RoutingForm["condition"]; token: RoutingToken } \| null` | Reads the condition and token of a transfer or fixed-time trigger. |
| `parseTransferTriggerAccount` | `(triggerLines: readonly string[]) => string \| null` | The `account: "0x…"` of a transfer trigger. |
| `watchedTokenOf` | `(yaml: string, native: RoutingToken) => WatchedAsset \| null` | The asset that the `incoming_tx` trigger of the first rule watches; `"any"` for no range; `null` for another trigger. |
| `splitActionItems` | `(actionLines: readonly string[]) => DslActionItem[] \| null` | Splits the lines under `actions:` at each `- type:` line. |
| `parsePayeeActionItem` | `(item: DslActionItem) => RoutingRecipient[] \| null` | The payees of one `send_one`, `send_batch` or `off_ramp`. |
| `parsePayeeActions` | `(actionLines: string[]) => RoutingForm["recipients"] \| null` | At most one send first, then `off_ramp` items, at least one payee. |
| `exchangeAction` | `(inText: string, out: RoutingToken) => DslMap` | `{ type: "exchange", in, out }`. |
| `parseExchangeAction` | `(actionLines: string[]) => { amount: string; amountUnit: RoutingToken \| "percent"; out: RoutingToken } \| null` | Reads lines that hold exactly one `exchange`. |
| `parseSingleRuleName` | `(lines: string[]) => string \| null` | The name when exactly one line is a rule key at two spaces of indent. |
| `dcaScheduleParts` | `(form: Pick<DcaForm, "startAt" \| "timezone">) => { weekday: string; dayOfMonth: number; timeOfDay: string } \| null` | The weekday, day of month and `HH:MM` of `startAt` in `timezone`. |
| `dcaTimeOfDay` | `(form: Pick<DcaForm, "cadence" \| "startAt" \| "timezone">) => string \| null` | `"HH:MM"`, or `"*:MM"` for hourly. |
| `normalisedInstant` | `(at: string) => string` | The instant through `toISOString()`, or `""` when it cannot be read. |
| `dcaScheduleRuleFields` | `(schedule: DcaSchedule) => DslMap` | The `trigger`, `start` and `expiry` fields of a schedule. |
| `parseDcaSchedule` | `(triggerLines: readonly string[], tailLines: readonly string[]) => DcaSchedule \| null` | The inverse. |

```ts theme={null}
interface DslActionItem {
  type: string;    // the action type of the item
  lines: string[]; // its lines, the "- type:" line first
}
```

## Generate a document from text

```ts theme={null}
function generateDsl(backendUrl: string, request: GenerateDslRequest, fetchImpl: typeof fetch): Promise<string>;

interface GenerateDslRequest {
  prompt: string;
  aa?: Hex;
  currentYaml?: string;
  now: string;       // RFC 3339 with an offset
  timezone: string;  // IANA, for example "Europe/Berlin"
  siweMessage: string;
  signature: Hex;
}

interface GenerateDslResponse {
  yaml: string;
}

function siweSessionMessage(args: { domain: string; eoa: Hex; chainId: number; nonce: string; issuedAt: string }): string;
```

`generateDsl` calls `POST /api/dsl/generate` and returns the text of a draft document. It commits, signs and stages nothing. The owner still stages and commits the draft. The request times out after 45 seconds.

| Field | Meaning |
| - | - |
| `prompt` | The description of the rule, in the words of the user. |
| `aa` | The account that the rule runs for, so that "my wallet" can be named. |
| `currentYaml` | The document in the editor. With it, the request changes that document. |
| `now`, `timezone` | The clock and zone of the caller. Send both. The API refuses a request that has only one of them. |
| `siweMessage` | The EIP-4361 text from `siweSessionMessage`, as signed. |
| `signature` | The `personal_sign` signature over `siweMessage`. |

`siweSessionMessage` renders the sign-in for this route with the statement `Sign in to Anafi to write rules from a description.` and no expiry line. The API derives the end of the session from `Issued At`. Sign once, and reuse the pair while the API accepts it. The API accepts the sign-in only when `domain` is the domain of the Anafi web app, and `chainId` is the chain of the host.

```text theme={null}
app.ana.fi wants you to sign in with your Ethereum account:
0x1111111111111111111111111111111111111111

Sign in to Anafi to write rules from a description.

URI: https://app.ana.fi
Version: 1
Chain ID: 137
Nonce: abc123def456
Issued At: 2026-12-03T10:00:00.000Z
```

On a failure it throws `GenerateDslError` with `failure`:

| `failure` | HTTP status | Meaning | What to do |
| - | - | - | - |
| `unavailable` | 404 | The network serves no such route. | Hide the feature. A new prompt does not help. |
| `signIn` | 401 | The sign-in did not verify, for example an expired session. | Sign again. |
| `failed` | any other, or an empty document | Any other failure. `reason` holds the sentence of the API, when it sent one. | Show `reason`. |


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