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 | 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 9x 9x 9x 1x 1x 1x 1x 1x 1x 1x | import { numberToHex } from 'viem';
import type { Address, ChainConfig, Hex } from '../types.ts';
const harden = globalThis.harden ?? (<T>(value: T): T => value);
/**
* A JSON-RPC provider for Ethereum.
*/
export type Provider = {
request: (method: string, params?: unknown[]) => Promise<unknown>;
broadcastTransaction: (signedTx: Hex) => Promise<Hex>;
getBalance: (address: Address) => Promise<string>;
getChainId: () => Promise<number>;
getNonce: (address: Address) => Promise<number>;
};
const RPC_TIMEOUT_MS = 30_000;
const MAX_RETRIES = 2;
const RETRYABLE_STATUS_CODES = new Set([408, 429, 502, 503, 504]);
// SES vat compartments lack setTimeout and AbortController.
const hasTimers = typeof globalThis.setTimeout === 'function';
/**
* Send a JSON-RPC request to the given URL with retries.
*
* @param rpcUrl - The RPC endpoint URL.
* @param method - The JSON-RPC method name.
* @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 jsonRpc(
rpcUrl: string,
method: string,
params: unknown[] = [],
counter: { value: number } = { value: 0 },
): Promise<unknown> {
counter.value += 1;
const id = counter.value;
Iif (!hasTimers) {
return jsonRpcOnce(rpcUrl, id, method, params);
}
let lastError: Error | undefined;
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
Iif (attempt > 0) {
await new Promise<void>((resolve) =>
setTimeout(resolve, 500 * 2 ** (attempt - 1)),
);
}
try {
return await jsonRpcOnce(rpcUrl, id, method, params);
} catch (error: unknown) {
const { status } = error as { status?: number };
if (status && RETRYABLE_STATUS_CODES.has(status)) {
lastError = error as Error;
continue;
}
const message = (error as Error).message ?? '';
if (
message.includes('timed out') ||
(error as Error).name === 'AbortError'
) {
lastError = new Error(
`RPC request timed out after ${RPC_TIMEOUT_MS}ms`,
);
continue;
}
throw error;
}
}
throw lastError ?? new Error('RPC request failed after retries');
}
/**
* Send a single JSON-RPC request (no retries).
*
* @param rpcUrl - The RPC endpoint URL.
* @param id - The JSON-RPC request ID.
* @param method - The JSON-RPC method name.
* @param params - The method parameters.
* @returns The JSON-RPC result.
*/
async function jsonRpcOnce(
rpcUrl: string,
id: number,
method: string,
params: unknown[],
): Promise<unknown> {
const body = JSON.stringify({ jsonrpc: '2.0', id, method, params });
const init: RequestInit = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
};
const response = await fetch(rpcUrl, init);
Iif (!response.ok) {
const error = new Error(
`RPC request 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 };
};
Iif (json.error) {
throw new Error(`RPC error ${json.error.code}: ${json.error.message}`);
}
return json.result;
}
/**
* Create a JSON-RPC provider for the given chain.
*
* Uses raw fetch instead of viem's createPublicClient to avoid
* Math.random() usage that is blocked under SES lockdown.
*
* @param config - The chain configuration.
* @returns The provider instance.
*/
export function makeProvider(config: ChainConfig): Provider {
const { rpcUrl } = config;
// Monotonic counter for JSON-RPC request IDs, scoped to this provider instance.
const requestCounter = { value: 0 };
return harden({
async request(method: string, params?: unknown[]): Promise<unknown> {
return jsonRpc(rpcUrl, method, params, requestCounter);
},
async broadcastTransaction(signedTx: Hex): Promise<Hex> {
return (await jsonRpc(
rpcUrl,
'eth_sendRawTransaction',
[signedTx],
requestCounter,
)) as Hex;
},
async getBalance(address: Address): Promise<string> {
return (await jsonRpc(
rpcUrl,
'eth_getBalance',
[address, 'latest'],
requestCounter,
)) as string;
},
async getChainId(): Promise<number> {
const result = (await jsonRpc(
rpcUrl,
'eth_chainId',
[],
requestCounter,
)) as string;
return Number(result);
},
async getNonce(address: Address): Promise<number> {
const result = (await jsonRpc(
rpcUrl,
'eth_getTransactionCount',
[address, 'latest'],
requestCounter,
)) as string;
return Number(result);
},
});
}
/**
* Send an HTTP GET request and parse the JSON response, with retries.
*
* @param url - The URL to fetch.
* @returns The parsed JSON response body.
*/
export async function httpGetJson(url: string): Promise<unknown> {
if (!hasTimers) {
return httpGetJsonOnce(url);
}
let lastError: Error | undefined;
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
if (attempt > 0) {
await new Promise<void>((resolve) =>
setTimeout(resolve, 500 * 2 ** (attempt - 1)),
);
}
try {
return await httpGetJsonOnce(url);
} catch (error: unknown) {
const { status } = error as { status?: number };
if (status && RETRYABLE_STATUS_CODES.has(status)) {
lastError = error as Error;
continue;
}
const message = (error as Error).message ?? '';
if (
message.includes('timed out') ||
(error as Error).name === 'AbortError'
) {
lastError = new Error(
`HTTP GET request timed out after ${RPC_TIMEOUT_MS}ms`,
);
continue;
}
throw error;
}
}
throw lastError ?? new Error('HTTP GET request failed after retries');
}
/**
* Send a single HTTP GET request (no retries).
*
* @param url - The URL to fetch.
* @returns The parsed JSON response body.
*/
async function httpGetJsonOnce(url: string): Promise<unknown> {
const response = await fetch(url);
if (!response.ok) {
const error = new Error(
`HTTP GET failed: ${response.status} ${response.statusText}`,
);
Object.assign(error, { status: response.status });
throw error;
}
return response.json();
}
// Re-export numberToHex for backward compatibility (used by provider-vat gas fees)
export { numberToHex };
|