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

92.06% Statements 58/63
92% Branches 46/50
90.9% Functions 10/11
93.44% Lines 57/61

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                                      5x                                   118x                                   5x                       99x 99x   99x 99x                                                           110x 110x   110x             110x                                               49x   49x                             16x                                                                     46x 2x       44x 39x 19x       19x 20x   19x 6x               33x 3x 3x       3x 3x 2x               31x 5x       5x 5x 3x               28x 4x       4x                     4x 4x 1x           3x 2x               25x 7x       7x 2x           5x 2x           3x 3x             3x 3x 3x 1x                         25x                                     34x                           94x            
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),
      ],
    ),
  );
}
 
// Monotonic counter for salt uniqueness in SES compartments where
// neither crypto.getRandomValues nor Math.random is available.
// This is intentionally module-level: generateSalt() is a standalone
// exported function (not part of a factory), so the counter must persist
// across calls for the lifetime of the module/compartment.
let saltCounter = 0;
 
/**
 * Generate a random salt for delegation uniqueness.
 *
 * Prefers crypto.getRandomValues when available. In SES compartments
 * where crypto is not endowed, falls back to keccak256(counter).
 *
 * @returns A hex-encoded random salt.
 */
export function generateSalt(): Hex {
  // eslint-disable-next-line n/no-unsupported-features/node-builtins
  Eif (globalThis.crypto?.getRandomValues) {
    const bytes = new Uint8Array(32);
    // eslint-disable-next-line n/no-unsupported-features/node-builtins
    globalThis.crypto.getRandomValues(bytes);
    return toHex(bytes);
  }
 
  // SES fallback: keccak256(counter). Unique per vat lifetime but not
  // cryptographically random. The salt only needs uniqueness, not
  // unpredictability.
  saltCounter += 1;
  return keccak256(encodePacked(['uint256'], [BigInt(saltCounter)]));
}
 
/**
 * 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.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;
  authority?: Hex;
}): Delegation {
  const salt = options.salt ?? 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') {
      const [targets] = decodeAbiParameters(
        parseAbiParameters('address[]'),
        caveat.terms,
      );
      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;
      const [methods] = decodeAbiParameters(
        parseAbiParameters('bytes4[]'),
        caveat.terms,
      );
      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') {
      const [token, maxAmount] = decodeAbiParameters(
        parseAbiParameters('address, uint256'),
        caveat.terms,
      );
      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',
  });
}