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

# Grammar reference

> The complete formal reference of the rule language in one place: the document schema, the expression grammar, the lexical forms, and every numeric limit.

After you read this page, you can check a rule document by hand against the full language that the engine accepts today. The other pages of this section explain each part with examples. This page states the parts without prose.

## Notation

| Notation | Meaning |
| - | - |
| `{ a: T, b?: T }` | A YAML mapping. `a` is required. `b?` is optional. No other key is accepted. |
| `T[]` | A YAML list of `T`. |
| `T[1..]` | A list with at least 1 item. |
| `Map<str, T>` | A mapping from text keys to `T`. |
| `"x"` | The exact text `x`. |
| `A \| B` | `A` or `B`. |
| `<TOKEN>` | A token symbol from the [token universe](#token-universe). |
| `<N>`, `<M>` | A number literal. See [lexical forms](#lexical-forms). |

## Document schema

```text theme={null}
DslDocument    = { variables?:       Map<VarName, scalar>,
                   global?:          GlobalConstraints,
                   rules?:           Map<RuleName, Rule>,
                   agent_envelope?:  AgentEnvelope }
                 # At least one of the keys `rules` or `agent_envelope` must be present.
                 # `rules: {}` is valid: a document with nothing to run.
                 # At most 32 rules.

Rule           = { trigger:   Trigger,
                   actions:   Action[1..],
                   enabled?:  bool            (default true),
                   start?:    Instant,
                   expiry?:   Instant }

GlobalConstraints = { token_allowlist?:      <TOKEN>[1..],
                      recipient_allowlist?:  Addr[1..],
                      iban_allowlist?:       Iban[1..],
                      notification_email?:   str,
                      fees_method?:          FeesMethod }

FeesMethod     = { type:  "fixed_token",
                   token: <TOKEN> }

AgentEnvelope  = { to:                   Addr,
                   token_allowlist:      <TOKEN>[1..],
                   recipient_allowlist?: Addr[],
                   balance_floor?:       TokenValue,
                   per_tx_max?:          TokenValue,
                   expiry?:              Instant }
                 # Accepted. The engine enforces no field of it.

--- Triggers ---

Trigger        = Periodic | Calendar | AtFixedTime | IncomingTx | OutgoingTx | PriceCrossed

Periodic       = { type: "periodic",
                   interval_seconds: u64 in 10..=3153600000 }

Calendar       = { type: "calendar",
                   day_of_month?: u8 in 1..=31 [1..], no duplicate,
                   day_of_week?:  ("mon"|"tue"|"wed"|"thu"|"fri"|"sat"|"sun") [1..], no duplicate,
                   time_of_day:   TimeOfDay,
                   timezone?:     IANA time zone name (default "UTC") }
                 # At least one of day_of_month or day_of_week.
                 # Both set: a day must match both.

AtFixedTime    = { type: "at_fixed_time",
                   timestamps: Instant[1..], no duplicate text }

IncomingTx     = { type: "incoming_tx",
                   account?: Addr,
                   from?:    Addr,
                   value?:   ValueRange }

OutgoingTx     = { type: "outgoing_tx",
                   account?: Addr,
                   to?:      Addr,
                   value?:   ValueRange }
                 # account: not the zero address, not equal to from or to,
                 #          not the account of the document (stage).
                 # outgoing_tx.to: not the zero address.

PriceCrossed   = { type: "price_crossed",
                   token:            <TOKEN>,
                   direction:        "above" | "below",
                   price_usd:        <N> > 0,
                   hold_seconds:     u64,
                   cooldown_seconds: u64 }

--- Actions ---

Action         = SendOne | SendBatch | Exchange | Notify | OffRamp

SendOne        = { type: "send_one",
                   to:    Addr,
                   value: ValueExpr }

SendBatch      = { type: "send_batch",
                   recipients: SendRecipient[1..] }      # at most 24 (stage)

SendRecipient  = { to: Addr, value: ValueExpr }

Exchange       = { type: "exchange",
                   in:  ValueExpr,
                   out: <TOKEN> }
                 # The token of `in` must differ from `out` when it is known.

Notify         = { type: "notify",
                   channel: "push" | "email" | "telegram",
                   message: str }
                 # Every channel delivers by email to global.notification_email.

OffRamp        = { type: "off_ramp",
                   provider: "monerium",
                   value:    ValueExpr,          # an amount of EURe
                   to:       BankRecipient,
                   memo?:    str }               # 5 to 140 characters

BankRecipient  = { iban:    Iban,
                   ( first_name: str, last_name: str ) | company_name: str,
                   country: two uppercase ASCII letters }
                 # Exactly one holder form. No name may be blank.

--- Scalars ---

Addr           = "0x" followed by 40 hex characters | "$" VarName
Iban           = canonical IBAN | "$" VarName
Instant        = RFC 3339 date-time with an offset
TokenValue     = "<N> <TOKEN>"
ValueRange     = "<N> <TOKEN>"          # exact
               | "<N>..<M> <TOKEN>"     # bounded, N <= M
               | "<N>.. <TOKEN>"        # open upper
               | "..<M> <TOKEN>"        # open lower
TimeOfDay      = "HH:MM" | "*:MM" | "*/N:MM"
VarName        = [A-Za-z_][A-Za-z0-9_]*
RuleName       = a YAML text or number key, not empty
```

## Expression grammar

`ValueExpr` is the text of `send_one.value`, of each `send_batch` item `value`, of `exchange.in` and of `off_ramp.value`. The grammar has no ambiguity. Space characters between symbols are ignored.

```text theme={null}
ValueExpr  := AddExpr

AddExpr    := AddExpr "+" MulExpr
            | AddExpr "-" MulExpr
            | MulExpr                       # left-associative, lowest precedence

MulExpr    := MulExpr "*" Atom
            | Atom                          # left-associative

Atom       := Number TokenName              # an amount, for example 100 USDC
            | Number                        # a bare number, for example 1.5
            | Percent                       # a percentage, for example 50% = 0.5
            | "trigger.value"
            | "min" "(" ValueExpr "," ValueExpr ")"
            | "max" "(" ValueExpr "," ValueExpr ")"
            | "(" ValueExpr ")"

Number     := [0-9]{1,19}
            | [0-9]{1,19} "." [0-9]{1,18}
Percent    := Number "%"                    # no space before %
TokenName  := a symbol of the token universe
```

A symbol in an expression must be one of these:

* `min` or `max` before `(`,
* `trigger.value`,
* a token symbol directly after a number.

Each other symbol is refused: a bare token name, a `$name`, and `trigger.<field>` for a field other than `value`. The language has no division, no unary minus, no negative literal, no comparison and no condition. The maximum length of one expression is 256 bytes.

## Unit rules

Each expression has one unit: an amount of token `T`, a percentage, a bare number, or open. Open is the unit of `trigger.value` under a transfer trigger without a range. A percentage and a bare number are two different units.

| Expression | Unit of the result |
| - | - |
| `<N> <T>` | amount of `T` |
| `<N>%` | percentage |
| `<N>` | bare number |
| `trigger.value` under a range in `T` | amount of `T` |
| `trigger.value` under a transfer trigger without a range | open |
| `trigger.value` under another trigger | refused |
| `a + b`, `a - b`, `min(a, b)`, `max(a, b)` | the shared unit; open joins any unit; two different units are refused, also a percentage and a bare number |
| amount `*` amount | refused |
| amount of `T` `*` anything else | amount of `T` (either order) |
| open `*` percentage, open `*` bare number, open `*` open | open (either order) |
| percentage `*` percentage, percentage `*` bare number | percentage (either order) |
| bare number `*` bare number | bare number |

The value of every action must have the unit "amount" or "open". The value of `off_ramp` must have the unit "amount of `EURe`". An open product of two amounts, such as `trigger.value * trigger.value`, passes these rules, and every fire refuses it.

## Evaluation rules

| Rule | Detail |
| - | - |
| Number format | Fixed point with 18 decimals. |
| Percent | `p%` is the ratio `p / 100`. |
| Product | Exact, then cut to 18 decimals toward zero. |
| Sum, difference | Exact. A result outside the format stops at its largest value. |
| Conversion to the token | Cut to the decimals of the token, toward zero. |
| Negative result | Refused at the fire. |
| Zero `exchange.in` | Refused at the fire. |
| `off_ramp` amount | Rounded down to whole cents. Under one cent: not paid. |

## Lexical forms

| Form | Rule |
| - | - |
| Number literal | Digits, with an optional point and 1 to 18 digits after it. No sign, no exponent. |
| `price_usd` | A YAML number or a text number. Greater than 0. At most 18 decimals. The parser also accepts a leading `+`, and a YAML number in exponent form such as `1e3`. |
| Value range bound | The digits of a number literal, at most 18 decimals. The parser also accepts a leading `+` or `-`, and a point with no digits after it, such as `1.`. A negative lower bound matches the same transfers as `0`. Write plain digits. |
| Integer fields | `interval_seconds`, `hold_seconds`, `cooldown_seconds`: a YAML integer or a text of digits, with an optional leading `+`, 0 to 18446744073709551615 before the range checks. |
| `day_of_month` entry | A YAML integer or a text of digits, 1 to 31. |
| Boolean | A YAML boolean, or the exact text `"true"` or `"false"`. |
| `HH`, `MM` | Exactly two digits. `HH` in `00`..`23`, `MM` in `00`..`59`. |
| `N` in `"*/N:MM"` | `1` to `23`, no leading zero. |
| Address | `0x` and exactly 40 hex characters, any letter case. |
| Canonical IBAN | Uppercase letters and digits only, 15 to 34 characters, two letters, two digits, then letters and digits, remainder 1 under modulo 97 after the ISO 13616 rearrangement. |
| Country | Exactly two uppercase ASCII letters. |
| Instant | RFC 3339, with date, time and offset (`Z` or `+hh:mm` or `-hh:mm`). |
| Time zone | A name of the IANA time zone database, for example `Europe/Berlin`. |
| YAML tag | The parser ignores a tag such as `!x` on a scalar or a list. A mapping with a tag is refused with `expected a mapping; got tagged`. Do not write tags. |

## Token universe

The parser accepts these 26 symbols, case-sensitive:

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

The stage then accepts only the tokens of the network:

| Network | Native coin | ERC-20 tokens |
| - | - | - |
| `polygon` | `POL` | `AAVE`, `EURe`, `LINK`, `USDC`, `USDC.e`, `USDT0`, `WBTC`, `WETH` |
| `xlayer` | `OKB` | `frxUSD`, `LINK`, `PAXGy`, `PYUSD`, `rsETH`, `sUSDe`, `uniBTC`, `USDC`, `USDe`, `USDG`, `USDT0`, `wNVDAx`, `wSPYx`, `xBTC`, `xETH`, `xSOL` |
| `polygon-amoy` | `POL` | `EURe`, `USDC` |

| Network | Fee tokens (`fees_method.token`) | `price_crossed` tokens |
| - | - | - |
| `polygon` | `POL`, `USDC`, `USDC.e`, `USDT0` | `AAVE`, `EURe`, `LINK`, `POL`, `WBTC`, `WETH` |
| `xlayer` | `OKB`, `USDC`, `USDG`, `USDT0` | `frxUSD`, `LINK`, `OKB`, `PAXGy`, `PYUSD`, `rsETH`, `sUSDe`, `uniBTC`, `USDe`, `wNVDAx`, `wSPYx`, `xBTC`, `xETH`, `xSOL` |
| `polygon-amoy` | `POL`, `USDC` | `EURe`, `POL` |

## Availability by network and account kind

| Construct | `polygon` | `xlayer` | `polygon-amoy` | `safe_module` | `erc20_allow` |
| - | - | - | - | - | - |
| `periodic`, `calendar`, `at_fixed_time` | yes | yes | yes | yes | yes |
| `incoming_tx`, `outgoing_tx` | yes | yes | yes | yes | yes |
| `price_crossed` | yes | yes | yes, on `EURe` and `POL`, with fixed test prices | yes | yes |
| `send_one`, `send_batch` | yes | yes | yes | yes | ERC-20 tokens named by the document |
| `exchange` | yes | yes | no | yes | ERC-20 on both sides, input named by the document, adapter runs swaps |
| `notify` | yes | yes | yes | yes | yes |
| `off_ramp` | no | no | yes | yes, Safe linked to Monerium | no |
| `global.fees_method` | optional | optional | optional | optional | required, not the native coin |

"Named by the document" means a literal amount, or `trigger.value` under a transfer trigger with a range.

## Numeric limits

| Limit | Value | Checked |
| - | - | - |
| Document length | 65536 bytes | before the YAML parse |
| Nesting depth | 32 levels | before the YAML parse |
| YAML anchors and aliases | 0 | before the YAML parse |
| Rules per document | 32 | parse |
| Actions per rule | at least 1; no other limit than the document length | parse |
| Value expression length | 256 bytes | parse |
| Integer digits of a literal | 19 | parse |
| Fraction digits of a literal | 18 | parse |
| `periodic.interval_seconds` | 10 to 3153600000 | parse |
| `day_of_month` entry | 1 to 31 | parse |
| `time_of_day` step `N` | 1 to 23 | parse |
| `price_usd` | greater than 0 | parse |
| `off_ramp.memo` | 5 to 140 characters, at least 5 after trim | parse |
| IBAN length | 15 to 34 characters | parse |
| `send_batch` recipients | 1 to 24 | parse (minimum), stage (maximum) |
| Literal action amount | above the fee floor, \$0.20 worth | stage |
| `off_ramp` literal amount | whole cents | parse |
| ERC20Allow cap period | at least 3600 seconds | on chain |

## Check a document by hand

Apply these checks in this order. The engine applies them in the same order, and it reports the first failure.

**1. Size**

The text is at most 65536 bytes, nests at most 32 levels, and has no `&anchor` or `*alias`.

**2. YAML**

The text is valid YAML. The top level is a mapping. No key occurs twice in one mapping.

**3. Shape**

Every mapping has only its known keys and every required key. Every scalar has its form. Every list that needs an item has one. `rules` or `agent_envelope` is present.

**4. Units**

Every expression follows the [unit rules](#unit-rules). Each `exchange` has two different tokens when the input token is known.

**5. References and allowlists**

Every `$name` exists and holds the right form. `trigger.value` occurs only under a transfer trigger. Transfer filters avoid the zero address and self-matches. Each literal `off_ramp` amount has whole cents. Each token, recipient and IBAN is on its allowlist.

**6. Network and account**

Every token is a token of the network. No payment goes to the account itself or to the zero address. Each action and trigger is available on the network and for the account kind. Each literal amount is above the fee floor. The fee token is allowed and is on `token_allowlist`.

The refusal text of each check is on [Validation](https://docs.ana.fi/rules/validation.md).


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