All files / evm-wallet-experiment/src/vats provider-vat.ts

78.57% Statements 55/70
67.56% Branches 25/37
90% Functions 18/20
79.71% Lines 55/69

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                      1x         1x                                                         26x           26x                                 7x 7x             26x           12x   12x 12x     12x               8x         8x 8x     8x         2x 1x   1x       1x     1x       1x     1x       1x     1x       1x     1x               2x 2x                             2x 2x       1x                                         1x 1x                                     3x 1x   2x       3x   3x       2x             2x 2x       2x             5x 1x   4x         1x   1x 1x           4x 4x         2x       2x 2x   2x 2x              
import { makeDefaultExo } from '@metamask/kernel-utils/exo';
import type { Logger } from '@metamask/logger';
import type { Baggage } from '@metamask/ocap-kernel';
import { encodeAbiParameters, parseAbiParameters } from 'viem';
 
import { makeBundlerClient } from '../lib/bundler-client.ts';
import type { ViemBundlerClient } from '../lib/bundler-client.ts';
import { httpGetJson, makeProvider } from '../lib/provider.ts';
import type { Provider } from '../lib/provider.ts';
import type { Address, ChainConfig, Hex, UserOperation } from '../types.ts';
 
const harden = globalThis.harden ?? (<T>(value: T): T => value);
 
/**
 * Function selector for EntryPoint.getNonce(address,uint192).
 */
const GET_NONCE_SELECTOR = '0x35567e1a' as Hex;
 
/**
 * Vat powers for the provider vat.
 */
type VatPowers = {
  logger?: Logger;
};
 
/**
 * Build the root object for the provider vat.
 *
 * The provider vat handles all Ethereum JSON-RPC communication.
 * It wraps the lib/provider module in an exo interface.
 *
 * @param _vatPowers - Special powers granted to this vat.
 * @param _parameters - Initialization parameters.
 * @param baggage - Root of vat's persistent state.
 * @returns The root object for the provider vat.
 */
export function buildRootObject(
  _vatPowers: VatPowers,
  _parameters: unknown,
  baggage: Baggage,
): object {
  let provider: Provider | undefined;
  let bundlerClient: ViemBundlerClient | undefined;
 
  // Restore provider from persisted chain config
  Iif (baggage.has('chainConfig')) {
    const chainConfig = baggage.get('chainConfig') as ChainConfig;
    provider = makeProvider(chainConfig);
  }
 
  // Restore bundler client from persisted config
  Iif (baggage.has('bundlerConfig')) {
    const config = baggage.get('bundlerConfig') as {
      bundlerUrl: string;
      chainId: number;
    };
    bundlerClient = makeBundlerClient({
      bundlerUrl: config.bundlerUrl,
      chainId: config.chainId,
    });
  }
 
  /**
   * Get the pre-configured bundler client.
   *
   * @returns A bundler client.
   */
  function getBundlerClient(): ViemBundlerClient {
    Eif (bundlerClient) {
      return bundlerClient;
    }
    throw new Error(
      'Bundler client not configured. Call configureBundler() first.',
    );
  }
 
  return makeDefaultExo('walletProvider', {
    async bootstrap(): Promise<void> {
      // No services needed for the provider vat
    },
 
    async configure(chainConfig: ChainConfig): Promise<void> {
      provider = makeProvider(chainConfig);
 
      const hardenedConfig = harden({ ...chainConfig });
      Iif (baggage.has('chainConfig')) {
        baggage.set('chainConfig', hardenedConfig);
      } else {
        baggage.init('chainConfig', hardenedConfig);
      }
    },
 
    async configureBundler(config: {
      bundlerUrl: string;
      chainId: number;
    }): Promise<void> {
      bundlerClient = makeBundlerClient({
        bundlerUrl: config.bundlerUrl,
        chainId: config.chainId,
      });
 
      const hardenedBundlerConfig = harden({ ...config });
      Iif (baggage.has('bundlerConfig')) {
        baggage.set('bundlerConfig', hardenedBundlerConfig);
      } else {
        baggage.init('bundlerConfig', hardenedBundlerConfig);
      }
    },
 
    async request(method: string, params?: unknown[]): Promise<unknown> {
      if (!provider) {
        throw new Error('Provider not configured');
      }
      return provider.request(method, params);
    },
 
    async broadcastTransaction(signedTx: Hex): Promise<Hex> {
      Iif (!provider) {
        throw new Error('Provider not configured');
      }
      return provider.broadcastTransaction(signedTx);
    },
 
    async getBalance(address: Address): Promise<string> {
      Iif (!provider) {
        throw new Error('Provider not configured');
      }
      return provider.getBalance(address);
    },
 
    async getChainId(): Promise<number> {
      Iif (!provider) {
        throw new Error('Provider not configured');
      }
      return provider.getChainId();
    },
 
    async getNonce(address: Address): Promise<number> {
      Iif (!provider) {
        throw new Error('Provider not configured');
      }
      return provider.getNonce(address);
    },
 
    async submitUserOp(options: {
      bundlerUrl: string;
      entryPoint: Hex;
      userOp: UserOperation;
    }): Promise<Hex> {
      const client = getBundlerClient();
      return client.sendUserOperation({
        userOp: options.userOp as never,
        entryPointAddress: options.entryPoint,
      });
    },
 
    async estimateUserOpGas(options: {
      bundlerUrl: string;
      entryPoint: Hex;
      userOp: UserOperation;
    }): Promise<{
      callGasLimit: Hex;
      verificationGasLimit: Hex;
      preVerificationGas: Hex;
    }> {
      const client = getBundlerClient();
      const estimate = await client.estimateUserOperationGas({
        userOp: options.userOp as never,
        entryPointAddress: options.entryPoint,
      });
      return {
        callGasLimit: `0x${estimate.callGasLimit.toString(16)}`,
        verificationGasLimit: `0x${estimate.verificationGasLimit.toString(16)}`,
        preVerificationGas: `0x${estimate.preVerificationGas.toString(16)}`,
      };
    },
 
    async sponsorUserOp(options: {
      bundlerUrl: string;
      entryPoint: Hex;
      userOp: UserOperation;
      context?: Record<string, unknown>;
    }): Promise<{
      paymaster: Address;
      paymasterData: Hex;
      paymasterVerificationGasLimit: Hex;
      paymasterPostOpGasLimit: Hex;
      callGasLimit: Hex;
      verificationGasLimit: Hex;
      preVerificationGas: Hex;
    }> {
      const client = getBundlerClient();
      return client.sponsorUserOperation({
        userOp: options.userOp as never,
        entryPointAddress: options.entryPoint,
        context: options.context,
      });
    },
 
    async getUserOperationGasPrice(): Promise<{
      fast: { maxFeePerGas: Hex; maxPriorityFeePerGas: Hex };
    }> {
      const client = getBundlerClient();
      return client.getUserOperationGasPrice();
    },
 
    async getEntryPointNonce(options: {
      entryPoint: Address;
      sender: Address;
      key?: Hex;
    }): Promise<Hex> {
      if (!provider) {
        throw new Error('Provider not configured');
      }
      const encoded = encodeAbiParameters(
        parseAbiParameters('address, uint192'),
        [options.sender, options.key ? BigInt(options.key) : 0n],
      );
      const callData = (GET_NONCE_SELECTOR + encoded.slice(2)) as Hex;
 
      const result = await provider.request('eth_call', [
        { to: options.entryPoint, data: callData },
        'latest',
      ]);
      return result as Hex;
    },
 
    async getUserOpReceipt(options: {
      bundlerUrl: string;
      userOpHash: Hex;
    }): Promise<unknown> {
      const client = getBundlerClient();
      return client.getUserOperationReceipt(options.userOpHash);
    },
 
    async httpGetJson(url: string): Promise<unknown> {
      return httpGetJson(url);
    },
 
    async getGasFees(): Promise<{
      maxFeePerGas: Hex;
      maxPriorityFeePerGas: Hex;
    }> {
      if (!provider) {
        throw new Error('Provider not configured');
      }
      const [block, priorityFee] = await Promise.all([
        provider.request('eth_getBlockByNumber', ['latest', false]),
        provider
          .request('eth_maxPriorityFeePerGas', [])
          .catch((error: unknown) => {
            const message = String((error as Error).message ?? error);
            // JSON-RPC -32601 = method not found. Expected on non-EIP-1559 chains.
            Eif (message.includes('-32601')) {
              return '0x3b9aca00';
            }
            throw new Error(`Failed to get priority fee: ${message}`);
          }),
      ]);
      // Validate RPC response shape before using it
      const blockObj = block as Record<string, unknown> | null;
      if (
        !blockObj ||
        typeof blockObj !== 'object' ||
        typeof blockObj.baseFeePerGas !== 'string'
      ) {
        throw new Error(
          'Invalid block response: missing or malformed baseFeePerGas',
        );
      }
      const baseFee = BigInt(blockObj.baseFeePerGas);
      const priority = BigInt(priorityFee as string);
      // maxFeePerGas = 2 * baseFee + maxPriorityFeePerGas (standard EIP-1559 heuristic)
      const maxFee = baseFee * 2n + priority;
      return {
        maxFeePerGas: `0x${maxFee.toString(16)}`,
        maxPriorityFeePerGas: `0x${priority.toString(16)}`,
      };
    },
  });
}