# CEL Variables Reference

Context variables available in CEL expressions across Twisp APIs.

Twisp uses [Common Expression Language](https://cel.dev/) extensively for computation across the API. Different contexts expose different variables depending on their purpose. This reference documents what variables are available in each context.

## Overview

| Context                       | Primary Variable | Description                     |
|-------------------------------|------------------|---------------------------------|
| [Indexes](https://www.twisp.com/docs/reference/cel/variables.md#indexes)           | `document`       | The record being indexed        |
| [Calculations](https://www.twisp.com/docs/reference/cel/variables.md#calculations) | `context.vars`   | Transaction and account context |
| [Tran Codes](https://www.twisp.com/docs/reference/cel/variables.md#tran-codes)     | `params`         | Post-time parameters            |

---

## Indexes

Custom indexes use CEL expressions to define partition keys, sort keys, and filter constraints. In all index expressions, the primary variable is `document`, which represents the record being indexed.

### Available Variables

| Variable   | Type             | Description              |
|------------|------------------|--------------------------|
| `document` | Protobuf message | The entity being indexed |

The type of `document` depends on the `on` field specified when creating the index:

- `Account` → [Account](https://www.twisp.com/docs/reference/cel/variables.md#account-fields)
- `AccountSet` → [AccountSet](https://www.twisp.com/docs/reference/cel/variables.md#account-set-fields)
- `Transaction` → [Transaction](https://www.twisp.com/docs/reference/cel/variables.md#transaction-fields)
- `TranCode` → [TranCode](https://www.twisp.com/docs/reference/cel/variables.md#trancode-fields)
- `Balance` → [Balance](https://www.twisp.com/docs/reference/cel/variables.md#balance-fields)
- `Entry` → [Entry](https://www.twisp.com/docs/reference/cel/variables.md#entry-fields)

### Partition Expressions

Partition keys determine how records are grouped in the index.

```graphql
mutation CreatePartitionedIndex {
  schema {
    createIndex(
      input: {
        name: "entries_by_account"
        on: Entry
        partition: [
          { alias: "accountId", value: "document.account_id" }
          { alias: "journalId", value: "document.journal_id" }
        ]
        sort: [{ alias: "created", value: "document.created", sort: DESC }]
      }
    ) { name }
  }
}
```

Partition expressions can return arrays to create multiple index entries. For example, this creates one partition for the account ID and one for each of its parent account sets (at the time of posting):

```graphql
partition: [
  {
    alias: "accountId",
    value: "document.parent_account_ids + [document.account_id]"
  }
]
```

### Sort Expressions

Sort keys define the ordering within each partition. Every index needs at least one sort key. This example sorts by `metadata.effective` when the entry has one, and by its creation time otherwise:

```graphql
mutation CreateSortedIndex {
  schema {
    createIndex(
      input: {
        name: "entries_by_effective"
        on: Entry
        partition: [{ alias: "accountId", value: "document.account_id" }]
        sort: [
          {
            alias: "effective"
            value: "'effective' in document.metadata && document.metadata.effective != null ? document.metadata.effective : document.created"
            type: STRING
            sort: DESC
          }
        ]
      }
    ) { name }
  }
}
```

### Filter Constraints

Constraints are boolean expressions that must all evaluate to `true` for a record to be included in the index.

```graphql
mutation CreateFilteredIndex {
  schema {
    createIndex(
      input: {
        name: "active_entries"
        on: Entry
        partition: [{ alias: "accountId", value: "document.account_id" }]
        sort: [{ alias: "created", value: "document.created", sort: DESC }]
        constraints: {
          isNotVoidEntry: "!document.is_void_entry"
          isNotVoidedEntry: "!document.is_voided_entry"
          isSettled: "document.layer == SETTLED"
        }
      }
    ) { name }
  }
}
```

---

## Calculations

Calculations define how balances are computed and grouped. CEL expressions are used in dimension definitions and conditions.

> **Note:**
>
> **Expressions must resolve to a concrete type.** When you call `createCalculation`, each dimension expression is evaluated against an example record so its storage type can be inferred, and the `condition` expression must resolve to a boolean. Paths that reach into `dyn` JSON fields — like `context.vars.account.metadata.*` or `context.vars.entry.metadata.*` — won't resolve on their own. Two ways to fix this:
>
> - **Cast the result**: `string(context.vars.account.metadata.region)`, `int(context.vars.entry.metadata.score)`, `bool(context.vars.account.metadata.verified)`.
> - **Provide a typed fallback** with optional access: `context.vars.account.?metadata.orValue({}).?region.orValue('')` resolves to a string even when `metadata.region` is missing.
>
> The same rule applies to `condition` — it must resolve to a `bool`. Use `bool(...)` or `.orValue(false)` if your expression reaches into untyped metadata.

### Available Variables

| Variable | Type | Description |
|----------|------|-------------|
| `context.vars.entry` | [Entry](https://www.twisp.com/docs/reference/cel/variables.md#entry-fields) | The entry being evaluated |
| `context.vars.transaction` | [Transaction](https://www.twisp.com/docs/reference/cel/variables.md#transaction-fields) | The parent transaction of the entry |
| `context.vars.account` | [Account](https://www.twisp.com/docs/reference/cel/variables.md#account-fields) | The account the entry is posted to |

### Dimension Expressions

Dimensions define how balances are grouped. Common use cases include grouping by date, metadata values, or account properties.

```graphql
mutation CreateEffectiveDateCalculation {
  createCalculation(
    input: {
      calculationId: "5867b5dd-fc69-416c-80f5-62e8a53610d5"
      code: "EFFECTIVE_DATE"
      description: "Track balances per effective date."
      dimensions: [
        {
          alias: "effectiveDate"
          value: "context.vars.transaction.effective"
        }
      ]
      scope: LOCAL
    }
  ) {
    calculationId
    code
  }
}
```

Multi-dimensional calculations:

```graphql
mutation CreateMultiDimensionCalculation {
  createCalculation(
    input: {
      calculationId: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
      code: "BY_REGION_AND_DATE"
      description: "Track balances by account region and effective date."
      dimensions: [
        {
          alias: "region"
          value: "context.vars.account.?metadata.orValue({}).?region.orValue('')"
        }
        {
          alias: "effectiveDate"
          value: "context.vars.transaction.effective"
        }
      ]
      scope: LOCAL
    }
  ) { calculationId }
}
```

### Condition Expressions

Conditions filter which entries are included in the calculation. They must evaluate to a boolean.

```graphql
mutation CreateConditionalCalculation {
  createCalculation(
    input: {
      calculationId: "b2c3d4e5-f6a7-8901-bcde-f23456789012"
      code: "POLICY_PAYMENTS"
      description: "Track only entries to accounts with policy payment metadata."
      dimensions: [
        { alias: "effectiveDate", value: "context.vars.transaction.effective" }
      ]
      condition: "has(context.vars.account.metadata.policyPayment)"
      scope: LOCAL
    }
  ) { calculationId }
}
```

Using entry fields in conditions. In calculation expressions, enum fields compare as numbers: `layer` is `0` (SETTLED), `1` (PENDING) or `2` (ENCUMBRANCE), and `direction` is `0` (DEBIT) or `1` (CREDIT). Comparing them to a name such as `'SETTLED'` matches no entries. This condition keeps only settled debits:

```graphql
condition: "context.vars.entry.layer == 0 && context.vars.entry.direction == 0"
```

---

## Tran Codes

Tran codes are templates that define how transactions and entries are created. CEL expressions are used extensively to dynamically compute values at post time.

### Available Variables

| Variable | Type | Description |
|----------|------|-------------|
| `params` | Struct | Parameters passed when posting the transaction, with defaults applied |
| `vars` | Struct | Values computed in the tran code's `vars` field |
| `metadata` | Struct | The tran code's own `metadata` |
| `trancode` | [TranCode](https://www.twisp.com/docs/reference/cel/variables.md#trancode-fields) | The tran code being invoked |
| `transaction_id` | UUID | The `transactionId` of the transaction being posted |

### Parameter Access

Parameters are defined in the tran code and passed at post time. Access them with `params.<paramName>`:

```graphql
mutation CreateTranCode {
  createTranCode(
    input: {
      tranCodeId: "3f1c9a52-2d4e-4b8a-9c71-5e0d6a7b8c90"
      code: "TRANSFER"
      description: "Transfer funds between accounts."
      params: [
        { name: "amount", type: DECIMAL, description: "Transfer amount" }
        { name: "fromAccount", type: UUID, description: "Source account" }
        { name: "toAccount", type: UUID, description: "Destination account" }
        { name: "memo", type: STRING, default: "Transfer", description: "Optional memo" }
      ]
      transaction: {
        description: "'Transfer ' + string(params.amount) + ' - ' + params.memo"
      }
      entries: [
        {
          entryType: "'TRANSFER_DR'"
          accountId: "params.fromAccount"
          direction: "DEBIT"
          units: "params.amount"
          currency: "'USD'"
        }
        {
          entryType: "'TRANSFER_CR'"
          accountId: "params.toAccount"
          direction: "CREDIT"
          units: "params.amount"
          currency: "'USD'"
        }
      ]
    }
  ) { code }
}
```

Posting with `amount: "25.00"` and no `memo` writes a transaction described as `Transfer 25.00 - Transfer`.

> **Warning:**
>
> **A param's `default` is a literal value, not a CEL expression.** Write `default: "Transfer"`, `default: "USD"` or `default: "2026-10-01"`. A quoted default such as `default: "'USD'"` is kept as the five characters `'USD'`, quotes included, and entries using it are posted in a currency named `'USD'`. A `DATE` param's default must be a date such as `2026-10-01`; `date.Today()` is rejected when the tran code is created. The same applies to a param's `example`.

To default a date to the posting day, compute it in the transaction's `effective` expression instead of in the param default:

```graphql
params: [
  { name: "amount", type: DECIMAL }
  { name: "effective", type: STRING, default: "", description: "Effective date. Defaults to today (UTC)." }
]
transaction: {
  effective: "params.effective == '' ? date.Today() : date(params.effective)"
}
```

### Vars (Scratch Pad)

The `vars` field holds intermediate values. Each var is a CEL expression that can read `params`, and transaction and entry expressions can read the results as `vars.<name>`. A var cannot read another var. Group related values in nested maps, such as `vars: { fees: { flat: "...", pct: "..." } }`, read as `vars.fees.flat`.

Decimal values support `+`, `-` and comparisons. Use `decimal.Mul`, `decimal.Quo` and `decimal.Round` to multiply, divide and round (see [Functions and Examples](https://www.twisp.com/docs/reference/cel/examples.md)).

```graphql
mutation CreateTranCodeWithVars {
  createTranCode(
    input: {
      tranCodeId: "8b2e4f61-7a3c-4d95-b0e8-1f6a2c9d3e47"
      code: "TRANSFER_NET_OF_FEE"
      description: "Transfer funds and keep a 2.5% fee."
      params: [
        { name: "amount", type: DECIMAL }
        { name: "fromAccount", type: UUID }
        { name: "toAccount", type: UUID }
        { name: "feeAccount", type: UUID }
      ]
      vars: {
        feeAmount: "decimal.Round(decimal.Mul(params.amount, decimal('0.025')), 'half_up', 2)"
      }
      transaction: {
        description: "'Transfer ' + string(params.amount) + ', fee ' + string(vars.feeAmount)"
      }
      entries: [
        {
          entryType: "'TRANSFER_DR'"
          accountId: "params.fromAccount"
          direction: "DEBIT"
          units: "params.amount"
          currency: "'USD'"
        }
        {
          entryType: "'TRANSFER_CR'"
          accountId: "params.toAccount"
          direction: "CREDIT"
          units: "params.amount - vars.feeAmount"
          currency: "'USD'"
        }
        {
          entryType: "'FEE_CR'"
          accountId: "params.feeAccount"
          direction: "CREDIT"
          units: "vars.feeAmount"
          currency: "'USD'"
        }
      ]
    }
  ) { code }
}
```

Posting with `amount: "100.00"` writes a 100.00 debit, a 97.50 credit and a 2.50 fee credit.

### Entry Conditions

An entry's `condition` decides whether the entry is written. The entry is written only when the condition evaluates to `true`. The entries that are written must still balance, so make both sides of an optional pair conditional:

```graphql
entries: [
  # ... the main debit and credit ...
  {
    entryType: "'FEE_DR'"
    accountId: "params.fromAccount"
    direction: "DEBIT"
    units: "params.fee"
    currency: "'USD'"
    condition: "params.fee > decimal('0')"
  }
  {
    entryType: "'FEE_CR'"
    accountId: "params.feeAccount"
    direction: "CREDIT"
    units: "params.fee"
    currency: "'USD'"
    condition: "params.fee > decimal('0')"
  }
]
```

Compare decimals with decimals. `params.fee > 0` and `params.fee > decimal(0.00)` are rejected when the tran code is created; write `decimal('0')`.

### Transaction Fields

All fields in the `transaction` block accept CEL expressions:

| Field | Expected Type | Example |
|-------|--------------|---------|
| `journalId` | UUID | `"uuid('b28f5684-0834-4292-8016-d2f2fb0367a9')"` |
| `correlationId` | String | `"params.correlationId"` |
| `externalId` | String | `"params.externalId"` |
| `effective` | Date | `"date('2024-01-15')"`, `"params.effectiveDate"` or `"date.Today('America/New_York')"` |
| `description` | String | `"'Payment: ' + string(params.amount)"` |
| `metadata` | JSON | `"{ 'source': 'api', 'amount': string(params.amount) }"` |

When `journalId` is omitted, the default journal is used. When `effective` is omitted, it is `date.Today()`, the current date in UTC.

### Entry Fields

All fields in each entry accept CEL expressions:

| Field | Expected Type | Example |
|-------|--------------|---------|
| `entryType` | String | `"'ACH_CREDIT'"` |
| `accountId` | UUID | `"params.accountId"` |
| `layer` | Enumeration | `"SETTLED"` or `"PENDING"` or `"ENCUMBRANCE"` |
| `direction` | Enumeration | `"DEBIT"` or `"CREDIT"` |
| `units` | Decimal | `"params.amount"` or `"decimal('100.00')"` |
| `currency` | String | `"'USD'"` or `"params.currency"` |
| `description` | String | `"'Entry for ' + params.memo"` |
| `metadata` | CEL Map/JSON | `"{ 'lineItem': params.lineItem }"` |
| `condition` | Boolean | `"params.amount > decimal('0')"` |

`layer` and `direction` take the bare names shown above. They can also be computed, for example `"params.amount > decimal('0') ? DEBIT : CREDIT"`. When `layer` is omitted it is `SETTLED`. When `entryType` is omitted it is the tran code's `code` followed by `_DR` or `_CR`.

---

## Entity Field Reference

### Account Fields

| Field | Type | Description |
|-------|------|-------------|
| `account_id` | UUID | Unique identifier |
| `status` | Enum | ACTIVE, LOCKED, or INACTIVE |
| `name` | String | Account name |
| `code` | String | Shorthand code |
| `normal_balance_type` | Enum | DEBIT (0) or CREDIT (1) |
| `description` | String | Account description |
| `metadata` | Struct | Arbitrary JSON data |
| `created` | Timestamp | Creation time |
| `modified` | Timestamp | Last modification time |
| `external_id` | String | External system identifier |

### Account Set Fields

| Field | Type | Description |
|-------|------|-------------|
| `account_set_id` | UUID | Unique identifier |
| `journal_id` | UUID | Associated journal |
| `account_id` | UUID | Associated account ID |
| `name` | String | Set name |
| `description` | String | Set description |
| `metadata` | Struct | Arbitrary JSON data |
| `created` | Timestamp | Creation time |
| `modified` | Timestamp | Last modification time |
| `code` | String | Unique code |
| `has_members` | Boolean | True once the set has ever contained a member; never reset — not a current-emptiness check |

### Transaction Fields

| Field | Type | Description |
|-------|------|-------------|
| `transaction_id` | UUID | Unique identifier |
| `tran_code_id` | UUID | Associated tran code |
| `journal_id` | UUID | Associated journal |
| `correlation_id` | String | Groups related transactions |
| `external_id` | String | External system identifier |
| `effective` | Date | Accounting effective date |
| `description` | String | Transaction description |
| `metadata` | Struct | Arbitrary JSON data |
| `created` | Timestamp | Creation time |
| `modified` | Timestamp | Last modification time |

### Entry Fields

| Field | Type | Description |
|-------|------|-------------|
| `entry_id` | UUID | Unique identifier |
| `transaction_id` | UUID | Parent transaction |
| `journal_id` | UUID | Associated journal |
| `account_id` | UUID | Target account |
| `entry_type` | String | Entry type code |
| `layer` | Enum | SETTLED (0), PENDING (1), or ENCUMBRANCE (2) |
| `direction` | Enum | DEBIT (0) or CREDIT (1) |
| `description` | String | Entry description |
| `amount` | Money | Entry amount with currency |
| `metadata` | Struct | Arbitrary JSON data |
| `created` | Timestamp | Creation time |
| `modified` | Timestamp | Last modification time |
| `parent_account_ids` | List[UUID] | Parent account set IDs |
| `is_void_entry` | Boolean | True if this is a voiding entry |
| `is_voided_entry` | Boolean | True if this entry was voided |

### TranCode Fields

| Field | Type | Description |
|-------|------|-------------|
| `tran_code_id` | UUID | Unique identifier |
| `code` | String | Unique code identifier |
| `description` | String | Tran code description |
| `status` | Enum | ACTIVE, LOCKED, or INACTIVE |
| `params` | List | Parameter definitions |
| `transaction` | Struct | Transaction template |
| `entries` | List | Entry templates |
| `metadata` | Struct | Arbitrary JSON data |
| `created` | Timestamp | Creation time |
| `modified` | Timestamp | Last modification time |

### Balance Fields

| Field | Type | Description |
|-------|------|-------------|
| `journal_id` | UUID | Associated journal |
| `account_id` | UUID | Associated account |
| `transaction_id` | UUID | Last transaction |
| `entry_id` | UUID | Last entry |
| `currency` | String | Currency code |
| `settled` | BalanceAmount | Settled layer balance |
| `pending` | BalanceAmount | Pending layer balance |
| `encumbrance` | BalanceAmount | Encumbrance layer balance |
| `created` | Timestamp | Creation time |
| `modified` | Timestamp | Last modification time |
| `calculation_id` | UUID | Associated calculation |
| `dimensions` | Struct | Dimension values |

---

## Type Constructors

When working with CEL expressions, use these constructors to create typed values:

| Constructor | Example | Description |
|------------|---------|-------------|
| `uuid(string)` | `uuid('a1b2c3d4-...')` | Parse UUID from string |
| `decimal(string)` | `decimal('100.50')` | High-precision decimal |
| `money(string, string)` | `money('100.00', 'USD')` | Money with currency |
| `date(string)` | `date('2024-01-15')` | Parse date (YYYY-MM-DD) |
| `timestamp(string)` | `timestamp('2024-01-15T10:30:00Z')` | Parse ISO 8601 timestamp |
| `bool(string)` | `bool('true')` | Parse boolean |
| `int(string)` | `int('42')` | Parse integer |
| `string(any)` | `string(params.amount)` | Convert to string |

For a complete list of functions, see the [CEL Functions Reference](https://www.twisp.com/docs/reference/cel/examples.md).
