{"version":3,"file":"delegation-compiler.mjs","names":[],"sources":["../../../src/services/delegation-compiler.ts"],"sourcesContent":["/**\n * Delegation Compiler — Converts openclawnch policies to EIP-7710 delegations.\n *\n * Takes a Policy (with its PolicyRules) and produces an UnsignedDelegation\n * containing the corresponding on-chain caveat enforcers.\n *\n * Rules without a direct on-chain mapping (blocklist, approval_threshold)\n * are flagged as \"app-layer only\" — they're still enforced by the policy\n * engine but won't have on-chain caveats.\n *\n * Uses viem's encodeAbiParameters for terms encoding. No external SDK needed.\n */\n\nimport { encodeAbiParameters, encodePacked, type Address, type Hex } from 'viem';\nimport type { PolicyRule, Policy } from './policy-types.js';\nimport {\n  DELEGATION_CONTRACTS,\n  PERIOD_SECONDS,\n  SUPPORTED_CHAIN_IDS,\n  type Caveat,\n  type CaveatMappingResult,\n  type UnsignedDelegation,\n} from './delegation-types.js';\n\n// ─── Compilation Context ────────────────────────────────────────────────\n\n/**\n * Optional context for price-aware compilation.\n * When provided, USD amounts are converted to real token amounts\n * using live prices. Without it, USD * 1e18 placeholder is used.\n */\nexport interface CompilationContext {\n  /** ETH price in USD at compilation time. */\n  ethPriceUsd?: number;\n  /** ERC-20 token address → { priceUsd, decimals } for token-aware enforcers. */\n  tokenPrices?: Map<string, { priceUsd: number; decimals: number }>;\n}\n\n// ─── Compilation Result ─────────────────────────────────────────────────\n\nexport interface CompilationResult {\n  /** The unsigned delegation struct, ready for signing. */\n  delegation: UnsignedDelegation;\n  /** Rules that mapped to on-chain caveats. */\n  mappedRules: Array<{ rule: PolicyRule; caveats: Caveat[] }>;\n  /** Rules that have no on-chain enforcer and are app-layer only. */\n  unmappedRules: Array<{ rule: PolicyRule; reason: string }>;\n  /** Warnings about the compilation (e.g., approximate mappings). */\n  warnings: string[];\n}\n\nexport interface CompilationError {\n  type: 'error';\n  message: string;\n}\n\n// ─── Module-level compilation context ───────────────────────────────────\n// Set before compilePolicyToDelegation via setCompilationContext().\n\nlet _compCtx: CompilationContext = {};\n\n/** Set compilation context (prices) before compiling. */\nexport function setCompilationContext(ctx: CompilationContext): void {\n  _compCtx = ctx;\n}\n\n/** Get current compilation context. */\nexport function getCompilationContext(): CompilationContext {\n  return _compCtx;\n}\n\n// ─── USD → Token Conversion ─────────────────────────────────────────────\n\n/**\n * Convert a USD amount to native token (ETH) wei.\n * Returns the placeholder (usd * 1e18) if no ETH price is available.\n */\nfunction usdToNativeWei(usdAmount: number): { wei: bigint; converted: boolean; ethPrice?: number } {\n  const ethPrice = _compCtx.ethPriceUsd;\n  if (ethPrice && ethPrice > 0) {\n    const ethAmount = usdAmount / ethPrice;\n    // ETH has 18 decimals\n    const wei = BigInt(Math.floor(ethAmount * 1e18));\n    return { wei, converted: true, ethPrice };\n  }\n  // Fallback: store raw USD * 1e18 as a placeholder\n  return { wei: BigInt(Math.floor(usdAmount * 1e18)), converted: false };\n}\n\n// ─── Policy → Caveats Compilation ───────────────────────────────────────\n\n/**\n * Compile a single PolicyRule into zero or more on-chain caveats.\n */\nexport function compileRuleToCaveats(rule: PolicyRule): CaveatMappingResult {\n  switch (rule.type) {\n    case 'spending_limit':\n      return compileSpendingLimit(rule);\n\n    case 'max_amount':\n      return compileMaxAmount(rule);\n\n    case 'rate_limit':\n      return compileRateLimit(rule);\n\n    case 'allowlist':\n      return compileAllowlist(rule);\n\n    case 'time_window':\n      return compileTimeWindow(rule);\n\n    case 'erc20_limit':\n      return compileErc20Limit(rule);\n\n    case 'blocklist':\n      return {\n        type: 'app_layer_only',\n        reason: 'Blocklist has no direct on-chain enforcer. The delegation framework uses allowlists (AllowedTargetsEnforcer). Blocklists are enforced at the app layer only.',\n      };\n\n    case 'approval_threshold':\n      return {\n        type: 'app_layer_only',\n        reason: 'Approval threshold is an app-layer concept (human confirmation). On-chain, use max_amount to hard-block above a threshold instead.',\n      };\n\n    default:\n      return {\n        type: 'app_layer_only',\n        reason: `Unknown rule type: ${(rule as any).type}`,\n      };\n  }\n}\n\n/**\n * spending_limit → NativeTokenPeriodTransferEnforcer.\n *\n * Converts USD to ETH wei using live price when available.\n * Falls back to USD * 1e18 placeholder when no price context is set.\n */\nfunction compileSpendingLimit(rule: { type: 'spending_limit'; maxAmountUsd: number; period: string }): CaveatMappingResult {\n  const periodSec = PERIOD_SECONDS[rule.period];\n  if (!periodSec) {\n    return { type: 'app_layer_only', reason: `Unknown period: ${rule.period}` };\n  }\n\n  const { wei: allowanceWei } = usdToNativeWei(rule.maxAmountUsd);\n  const startTime = 0n;  // 0 = from first use\n  const period = BigInt(periodSec);\n\n  const terms = encodeAbiParameters(\n    [\n      { type: 'uint256', name: 'allowance' },\n      { type: 'uint256', name: 'startTime' },\n      { type: 'uint256', name: 'period' },\n    ],\n    [allowanceWei, startTime, period],\n  );\n\n  return {\n    type: 'mapped',\n    caveats: [{\n      enforcer: DELEGATION_CONTRACTS.NativeTokenPeriodTransferEnforcer,\n      terms,\n      args: '0x' as Hex,\n    }],\n  };\n}\n\n/**\n * max_amount → ValueLteEnforcer + NativeTokenTransferAmountEnforcer.\n *\n * ValueLteEnforcer caps msg.value per call. NativeTokenTransferAmountEnforcer\n * caps cumulative native token transfers. Both use ETH wei.\n */\nfunction compileMaxAmount(rule: { type: 'max_amount'; maxAmountUsd: number }): CaveatMappingResult {\n  const { wei: maxValueWei } = usdToNativeWei(rule.maxAmountUsd);\n\n  // ValueLteEnforcer: caps msg.value per call\n  const valueLteTerms = encodeAbiParameters(\n    [{ type: 'uint256', name: 'maxValue' }],\n    [maxValueWei],\n  );\n\n  // NativeTokenTransferAmountEnforcer: caps cumulative ETH transfers\n  const nativeCapTerms = encodeAbiParameters(\n    [{ type: 'uint256', name: 'amount' }],\n    [maxValueWei],\n  );\n\n  return {\n    type: 'mapped',\n    caveats: [\n      {\n        enforcer: DELEGATION_CONTRACTS.ValueLteEnforcer,\n        terms: valueLteTerms,\n        args: '0x' as Hex,\n      },\n      {\n        enforcer: DELEGATION_CONTRACTS.NativeTokenTransferAmountEnforcer,\n        terms: nativeCapTerms,\n        args: '0x' as Hex,\n      },\n    ],\n  };\n}\n\n/**\n * erc20_limit → ERC20TransferAmountEnforcer.\n *\n * Caps cumulative ERC-20 transfers for a specific token.\n * Terms: encodePacked(address token, uint256 maxAmount) — 52 bytes.\n * The enforcer tracks cumulative transfer(to, amount) calldata\n * and reverts when the total exceeds the cap.\n *\n * Example: \"max 100 USDC\" becomes:\n *   - ERC20TransferAmountEnforcer(USDC_address, 100_000_000)\n */\nfunction compileErc20Limit(rule: { type: 'erc20_limit'; token: string; maxAmount: string; decimals: number }): CaveatMappingResult {\n  if (!rule.token || !/^0x[0-9a-fA-F]{40}$/.test(rule.token)) {\n    return { type: 'app_layer_only', reason: `Invalid token address: ${rule.token}` };\n  }\n\n  // Parse the human-readable amount to smallest unit\n  const [whole = '0', frac = ''] = rule.maxAmount.split('.');\n  const paddedFrac = (frac + '0'.repeat(rule.decimals)).slice(0, rule.decimals);\n  const amountSmallest = BigInt(whole + paddedFrac);\n\n  if (amountSmallest <= 0n) {\n    return { type: 'app_layer_only', reason: 'ERC-20 limit amount must be positive.' };\n  }\n\n  // ERC20TransferAmountEnforcer uses encodePacked(address, uint256) — 52 bytes\n  const terms = encodePacked(\n    ['address', 'uint256'],\n    [rule.token as Address, amountSmallest],\n  );\n\n  return {\n    type: 'mapped',\n    caveats: [\n      {\n        enforcer: DELEGATION_CONTRACTS.ERC20TransferAmountEnforcer,\n        terms,\n        args: '0x' as Hex,\n      },\n    ],\n  };\n}\n\n/**\n * rate_limit → LimitedCallsEnforcer + TimestampEnforcer.\n *\n * LimitedCallsEnforcer is a lifetime cap — it never resets. To approximate\n * a windowed rate limit, we pair it with a TimestampEnforcer that expires\n * the delegation at the end of the current window. The user must create\n * a new delegation for the next window.\n *\n * Example: \"max 10 calls per day\" becomes:\n *   - LimitedCallsEnforcer(10)\n *   - TimestampEnforcer(now, now + 86400)\n */\nfunction compileRateLimit(rule: { type: 'rate_limit'; maxCalls: number; periodMs: number }): CaveatMappingResult {\n  const callsTerms = encodeAbiParameters(\n    [{ type: 'uint256', name: 'count' }],\n    [BigInt(rule.maxCalls)],\n  );\n\n  const caveats: Caveat[] = [{\n    enforcer: DELEGATION_CONTRACTS.LimitedCallsEnforcer,\n    terms: callsTerms,\n    args: '0x' as Hex,\n  }];\n\n  // Add TimestampEnforcer to bound the window\n  if (rule.periodMs > 0) {\n    const nowSec = BigInt(Math.floor(Date.now() / 1000));\n    const periodSec = BigInt(Math.floor(rule.periodMs / 1000));\n    const expiry = nowSec + periodSec;\n\n    const timestampTerms = encodeAbiParameters(\n      [\n        { type: 'uint128', name: 'executeAfter' },\n        { type: 'uint128', name: 'executeBefore' },\n      ],\n      [nowSec, expiry],\n    );\n\n    caveats.push({\n      enforcer: DELEGATION_CONTRACTS.TimestampEnforcer,\n      terms: timestampTerms,\n      args: '0x' as Hex,\n    });\n  }\n\n  return { type: 'mapped', caveats };\n}\n\n/**\n * allowlist (addresses/contracts) → AllowedTargetsEnforcer.\n * allowlist (tokens) → ERC20TransferAmountEnforcer per token (if addresses known).\n * allowlist (chains) → App-layer only (delegation is per-chain).\n */\nfunction compileAllowlist(rule: { type: 'allowlist'; field: string; values: string[] }): CaveatMappingResult {\n  if (rule.field === 'addresses' || rule.field === 'contracts') {\n    const addresses = rule.values\n      .filter(v => /^0x[0-9a-fA-F]{40}$/.test(v))\n      .map(v => v as Address);\n\n    if (addresses.length === 0) {\n      return { type: 'app_layer_only', reason: 'No valid addresses in allowlist.' };\n    }\n\n    const terms = encodeAbiParameters(\n      [{ type: 'address[]', name: 'targets' }],\n      [addresses],\n    );\n\n    return {\n      type: 'mapped',\n      caveats: [{\n        enforcer: DELEGATION_CONTRACTS.AllowedTargetsEnforcer,\n        terms,\n        args: '0x' as Hex,\n      }],\n    };\n  }\n\n  if (rule.field === 'tokens') {\n    // Token allowlist: if any values are 0x addresses, use AllowedTargetsEnforcer\n    // to restrict which token contracts can be called\n    const tokenAddresses = rule.values\n      .filter(v => /^0x[0-9a-fA-F]{40}$/.test(v))\n      .map(v => v as Address);\n\n    if (tokenAddresses.length > 0) {\n      const terms = encodeAbiParameters(\n        [{ type: 'address[]', name: 'targets' }],\n        [tokenAddresses],\n      );\n      return {\n        type: 'mapped',\n        caveats: [{\n          enforcer: DELEGATION_CONTRACTS.AllowedTargetsEnforcer,\n          terms,\n          args: '0x' as Hex,\n        }],\n      };\n    }\n\n    return {\n      type: 'app_layer_only',\n      reason: 'Token allowlist with symbols only (no contract addresses) cannot be enforced on-chain. Use token contract addresses for on-chain enforcement.',\n    };\n  }\n\n  if (rule.field === 'chains') {\n    return {\n      type: 'app_layer_only',\n      reason: 'Chain restrictions are inherent to delegation scope (each delegation is per-chain). No enforcer needed.',\n    };\n  }\n\n  return { type: 'app_layer_only', reason: `Unknown allowlist field: ${rule.field}` };\n}\n\n/**\n * time_window → TimestampEnforcer.\n *\n * TimestampEnforcer uses (uint128 executeAfter, uint128 executeBefore).\n * Recurring windows (weekdays, hours) are enforced at app layer only.\n */\nfunction compileTimeWindow(rule: {\n  type: 'time_window';\n  allowedHours?: { start: number; end: number };\n  allowedDays?: number[];\n  timezone?: string;\n}): CaveatMappingResult {\n  if (rule.allowedDays && rule.allowedDays.length > 0) {\n    return {\n      type: 'app_layer_only',\n      reason: 'Recurring day-of-week restrictions have no on-chain equivalent. TimestampEnforcer only supports absolute time ranges. Enforced at app layer.',\n    };\n  }\n\n  if (rule.allowedHours) {\n    return {\n      type: 'app_layer_only',\n      reason: 'Recurring hour-of-day restrictions have no on-chain equivalent. TimestampEnforcer only supports absolute time ranges. Enforced at app layer.',\n    };\n  }\n\n  return { type: 'app_layer_only', reason: 'No time constraints to enforce on-chain.' };\n}\n\n// ─── Full Policy → Delegation Compilation ───────────────────────────────\n\n/**\n * Compile a full Policy into an UnsignedDelegation.\n *\n * @param policy - The policy to compile\n * @param delegator - The user's wallet address (who grants the delegation)\n * @param delegate - The agent's wallet address (who receives the delegation)\n * @param chainId - Target chain ID\n * @returns CompilationResult with the delegation and mapping details, or error\n */\nexport function compilePolicyToDelegation(\n  policy: Policy,\n  delegator: Address,\n  delegate: Address,\n  chainId: number,\n): CompilationResult | CompilationError {\n  // Validate chain\n  if (!SUPPORTED_CHAIN_IDS.has(chainId)) {\n    return {\n      type: 'error',\n      message: `Chain ${chainId} is not supported by the MetaMask Delegation Framework. Supported: ${[...SUPPORTED_CHAIN_IDS].join(', ')}`,\n    };\n  }\n\n  // Validate policy has rules\n  if (!policy.rules || policy.rules.length === 0) {\n    return {\n      type: 'error',\n      message: `Policy \"${policy.name}\" has no rules to compile.`,\n    };\n  }\n\n  // Validate policy is active\n  if (policy.status !== 'active') {\n    return {\n      type: 'error',\n      message: `Policy \"${policy.name}\" is not active (status: ${policy.status}). Enable it first.`,\n    };\n  }\n\n  const allCaveats: Caveat[] = [];\n  const mappedRules: CompilationResult['mappedRules'] = [];\n  const unmappedRules: CompilationResult['unmappedRules'] = [];\n  const warnings: string[] = [];\n\n  for (const rule of policy.rules) {\n    const result = compileRuleToCaveats(rule);\n    if (result.type === 'mapped') {\n      allCaveats.push(...result.caveats);\n      mappedRules.push({ rule, caveats: result.caveats });\n    } else {\n      unmappedRules.push({ rule, reason: result.reason });\n    }\n  }\n\n  // Warn if no caveats were mapped — delegation would be unrestricted\n  if (allCaveats.length === 0) {\n    warnings.push(\n      'No policy rules mapped to on-chain caveats. All rules are app-layer only. ' +\n      'The delegation would have NO on-chain restrictions. This is likely not what you want.',\n    );\n  }\n\n  // Warn about USD → token conversion\n  const hasSpendingRules = policy.rules.some(r =>\n    r.type === 'spending_limit' || r.type === 'max_amount',\n  );\n  if (hasSpendingRules) {\n    const ctx = getCompilationContext();\n    if (ctx.ethPriceUsd) {\n      warnings.push(\n        `Spending limits converted at ETH = $${ctx.ethPriceUsd.toFixed(2)}. ` +\n        'On-chain enforcers use token amounts, not USD. Re-compile if price drifts significantly.',\n      );\n    } else {\n      warnings.push(\n        'No ETH price available at compile time. Amounts use placeholder encoding (USD * 1e18). ' +\n        'Re-compile with a connected network to get accurate token amounts.',\n      );\n    }\n  }\n\n  // Warn about rate limit expiry\n  const hasRateLimit = policy.rules.some(r => r.type === 'rate_limit');\n  if (hasRateLimit) {\n    warnings.push(\n      'Rate limits use LimitedCallsEnforcer (lifetime cap) + TimestampEnforcer (expiry). ' +\n      'The delegation expires at the end of the rate limit window. Create a new delegation for the next window.',\n    );\n  }\n\n  // Generate a unique salt from the policy ID + timestamp\n  const saltBytes = Buffer.from(`${policy.id}-${Date.now()}`);\n  const salt = BigInt('0x' + saltBytes.subarray(0, 32).toString('hex').padEnd(64, '0'));\n\n  const delegation: UnsignedDelegation = {\n    delegate,\n    delegator,\n    authority: ('0x' + 'f'.repeat(64)) as Hex, // ROOT_AUTHORITY — sentinel for top-level delegations\n    caveats: allCaveats,\n    salt,\n  };\n\n  return {\n    delegation,\n    mappedRules,\n    unmappedRules,\n    warnings,\n  };\n}\n\n/**\n * Generate a human-readable compilation summary for user review.\n */\nexport function formatCompilationSummary(result: CompilationResult, chainId: number): string {\n  const lines: string[] = [];\n\n  lines.push('**Delegation Compilation Summary**');\n  lines.push('');\n  lines.push(`Chain: ${chainId}`);\n  lines.push(`Delegate: \\`${result.delegation.delegate}\\``);\n  lines.push(`Delegator: \\`${result.delegation.delegator}\\``);\n  lines.push(`Caveats: ${result.delegation.caveats.length}`);\n  lines.push('');\n\n  if (result.mappedRules.length > 0) {\n    lines.push('**On-chain enforced rules:**');\n    for (const { rule, caveats } of result.mappedRules) {\n      const enforcerNames = caveats.map(c => {\n        const entry = Object.entries(DELEGATION_CONTRACTS).find(([, addr]) => addr === c.enforcer);\n        return entry ? entry[0] : c.enforcer;\n      });\n      lines.push(`  - ${rule.type} -> ${enforcerNames.join(', ')}`);\n    }\n    lines.push('');\n  }\n\n  if (result.unmappedRules.length > 0) {\n    lines.push('**App-layer only rules** (not enforced on-chain):');\n    for (const { rule, reason } of result.unmappedRules) {\n      lines.push(`  - ${rule.type}: ${reason}`);\n    }\n    lines.push('');\n  }\n\n  if (result.warnings.length > 0) {\n    lines.push('**Warnings:**');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