> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gu1.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Rules Configuration

> Complete guide for creating and configuring transaction monitoring rules — in the gu1 transaction monitoring product for fraud and AML.

## Introduction

gu1's rules engine allows you to create custom logic to analyze transactions in real-time. Rules can be **synchronous** (affect transaction decision) or **asynchronous** (monitoring only).

## Sync vs Async Rules

### Synchronous Rules (SYNC)

**Execute during API call and affect transaction decision**

**When to use:**

* Block fraudulent transactions
* Enforce transaction limits
* Require additional authentication
* Regulatory requirements

**Characteristics:**

* Evaluated before response
* Can change transaction state
* Performance target: \< 100ms
* Limited to lightweight operations

**Example:**

```
Daily limit exceeded → REJECT transaction
```

### Asynchronous Rules (ASYNC)

**Execute in parallel without affecting transaction**

**When to use:**

* Pattern monitoring
* Behavioral analysis
* Complex aggregations
* Historical analysis

**Characteristics:**

* Don't block API response
* Can perform heavy queries
* Generate alerts only
* Feed Intelligence Dashboard

**Example:**

```
User has 15 transactions today → Generate MEDIUM alert
```

## Rule Structure

```json theme={null}
{
  "name": "Rule Name",
  "category": "fraud|aml|compliance|risk",
  "priority": 100,
  "enabled": true,
  "evaluationMode": "sync|async",
  "targetEntityTypes": ["transaction"],
  "conditions": {
    "operator": "AND|OR",
    "conditions": [...]
  },
  "actions": [...]
}
```

## Configuration Fields

### Basic Fields

| Field               | Type    | Description                                 |
| ------------------- | ------- | ------------------------------------------- |
| `name`              | string  | Rule name (unique)                          |
| `category`          | string  | Category: fraud, aml, compliance, risk      |
| `priority`          | number  | Execution priority (1-1000, higher = first) |
| `enabled`           | boolean | Enable/disable rule                         |
| `evaluationMode`    | string  | "sync" or "async"                           |
| `targetEntityTypes` | array   | Entity types to evaluate (\["transaction"]) |

### Conditions

Rules use a flexible conditions system:

```json theme={null}
{
  "conditions": {
    "operator": "AND",
    "conditions": [
      {
        "field": "amount",
        "operator": "GREATER_THAN",
        "value": 10000
      },
      {
        "field": "currency",
        "operator": "IN",
        "value": ["USD", "EUR", "GBP"]
      }
    ]
  }
}
```

### Condition Operators

| Operator                | Description            | Example                          |
| ----------------------- | ---------------------- | -------------------------------- |
| `EQUALS`                | Exact equality         | `"type" EQUALS "PAYMENT"`        |
| `NOT_EQUALS`            | Not equal              | `"status" NOT_EQUALS "blocked"`  |
| `GREATER_THAN`          | Greater than           | `"amount" > 1000`                |
| `GREATER_THAN_OR_EQUAL` | Greater or equal       | `"amount" >= 1000`               |
| `LESS_THAN`             | Less than              | `"amount" < 100`                 |
| `LESS_THAN_OR_EQUAL`    | Less or equal          | `"amount" <= 100`                |
| `IN`                    | In list                | `"country" IN ["US", "CA"]`      |
| `NOT_IN`                | Not in list            | `"country" NOT_IN ["KP", "IR"]`  |
| `CONTAINS`              | String contains        | `"description" CONTAINS "test"`  |
| `NOT_CONTAINS`          | String doesn't contain | `"email" NOT_CONTAINS "@temp"`   |
| `STARTS_WITH`           | String starts with     | `"accountId" STARTS_WITH "4532"` |
| `ENDS_WITH`             | String ends with       | `"domain" ENDS_WITH ".ru"`       |
| `REGEX`                 | Regex match            | `"email" REGEX "^[a-z]+@"`       |
| `EXISTS`                | Field exists           | `"metadata.userId" EXISTS`       |
| `NOT_EXISTS`            | Field doesn't exist    | `"referralCode" NOT_EXISTS`      |

### Available Transaction Fields

```javascript theme={null}
// Core Fields
transaction.externalId
transaction.type          // PAYMENT, TRANSFER, WITHDRAWAL, etc.
transaction.amount
transaction.currency
transaction.timestamp

// Entity References
transaction.originEntityId
transaction.destinationEntityId

// Payment Details
transaction.origin.paymentMethod
transaction.origin.accountType
transaction.destination.paymentMethod

// Device Data
transaction.originDeviceData.ipAddress
transaction.originDeviceData.platform
transaction.originDeviceData.location.country
transaction.originDeviceData.location.city

// MCC and Description
transaction.mccCode
transaction.description

// Tags and Metadata
transaction.tags
transaction.metadata.*     // Any custom field

// Computed Fields (available in rules)
amountInUsd               // Amount converted to USD
metadata.userTransactionCount30d
metadata.merchantChargebackRate
metadata.deviceFirstSeen
metadata.ipRiskScore
```

### Actions

Rules can trigger multiple actions:

#### 1. Generate Alert

```json theme={null}
{
  "type": "generate_alert",
  "config": {
    "severity": "low|medium|high|critical",
    "type": "custom_alert_type",
    "message": "Alert description with {{variables}}"
  }
}
```

#### 2. Set Decision (SYNC only)

```json theme={null}
{
  "type": "set_decision",
  "config": {
    "decision": "APPROVE|REJECT|HOLD|REVIEW_REQUIRED|ADDITIONAL_AUTH_REQUIRED",
    "reason": "Reason for decision"
  }
}
```

#### 3. Create Investigation

```json theme={null}
{
  "type": "create_investigation",
  "config": {
    "priority": "low|medium|high|critical",
    "assignToTeam": "team_id",
    "assignToUser": "user_id",
    "requiresSAR": true
  }
}
```

## Example Rules

### 1. Daily Transaction Limit (SYNC)

```json theme={null}
{
  "name": "Daily Limit - $10,000",
  "category": "compliance",
  "priority": 950,
  "enabled": true,
  "evaluationMode": "sync",
  "targetEntityTypes": ["transaction"],
  "conditions": {
    "operator": "AND",
    "conditions": [
      {
        "field": "metadata.userTransactionSum24h",
        "operator": "GREATER_THAN",
        "value": 10000
      },
      {
        "field": "amount",
        "operator": "GREATER_THAN",
        "value": 0
      }
    ]
  },
  "actions": [
    {
      "type": "generate_alert",
      "config": {
        "severity": "high",
        "type": "daily_limit_exceeded",
        "message": "User {{originEntityId}} exceeded daily limit of $10,000"
      }
    },
    {
      "type": "set_decision",
      "config": {
        "decision": "HOLD",
        "reason": "Daily transaction limit exceeded"
      }
    }
  ]
}
```

### 2. Transaction Velocity Alert (ASYNC)

```json theme={null}
{
  "name": "High Transaction Velocity",
  "category": "fraud",
  "priority": 800,
  "enabled": true,
  "evaluationMode": "async",
  "targetEntityTypes": ["transaction"],
  "conditions": {
    "operator": "AND",
    "conditions": [
      {
        "field": "metadata.userTransactionCount1h",
        "operator": "GREATER_THAN",
        "value": 10
      },
      {
        "field": "metadata.userAverageTransactionsPerHour",
        "operator": "LESS_THAN",
        "value": 3
      }
    ]
  },
  "actions": [
    {
      "type": "generate_alert",
      "config": {
        "severity": "medium",
        "type": "velocity_anomaly",
        "message": "User has {{metadata.userTransactionCount1h}} transactions in last hour (average: {{metadata.userAverageTransactionsPerHour}})"
      }
    }
  ]
}
```

### 3. High-Risk Country Block (SYNC)

```json theme={null}
{
  "name": "Block High-Risk Countries",
  "category": "fraud",
  "priority": 1000,
  "enabled": true,
  "evaluationMode": "sync",
  "targetEntityTypes": ["transaction"],
  "conditions": {
    "operator": "AND",
    "conditions": [
      {
        "field": "originDeviceData.location.country",
        "operator": "IN",
        "value": ["KP", "IR", "SY"]
      },
      {
        "field": "amount",
        "operator": "GREATER_THAN",
        "value": 100
      }
    ]
  },
  "actions": [
    {
      "type": "generate_alert",
      "config": {
        "severity": "critical",
        "type": "high_risk_country",
        "message": "Transaction from high-risk country: {{originDeviceData.location.country}}"
      }
    },
    {
      "type": "set_decision",
      "config": {
        "decision": "REJECT",
        "reason": "Transaction from sanctioned country"
      }
    }
  ]
}
```

### 4. Structuring Pattern Detection (ASYNC)

```json theme={null}
{
  "name": "Possible Structuring - $10K Threshold",
  "category": "aml",
  "priority": 900,
  "enabled": true,
  "evaluationMode": "async",
  "targetEntityTypes": ["transaction"],
  "conditions": {
    "operator": "AND",
    "conditions": [
      {
        "field": "amountInUsd",
        "operator": "GREATER_THAN",
        "value": 9000
      },
      {
        "field": "amountInUsd",
        "operator": "LESS_THAN",
        "value": 10000
      },
      {
        "field": "metadata.userTransactionsSameAmountRange7d",
        "operator": "GREATER_THAN_OR_EQUAL",
        "value": 3
      }
    ]
  },
  "actions": [
    {
      "type": "generate_alert",
      "config": {
        "severity": "high",
        "type": "possible_structuring",
        "message": "User has {{metadata.userTransactionsSameAmountRange7d}} transactions near $10K threshold in last 7 days"
      }
    },
    {
      "type": "create_investigation",
      "config": {
        "priority": "high",
        "assignToTeam": "aml_compliance",
        "requiresSAR": true
      }
    }
  ]
}
```

### 5. New Card High Amount (SYNC)

```json theme={null}
{
  "name": "New Card - High Amount Alert",
  "category": "fraud",
  "priority": 850,
  "enabled": true,
  "evaluationMode": "sync",
  "targetEntityTypes": ["transaction"],
  "conditions": {
    "operator": "AND",
    "conditions": [
      {
        "field": "origin.paymentMethod",
        "operator": "EQUALS",
        "value": "CARD"
      },
      {
        "field": "metadata.cardFirstSeen",
        "operator": "LESS_THAN",
        "value": "{{timestamp - 3600}}"
      },
      {
        "field": "amount",
        "operator": "GREATER_THAN",
        "value": 500
      }
    ]
  },
  "actions": [
    {
      "type": "generate_alert",
      "config": {
        "severity": "high",
        "type": "new_card_high_amount",
        "message": "First transaction with new card for ${{amount}}"
      }
    },
    {
      "type": "set_decision",
      "config": {
        "decision": "ADDITIONAL_AUTH_REQUIRED",
        "reason": "High amount transaction with new card - require 3DS"
      }
    }
  ]
}
```

### 6. Unusual Time Pattern (ASYNC)

```json theme={null}
{
  "name": "Transaction Outside Normal Hours",
  "category": "fraud",
  "priority": 700,
  "enabled": true,
  "evaluationMode": "async",
  "targetEntityTypes": ["transaction"],
  "conditions": {
    "operator": "AND",
    "conditions": [
      {
        "field": "metadata.transactionHour",
        "operator": "IN",
        "value": [0, 1, 2, 3, 4, 5]
      },
      {
        "field": "metadata.userNormalHours",
        "operator": "NOT_CONTAINS",
        "value": "{{metadata.transactionHour}}"
      },
      {
        "field": "amount",
        "operator": "GREATER_THAN",
        "value": 1000
      }
    ]
  },
  "actions": [
    {
      "type": "generate_alert",
      "config": {
        "severity": "medium",
        "type": "unusual_time",
        "message": "Transaction at {{metadata.transactionHour}}:00 - outside user's normal hours"
      }
    }
  ]
}
```

## Advanced Conditions

### Nested Conditions

```json theme={null}
{
  "conditions": {
    "operator": "OR",
    "conditions": [
      {
        "operator": "AND",
        "conditions": [
          {"field": "amount", "operator": "GREATER_THAN", "value": 5000},
          {"field": "type", "operator": "EQUALS", "value": "WITHDRAWAL"}
        ]
      },
      {
        "operator": "AND",
        "conditions": [
          {"field": "amount", "operator": "GREATER_THAN", "value": 10000},
          {"field": "type", "operator": "EQUALS", "value": "TRANSFER"}
        ]
      }
    ]
  }
}
```

### Regex Patterns

```json theme={null}
{
  "field": "description",
  "operator": "REGEX",
  "value": "^(test|demo|fake).*"
}
```

### Time-Based Aggregations

```json theme={null}
{
  "field": "metadata.userTransactionCount",
  "operator": "GREATER_THAN",
  "value": 5,
  "timeWindow": "1h"
}
```

## Best Practices

### ✅ DO

1. **Use appropriate evaluation mode**
   * SYNC for decisions that must block
   * ASYNC for monitoring and analysis

2. **Set correct priorities**
   * Critical blocks: 900-1000
   * Standard checks: 500-899
   * Monitoring: 100-499

3. **Include meaningful messages**
   * Use template variables: `{{field}}`
   * Provide context for analysts
   * Include relevant metrics

4. **Test thoroughly**
   * Start with ASYNC mode
   * Monitor false positive rate
   * Adjust thresholds based on data

5. **Use metadata fields**
   * Aggregate data for patterns
   * Track historical behavior
   * Calculate risk scores

### ❌ DON'T

1. **Don't use heavy queries in SYNC rules**
   * Keep SYNC rules fast (\< 100ms)
   * Move complex logic to ASYNC

2. **Don't over-block**
   * Start with HOLD instead of REJECT
   * Allow for manual review
   * Monitor customer impact

3. **Don't create overlapping rules**
   * One rule should handle one pattern
   * Use priorities correctly
   * Avoid redundant checks

4. **Don't ignore false positives**
   * Track and analyze
   * Adjust thresholds
   * Use machine learning when available

## Testing Rules

### Test Mode

Enable test mode to evaluate rules without affecting transactions:

```json theme={null}
{
  "name": "Test Rule",
  "enabled": true,
  "testMode": true,
  ...
}
```

### A/B Testing

Create variant rules to compare effectiveness:

```json theme={null}
{
  "name": "Fraud Check - Variant A",
  "variant": "A",
  "percentage": 50,
  ...
}
```

### Monitoring Metrics

Track for each rule:

* **Execution count**: How often rule runs
* **Match rate**: % of times conditions met
* **False positive rate**: Incorrectly flagged
* **True positive rate**: Correctly flagged
* **Average execution time**: Performance

## Next Steps

<CardGroup cols={3}>
  <Card title="Fraud Detection" icon="shield" href="/en/use-cases/transaction-monitoring/fraud-detection">
    Production-ready fraud rules
  </Card>

  <Card title="AML Monitoring" icon="building-columns" href="/en/use-cases/transaction-monitoring/aml-monitoring">
    AML compliance rules
  </Card>

  <Card title="Merchant Monitoring" icon="shop" href="/en/use-cases/transaction-monitoring/merchant-monitoring">
    Merchant risk rules
  </Card>

  <Card title="API Reference" icon="code" href="/en/use-cases/transaction-monitoring/api-reference">
    Complete API documentation
  </Card>

  <Card title="Custom lists API" icon="list" href="/en/api-reference/data-lists/overview">
    Create lists and items for `in_custom_list` and related operators
  </Card>
</CardGroup>
