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 | 1x 1x 1x 1x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 8x 8x 8x 1x 1x 1x 2x 2x 3x 3x 3x 3x 11x 11x 2x 9x 9x 1x | /**
* Bundler client using raw fetch for ERC-4337 interactions.
*
* Avoids viem's createClient/http which use Math.random() (blocked under
* SES lockdown). All methods are simple JSON-RPC calls over fetch.
*
* @module lib/bundler-client
*/
import type { Address, Hex } from '../types.ts';
const harden = globalThis.harden ?? (<T>(value: T): T => value);
/**
* Configuration for the bundler client.
*/
export type BundlerClientConfig = {
bundlerUrl: string;
rpcUrl?: string;
chainId: number;
apiKey?: string;
};
/**
* Result from a paymaster sponsorship request.
*/
export type PaymasterSponsorResult = {
paymaster: Address;
paymasterData: Hex;
paymasterVerificationGasLimit: Hex;
paymasterPostOpGasLimit: Hex;
callGasLimit: Hex;
verificationGasLimit: Hex;
preVerificationGas: Hex;
};
/**
* UserOperation type for ERC-4337 v0.7 (simplified for bundler RPC).
*/
type UserOp07 = Record<string, unknown>;
/**
* Receipt returned by the bundler for a submitted UserOperation.
*/
export type UserOpReceiptResult = {
receipt: { transactionHash: Hex; blockNumber: Hex; status: Hex };
success: boolean;
userOpHash: Hex;
};
/**
* Gas price recommendation from the bundler (e.g. Pimlico).
*/
export type GasPriceResult = {
maxFeePerGas: Hex;
maxPriorityFeePerGas: Hex;
};
/**
* A bundler client with ERC-4337 capabilities.
*/
export type ViemBundlerClient = {
sendUserOperation: (options: {
userOp: UserOp07;
entryPointAddress: Address;
}) => Promise<Hex>;
estimateUserOperationGas: (options: {
userOp: Partial<UserOp07>;
entryPointAddress: Address;
}) => Promise<{
callGasLimit: bigint;
verificationGasLimit: bigint;
preVerificationGas: bigint;
}>;
sponsorUserOperation: (options: {
userOp: Partial<UserOp07>;
entryPointAddress: Address;
context?: Record<string, unknown>;
}) => Promise<PaymasterSponsorResult>;
getUserOperationGasPrice: () => Promise<{
slow: GasPriceResult;
standard: GasPriceResult;
fast: GasPriceResult;
}>;
getUserOperationReceipt: (hash: Hex) => Promise<UserOpReceiptResult | null>;
waitForUserOperationReceipt: (options: {
hash: Hex;
pollingInterval?: number;
timeout?: number;
}) => Promise<UserOpReceiptResult>;
};
const BUNDLER_MAX_RETRIES = 2;
const RETRYABLE_STATUS_CODES = new Set([408, 429, 502, 503, 504]);
const hasTimers = typeof globalThis.setTimeout === 'function';
/**
* Send a JSON-RPC request to the bundler with retries.
*
* @param bundlerUrl - The bundler RPC URL.
* @param method - The JSON-RPC method.
* @param params - The method parameters.
* @param counter - Monotonic counter for JSON-RPC request IDs.
* @param counter.value - The current counter value (mutated on each call).
* @returns The JSON-RPC result.
*/
async function bundlerRpc(
bundlerUrl: string,
method: string,
params: unknown[] = [],
counter: { value: number } = { value: 0 },
): Promise<unknown> {
counter.value += 1;
const id = counter.value;
Iif (!hasTimers) {
return bundlerRpcOnce(bundlerUrl, id, method, params);
}
let lastError: Error | undefined;
for (let attempt = 0; attempt <= BUNDLER_MAX_RETRIES; attempt++) {
Iif (attempt > 0) {
await new Promise<void>((resolve) =>
setTimeout(resolve, 500 * 2 ** (attempt - 1)),
);
}
try {
return await bundlerRpcOnce(bundlerUrl, id, method, params);
} catch (error: unknown) {
const { status } = error as { status?: number };
if (status && RETRYABLE_STATUS_CODES.has(status)) {
lastError = error as Error;
continue;
}
throw error;
}
}
throw lastError ?? new Error('Bundler RPC failed after retries');
}
/**
* Send a single JSON-RPC request to the bundler (no retries).
*
* @param bundlerUrl - The bundler RPC URL.
* @param id - The JSON-RPC request ID.
* @param method - The JSON-RPC method.
* @param params - The method parameters.
* @returns The JSON-RPC result.
*/
async function bundlerRpcOnce(
bundlerUrl: string,
id: number,
method: string,
params: unknown[],
): Promise<unknown> {
const response = await fetch(bundlerUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ jsonrpc: '2.0', id, method, params }),
});
Iif (!response.ok) {
const error = new Error(
`Bundler RPC failed: ${response.status} ${response.statusText}`,
);
Object.assign(error, { status: response.status });
throw error;
}
const json = (await response.json()) as {
result?: unknown;
error?: { code: number; message: string; data?: unknown };
};
Iif (json.error) {
const detail = json.error.data
? ` (${JSON.stringify(json.error.data)})`
: '';
throw new Error(
`Bundler RPC error ${json.error.code}: ${json.error.message}${detail}`,
);
}
return json.result;
}
/**
* Create a bundler client for ERC-4337 operations.
*
* Uses raw fetch instead of viem's createClient to avoid Math.random()
* usage that is blocked under SES lockdown.
*
* @param config - Bundler configuration.
* @returns A bundler client with ERC-4337 actions.
*/
export function makeBundlerClient(
config: BundlerClientConfig,
): ViemBundlerClient {
const bundlerUrl = config.apiKey
? `${config.bundlerUrl}?apikey=${config.apiKey}`
: config.bundlerUrl;
// Monotonic counter for JSON-RPC request IDs, scoped to this client instance.
const requestCounter = { value: 0 };
return harden({
async sendUserOperation(options: {
userOp: UserOp07;
entryPointAddress: Address;
}): Promise<Hex> {
return (await bundlerRpc(
bundlerUrl,
'eth_sendUserOperation',
[options.userOp, options.entryPointAddress],
requestCounter,
)) as Hex;
},
async estimateUserOperationGas(options: {
userOp: Partial<UserOp07>;
entryPointAddress: Address;
}): Promise<{
callGasLimit: bigint;
verificationGasLimit: bigint;
preVerificationGas: bigint;
}> {
const result = (await bundlerRpc(
bundlerUrl,
'eth_estimateUserOperationGas',
[options.userOp, options.entryPointAddress],
requestCounter,
)) as {
callGasLimit: Hex;
verificationGasLimit: Hex;
preVerificationGas: Hex;
};
return {
callGasLimit: BigInt(result.callGasLimit),
verificationGasLimit: BigInt(result.verificationGasLimit),
preVerificationGas: BigInt(result.preVerificationGas),
};
},
async sponsorUserOperation(options: {
userOp: Partial<UserOp07>;
entryPointAddress: Address;
context?: Record<string, unknown>;
}): Promise<PaymasterSponsorResult> {
return (await bundlerRpc(
bundlerUrl,
'pm_sponsorUserOperation',
[options.userOp, options.entryPointAddress, options.context ?? {}],
requestCounter,
)) as PaymasterSponsorResult;
},
async getUserOperationGasPrice(): Promise<{
slow: GasPriceResult;
standard: GasPriceResult;
fast: GasPriceResult;
}> {
return (await bundlerRpc(
bundlerUrl,
'pimlico_getUserOperationGasPrice',
[],
requestCounter,
)) as {
slow: GasPriceResult;
standard: GasPriceResult;
fast: GasPriceResult;
};
},
async getUserOperationReceipt(
hash: Hex,
): Promise<UserOpReceiptResult | null> {
const result = (await bundlerRpc(
bundlerUrl,
'eth_getUserOperationReceipt',
[hash],
requestCounter,
)) as UserOpReceiptResult | undefined;
return result ?? null;
},
async waitForUserOperationReceipt(options: {
hash: Hex;
pollingInterval?: number;
timeout?: number;
}): Promise<UserOpReceiptResult> {
Iif (!hasTimers) {
throw new Error(
'waitForUserOperationReceipt requires timer support ' +
'(not available in SES compartments)',
);
}
const { pollingInterval = 2000, timeout = 60000 } = options;
const deadline = Date.now() + timeout;
while (Date.now() < deadline) {
const receipt = (await bundlerRpc(
bundlerUrl,
'eth_getUserOperationReceipt',
[options.hash],
requestCounter,
)) as UserOpReceiptResult | undefined;
if (receipt !== null && receipt !== undefined) {
return receipt;
}
await new Promise<void>((resolve) =>
setTimeout(resolve, pollingInterval),
);
}
throw new Error(
`UserOperation ${options.hash} not included after ${timeout}ms`,
);
},
});
}
|