All files / evm-wallet-experiment/src/lib delegation.ts

85% Statements 68/80
88.88% Branches 48/54
71.42% Functions 10/14
85.52% Lines 65/76

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391                                      5x                                   75x                                                                   35x 35x 68x   68x 68x                                                           5x                                                 71x 71x   71x             71x                                               1x   1x                                                                                                   26x 2x       24x 22x   3x 3x 3x 3x   3x 3x   3x 2x               20x 3x   3x 3x 3x 3x   3x 3x 2x               18x 4x       4x 4x 2x               16x 4x       4x                     4x 4x 1x           3x 2x               13x   7x 7x 7x 7x 2x           5x 2x           3x 3x             3x 3x 3x 1x                         10x                                     18x                           39x            
import {
  keccak256,
  toHex,
  encodePacked,
  decodeAbiParameters,
  parseAbiParameters,
} from 'viem';
 
import { DELEGATION_TYPES, ROOT_AUTHORITY } from '../constants.ts';
import type {
  Action,
  Address,
  Caveat,
  Delegation,
  DelegationMatchResult,
  Eip712TypedData,
  Hex,
} from '../types.ts';
 
const harden = globalThis.harden ?? (<T>(value: T): T => value);
 
/**
 * Generate a deterministic delegation ID from its components.
 *
 * @param delegation - The delegation to compute the ID for.
 * @param delegation.delegator - The delegator address.
 * @param delegation.delegate - The delegate address.
 * @param delegation.authority - The parent delegation hash.
 * @param delegation.salt - The delegation salt.
 * @returns The delegation ID as a hex hash.
 */
export function computeDelegationId(delegation: {
  delegator: Address;
  delegate: Address;
  authority: Hex;
  salt: Hex;
}): string {
  return keccak256(
    encodePacked(
      ['address', 'address', 'bytes32', 'uint256'],
      [
        delegation.delegator,
        delegation.delegate,
        delegation.authority,
        BigInt(delegation.salt),
      ],
    ),
  );
}
 
/**
 * A function that generates a unique delegation salt on each call.
 */
export type SaltGenerator = () => Hex;
 
/**
 * Create a salt generator for delegation uniqueness.
 *
 * Prefers crypto.getRandomValues when available. In SES compartments
 * where crypto is not endowed, falls back to a closure-local counter
 * hashed with optional caller-supplied entropy. Each call to
 * makeSaltGenerator produces an independent counter, so two vat instances
 * each get their own sequence rather than sharing module-level state.
 *
 * @param entropy - Optional caller-supplied entropy hex string. When provided
 *   and crypto is unavailable, mixed into the counter hash so that separate
 *   vat instances produce distinct salts even though both start at counter 1.
 * @returns A salt generator function.
 */
export function makeSaltGenerator(entropy?: Hex): SaltGenerator {
  // eslint-disable-next-line n/no-unsupported-features/node-builtins
  Eif (globalThis.crypto?.getRandomValues) {
    return () => {
      const bytes = new Uint8Array(32);
      // eslint-disable-next-line n/no-unsupported-features/node-builtins
      globalThis.crypto.getRandomValues(bytes);
      return toHex(bytes);
    };
  }
 
  // SES fallback: unique per generator lifetime but not cryptographically random.
  // The salt only needs uniqueness, not unpredictability.
  let counter = 0;
  if (entropy !== undefined) {
    return () => {
      counter += 1;
      return keccak256(
        encodePacked(['bytes', 'uint256'], [entropy, BigInt(counter)]),
      );
    };
  }
  return () => {
    counter += 1;
    return keccak256(encodePacked(['uint256'], [BigInt(counter)]));
  };
}
 
/**
 * Generate a random salt for delegation uniqueness.
 *
 * Uses a module-level counter as the SES fallback. Prefer
 * {@link makeSaltGenerator} when creating delegations in a vat, since it
 * gives each vat instance an independent counter.
 *
 * @returns A hex-encoded random salt.
 */
export const generateSalt: SaltGenerator = makeSaltGenerator();
 
/**
 * Create a new unsigned delegation struct.
 *
 * @param options - Creation options.
 * @param options.delegator - The account granting the delegation.
 * @param options.delegate - The account receiving the delegation.
 * @param options.caveats - The caveats restricting the delegation.
 * @param options.chainId - The chain ID.
 * @param options.salt - Optional salt (generated if omitted).
 * @param options.saltGenerator - Optional salt generator to use when no
 *   explicit salt is provided. Defaults to {@link generateSalt}.
 * @param options.authority - Optional parent delegation hash (root if omitted).
 * @returns The unsigned Delegation struct.
 */
export function makeDelegation(options: {
  delegator: Address;
  delegate: Address;
  caveats: Caveat[];
  chainId: number;
  salt?: Hex;
  saltGenerator?: SaltGenerator;
  authority?: Hex;
}): Delegation {
  const salt = options.salt ?? (options.saltGenerator ?? generateSalt)();
  const authority = options.authority ?? ROOT_AUTHORITY;
 
  const id = computeDelegationId({
    delegator: options.delegator,
    delegate: options.delegate,
    authority,
    salt,
  });
 
  return harden({
    id,
    delegator: options.delegator,
    delegate: options.delegate,
    authority,
    caveats: options.caveats,
    salt,
    chainId: options.chainId,
    status: 'pending',
  });
}
 
/**
 * Prepare the EIP-712 typed data payload for signing a delegation.
 *
 * @param options - Options.
 * @param options.delegation - The delegation to prepare for signing.
 * @param options.verifyingContract - The DelegationManager contract address.
 * @returns The EIP-712 typed data payload.
 */
export function prepareDelegationTypedData(options: {
  delegation: Delegation;
  verifyingContract: Address;
}): Eip712TypedData {
  const { delegation, verifyingContract } = options;
 
  return {
    domain: {
      name: 'DelegationManager',
      version: '1',
      chainId: delegation.chainId,
      verifyingContract,
    },
    types: {
      ...DELEGATION_TYPES,
    },
    primaryType: 'Delegation',
    message: {
      delegate: delegation.delegate,
      delegator: delegation.delegator,
      authority: delegation.authority,
      caveats: delegation.caveats.map((caveat) => ({
        enforcer: caveat.enforcer,
        terms: caveat.terms,
      })),
      salt: BigInt(delegation.salt),
    },
  };
}
 
/**
 * Explain whether a signed delegation potentially covers an action.
 *
 * Returns a detailed result indicating whether the delegation matches,
 * and if not, which caveat failed and why.
 *
 * This performs a client-side check based on the caveat types:
 * - allowedTargets: checks if action.to is in the allowed list
 * - allowedMethods: checks if action.data starts with an allowed selector
 * - valueLte: checks if action.value is within the limit
 * - timestamp: checks if current time is within the window
 * - erc20TransferAmount: checks token, selector, and amount
 * - nativeTokenTransferAmount: cannot be enforced client-side (requires on-chain accounting)
 *
 * This is a best-effort match. On-chain enforcement is authoritative.
 *
 * @param delegation - The delegation to check.
 * @param action - The action to match against.
 * @param currentTime - Optional current time in milliseconds (defaults to Date.now()).
 * @returns A result object with match status and failure details.
 */
export function explainDelegationMatch(
  delegation: Delegation,
  action: Action,
  currentTime?: number,
): DelegationMatchResult {
  if (delegation.status !== 'signed') {
    return { matches: false, reason: 'Delegation is not signed' };
  }
 
  // Check each caveat - all must pass for the delegation to match
  for (const caveat of delegation.caveats) {
    if (caveat.type === 'allowedTargets') {
      // Packed 20-byte addresses (40 hex chars each, after '0x' prefix).
      const termsBody = caveat.terms.slice(2);
      const targets: string[] = [];
      for (let i = 0; i < termsBody.length; i += 40) {
        targets.push(`0x${termsBody.slice(i, i + 40)}`);
      }
      const match = targets.some(
        (target) => target.toLowerCase() === action.to.toLowerCase(),
      );
      if (!match) {
        return {
          matches: false,
          failedCaveat: 'allowedTargets',
          reason: `Target ${action.to} is not in the allowed targets list`,
        };
      }
    }
 
    if (caveat.type === 'allowedMethods' && action.data) {
      const selector = action.data.slice(0, 10).toLowerCase() as Hex;
      // Packed 4-byte selectors (8 hex chars each, after '0x' prefix).
      const termsBody = caveat.terms.slice(2);
      const methods: string[] = [];
      for (let i = 0; i < termsBody.length; i += 8) {
        methods.push(`0x${termsBody.slice(i, i + 8)}`);
      }
      const match = methods.some((method) => method.toLowerCase() === selector);
      if (!match) {
        return {
          matches: false,
          failedCaveat: 'allowedMethods',
          reason: `Method selector ${selector} is not in the allowed methods list`,
        };
      }
    }
 
    if (caveat.type === 'valueLte') {
      const [maxValue] = decodeAbiParameters(
        parseAbiParameters('uint256'),
        caveat.terms,
      );
      const actionValue = action.value ? BigInt(action.value) : 0n;
      if (actionValue > maxValue) {
        return {
          matches: false,
          failedCaveat: 'valueLte',
          reason: `Value ${actionValue} exceeds maximum ${maxValue}`,
        };
      }
    }
 
    if (caveat.type === 'timestamp') {
      const [after, before] = decodeAbiParameters(
        parseAbiParameters('uint128, uint128'),
        caveat.terms,
      );
      Iif (
        currentTime === undefined &&
        typeof globalThis.Date?.now !== 'function'
      ) {
        return {
          matches: false,
          failedCaveat: 'timestamp',
          reason:
            'Cannot evaluate timestamp caveat: Date.now() is not available (SES compartment) and no currentTime was provided',
        };
      }
      const now = BigInt(Math.floor((currentTime ?? Date.now()) / 1000));
      if (now < after) {
        return {
          matches: false,
          failedCaveat: 'timestamp',
          reason: `Current time ${now} is before the allowed window (starts at ${after})`,
        };
      }
      if (now > before) {
        return {
          matches: false,
          failedCaveat: 'timestamp',
          reason: `Current time ${now} is after the allowed window (ended at ${before})`,
        };
      }
    }
 
    if (caveat.type === 'erc20TransferAmount') {
      // Packed: 20-byte address (40 hex chars) + 32-byte uint256 (64 hex chars).
      const erc20Hex = caveat.terms.slice(2);
      const token = `0x${erc20Hex.slice(0, 40)}`;
      const maxAmount = BigInt(`0x${erc20Hex.slice(40, 104)}`);
      if (action.to.toLowerCase() !== token.toLowerCase()) {
        return {
          matches: false,
          failedCaveat: 'erc20TransferAmount',
          reason: `Target ${action.to} does not match token contract ${token}`,
        };
      }
      if (!action.data || action.data.length < 138) {
        return {
          matches: false,
          failedCaveat: 'erc20TransferAmount',
          reason: 'Missing or incomplete ERC-20 transfer calldata',
        };
      }
      const selector = action.data.slice(0, 10).toLowerCase();
      Iif (selector !== '0xa9059cbb') {
        return {
          matches: false,
          failedCaveat: 'erc20TransferAmount',
          reason: `Selector ${selector} is not transfer(address,uint256)`,
        };
      }
      const amountHex = `0x${action.data.slice(74, 138)}`;
      const transferAmount = BigInt(amountHex);
      if (transferAmount > maxAmount) {
        return {
          matches: false,
          failedCaveat: 'erc20TransferAmount',
          reason: `Transfer amount ${transferAmount} exceeds maximum ${maxAmount}`,
        };
      }
    }
 
    // limitedCalls: Cannot enforce client-side (requires on-chain call counter).
    // nativeTokenTransferAmount: Cannot enforce client-side (requires on-chain accounting).
    // The on-chain enforcers are authoritative — pass through.
  }
 
  return { matches: true };
}
 
/**
 * Check whether a signed delegation potentially covers an action.
 *
 * This is a convenience wrapper around {@link explainDelegationMatch}
 * that returns a simple boolean.
 *
 * @param delegation - The delegation to check.
 * @param action - The action to match against.
 * @param currentTime - Optional current time in milliseconds (defaults to Date.now()).
 * @returns True if the delegation might cover the action.
 */
export function delegationMatchesAction(
  delegation: Delegation,
  action: Action,
  currentTime?: number,
): boolean {
  return explainDelegationMatch(delegation, action, currentTime).matches;
}
 
/**
 * Mark a delegation as signed with the given signature.
 *
 * @param delegation - The delegation to finalize.
 * @param signature - The EIP-712 signature.
 * @returns The signed delegation.
 */
export function finalizeDelegation(
  delegation: Delegation,
  signature: Hex,
): Delegation {
  return harden({
    ...delegation,
    signature,
    status: 'signed',
  });
}