Docs/Core SDK/Policy Engine

Policy Engine

Define and enforce permission boundaries with spending caps, rate limits, allowlists, and custom predicates evaluated locally before any action executes.

import { Invariance, checkPolicies } from '@invariance/sdk';
Prerequisites: Initialization

Overview

The policy engine provides local, in-process enforcement of action constraints. Policies are defined as an array of `PolicyRule` objects passed to `Invariance.init()`. When you call `inv.wrap()`, all configured policies are evaluated before the function executes.

Four rule types are available: `maxAmountUsd` caps the dollar value, `allowlist` restricts a field to specific values, `rateLimit` throttles actions per time window, and `custom` lets you write arbitrary predicates. Rules are matched by action name pattern — use `*` for wildcard or `transfer.*` for prefix matching.

Policies use a deny-first model: if ANY rule denies, the action is blocked with a `POLICY_DENIED` error.

Architecture

Policy evaluation is purely local (no network calls). Rate limit state is held in memory and resets on process restart.

Important Notes

Rate limits are in-memory
Rate limit counters reset on restart and are not shared across instances.
Use custom predicates for complex logic
The custom rule type accepts any synchronous function for full flexibility.

Quick Example

Configure and enforce policiestypescript
const inv = Invariance.init({
  apiKey: 'dev_...', privateKey: '...',
  policies: [
    { action: 'transfer', maxAmountUsd: 10000 },
    { action: 'swap', allowlist: { field: 'to', values: ['ETH', 'USDC', 'WBTC'] } },
    { action: 'swap', rateLimit: { max: 5, windowMs: 60000 } },
    { action: '*', custom: () => {
        const hour = new Date().getHours();
        return hour >= 9 && hour < 17;
    }},
  ],
});

Type Definitions

PolicyRule
interface PolicyRule {
  action: string;
  maxAmountUsd?: number;
  allowlist?: { field: string; values: string[] };
  rateLimit?: { max: number; windowMs: number };
  custom?: (action: Action) => boolean;
}
A policy rule that constrains agent actions. Multiple rule types can be combined.
PolicyCheck
interface PolicyCheck {
  allowed: boolean;
  reason?: string;
}
Result of a policy evaluation.

API Reference

check
Evaluate configured policies against an action without executing it.
check(action: Action): PolicyCheck
Parameters
actionActionThe action to evaluate
ReturnsPolicyCheck
checkPolicies
Standalone policy evaluation function (exported for use outside the SDK client).
checkPolicies(rules: PolicyRule[], action: Action): PolicyCheck
Parameters
rulesPolicyRule[]Array of policy rules
actionActionThe action to check
ReturnsPolicyCheck

Walkthrough

Building a comprehensive policy configuration
1
Define spending limits
Cap the maximum value of financial operations.
typescript
const policies = [
  { action: 'transfer', maxAmountUsd: 10000 },
  { action: 'swap', maxAmountUsd: 50000 },
];
2
Add allowlists
Restrict specific fields to approved values.
typescript
policies.push(
  { action: 'swap', allowlist: { field: 'to', values: ['ETH', 'USDC', 'WBTC'] } },
  { action: 'transfer', allowlist: { field: 'chain', values: ['ethereum', 'polygon'] } },
);
3
Configure rate limits
Throttle high-frequency actions to prevent runaway behavior.
typescript
policies.push(
  { action: 'swap', rateLimit: { max: 10, windowMs: 60000 } },    // 10 swaps/min
  { action: 'transfer', rateLimit: { max: 3, windowMs: 300000 } }, // 3 transfers/5min
);
4
Add custom predicates
Write arbitrary business logic for complex constraints.
typescript
policies.push(
  {
    action: '*',
    custom: () => {
      const hour = new Date().getUTCHours();
      return hour >= 9 && hour < 17; // business hours only
    },
  },
);

const inv = Invariance.init({
  apiKey: 'dev_...', privateKey: '...', policies,
});
5
Pre-check before execution
Use checkPolicies() to validate actions without executing them.
typescript
import { checkPolicies } from '@invariance/sdk';

const result = checkPolicies(policies, {
  action: 'swap',
  input: { from: 'ETH', to: 'DOGE', amount: '100' },
});

if (!result.allowed) {
  console.log('Blocked:', result.reason);
  // "Blocked: Value DOGE not in allowlist for field to"
}

Use Cases

  • Enforce spending limits on trading agents
  • Restrict agent actions to approved token lists
  • Rate limit high-frequency operations
  • Implement business-hours-only execution
  • Pre-check actions before execution to provide user-facing feedback
On this page
OverviewArchitectureImportant NotesQuick ExampleType DefinitionsAPI ReferenceWalkthroughUse CasesRelated Modules