All files / evm-wallet-experiment/src types.ts

91.3% Statements 21/23
0% Branches 0/4
33.33% Functions 1/3
91.3% Lines 21/23

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                                                    2x                 2x               2x                                           4x                     2x                       2x   2x                         2x       2x                                   2x                                                                 2x                                           2x                           2x                                             2x                             2x                       2x                             2x                   2x                         2x                                               2x                                           2x                                                              
import {
  array,
  boolean,
  create,
  define,
  enums,
  literal,
  number,
  object,
  optional,
  record,
  string,
  union,
  unknown,
} from '@metamask/superstruct';
import type { Infer } from '@metamask/superstruct';
 
// ---------------------------------------------------------------------------
// Hex string helpers
// ---------------------------------------------------------------------------
 
/**
 * A 0x-prefixed hex string.
 */
export type Hex = `0x${string}`;
 
const HexStruct = define<Hex>('Hex', (value) => {
  return typeof value === 'string' && /^0x[\da-f]*$/iu.test(value);
});
 
/**
 * A 0x-prefixed Ethereum address (20 bytes).
 */
export type Address = Hex;
 
const AddressStruct = define<Address>('Address', (value) => {
  return typeof value === 'string' && /^0x[\da-f]{40}$/iu.test(value);
});
 
// ---------------------------------------------------------------------------
// Chain configuration
// ---------------------------------------------------------------------------
 
export const ChainConfigStruct = object({
  chainId: number(),
  rpcUrl: string(),
  name: optional(string()),
});
 
export type ChainConfig = Infer<typeof ChainConfigStruct>;
 
/**
 * Create a validated ChainConfig.
 *
 * @param options - Chain configuration options.
 * @param options.chainId - The numeric chain ID.
 * @param options.rpcUrl - The JSON-RPC endpoint URL.
 * @param options.name - Optional human-readable chain name.
 * @returns A validated ChainConfig object.
 */
export function makeChainConfig(options: {
  chainId: number;
  rpcUrl: string;
  name?: string;
}): ChainConfig {
  return create(options, ChainConfigStruct);
}
 
// ---------------------------------------------------------------------------
// Caveat types (MetaMask Delegation Framework / Gator)
// ---------------------------------------------------------------------------
 
/**
 * Supported caveat enforcer types.
 * Each maps to a deployed enforcer contract on the delegation framework.
 */
export const CaveatTypeValues = [
  'allowedTargets',
  'allowedMethods',
  'valueLte',
  'nativeTokenTransferAmount',
  'erc20TransferAmount',
  'limitedCalls',
  'timestamp',
] as const;
 
export type CaveatType = (typeof CaveatTypeValues)[number];
 
const CaveatTypeStruct = enums(CaveatTypeValues);
 
export const CaveatStruct = object({
  enforcer: AddressStruct,
  terms: HexStruct,
  args: optional(HexStruct),
  type: CaveatTypeStruct,
});
 
export type Caveat = Infer<typeof CaveatStruct>;
 
// ---------------------------------------------------------------------------
// Delegation
// ---------------------------------------------------------------------------
 
export const DelegationStatusValues = ['pending', 'signed', 'revoked'] as const;
 
export type DelegationStatus = (typeof DelegationStatusValues)[number];
 
export const DelegationStruct = object({
  id: string(),
  delegator: AddressStruct,
  delegate: AddressStruct,
  authority: HexStruct,
  caveats: array(CaveatStruct),
  salt: HexStruct,
  signature: optional(HexStruct),
  chainId: number(),
  status: enums(DelegationStatusValues),
});
 
export type Delegation = Infer<typeof DelegationStruct>;
 
// ---------------------------------------------------------------------------
// Transaction types
// ---------------------------------------------------------------------------
 
export const TransactionRequestStruct = object({
  from: AddressStruct,
  to: AddressStruct,
  value: optional(HexStruct),
  data: optional(HexStruct),
  nonce: optional(number()),
  gasLimit: optional(HexStruct),
  gasPrice: optional(HexStruct),
  maxFeePerGas: optional(HexStruct),
  maxPriorityFeePerGas: optional(HexStruct),
  chainId: optional(number()),
});
 
export type TransactionRequest = Infer<typeof TransactionRequestStruct> & {
  /**
   * EIP-7702 signed authorization list. When present, the transaction is
   * serialized as a type-4 (EIP-7702) transaction instead of EIP-1559.
   * Not struct-validated; only flows internally.
   */
  authorizationList?: readonly {
    contractAddress: Address;
    chainId: number;
    nonce: number;
    r?: Hex;
    s?: Hex;
    yParity?: number;
  }[];
};
 
// ---------------------------------------------------------------------------
// Signing request (used for peer wallet communication)
// ---------------------------------------------------------------------------
 
export const SigningRequestStruct = union([
  object({
    type: literal('transaction'),
    tx: TransactionRequestStruct,
  }),
  object({
    type: literal('typedData'),
    data: record(string(), unknown()),
  }),
  object({
    type: literal('message'),
    message: string(),
    account: AddressStruct,
  }),
]);
 
export type SigningRequest = Infer<typeof SigningRequestStruct>;
 
// ---------------------------------------------------------------------------
// Wallet capabilities introspection
// ---------------------------------------------------------------------------
 
export const DelegationInfoStruct = object({
  id: string(),
  delegator: AddressStruct,
  delegate: AddressStruct,
  caveats: array(
    object({
      type: CaveatTypeStruct,
      humanReadable: string(),
    }),
  ),
});
 
export type DelegationInfo = Infer<typeof DelegationInfoStruct>;
 
export const WalletCapabilitiesStruct = object({
  hasLocalKeys: boolean(),
  localAccounts: array(AddressStruct),
  delegationCount: number(),
  delegations: optional(array(DelegationInfoStruct)),
  hasPeerWallet: boolean(),
  hasExternalSigner: boolean(),
  hasBundlerConfig: boolean(),
  smartAccountAddress: optional(AddressStruct),
  chainId: optional(number()),
  signingMode: optional(string()),
  autonomy: optional(string()),
  peerAccountsCached: optional(boolean()),
  cachedPeerAccounts: optional(array(AddressStruct)),
  hasAwayWallet: optional(boolean()),
});
 
export type WalletCapabilities = Infer<typeof WalletCapabilitiesStruct>;
 
// ---------------------------------------------------------------------------
// Smart account configuration
// ---------------------------------------------------------------------------
 
export const SmartAccountConfigStruct = object({
  implementation: union([literal('hybrid'), literal('stateless7702')]),
  deploySalt: optional(HexStruct),
  address: optional(AddressStruct),
  factory: optional(AddressStruct),
  factoryData: optional(HexStruct),
  deployed: optional(boolean()),
});
 
export type SmartAccountConfig = Infer<typeof SmartAccountConfigStruct>;
 
// ---------------------------------------------------------------------------
// Action descriptor (for delegation matching)
// ---------------------------------------------------------------------------
 
export const ActionStruct = object({
  to: AddressStruct,
  value: optional(HexStruct),
  data: optional(HexStruct),
});
 
export type Action = Infer<typeof ActionStruct>;
 
// ---------------------------------------------------------------------------
// Delegation creation options
// ---------------------------------------------------------------------------
 
export const CreateDelegationOptionsStruct = object({
  delegate: AddressStruct,
  caveats: array(CaveatStruct),
  chainId: number(),
  salt: optional(HexStruct),
});
 
export type CreateDelegationOptions = Infer<
  typeof CreateDelegationOptionsStruct
>;
 
// ---------------------------------------------------------------------------
// EIP-712 typed data (generic representation)
// ---------------------------------------------------------------------------
 
export const Eip712DomainStruct = object({
  name: optional(string()),
  version: optional(string()),
  chainId: optional(number()),
  verifyingContract: optional(AddressStruct),
  salt: optional(HexStruct),
});
 
export type Eip712Domain = Infer<typeof Eip712DomainStruct>;
 
export const Eip712TypedDataStruct = object({
  domain: Eip712DomainStruct,
  types: record(string(), array(object({ name: string(), type: string() }))),
  primaryType: string(),
  message: record(string(), unknown()),
});
 
export type Eip712TypedData = Infer<typeof Eip712TypedDataStruct>;
 
// ---------------------------------------------------------------------------
// ERC-4337 UserOperation (off-chain representation, v0.7)
// ---------------------------------------------------------------------------
 
export const UserOperationStruct = object({
  sender: AddressStruct,
  nonce: HexStruct,
  factory: optional(AddressStruct),
  factoryData: optional(HexStruct),
  callData: HexStruct,
  callGasLimit: HexStruct,
  verificationGasLimit: HexStruct,
  preVerificationGas: HexStruct,
  maxFeePerGas: HexStruct,
  maxPriorityFeePerGas: HexStruct,
  paymaster: optional(AddressStruct),
  paymasterVerificationGasLimit: optional(HexStruct),
  paymasterPostOpGasLimit: optional(HexStruct),
  paymasterData: optional(HexStruct),
  signature: HexStruct,
});
 
export type UserOperation = Infer<typeof UserOperationStruct>;
 
// ---------------------------------------------------------------------------
// Execution descriptor (for delegation redemption)
// ---------------------------------------------------------------------------
 
export const ExecutionStruct = object({
  target: AddressStruct,
  value: HexStruct,
  callData: HexStruct,
});
 
export type Execution = Infer<typeof ExecutionStruct>;
 
// ---------------------------------------------------------------------------
// Delegation match result (for delegation matching diagnostics)
// ---------------------------------------------------------------------------
 
export type DelegationMatchResult = {
  matches: boolean;
  failedCaveat?: CaveatType;
  reason?: string;
};
 
// ---------------------------------------------------------------------------
// Swap types (MetaSwap API)
// ---------------------------------------------------------------------------
 
export const SwapQuoteStruct = object({
  trade: object({
    to: string(),
    from: string(),
    data: string(),
    value: string(),
    gas: string(),
  }),
  approvalNeeded: union([
    object({ to: string(), data: string(), value: string() }),
    literal(null),
  ]),
  sourceAmount: string(),
  destinationAmount: string(),
  aggregator: string(),
  fee: number(),
  gasEstimate: string(),
  priceSlippage: number(),
  quoteRefreshSeconds: number(),
});
 
export type SwapQuote = Infer<typeof SwapQuoteStruct>;
 
export type SwapResult = {
  approvalTxHash?: Hex | undefined;
  swapTxHash: Hex;
  sourceAmount: string;
  destinationAmount: string;
  aggregator: string;
  batched?: boolean | undefined;
};