{"version":3,"file":"delegation-types.mjs","names":[],"sources":["../../../src/services/delegation-types.ts"],"sourcesContent":["/**\n * Delegation Types — EIP-7710/7715 on-chain delegation type system.\n *\n * Maps the openclawnch policy engine to the MetaMask Delegation Framework's\n * on-chain caveat enforcers. No external SDK dependency — uses viem directly\n * for ABI encoding and contract interaction.\n *\n * Contract addresses are from MetaMask Delegation Framework v1.3.0,\n * deployed deterministically across all major EVM chains.\n *\n * References:\n *   - EIP-7710: https://eips.ethereum.org/EIPS/eip-7710\n *   - EIP-7715: https://eips.ethereum.org/EIPS/eip-7715\n *   - MetaMask Delegation Framework: https://github.com/MetaMask/delegation-framework\n */\n\nimport type { Address, Hex } from 'viem';\n\n// ─── Core Delegation Types (EIP-7710) ───────────────────────────────────\n\n/**\n * A single caveat restricting a delegation.\n * Each caveat references an on-chain enforcer contract and ABI-encoded terms.\n */\nexport interface Caveat {\n  /** Address of the caveat enforcer contract. */\n  enforcer: Address;\n  /** ABI-encoded terms the enforcer checks. Encoding varies by enforcer. */\n  terms: Hex;\n  /** Runtime arguments passed during redemption (usually '0x'). */\n  args: Hex;\n}\n\n/**\n * An unsigned delegation — all fields except the signature.\n * The delegator must sign this to produce a valid Delegation.\n */\nexport interface UnsignedDelegation {\n  /** Who receives the permission (the agent's address). */\n  delegate: Address;\n  /** Who grants the permission (the user's wallet). */\n  delegator: Address;\n  /**\n   * Parent delegation hash for chained delegations.\n   * 0x0...0 for root delegations (granted directly by the account owner).\n   */\n  authority: Hex;\n  /** Restrictions on the delegation. */\n  caveats: Caveat[];\n  /** Random salt for uniqueness. */\n  salt: bigint;\n}\n\n/**\n * A fully signed delegation ready for on-chain redemption.\n */\nexport interface SignedDelegation extends UnsignedDelegation {\n  /** The delegator's EIP-712 signature over the delegation. */\n  signature: Hex;\n}\n\n// ─── Delegation Metadata (stored alongside policies) ────────────────────\n\nexport type DelegationStatus = 'unsigned' | 'signed' | 'active' | 'revoked' | 'expired';\n\n/**\n * Metadata stored in the policy's `delegation` field.\n * Links an off-chain policy to its on-chain delegation.\n */\nexport interface DelegationMetadata {\n  /** Chain ID where the delegation is deployed. */\n  chainId: number;\n  /** Keccak256 hash of the delegation struct. */\n  hash: Hex;\n  /** DelegationManager contract address on this chain. */\n  delegationManager: Address;\n  /** Current lifecycle status. */\n  status: DelegationStatus;\n  /** The delegate address (agent). */\n  delegate: Address;\n  /** The delegator address (user). */\n  delegator: Address;\n  /** Salt used for uniqueness. */\n  salt: string;\n  /** ISO timestamp when the delegation was created. */\n  createdAt: string;\n  /** ISO timestamp when last status check was performed. */\n  lastCheckedAt?: string;\n  /** Caveats that couldn't be mapped (app-layer only). */\n  unmappedRules?: string[];\n}\n\n// ─── Contract Addresses (MetaMask Delegation Framework v1.3.0) ──────────\n//\n// These are deployed at deterministic addresses via CREATE2 across all\n// supported chains. Verified from the official deployments registry.\n\nexport const DELEGATION_CONTRACTS = {\n  /** Core delegation manager — handles creation, redemption, revocation. */\n  DelegationManager: '0xdb9B1e94B5b69Df7e401DDbedE43491141047dB3' as Address,\n\n  // ── DeleGator Implementations ────────────────────────────────────────\n\n  /** MetaMask EIP-7702 Stateless DeleGator — production audited implementation.\n   *  Use as the designation target for `/upgrade 7702`. Deterministic CREATE2 across all chains. */\n  EIP7702StatelessDeleGator: '0x63c0c19a282a1B52b07dD5a65b58948A07DAE32B' as Address,\n\n  /** MetaMask HybridDeleGator — ERC-4337 + EIP-712 hybrid account implementation. */\n  HybridDeleGator: '0x48dBe696A4D990079e039489bA2053B36E8FFEC4' as Address,\n\n  /** MetaMask MultiSigDeleGator — multi-signature DeleGator implementation. */\n  MultiSigDeleGator: '0x56a9EdB16a0105eb5a4C54f4C062e2868844f3A7' as Address,\n\n  // ── Caveat Enforcers ─────────────────────────────────────────────────\n\n  /** Limits total ERC-20 transfer amount. Terms: (address token, uint256 amount) */\n  ERC20TransferAmountEnforcer: '0xf100b0819427117EcF76Ed94B358B1A5b5C6D2Fc' as Address,\n\n  /** Limits ERC-20 transfers per time period. Terms: (address token, uint256 allowance, uint256 startTime, uint256 period) */\n  ERC20PeriodTransferEnforcer: '0x474e3Ae7E169e940607cC624Da8A15Eb120139aB' as Address,\n\n  /** Limits total number of calls. Terms: (uint256 count) */\n  LimitedCallsEnforcer: '0x04658B29F6b82ed55274221a06Fc97D318E25416' as Address,\n\n  /** Restricts which contract addresses can be called. Terms: (address[]) */\n  AllowedTargetsEnforcer: '0x7F20f61b1f09b08D970938F6fa563634d65c4EeB' as Address,\n\n  /** Restricts which function selectors can be called. Terms: (bytes4[]) */\n  AllowedMethodsEnforcer: '0x2c21fD0Cb9DC8445CB3fb0DC5E7Bb0Aca01842B5' as Address,\n\n  /** Enforces time bounds on delegation. Terms: (uint128 executeAfter, uint128 executeBefore) */\n  TimestampEnforcer: '0x1046bb45C8d673d4ea75321280DB34899413c069' as Address,\n\n  /** Limits total native token (ETH) transfer amount. Terms: (uint256 amount) */\n  NativeTokenTransferAmountEnforcer: '0xF71af580b9c3078fbc2BBF16FbB8EEd82b330320' as Address,\n\n  /** Limits native token transfers per time period. Terms: (uint256 allowance, uint256 startTime, uint256 period) */\n  NativeTokenPeriodTransferEnforcer: '0x9BC0FAf4Aca5AE429F4c06aEEaC517520CB16BD9' as Address,\n\n  /** Limits msg.value to be <= encoded amount. Terms: (uint256 maxValue) */\n  ValueLteEnforcer: '0x92Bf12322527cAA612fd31a0e810472BBB106A8F' as Address,\n\n  /** Requires a specific nonce for single-use delegations. Terms: (uint256 nonce) */\n  NonceEnforcer: '0xDE4f2FAC4B3D87A1d9953Ca5FC09FCa7F366254f' as Address,\n} as const;\n\n// ─── Supported Chains ───────────────────────────────────────────────────\n//\n// The delegation framework contracts are deployed on these chains.\n// The addresses are the same on all chains (CREATE2 deterministic deployment).\n\nexport const SUPPORTED_CHAIN_IDS = new Set([\n  1,        // Ethereum Mainnet\n  8453,     // Base\n  42161,    // Arbitrum One\n  10,       // Optimism\n  137,      // Polygon\n  59144,    // Linea\n  11155111, // Sepolia (testnet)\n  84532,    // Base Sepolia (testnet)\n]);\n\nexport const CHAIN_NAMES: Record<number, string> = {\n  1:        'Ethereum',\n  8453:     'Base',\n  42161:    'Arbitrum',\n  10:       'Optimism',\n  137:      'Polygon',\n  59144:    'Linea',\n  11155111: 'Sepolia',\n  84532:    'Base Sepolia',\n};\n\n// ─── EIP-712 Type Definitions ───────────────────────────────────────────\n//\n// Used for signing delegations. The delegator signs an EIP-712 typed\n// message containing the delegation struct.\n\n// NOTE: The on-chain DelegationManager's DELEGATION_TYPEHASH uses\n// Caveat(address enforcer,bytes terms) — WITHOUT the `args` field.\n// The `args` field exists in the ABI struct for runtime data passed\n// during caveat enforcement, but is NOT part of the EIP-712 signature.\nexport const DELEGATION_EIP712_TYPES = {\n  Delegation: [\n    { name: 'delegate', type: 'address' },\n    { name: 'delegator', type: 'address' },\n    { name: 'authority', type: 'bytes32' },\n    { name: 'caveats', type: 'Caveat[]' },\n    { name: 'salt', type: 'uint256' },\n  ],\n  Caveat: [\n    { name: 'enforcer', type: 'address' },\n    { name: 'terms', type: 'bytes' },\n  ],\n} as const;\n\n/**\n * Build the EIP-712 domain for a DelegationManager on a specific chain.\n */\nexport function getDelegationDomain(chainId: number) {\n  return {\n    name: 'DelegationManager',\n    version: '1',\n    chainId,\n    verifyingContract: DELEGATION_CONTRACTS.DelegationManager,\n  } as const;\n}\n\n// ─── Execution Modes (ERC-7579) ─────────────────────────────────────────\n//\n// DelegationManager.redeemDelegations uses ERC-7579 execution modes.\n// Mode is a bytes32 encoding: callType (1 byte) + execType (1 byte) + unused (4) + modeSelector (4) + modePayload (22).\n// For single calls with default execution: 0x00...00.\n\n/**\n * Root authority for top-level delegations (no parent).\n * The DelegationManager uses 0xfff...f as the sentinel value.\n */\nexport const ROOT_AUTHORITY = ('0x' + 'f'.repeat(64)) as Hex;\n\n/**\n * Default single-call execution mode.\n * callType=0x00 (single), execType=0x00 (default), rest zeros.\n */\nexport const EXECUTE_MODE_DEFAULT = ('0x' + '0'.repeat(64)) as Hex;\n\n/**\n * Encode a single execution as callData for redeemDelegations.\n * ERC-7579 single execution: abi.encodePacked(target, value, callData).\n * But DelegationManager expects: abi.encode(target, value, callData) as the\n * executionCallData parameter.\n */\nexport interface ExecutionAction {\n  /** Target contract address. */\n  target: Address;\n  /** Value in wei to send with the call. */\n  value: bigint;\n  /** Encoded function calldata (e.g., from encodeFunctionData). */\n  callData: Hex;\n}\n\n// ─── Caveat Enforcer Mapping ────────────────────────────────────────────\n//\n// Maps PolicyRule types to their on-chain caveat enforcers.\n// Each mapping specifies the enforcer address and how to encode the terms.\n//\n// Rules without a direct on-chain mapping are flagged as 'app_layer_only'.\n\nexport type CaveatMappingResult =\n  | { type: 'mapped'; caveats: Caveat[] }\n  | { type: 'app_layer_only'; reason: string };\n\n/**\n * Well-known period durations in seconds, for on-chain period enforcers.\n */\nexport const PERIOD_SECONDS: Record<string, number> = {\n  hourly:  3600,\n  daily:   86400,\n  weekly:  604800,\n  monthly: 2592000,  // 30 days\n};\n\n// ─── DelegationManager ABI (minimal) ────────────────────────────────────\n//\n// Only the functions we need for delegation lifecycle management.\n\nexport const DELEGATION_MANAGER_ABI = [\n  {\n    name: 'redeemDelegations',\n    type: 'function',\n    stateMutability: 'nonpayable',\n    inputs: [\n      { name: '_permissionContexts', type: 'bytes[]' },\n      { name: '_modes', type: 'bytes32[]' },\n      { name: '_executionCallData', type: 'bytes[]' },\n    ],\n    outputs: [],\n  },\n  {\n    name: 'disableDelegation',\n    type: 'function',\n    stateMutability: 'nonpayable',\n    inputs: [\n      {\n        name: '_delegation',\n        type: 'tuple',\n        components: [\n          { name: 'delegate', type: 'address' },\n          { name: 'delegator', type: 'address' },\n          { name: 'authority', type: 'bytes32' },\n          {\n            name: 'caveats',\n            type: 'tuple[]',\n            components: [\n              { name: 'enforcer', type: 'address' },\n              { name: 'terms', type: 'bytes' },\n              { name: 'args', type: 'bytes' },\n            ],\n          },\n          { name: 'salt', type: 'uint256' },\n          { name: 'signature', type: 'bytes' },\n        ],\n      },\n    ],\n    outputs: [],\n  },\n  {\n    name: 'getDelegationHash',\n    type: 'function',\n    stateMutability: 'view',\n    inputs: [\n      {\n        name: '_delegation',\n        type: 'tuple',\n        components: [\n          { name: 'delegate', type: 'address' },\n          { name: 'delegator', type: 'address' },\n          { name: 'authority', type: 'bytes32' },\n          {\n            name: 'caveats',\n            type: 'tuple[]',\n            components: [\n              { name: 'enforcer', type: 'address' },\n              { name: 'terms', type: 'bytes' },\n              { name: 'args', type: 'bytes' },\n            ],\n          },\n          { name: 'salt', type: 'uint256' },\n          { name: 'signature', type: 'bytes' },\n        ],\n      },\n    ],\n    outputs: [{ name: '', type: 'bytes32' }],\n  },\n  {\n    name: 'disabledDelegations',\n    type: 'function',\n    stateMutability: 'view',\n    inputs: [{ name: '_delegationHash', type: 'bytes32' }],\n    outputs: [{ name: '', type: 'bool' }],\n  },\n] as const;\n\n// ─── Enforcer ABIs (for on-chain state reads) ──────────────────────────\n//\n// Period-based enforcers track cumulative spending on-chain via a\n// `spentMap` mapping: (address delegationManager, bytes32 delegationHash) → SpentInfo.\n// We read this to compare on-chain usage against local tracking.\n\n/** ABI for NativeTokenPeriodTransferEnforcer.spentMap (read cumulative ETH usage). */\nexport const NATIVE_PERIOD_ENFORCER_ABI = [\n  {\n    name: 'spentMap',\n    type: 'function',\n    stateMutability: 'view',\n    inputs: [\n      { name: '_delegationManager', type: 'address' },\n      { name: '_delegationHash', type: 'bytes32' },\n    ],\n    outputs: [\n      { name: 'spent', type: 'uint256' },\n      { name: 'lastUpdated', type: 'uint256' },\n    ],\n  },\n] as const;\n\n/** ABI for ERC20PeriodTransferEnforcer.spentMap (read cumulative ERC-20 usage). */\nexport const ERC20_PERIOD_ENFORCER_ABI = [\n  {\n    name: 'spentMap',\n    type: 'function',\n    stateMutability: 'view',\n    inputs: [\n      { name: '_delegationManager', type: 'address' },\n      { name: '_delegationHash', type: 'bytes32' },\n    ],\n    outputs: [\n      { name: 'spent', type: 'uint256' },\n      { name: 'lastUpdated', type: 'uint256' },\n    ],\n  },\n] as const;\n\n/** ABI for LimitedCallsEnforcer.callCounts (read cumulative call count). */\nexport const LIMITED_CALLS_ENFORCER_ABI = [\n  {\n    name: 'callCounts',\n    type: 'function',\n    stateMutability: 'view',\n    inputs: [\n      { name: '_delegationManager', type: 'address' },\n      { name: '_delegationHash', type: 'bytes32' },\n    ],\n    outputs: [\n      { name: '', type: 'uint256' },\n    ],\n  },\n] as const;\n"],"mappings":";AAiGA,MAAa,uBAAuB;CAElC,mBAAmB;CAMnB,2BAA2B;CAG3B,iBAAiB;CAGjB,mBAAmB;CAKnB,6BAA6B;CAG7B,6BAA6B;CAG7B,sBAAsB;CAGtB,wBAAwB;CAGxB,wBAAwB;CAGxB,mBAAmB;CAGnB,mCAAmC;CAGnC,mCAAmC;CAGnC,kBAAkB;CAGlB,eAAe;CAChB;AAOD,MAAa,sBAAsB,IAAI,IAAI;CACzC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,MAAa,cAAsC;CACjD,GAAU;CACV,MAAU;CACV,OAAU;CACV,IAAU;CACV,KAAU;CACV,OAAU;CACV,UAAU;CACV,OAAU;CACX;AAWD,MAAa,0BAA0B;CACrC,YAAY;EACV;GAAE,MAAM;GAAY,MAAM;GAAW;EACrC;GAAE,MAAM;GAAa,MAAM;GAAW;EACtC;GAAE,MAAM;GAAa,MAAM;GAAW;EACtC;GAAE,MAAM;GAAW,MAAM;GAAY;EACrC;GAAE,MAAM;GAAQ,MAAM;GAAW;EAClC;CACD,QAAQ,CACN;EAAE,MAAM;EAAY,MAAM;EAAW,EACrC;EAAE,MAAM;EAAS,MAAM;EAAS,CACjC;CACF;;;;AAKD,SAAgB,oBAAoB,SAAiB;AACnD,QAAO;EACL,MAAM;EACN,SAAS;EACT;EACA,mBAAmB,qBAAqB;EACzC;;;;;;AAaH,MAAa,iBAAkB,OAAO,IAAI,OAAO,GAAG;;;;;AAMpD,MAAa,uBAAwB,OAAO,IAAI,OAAO,GAAG;;;;AA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