@lodestar/prover 1.35.0-dev.e18102ed8c → 1.35.0-dev.f45a2be721

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/bin/lodestar-prover.js +3 -0
  2. package/lib/browser/index.d.ts.map +1 -0
  3. package/lib/cli/applyPreset.d.ts.map +1 -0
  4. package/lib/cli/cli.d.ts.map +1 -0
  5. package/lib/cli/cmds/index.d.ts.map +1 -0
  6. package/lib/cli/cmds/start/handler.d.ts.map +1 -0
  7. package/lib/cli/cmds/start/index.d.ts.map +1 -0
  8. package/lib/cli/cmds/start/options.d.ts.map +1 -0
  9. package/lib/cli/index.d.ts.map +1 -0
  10. package/lib/cli/options.d.ts.map +1 -0
  11. package/lib/constants.d.ts.map +1 -0
  12. package/lib/index.d.ts.map +1 -0
  13. package/lib/interfaces.d.ts.map +1 -0
  14. package/lib/proof_provider/index.d.ts.map +1 -0
  15. package/lib/proof_provider/ordered_map.d.ts.map +1 -0
  16. package/lib/proof_provider/payload_store.d.ts.map +1 -0
  17. package/lib/proof_provider/proof_provider.d.ts.map +1 -0
  18. package/lib/provider_types/eip1193_provider_type.d.ts.map +1 -0
  19. package/lib/provider_types/ethers_provider_type.d.ts.map +1 -0
  20. package/lib/provider_types/legacy_provider_type.d.ts.map +1 -0
  21. package/lib/provider_types/web3_js_provider_type.d.ts.map +1 -0
  22. package/lib/types.d.ts.map +1 -0
  23. package/lib/utils/assertion.d.ts.map +1 -0
  24. package/lib/utils/consensus.d.ts.map +1 -0
  25. package/lib/utils/conversion.d.ts.map +1 -0
  26. package/lib/utils/errors.d.ts.map +1 -0
  27. package/lib/utils/evm.d.ts.map +1 -0
  28. package/lib/utils/execution.d.ts.map +1 -0
  29. package/lib/utils/file.d.ts.map +1 -0
  30. package/lib/utils/gitData/gitDataPath.d.ts.map +1 -0
  31. package/lib/utils/gitData/index.d.ts.map +1 -0
  32. package/lib/utils/gitData/writeGitData.d.ts.map +1 -0
  33. package/lib/utils/json_rpc.d.ts.map +1 -0
  34. package/lib/utils/process.d.ts.map +1 -0
  35. package/lib/utils/req_resp.d.ts.map +1 -0
  36. package/lib/utils/rpc_provider.d.ts.map +1 -0
  37. package/lib/utils/validation.d.ts.map +1 -0
  38. package/lib/utils/verification.d.ts.map +1 -0
  39. package/lib/utils/version.d.ts.map +1 -0
  40. package/lib/verified_requests/eth_call.d.ts.map +1 -0
  41. package/lib/verified_requests/eth_estimateGas.d.ts.map +1 -0
  42. package/lib/verified_requests/eth_getBalance.d.ts.map +1 -0
  43. package/lib/verified_requests/eth_getBlockByHash.d.ts.map +1 -0
  44. package/lib/verified_requests/eth_getBlockByNumber.d.ts.map +1 -0
  45. package/lib/verified_requests/eth_getCode.d.ts.map +1 -0
  46. package/lib/verified_requests/eth_getTransactionCount.d.ts.map +1 -0
  47. package/lib/web3_provider.d.ts.map +1 -0
  48. package/lib/web3_provider_inspector.d.ts.map +1 -0
  49. package/lib/web3_proxy.d.ts.map +1 -0
  50. package/package.json +16 -15
  51. package/src/browser/index.ts +3 -0
  52. package/src/cli/applyPreset.ts +83 -0
  53. package/src/cli/cli.ts +58 -0
  54. package/src/cli/cmds/index.ts +7 -0
  55. package/src/cli/cmds/start/handler.ts +27 -0
  56. package/src/cli/cmds/start/index.ts +18 -0
  57. package/src/cli/cmds/start/options.ts +85 -0
  58. package/src/cli/index.ts +30 -0
  59. package/src/cli/options.ts +73 -0
  60. package/src/constants.ts +6 -0
  61. package/src/index.ts +5 -0
  62. package/src/interfaces.ts +90 -0
  63. package/src/proof_provider/index.ts +1 -0
  64. package/src/proof_provider/ordered_map.ts +25 -0
  65. package/src/proof_provider/payload_store.ts +223 -0
  66. package/src/proof_provider/proof_provider.ts +210 -0
  67. package/src/provider_types/eip1193_provider_type.ts +32 -0
  68. package/src/provider_types/ethers_provider_type.ts +44 -0
  69. package/src/provider_types/legacy_provider_type.ts +123 -0
  70. package/src/provider_types/web3_js_provider_type.ts +35 -0
  71. package/src/types.ts +163 -0
  72. package/src/utils/assertion.ts +11 -0
  73. package/src/utils/consensus.ts +122 -0
  74. package/src/utils/conversion.ts +107 -0
  75. package/src/utils/errors.ts +4 -0
  76. package/src/utils/evm.ts +284 -0
  77. package/src/utils/execution.ts +76 -0
  78. package/src/utils/file.ts +51 -0
  79. package/src/utils/gitData/gitDataPath.ts +48 -0
  80. package/src/utils/gitData/index.ts +70 -0
  81. package/src/utils/gitData/writeGitData.ts +10 -0
  82. package/src/utils/json_rpc.ts +170 -0
  83. package/src/utils/process.ts +111 -0
  84. package/src/utils/req_resp.ts +34 -0
  85. package/src/utils/rpc_provider.ts +117 -0
  86. package/src/utils/validation.ts +161 -0
  87. package/src/utils/verification.ts +112 -0
  88. package/src/utils/version.ts +74 -0
  89. package/src/verified_requests/eth_call.ts +50 -0
  90. package/src/verified_requests/eth_estimateGas.ts +49 -0
  91. package/src/verified_requests/eth_getBalance.ts +26 -0
  92. package/src/verified_requests/eth_getBlockByHash.ts +24 -0
  93. package/src/verified_requests/eth_getBlockByNumber.ts +25 -0
  94. package/src/verified_requests/eth_getCode.ts +50 -0
  95. package/src/verified_requests/eth_getTransactionCount.ts +26 -0
  96. package/src/web3_provider.ts +58 -0
  97. package/src/web3_provider_inspector.ts +88 -0
  98. package/src/web3_proxy.ts +175 -0
@@ -0,0 +1,32 @@
1
+ import {Web3ProviderType} from "../interfaces.js";
2
+ import {JsonRpcRequestOrBatch, JsonRpcResponseOrBatch} from "../types.js";
3
+
4
+ // Modern providers uses this structure e.g. Web3 4.x
5
+ export interface EIP1193Provider {
6
+ request: (payload: JsonRpcRequestOrBatch) => Promise<JsonRpcResponseOrBatch>;
7
+ }
8
+ export default {
9
+ name: "eip1193",
10
+ matched(provider): provider is EIP1193Provider {
11
+ return (
12
+ "request" in provider &&
13
+ typeof provider.request === "function" &&
14
+ provider.request.constructor.name === "AsyncFunction"
15
+ );
16
+ },
17
+ handler(provider) {
18
+ const request = provider.request.bind(provider);
19
+
20
+ return async (payload: JsonRpcRequestOrBatch): Promise<JsonRpcResponseOrBatch | undefined> => {
21
+ const response = await request(payload);
22
+ return response;
23
+ };
24
+ },
25
+ mutateProvider(provider, newHandler) {
26
+ Object.assign(provider, {
27
+ request: async function newRequest(payload: JsonRpcRequestOrBatch): Promise<JsonRpcResponseOrBatch | undefined> {
28
+ return newHandler(payload);
29
+ },
30
+ });
31
+ },
32
+ } as Web3ProviderType<EIP1193Provider>;
@@ -0,0 +1,44 @@
1
+ import {Web3ProviderType} from "../interfaces.js";
2
+ import {JsonRpcRequestOrBatch, JsonRpcResponse, JsonRpcResponseOrBatch} from "../types.js";
3
+ import {isBatchRequest} from "../utils/json_rpc.js";
4
+ import web3JsProviderType from "./web3_js_provider_type.js";
5
+
6
+ export interface EthersProvider {
7
+ // Ethers provider does not have a public interface for batch requests
8
+ send(method: string, params: Array<unknown>): Promise<JsonRpcResponse>;
9
+ }
10
+ export default {
11
+ name: "ethers",
12
+ matched(provider): provider is EthersProvider {
13
+ return (
14
+ !web3JsProviderType.matched(provider) &&
15
+ "send" in provider &&
16
+ typeof provider.send === "function" &&
17
+ provider.send.length > 1 &&
18
+ provider.send.constructor.name === "AsyncFunction"
19
+ );
20
+ },
21
+ handler(provider) {
22
+ const send = provider.send.bind(provider);
23
+
24
+ return async (payload: JsonRpcRequestOrBatch): Promise<JsonRpcResponseOrBatch | undefined> => {
25
+ // Because ethers provider public interface does not support batch requests
26
+ // so we need to handle it manually
27
+ if (isBatchRequest(payload)) {
28
+ const responses = [];
29
+ for (const request of payload) {
30
+ responses.push(await send(request.method, request.params));
31
+ }
32
+ return responses;
33
+ }
34
+ return send(payload.method, payload.params);
35
+ };
36
+ },
37
+ mutateProvider(provider, newHandler) {
38
+ Object.assign(provider, {
39
+ send: function newSend(method: string, params: Array<unknown>): Promise<JsonRpcResponseOrBatch | undefined> {
40
+ return newHandler({jsonrpc: "2.0", id: 0, method, params});
41
+ },
42
+ });
43
+ },
44
+ } as Web3ProviderType<EthersProvider>;
@@ -0,0 +1,123 @@
1
+ import {AnyWeb3Provider, Web3ProviderType} from "../interfaces.js";
2
+ import {JsonRpcRequest, JsonRpcRequestOrBatch, JsonRpcResponse, JsonRpcResponseOrBatch} from "../types.js";
3
+ import web3JsProviderType from "./web3_js_provider_type.js";
4
+
5
+ // Some providers uses `request` instead of the `send`. e.g. Ganache
6
+ interface RequestProvider {
7
+ request(
8
+ payload: JsonRpcRequestOrBatch,
9
+ callback: (err: Error | undefined, response: JsonRpcResponseOrBatch) => void
10
+ ): void;
11
+ }
12
+ // The legacy Web3 1.x use this structure
13
+ interface SendProvider {
14
+ send(payload: JsonRpcRequest, callback: (err?: Error | null, response?: JsonRpcResponse) => void): void;
15
+ }
16
+ // Some legacy providers use this very old structure
17
+ interface SendAsyncProvider {
18
+ sendAsync(payload: JsonRpcRequestOrBatch): Promise<JsonRpcResponseOrBatch>;
19
+ }
20
+
21
+ type LegacyProvider = RequestProvider | SendProvider | SendAsyncProvider;
22
+
23
+ export default {
24
+ name: "legacy",
25
+ matched(provider): provider is LegacyProvider {
26
+ return isRequestProvider(provider) || isSendProvider(provider) || isSendAsyncProvider(provider);
27
+ },
28
+ handler(provider) {
29
+ if (isRequestProvider(provider)) {
30
+ const request = provider.request.bind(provider);
31
+ return function newHandler(payload: JsonRpcRequestOrBatch): Promise<JsonRpcResponseOrBatch | undefined> {
32
+ return new Promise((resolve, reject) => {
33
+ request(payload, (err, response) => {
34
+ if (err) {
35
+ reject(err);
36
+ } else {
37
+ resolve(response);
38
+ }
39
+ });
40
+ });
41
+ };
42
+ }
43
+ if (isSendProvider(provider)) {
44
+ const send = provider.send.bind(provider);
45
+ return function newHandler(payload: JsonRpcRequestOrBatch): Promise<JsonRpcResponseOrBatch | undefined> {
46
+ return new Promise((resolve, reject) => {
47
+ // web3 providers supports batch requests but don't have valid types
48
+ send(payload as JsonRpcRequest, (err, response) => {
49
+ if (err) {
50
+ reject(err);
51
+ } else {
52
+ resolve(response);
53
+ }
54
+ });
55
+ });
56
+ };
57
+ }
58
+
59
+ // sendAsync provider
60
+ const sendAsync = provider.sendAsync.bind(provider);
61
+ return async function newHandler(payload: JsonRpcRequestOrBatch): Promise<JsonRpcResponseOrBatch | undefined> {
62
+ const response = await sendAsync(payload);
63
+ return response;
64
+ };
65
+ },
66
+ mutateProvider(provider, newHandler) {
67
+ if (isRequestProvider(provider)) {
68
+ const newRequest = function newRequest(
69
+ payload: JsonRpcRequestOrBatch,
70
+ callback: (err?: Error | null, response?: JsonRpcResponseOrBatch) => void
71
+ ): void {
72
+ newHandler(payload)
73
+ .then((response) => callback(undefined, response))
74
+ .catch((err) => callback(err, undefined));
75
+ };
76
+
77
+ Object.assign(provider, {request: newRequest});
78
+ }
79
+
80
+ if (isSendProvider(provider)) {
81
+ const newSend = function newSend(
82
+ payload: JsonRpcRequestOrBatch,
83
+ callback: (err?: Error | null, response?: JsonRpcResponseOrBatch) => void
84
+ ): void {
85
+ newHandler(payload)
86
+ .then((response) => callback(undefined, response))
87
+ .catch((err) => callback(err, undefined));
88
+ };
89
+
90
+ Object.assign(provider, {send: newSend});
91
+ }
92
+
93
+ // sendAsync provider
94
+ Object.assign(provider, {sendAsync: newHandler});
95
+ },
96
+ } as Web3ProviderType<LegacyProvider>;
97
+
98
+ function isSendProvider(provider: AnyWeb3Provider): provider is SendProvider {
99
+ return (
100
+ !web3JsProviderType.matched(provider) &&
101
+ "send" in provider &&
102
+ typeof provider.send === "function" &&
103
+ provider.send.length > 1 &&
104
+ provider.send.constructor.name !== "AsyncFunction"
105
+ );
106
+ }
107
+
108
+ function isRequestProvider(provider: AnyWeb3Provider): provider is RequestProvider {
109
+ return (
110
+ !web3JsProviderType.matched(provider) &&
111
+ "request" in provider &&
112
+ typeof provider.request === "function" &&
113
+ provider.request.length > 1
114
+ );
115
+ }
116
+
117
+ function isSendAsyncProvider(provider: AnyWeb3Provider): provider is SendAsyncProvider {
118
+ return (
119
+ "sendAsync" in provider &&
120
+ typeof provider.sendAsync === "function" &&
121
+ provider.sendAsync.constructor.name === "AsyncFunction"
122
+ );
123
+ }
@@ -0,0 +1,35 @@
1
+ import {AnyWeb3Provider, Web3ProviderType} from "../interfaces.js";
2
+ import {JsonRpcRequest, JsonRpcRequestOrBatch, JsonRpcResponse, JsonRpcResponseOrBatch} from "../types.js";
3
+ import {isBatchRequest} from "../utils/json_rpc.js";
4
+
5
+ export interface Web3jsProvider {
6
+ request: (payload: JsonRpcRequest) => Promise<JsonRpcResponse>;
7
+ }
8
+
9
+ export default {
10
+ name: "web3js",
11
+ matched(provider): provider is Web3jsProvider {
12
+ return (
13
+ "isWeb3Provider" in provider.constructor &&
14
+ (provider.constructor as {isWeb3Provider: (provider: AnyWeb3Provider) => boolean}).isWeb3Provider(provider)
15
+ );
16
+ },
17
+ handler(provider) {
18
+ const request = provider.request.bind(provider);
19
+
20
+ return async (payload: JsonRpcRequestOrBatch): Promise<JsonRpcResponseOrBatch | undefined> => {
21
+ if (isBatchRequest(payload)) {
22
+ return Promise.all(payload.map((p) => request(p)));
23
+ }
24
+
25
+ return request(payload);
26
+ };
27
+ },
28
+ mutateProvider(provider, newHandler) {
29
+ Object.assign(provider, {
30
+ request: async function newRequest(payload: JsonRpcRequestOrBatch): Promise<JsonRpcResponseOrBatch | undefined> {
31
+ return newHandler(payload);
32
+ },
33
+ });
34
+ },
35
+ } as Web3ProviderType<Web3jsProvider>;
package/src/types.ts ADDED
@@ -0,0 +1,163 @@
1
+ export type JsonRpcId = number | string;
2
+ export type JsonRpcVersion = string & ("2.0" | "1.0");
3
+
4
+ export interface JsonRpcRequestPayload<T = unknown[]> {
5
+ readonly jsonrpc: JsonRpcVersion;
6
+ readonly id: JsonRpcId;
7
+ readonly method: string;
8
+ readonly params: T;
9
+ readonly requestOptions?: unknown;
10
+ }
11
+
12
+ export interface JsonRpcNotificationPayload<T = unknown[]> {
13
+ readonly jsonrpc: JsonRpcVersion;
14
+ readonly method: string;
15
+ readonly params: T;
16
+ readonly requestOptions?: unknown;
17
+ }
18
+
19
+ export type JsonRpcRequest<T = unknown[]> = JsonRpcRequestPayload<T> | JsonRpcNotificationPayload<T>;
20
+ export type JsonRpcBatchRequest<T = unknown[]> = JsonRpcRequest<T>[];
21
+
22
+ // The request can be a single request, a notification
23
+ // or an array of requests and notifications as batch request
24
+ export type JsonRpcRequestOrBatch<T = unknown[]> = JsonRpcRequest<T> | JsonRpcBatchRequest<T>;
25
+
26
+ // Make the response compatible with different libraries, we don't use the readonly modifier
27
+ export interface JsonRpcResponseWithResultPayload<T> {
28
+ readonly id?: JsonRpcId;
29
+ jsonrpc: JsonRpcVersion;
30
+ result: T;
31
+ error?: never;
32
+ }
33
+
34
+ export interface JsonRpcErrorPayload<T> {
35
+ readonly code?: number;
36
+ readonly data?: T;
37
+ readonly message: string;
38
+ }
39
+
40
+ export interface JsonRpcResponseWithErrorPayload<T> {
41
+ readonly id?: JsonRpcId;
42
+ jsonrpc: JsonRpcVersion;
43
+ result?: never;
44
+ error: JsonRpcErrorPayload<T>;
45
+ }
46
+
47
+ // Make the very flexible el response type to match different libraries easily
48
+ // biome-ignore lint/suspicious/noExplicitAny: We need to use `any` type here
49
+ export type JsonRpcResponse<T = any, E = any> =
50
+ | JsonRpcResponseWithResultPayload<T>
51
+ | JsonRpcResponseWithErrorPayload<E>;
52
+
53
+ // biome-ignore lint/suspicious/noExplicitAny: We need to use `any` type here
54
+ export type JsonRpcBatchResponse<T = any, E = any> = JsonRpcResponse<T, E>[];
55
+
56
+ // Response can be a single response or an array of responses in case of batch request
57
+ // Make the very flexible el response type to match different libraries easily
58
+ // biome-ignore lint/suspicious/noExplicitAny: We need to use `any` type here
59
+ export type JsonRpcResponseOrBatch<T = any, E = any> = JsonRpcResponse<T, E> | JsonRpcBatchResponse<T, E>;
60
+
61
+ export type HexString = string;
62
+
63
+ export type ELBlockNumberOrTag = number | string | "latest" | "earliest" | "pending";
64
+
65
+ export interface ELProof {
66
+ readonly address: string;
67
+ readonly balance: string;
68
+ readonly codeHash: string;
69
+ readonly nonce: string;
70
+ readonly storageHash: string;
71
+ readonly accountProof: string[];
72
+ readonly storageProof: {
73
+ readonly key: string;
74
+ readonly value: string;
75
+ readonly proof: string[];
76
+ }[];
77
+ }
78
+
79
+ export interface ELTransaction {
80
+ readonly type: string;
81
+ readonly nonce: string;
82
+ readonly to: string | null;
83
+ readonly chainId?: string;
84
+ readonly input: string;
85
+ readonly value: string;
86
+ readonly gasPrice?: string;
87
+ readonly gas: string;
88
+ readonly maxFeePerGas?: string;
89
+ readonly maxPriorityFeePerGas?: string;
90
+ readonly blockHash: string;
91
+ readonly blockNumber: string;
92
+ readonly from: string;
93
+ readonly hash: string;
94
+ readonly r: string;
95
+ readonly s: string;
96
+ readonly v: string;
97
+ readonly transactionIndex: string;
98
+ readonly accessList?: {address: string; storageKeys: string[]}[];
99
+ readonly data?: string;
100
+ }
101
+
102
+ export interface ELWithdrawal {
103
+ readonly index: string;
104
+ readonly validatorIndex: string;
105
+ readonly address: string;
106
+ readonly amount: string;
107
+ }
108
+
109
+ export interface ELBlock {
110
+ readonly parentHash: string;
111
+ readonly stateRoot: string;
112
+ readonly receiptsRoot: string;
113
+ readonly logsBloom: string;
114
+ readonly nonce: string;
115
+ readonly difficulty: string;
116
+ readonly totalDifficulty: string;
117
+ readonly number: string;
118
+ readonly gasLimit: string;
119
+ readonly gasUsed: string;
120
+ readonly timestamp: string;
121
+ readonly extraData?: Buffer | string;
122
+ readonly mixHash: string;
123
+ readonly hash: string;
124
+ readonly baseFeePerGas: string;
125
+ readonly miner: string;
126
+ readonly sha3Uncles: string;
127
+ readonly size: string;
128
+ readonly uncles: ELBlock[];
129
+ readonly transactions: ELTransaction[];
130
+ readonly transactionsRoot: string;
131
+ readonly withdrawals?: ELWithdrawal[];
132
+ readonly withdrawalsRoot?: string;
133
+ }
134
+
135
+ export interface ELAccessList {
136
+ readonly address: HexString;
137
+ readonly storageKeys: HexString[];
138
+ }
139
+
140
+ export interface ELAccessListResponse {
141
+ readonly error: string;
142
+ readonly gasUsed: HexString;
143
+ readonly accessList: ELAccessList[];
144
+ }
145
+
146
+ export type ELStorageProof = Pick<ELProof, "storageHash" | "storageProof">;
147
+
148
+ export type ELApi = {
149
+ eth_getBalance: (address: string, block?: number | string) => string;
150
+ eth_createAccessList: (transaction: ELTransaction, block?: ELBlockNumberOrTag) => ELAccessListResponse;
151
+ eth_call: (transaction: ELTransaction, block?: ELBlockNumberOrTag) => HexString;
152
+ eth_estimateGas: (transaction: ELTransaction, block?: ELBlockNumberOrTag) => HexString;
153
+ eth_getCode: (address: string, block?: ELBlockNumberOrTag) => HexString;
154
+ eth_getProof: (address: string, storageKeys: string[], block?: ELBlockNumberOrTag) => ELProof;
155
+ eth_getBlockByNumber: (block: ELBlockNumberOrTag, hydrated?: boolean) => ELBlock | undefined;
156
+ eth_getBlockByHash: (block: string, hydrated?: boolean) => ELBlock | undefined;
157
+ };
158
+ export type ELApiParams = {
159
+ [K in keyof ELApi]: Parameters<ELApi[K]>;
160
+ };
161
+ export type ELApiReturn = {
162
+ [K in keyof ELApi]: ReturnType<ELApi[K]>;
163
+ };
@@ -0,0 +1,11 @@
1
+ import {Lightclient} from "@lodestar/light-client";
2
+
3
+ export function assertLightClient(client?: Lightclient): asserts client is Lightclient {
4
+ if (!client) {
5
+ throw new Error("Light client is not initialized yet.");
6
+ }
7
+ }
8
+
9
+ export function isTruthy<T = unknown>(value: T): value is Exclude<T, undefined | null> {
10
+ return value !== undefined && value !== null && value !== false;
11
+ }
@@ -0,0 +1,122 @@
1
+ import {ApiClient} from "@lodestar/api/beacon";
2
+ import {GenesisData, Lightclient} from "@lodestar/light-client";
3
+ import {Bytes32, ExecutionPayload, capella} from "@lodestar/types";
4
+ import {Logger} from "@lodestar/utils";
5
+ import {MAX_PAYLOAD_HISTORY} from "../constants.js";
6
+ import {hexToBuffer} from "./conversion.js";
7
+
8
+ export async function fetchBlock(api: ApiClient, slot: number): Promise<capella.SignedBeaconBlock | undefined> {
9
+ const res = await api.beacon.getBlockV2({blockId: slot});
10
+
11
+ if (res.ok) return res.value() as capella.SignedBeaconBlock;
12
+ return;
13
+ }
14
+
15
+ export async function fetchNearestBlock(
16
+ api: ApiClient,
17
+ slot: number,
18
+ direction: "up" | "down" = "down"
19
+ ): Promise<capella.SignedBeaconBlock> {
20
+ const res = await api.beacon.getBlockV2({blockId: slot});
21
+
22
+ if (res.ok) return res.value() as capella.SignedBeaconBlock;
23
+
24
+ if (!res.ok && res.status === 404) {
25
+ return fetchNearestBlock(api, direction === "down" ? slot - 1 : slot + 1);
26
+ }
27
+
28
+ throw new Error(`Can not fetch nearest block for slot=${slot}`);
29
+ }
30
+
31
+ export async function getUnFinalizedRangeForPayloads(lightClient: Lightclient): Promise<{start: number; end: number}> {
32
+ const headSlot = lightClient.getHead().beacon.slot;
33
+ const finalizeSlot = lightClient.getFinalized().beacon.slot;
34
+ const endSlot = headSlot - MAX_PAYLOAD_HISTORY;
35
+
36
+ return {
37
+ start: headSlot,
38
+ end: endSlot < finalizeSlot ? finalizeSlot : endSlot,
39
+ };
40
+ }
41
+
42
+ export async function getExecutionPayloads({
43
+ api,
44
+ startSlot,
45
+ endSlot,
46
+ logger,
47
+ }: {
48
+ api: ApiClient;
49
+ startSlot: number;
50
+ endSlot: number;
51
+ logger: Logger;
52
+ }): Promise<Map<number, ExecutionPayload>> {
53
+ [startSlot, endSlot] = [Math.min(startSlot, endSlot), Math.max(startSlot, endSlot)];
54
+ if (startSlot === endSlot) {
55
+ logger.debug("Fetching EL payload", {slot: startSlot});
56
+ } else {
57
+ logger.debug("Fetching EL payloads", {startSlot, endSlot});
58
+ }
59
+
60
+ const payloads = new Map<number, ExecutionPayload>();
61
+
62
+ let slot = endSlot;
63
+ let block = await fetchNearestBlock(api, slot);
64
+ payloads.set(block.message.slot, block.message.body.executionPayload);
65
+ slot = block.message.slot - 1;
66
+
67
+ while (slot >= startSlot) {
68
+ const previousBlock = await fetchNearestBlock(api, block.message.slot - 1);
69
+
70
+ if (block.message.body.executionPayload.parentHash === previousBlock.message.body.executionPayload.blockHash) {
71
+ payloads.set(block.message.slot, block.message.body.executionPayload);
72
+ }
73
+
74
+ slot = block.message.slot - 1;
75
+ block = previousBlock;
76
+ }
77
+
78
+ return payloads;
79
+ }
80
+
81
+ export async function getExecutionPayloadForBlockNumber(
82
+ api: ApiClient,
83
+ startSlot: number,
84
+ blockNumber: number
85
+ ): Promise<Map<number, ExecutionPayload>> {
86
+ const payloads = new Map<number, ExecutionPayload>();
87
+
88
+ let block = await fetchNearestBlock(api, startSlot);
89
+ payloads.set(block.message.slot, block.message.body.executionPayload);
90
+
91
+ while (payloads.get(block.message.slot)?.blockNumber !== blockNumber) {
92
+ const previousBlock = await fetchNearestBlock(api, block.message.slot - 1);
93
+ block = previousBlock;
94
+ payloads.set(block.message.slot, block.message.body.executionPayload);
95
+ }
96
+
97
+ return payloads;
98
+ }
99
+
100
+ export async function getGenesisData(api: Pick<ApiClient, "beacon">): Promise<GenesisData> {
101
+ const {genesisTime, genesisValidatorsRoot} = (await api.beacon.getGenesis()).value();
102
+
103
+ return {
104
+ genesisTime,
105
+ genesisValidatorsRoot,
106
+ };
107
+ }
108
+
109
+ export async function getSyncCheckpoint(api: Pick<ApiClient, "beacon">, checkpoint?: string): Promise<Bytes32> {
110
+ let syncCheckpoint: Bytes32 | undefined = checkpoint ? hexToBuffer(checkpoint) : undefined;
111
+
112
+ if (syncCheckpoint && syncCheckpoint.byteLength !== 32) {
113
+ throw Error(`Checkpoint root must be 32 bytes. length=${syncCheckpoint.byteLength}`);
114
+ }
115
+
116
+ if (!syncCheckpoint) {
117
+ const res = await api.beacon.getStateFinalityCheckpoints({stateId: "head"});
118
+ syncCheckpoint = res.value().finalized.root;
119
+ }
120
+
121
+ return syncCheckpoint;
122
+ }
@@ -0,0 +1,107 @@
1
+ import {BlockData, HeaderData} from "@ethereumjs/block";
2
+ import {ELBlock, ELTransaction} from "../types.js";
3
+ import {isTruthy} from "./assertion.js";
4
+
5
+ export function numberToHex(num: number | bigint): string {
6
+ return "0x" + num.toString(16);
7
+ }
8
+
9
+ export function hexToNumber(num: string): number {
10
+ return num.startsWith("0x") ? parseInt(num.slice(2), 16) : parseInt(num, 16);
11
+ }
12
+
13
+ export function hexToBigInt(num: string): bigint {
14
+ return num.startsWith("0x") ? BigInt(num) : BigInt(`0x${num}`);
15
+ }
16
+
17
+ export function bigIntToHex(num: bigint): string {
18
+ return `0x${num.toString(16)}`;
19
+ }
20
+
21
+ export function bufferToHex(buffer: Buffer | Uint8Array): string {
22
+ return "0x" + Buffer.from(buffer).toString("hex");
23
+ }
24
+
25
+ export function hexToBuffer(val: string): Buffer {
26
+ const hexWithEvenLength = val.length % 2 ? `0${val}` : val;
27
+ return Buffer.from(hexWithEvenLength.replace("0x", ""), "hex");
28
+ }
29
+
30
+ export function padLeft<T extends Buffer | Uint8Array>(v: T, length: number): T {
31
+ const buf = Buffer.alloc(length);
32
+ Buffer.from(v).copy(buf, length - v.length);
33
+
34
+ if (Buffer.isBuffer(v)) return buf as T;
35
+
36
+ return Uint8Array.from(buf) as T;
37
+ }
38
+
39
+ export function headerDataFromELBlock(blockInfo: ELBlock): HeaderData {
40
+ return {
41
+ parentHash: blockInfo.parentHash,
42
+ uncleHash: blockInfo.sha3Uncles,
43
+ coinbase: blockInfo.miner,
44
+ stateRoot: blockInfo.stateRoot,
45
+ transactionsTrie: blockInfo.transactionsRoot,
46
+ receiptTrie: blockInfo.receiptsRoot,
47
+ logsBloom: blockInfo.logsBloom,
48
+ difficulty: BigInt(blockInfo.difficulty),
49
+ number: BigInt(blockInfo.number),
50
+ gasLimit: BigInt(blockInfo.gasLimit),
51
+ gasUsed: BigInt(blockInfo.gasUsed),
52
+ timestamp: BigInt(blockInfo.timestamp),
53
+ extraData: blockInfo.extraData,
54
+ mixHash: blockInfo.mixHash, // some reason the types are not up to date :(
55
+ nonce: blockInfo.nonce,
56
+ baseFeePerGas: blockInfo.baseFeePerGas ? BigInt(blockInfo.baseFeePerGas) : undefined,
57
+ withdrawalsRoot: blockInfo.withdrawalsRoot ?? undefined,
58
+ };
59
+ }
60
+
61
+ export function txDataFromELBlock(txInfo: ELTransaction) {
62
+ return {
63
+ ...txInfo,
64
+ data: txInfo.input,
65
+ gasPrice: isTruthy(txInfo.gasPrice) ? BigInt(txInfo.gasPrice) : null,
66
+ gasLimit: txInfo.gas,
67
+ to: isTruthy(txInfo.to) ? padLeft(hexToBuffer(txInfo.to), 20) : undefined,
68
+ value: txInfo.value ? BigInt(txInfo.value) : undefined,
69
+ maxFeePerGas: isTruthy(txInfo.maxFeePerGas) ? BigInt(txInfo.maxFeePerGas) : undefined,
70
+ maxPriorityFeePerGas: isTruthy(txInfo.maxPriorityFeePerGas) ? BigInt(txInfo.maxPriorityFeePerGas) : undefined,
71
+ };
72
+ }
73
+
74
+ export function blockDataFromELBlock(blockInfo: ELBlock): BlockData {
75
+ return {
76
+ header: headerDataFromELBlock(blockInfo),
77
+ transactions: blockInfo.transactions.map(txDataFromELBlock) as BlockData["transactions"],
78
+ };
79
+ }
80
+
81
+ export function cleanObject<T extends Record<string, unknown> | unknown[]>(obj: T): T {
82
+ const isNullify = (v: unknown): boolean => v === undefined || v === null;
83
+
84
+ if (Array.isArray(obj)) return obj.filter((v) => isNullify(v)) as T;
85
+
86
+ if (typeof obj === "object") {
87
+ for (const key of Object.keys(obj)) {
88
+ if (isNullify(obj[key])) {
89
+ delete obj[key];
90
+ } else if (typeof obj[key] === "object") {
91
+ cleanObject(obj[key] as Record<string, unknown>);
92
+ }
93
+ }
94
+ }
95
+
96
+ return obj;
97
+ }
98
+
99
+ /**
100
+ * Convert an array to array of chunks of length N
101
+ * @example
102
+ * chunkIntoN([1,2,3,4,5,6], 2)
103
+ * => [[1,2], [3,4], [5,6]]
104
+ */
105
+ export function chunkIntoN<T extends unknown[]>(arr: T, n: number): T[] {
106
+ return Array.from({length: Math.ceil(arr.length / n)}, (_, i) => arr.slice(i * n, i * n + n)) as T[];
107
+ }
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Expected error that shouldn't print a stack trace
3
+ */
4
+ export class YargsError extends Error {}