@le-space/chains 0.1.0 → 0.3.0
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.
- package/README.md +7 -3
- package/package.json +12 -4
- package/src/aleph.js +454 -0
- package/src/bitcoin.js +1 -1
- package/src/evm-address.js +36 -0
- package/src/evm-contracts.js +27 -0
- package/src/evm.js +6 -33
- package/src/http.js +7 -0
- package/src/index.js +3 -0
- package/src/registry.js +15 -27
- package/test/support/aleph-fetch.js +80 -0
- package/test/support/aleph-sample.js +74 -0
- package/test/support/aleph.js +6 -0
- package/test/support/fake-alchemy.js +749 -0
- package/test/support/fake-blockscout.js +279 -0
|
@@ -0,0 +1,749 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// A fake Alchemy on 127.0.0.1 for tests (Node): JSON-RPC over POST
|
|
3
|
+
// `/<network>/v2/<key>`, single calls and batches, as strict as the real one
|
|
4
|
+
// about what it is asked (method names, the number and types of parameters:
|
|
5
|
+
// a string where a boolean belongs is refused) and answering in its shapes:
|
|
6
|
+
// hex quantities, `uniqueId`s, `rawContract`, errors as
|
|
7
|
+
// `{ code, message }` with HTTP 401 (key), 403 (network not enabled for
|
|
8
|
+
// the app), 429 (compute units per second).
|
|
9
|
+
//
|
|
10
|
+
// It serves a made-up chain (`evmChain`), which `blockscoutView` also turns
|
|
11
|
+
// into the lists a fake Blockscout serves (fake-blockscout.js), so one history
|
|
12
|
+
// can be read through both. Every address, hash and amount is made up.
|
|
13
|
+
import http from 'node:http';
|
|
14
|
+
|
|
15
|
+
import { fakeHash } from './fake-cosmos.js';
|
|
16
|
+
import { EVM, fakeEvmAddress } from './fake-blockscout.js';
|
|
17
|
+
|
|
18
|
+
/** @typedef {{ trace: string, index: string, from: string, to: string, value: bigint }} FakeInternal */
|
|
19
|
+
/** @typedef {{ logIndex: number, contract: string, from: string, to: string, value: bigint, symbol?: string, decimals?: number }} FakeLog */
|
|
20
|
+
/**
|
|
21
|
+
* @typedef {object} FakeTx
|
|
22
|
+
* @property {string} hash
|
|
23
|
+
* @property {number} block
|
|
24
|
+
* @property {number} index position in the block
|
|
25
|
+
* @property {string} from
|
|
26
|
+
* @property {string | null} to
|
|
27
|
+
* @property {bigint} value
|
|
28
|
+
* @property {bigint} gasUsed
|
|
29
|
+
* @property {bigint} gasPrice the effective one
|
|
30
|
+
* @property {boolean} ok
|
|
31
|
+
* @property {boolean} [preByzantium] its receipt carries no `status`
|
|
32
|
+
* @property {FakeInternal[]} internal Alchemy's trace address and Blockscout's index of each
|
|
33
|
+
* @property {FakeLog[]} logs ERC-20 Transfer events
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
/** The networks the fake knows, with the chain id each answers. */
|
|
37
|
+
export const NETWORKS = /** @type {const} */ ({
|
|
38
|
+
'eth-mainnet': { chainId: 1, internal: true },
|
|
39
|
+
'base-mainnet': { chainId: 8453, internal: true },
|
|
40
|
+
'arb-mainnet': { chainId: 42161, internal: false },
|
|
41
|
+
'opt-mainnet': { chainId: 10, internal: false },
|
|
42
|
+
'polygon-mainnet': { chainId: 137, internal: true }
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
/** A key of the right form, made up. */
|
|
46
|
+
export const FAKE_ALCHEMY_KEY = 'fakeAlchemyKey_0123456789abcdef';
|
|
47
|
+
|
|
48
|
+
export const blockTime = (/** @type {number} */ block) =>
|
|
49
|
+
Math.floor(Date.parse('2026-09-01T00:00:00Z') / 1000) + (block - 100) * 12;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* @param {Partial<FakeTx> & { seed: string, block: number, from: string }} t
|
|
53
|
+
* @returns {FakeTx}
|
|
54
|
+
*/
|
|
55
|
+
export function fakeTx({ seed, ...t }) {
|
|
56
|
+
return {
|
|
57
|
+
hash: fakeHash(seed, true),
|
|
58
|
+
index: 0,
|
|
59
|
+
to: null,
|
|
60
|
+
value: 0n,
|
|
61
|
+
gasUsed: 21000n,
|
|
62
|
+
gasPrice: 1_000_000_000n,
|
|
63
|
+
ok: true,
|
|
64
|
+
internal: [],
|
|
65
|
+
logs: [],
|
|
66
|
+
...t
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* A made-up history of EVM.wallet: ETH and USDC in and out, a failed send,
|
|
72
|
+
* an approval (gas, nothing moved), ETH from a contract (two internal
|
|
73
|
+
* transfers in one transaction), a token that calls itself USDC, a USDC
|
|
74
|
+
* transfer out of the wallet in someone else's transaction (transferFrom),
|
|
75
|
+
* two identical USDC transfers in one transaction, and a claim the wallet
|
|
76
|
+
* sent that only brought something in.
|
|
77
|
+
*
|
|
78
|
+
* @param {{ fillerTransfers?: number }} [options] this many more incoming USDC transfers
|
|
79
|
+
* @returns {FakeTx[]}
|
|
80
|
+
*/
|
|
81
|
+
export function evmChain({ fillerTransfers = 0 } = {}) {
|
|
82
|
+
const w = EVM.wallet;
|
|
83
|
+
const spender = fakeEvmAddress('a spender contract');
|
|
84
|
+
/** @type {FakeTx[]} */
|
|
85
|
+
const txs = [
|
|
86
|
+
fakeTx({ seed: 'a-eth-in', block: 100, from: EVM.friend, to: w, value: 500000000000000000n }),
|
|
87
|
+
fakeTx({
|
|
88
|
+
seed: 'a-usdc-in',
|
|
89
|
+
block: 150,
|
|
90
|
+
index: 2,
|
|
91
|
+
from: EVM.friend,
|
|
92
|
+
to: EVM.usdc,
|
|
93
|
+
logs: [{ logIndex: 7, contract: EVM.usdc, from: EVM.friend, to: w, value: 750000000n }]
|
|
94
|
+
}),
|
|
95
|
+
fakeTx({
|
|
96
|
+
seed: 'a-usdc-out',
|
|
97
|
+
block: 200,
|
|
98
|
+
from: w,
|
|
99
|
+
to: EVM.usdc,
|
|
100
|
+
gasUsed: 50000n,
|
|
101
|
+
gasPrice: 2_000_000_000n,
|
|
102
|
+
logs: [{ logIndex: 3, contract: EVM.usdc, from: w, to: EVM.exchange, value: 300000000n }]
|
|
103
|
+
}),
|
|
104
|
+
fakeTx({
|
|
105
|
+
seed: 'a-approve',
|
|
106
|
+
block: 220,
|
|
107
|
+
from: w,
|
|
108
|
+
to: EVM.usdc,
|
|
109
|
+
gasUsed: 46000n
|
|
110
|
+
}),
|
|
111
|
+
fakeTx({
|
|
112
|
+
seed: 'a-spam',
|
|
113
|
+
block: 250,
|
|
114
|
+
from: EVM.friend,
|
|
115
|
+
to: EVM.spamToken,
|
|
116
|
+
logs: [
|
|
117
|
+
{ logIndex: 0, contract: EVM.spamToken, from: EVM.friend, to: w, value: 1000000000000n }
|
|
118
|
+
]
|
|
119
|
+
}),
|
|
120
|
+
fakeTx({
|
|
121
|
+
seed: 'a-failed',
|
|
122
|
+
block: 300,
|
|
123
|
+
from: w,
|
|
124
|
+
to: EVM.friend,
|
|
125
|
+
value: 100000000000000000n,
|
|
126
|
+
gasPrice: 3_000_000_000n,
|
|
127
|
+
ok: false
|
|
128
|
+
}),
|
|
129
|
+
fakeTx({
|
|
130
|
+
seed: 'a-pulled',
|
|
131
|
+
block: 350,
|
|
132
|
+
from: spender,
|
|
133
|
+
to: EVM.usdc,
|
|
134
|
+
logs: [{ logIndex: 1, contract: EVM.usdc, from: w, to: spender, value: 5000000n }]
|
|
135
|
+
}),
|
|
136
|
+
fakeTx({
|
|
137
|
+
seed: 'a-eth-out',
|
|
138
|
+
block: 400,
|
|
139
|
+
index: 1,
|
|
140
|
+
from: w,
|
|
141
|
+
to: EVM.friend,
|
|
142
|
+
value: 100000000000000000n
|
|
143
|
+
}),
|
|
144
|
+
fakeTx({
|
|
145
|
+
seed: 'a-contract-pays',
|
|
146
|
+
block: 500,
|
|
147
|
+
from: EVM.friend,
|
|
148
|
+
to: EVM.contract,
|
|
149
|
+
internal: [
|
|
150
|
+
{ trace: '3_0', index: '1', from: EVM.contract, to: w, value: 20000000000000000n },
|
|
151
|
+
{ trace: '0_3_0', index: '3', from: EVM.contract, to: w, value: 5000000000000000n }
|
|
152
|
+
]
|
|
153
|
+
}),
|
|
154
|
+
fakeTx({
|
|
155
|
+
seed: 'a-twice',
|
|
156
|
+
block: 600,
|
|
157
|
+
from: EVM.friend,
|
|
158
|
+
to: EVM.usdc,
|
|
159
|
+
logs: [
|
|
160
|
+
{ logIndex: 4, contract: EVM.usdc, from: EVM.friend, to: w, value: 1000000n },
|
|
161
|
+
{ logIndex: 9, contract: EVM.usdc, from: EVM.friend, to: w, value: 1000000n }
|
|
162
|
+
]
|
|
163
|
+
}),
|
|
164
|
+
fakeTx({
|
|
165
|
+
seed: 'a-claim',
|
|
166
|
+
block: 700,
|
|
167
|
+
from: w,
|
|
168
|
+
to: EVM.contract,
|
|
169
|
+
gasUsed: 80000n,
|
|
170
|
+
logs: [{ logIndex: 2, contract: EVM.usdc, from: EVM.contract, to: w, value: 2000000n }]
|
|
171
|
+
})
|
|
172
|
+
];
|
|
173
|
+
for (let i = 0; i < fillerTransfers; i++) {
|
|
174
|
+
txs.push(
|
|
175
|
+
fakeTx({
|
|
176
|
+
seed: `a-filler-${i}`,
|
|
177
|
+
block: 1000 + Math.floor(i / 3),
|
|
178
|
+
index: i % 3,
|
|
179
|
+
from: EVM.friend,
|
|
180
|
+
to: EVM.usdc,
|
|
181
|
+
logs: [{ logIndex: 0, contract: EVM.usdc, from: EVM.friend, to: w, value: 1n }]
|
|
182
|
+
})
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
return txs;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* The same chain as Blockscout's lists (for startFakeBlockscout): txlist,
|
|
190
|
+
* txlistinternal (its index), tokentx (without a log index, as Blockscout).
|
|
191
|
+
*
|
|
192
|
+
* @param {FakeTx[]} txs
|
|
193
|
+
*/
|
|
194
|
+
export function blockscoutView(txs) {
|
|
195
|
+
const time = (/** @type {number} */ b) => String(blockTime(b));
|
|
196
|
+
return {
|
|
197
|
+
normal: txs.map((t) => ({
|
|
198
|
+
blockNumber: String(t.block),
|
|
199
|
+
timeStamp: time(t.block),
|
|
200
|
+
hash: t.hash,
|
|
201
|
+
transactionIndex: String(t.index),
|
|
202
|
+
from: t.from,
|
|
203
|
+
to: t.to ?? '',
|
|
204
|
+
value: String(t.value),
|
|
205
|
+
gas: '100000',
|
|
206
|
+
gasUsed: String(t.gasUsed),
|
|
207
|
+
gasPrice: String(t.gasPrice),
|
|
208
|
+
isError: t.ok ? '0' : '1',
|
|
209
|
+
txreceipt_status: t.ok ? '1' : '0'
|
|
210
|
+
})),
|
|
211
|
+
internal: txs
|
|
212
|
+
.filter((t) => t.ok)
|
|
213
|
+
.flatMap((t) =>
|
|
214
|
+
t.internal.map((i) => ({
|
|
215
|
+
blockNumber: String(t.block),
|
|
216
|
+
timeStamp: time(t.block),
|
|
217
|
+
transactionHash: t.hash,
|
|
218
|
+
index: i.index,
|
|
219
|
+
from: i.from,
|
|
220
|
+
to: i.to,
|
|
221
|
+
value: String(i.value),
|
|
222
|
+
isError: '0',
|
|
223
|
+
type: 'call'
|
|
224
|
+
}))
|
|
225
|
+
),
|
|
226
|
+
tokens: txs
|
|
227
|
+
.filter((t) => t.ok)
|
|
228
|
+
.flatMap((t) =>
|
|
229
|
+
t.logs.map((l) => ({
|
|
230
|
+
blockNumber: String(t.block),
|
|
231
|
+
timeStamp: time(t.block),
|
|
232
|
+
hash: t.hash,
|
|
233
|
+
transactionIndex: String(t.index),
|
|
234
|
+
from: l.from,
|
|
235
|
+
to: l.to,
|
|
236
|
+
value: String(l.value),
|
|
237
|
+
contractAddress: l.contract,
|
|
238
|
+
tokenSymbol: 'USDC',
|
|
239
|
+
tokenDecimal: '6'
|
|
240
|
+
}))
|
|
241
|
+
)
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const hex = (/** @type {bigint | number} */ n) => `0x${n.toString(16)}`;
|
|
246
|
+
const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
|
|
247
|
+
const HASH = /^0x[0-9a-fA-F]{64}$/;
|
|
248
|
+
const QUANTITY = /^0x(0|[1-9a-fA-F][0-9a-fA-F]*)$/;
|
|
249
|
+
const TRANSFER_KEYS = new Set([
|
|
250
|
+
'fromBlock',
|
|
251
|
+
'toBlock',
|
|
252
|
+
'fromAddress',
|
|
253
|
+
'toAddress',
|
|
254
|
+
'contractAddresses',
|
|
255
|
+
'category',
|
|
256
|
+
'order',
|
|
257
|
+
'withMetadata',
|
|
258
|
+
'excludeZeroValue',
|
|
259
|
+
'maxCount',
|
|
260
|
+
'pageKey'
|
|
261
|
+
]);
|
|
262
|
+
const CATEGORIES = new Set(['external', 'internal', 'erc20', 'erc721', 'erc1155', 'specialnft']);
|
|
263
|
+
|
|
264
|
+
class RpcError extends Error {
|
|
265
|
+
/** @param {number} code @param {string} message */
|
|
266
|
+
constructor(code, message) {
|
|
267
|
+
super(message);
|
|
268
|
+
this.code = code;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
const invalid = (/** @type {string} */ nth, /** @type {string} */ why) =>
|
|
272
|
+
new RpcError(-32602, `invalid ${nth} argument: ${why}`);
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* @param {object} [options]
|
|
276
|
+
* @param {FakeTx[]} [options.txs]
|
|
277
|
+
* @param {string} [options.key] the only key it accepts
|
|
278
|
+
* @param {Record<string, bigint>} [options.balances] `native` and contract (lower case) → units, of EVM.wallet
|
|
279
|
+
* @param {string[]} [options.deniedNetworks] answer 403, as for a network not enabled for the app
|
|
280
|
+
* @param {number} [options.rateLimitedRequests] this many HTTP requests answer 429 first
|
|
281
|
+
* @param {number} [options.rateLimitedItems] this many batch items answer error 429 (in a 200) first
|
|
282
|
+
* @param {number} [options.computeUnitsPerSecond] Alchemy's budget: a token bucket of ten
|
|
283
|
+
* seconds, each call charged its compute units (a batch: each call), a call over it
|
|
284
|
+
* answering error 429; 0 is no budget
|
|
285
|
+
* @param {() => number} [options.now] milliseconds, for the budget
|
|
286
|
+
* @param {Record<string, number>} [options.chainIds] a network answering another chain id
|
|
287
|
+
* @param {boolean} [options.listFailedExternal] list the value of a reverted transaction as a
|
|
288
|
+
* transfer (not seen at Alchemy, but not ruled out either)
|
|
289
|
+
*/
|
|
290
|
+
export async function startFakeAlchemy({
|
|
291
|
+
txs = evmChain(),
|
|
292
|
+
key = FAKE_ALCHEMY_KEY,
|
|
293
|
+
balances = { native: 310000000000000000n, [EVM.usdc]: 450000000n },
|
|
294
|
+
deniedNetworks = [],
|
|
295
|
+
rateLimitedRequests = 0,
|
|
296
|
+
rateLimitedItems = 0,
|
|
297
|
+
listFailedExternal = false,
|
|
298
|
+
computeUnitsPerSecond = 0,
|
|
299
|
+
now = Date.now,
|
|
300
|
+
chainIds = {}
|
|
301
|
+
} = {}) {
|
|
302
|
+
// Alchemy's own table (docs: reference/compute-unit-costs), kept apart from the reader's.
|
|
303
|
+
const unitsOf = (/** @type {string} */ method) =>
|
|
304
|
+
({ eth_chainId: 0, eth_blockNumber: 10, alchemy_getAssetTransfers: 120 })[method] ?? 20;
|
|
305
|
+
let bucket = computeUnitsPerSecond * 10;
|
|
306
|
+
let filledAt = now();
|
|
307
|
+
/** Whether the budget covers a call; charges it when it does. */
|
|
308
|
+
const affords = (/** @type {string} */ method) => {
|
|
309
|
+
if (!computeUnitsPerSecond) return true;
|
|
310
|
+
const t = now();
|
|
311
|
+
bucket = Math.min(
|
|
312
|
+
computeUnitsPerSecond * 10,
|
|
313
|
+
bucket + ((t - filledAt) / 1000) * computeUnitsPerSecond
|
|
314
|
+
);
|
|
315
|
+
filledAt = t;
|
|
316
|
+
if (bucket < unitsOf(method)) return false;
|
|
317
|
+
bucket -= unitsOf(method);
|
|
318
|
+
return true;
|
|
319
|
+
};
|
|
320
|
+
/** the most compute units spent in any one second, for the tests */
|
|
321
|
+
const spent = {
|
|
322
|
+
peakSecond: 0,
|
|
323
|
+
refused: 0,
|
|
324
|
+
perSecond: /** @type {Map<number, number>} */ (new Map())
|
|
325
|
+
};
|
|
326
|
+
/** @type {{ network: string, method: string, params: any, url: string }[]} */
|
|
327
|
+
const calls = [];
|
|
328
|
+
/** @type {string[]} every request path, to look for the key */
|
|
329
|
+
const paths = [];
|
|
330
|
+
let limitedRequests = rateLimitedRequests;
|
|
331
|
+
let limitedItems = rateLimitedItems;
|
|
332
|
+
/** @type {Map<string, { filter: any, offset: number }>} */
|
|
333
|
+
const pages = new Map();
|
|
334
|
+
let pageSeq = 0;
|
|
335
|
+
const head = Math.max(...txs.map((t) => t.block), 100) + 10;
|
|
336
|
+
const byHash = new Map(txs.map((t) => [t.hash, t]));
|
|
337
|
+
const sorted = [...txs].sort((a, b) => a.block - b.block || a.index - b.index);
|
|
338
|
+
/** @param {FakeTx} t @param {string} from */
|
|
339
|
+
const nonceOf = (t, from) => sorted.filter((s) => s.from === from).indexOf(t);
|
|
340
|
+
|
|
341
|
+
/** @param {unknown} tag @param {string} nth */
|
|
342
|
+
function blockOf(tag, nth) {
|
|
343
|
+
if (tag === 'latest') return head;
|
|
344
|
+
if (typeof tag !== 'string' || !QUANTITY.test(tag)) throw invalid(nth, 'invalid block tag');
|
|
345
|
+
return Number(BigInt(tag));
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** @param {FakeTx} t */
|
|
349
|
+
const txObject = (t) => ({
|
|
350
|
+
hash: t.hash,
|
|
351
|
+
blockNumber: hex(t.block),
|
|
352
|
+
blockHash: fakeHash(`block ${t.block}`, true),
|
|
353
|
+
transactionIndex: hex(t.index),
|
|
354
|
+
from: t.from,
|
|
355
|
+
to: t.to,
|
|
356
|
+
value: hex(t.value),
|
|
357
|
+
nonce: hex(nonceOf(t, t.from)),
|
|
358
|
+
gas: hex(100000),
|
|
359
|
+
gasPrice: hex(t.gasPrice),
|
|
360
|
+
input: '0x',
|
|
361
|
+
type: '0x2'
|
|
362
|
+
});
|
|
363
|
+
/** @param {FakeTx} t */
|
|
364
|
+
const receiptObject = (t) => ({
|
|
365
|
+
transactionHash: t.hash,
|
|
366
|
+
blockNumber: hex(t.block),
|
|
367
|
+
transactionIndex: hex(t.index),
|
|
368
|
+
from: t.from,
|
|
369
|
+
to: t.to,
|
|
370
|
+
...(t.preByzantium
|
|
371
|
+
? { root: fakeHash(`root ${t.hash}`, true) }
|
|
372
|
+
: { status: t.ok ? '0x1' : '0x0' }),
|
|
373
|
+
gasUsed: hex(t.gasUsed),
|
|
374
|
+
cumulativeGasUsed: hex(t.gasUsed),
|
|
375
|
+
effectiveGasPrice: hex(t.gasPrice),
|
|
376
|
+
logs: [],
|
|
377
|
+
type: '0x2'
|
|
378
|
+
});
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* Every transfer on the chain, in Alchemy's shape, oldest first.
|
|
382
|
+
* @param {string} network
|
|
383
|
+
*/
|
|
384
|
+
function transfersOf(network) {
|
|
385
|
+
const iso = (/** @type {number} */ b) => new Date(blockTime(b) * 1000).toISOString();
|
|
386
|
+
/** @type {any[]} */
|
|
387
|
+
const out = [];
|
|
388
|
+
for (const t of sorted) {
|
|
389
|
+
// A reverted transaction moved nothing – at most its value is listed anyway.
|
|
390
|
+
if (!t.ok && !(listFailedExternal && t.value > 0n)) continue;
|
|
391
|
+
const common = {
|
|
392
|
+
blockNum: hex(t.block),
|
|
393
|
+
hash: t.hash,
|
|
394
|
+
erc721TokenId: null,
|
|
395
|
+
erc1155Metadata: null,
|
|
396
|
+
tokenId: null,
|
|
397
|
+
metadata: { blockTimestamp: iso(t.block) }
|
|
398
|
+
};
|
|
399
|
+
{
|
|
400
|
+
out.push({
|
|
401
|
+
...common,
|
|
402
|
+
uniqueId: `${t.hash}:external`,
|
|
403
|
+
from: t.from,
|
|
404
|
+
to: t.to,
|
|
405
|
+
value: Number(t.value) / 1e18,
|
|
406
|
+
asset: 'ETH',
|
|
407
|
+
category: 'external',
|
|
408
|
+
rawContract: { value: hex(t.value), address: null, decimal: '0x12' }
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
if (!t.ok) continue;
|
|
412
|
+
if (NETWORKS[/** @type {keyof typeof NETWORKS} */ (network)].internal) {
|
|
413
|
+
for (const i of t.internal) {
|
|
414
|
+
out.push({
|
|
415
|
+
...common,
|
|
416
|
+
uniqueId: `${t.hash}:internal:${i.trace}`,
|
|
417
|
+
from: i.from,
|
|
418
|
+
to: i.to,
|
|
419
|
+
value: Number(i.value) / 1e18,
|
|
420
|
+
asset: 'ETH',
|
|
421
|
+
category: 'internal',
|
|
422
|
+
rawContract: { value: hex(i.value), address: null, decimal: '0x12' }
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
for (const l of t.logs) {
|
|
427
|
+
out.push({
|
|
428
|
+
...common,
|
|
429
|
+
uniqueId: `${t.hash}:log:${l.logIndex}`,
|
|
430
|
+
from: l.from,
|
|
431
|
+
to: l.to,
|
|
432
|
+
value: Number(l.value) / 10 ** (l.decimals ?? 6),
|
|
433
|
+
// What the token says about itself: the spam token, too, calls itself USDC.
|
|
434
|
+
asset: l.symbol ?? 'USDC',
|
|
435
|
+
category: 'erc20',
|
|
436
|
+
rawContract: {
|
|
437
|
+
value: hex(l.value),
|
|
438
|
+
address: l.contract,
|
|
439
|
+
decimal: `0x${(l.decimals ?? 6).toString(16)}`
|
|
440
|
+
}
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
return out;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** @param {string} network @param {any[]} params */
|
|
448
|
+
function assetTransfers(network, params) {
|
|
449
|
+
if (!Array.isArray(params) || params.length !== 1) {
|
|
450
|
+
throw new RpcError(-32602, 'expected 1 argument');
|
|
451
|
+
}
|
|
452
|
+
const p = params[0];
|
|
453
|
+
if (!p || typeof p !== 'object' || Array.isArray(p)) throw invalid('1st', 'not an object');
|
|
454
|
+
for (const k of Object.keys(p)) {
|
|
455
|
+
if (!TRANSFER_KEYS.has(k)) throw invalid('1st', `unknown field ${k}`);
|
|
456
|
+
}
|
|
457
|
+
if (!Array.isArray(p.category) || !p.category.length) {
|
|
458
|
+
throw invalid('1st', 'category is required');
|
|
459
|
+
}
|
|
460
|
+
for (const c of p.category) {
|
|
461
|
+
if (typeof c !== 'string' || !CATEGORIES.has(c)) throw invalid('1st', `bad category ${c}`);
|
|
462
|
+
}
|
|
463
|
+
if (
|
|
464
|
+
p.category.includes('internal') &&
|
|
465
|
+
!NETWORKS[/** @type {keyof typeof NETWORKS} */ (network)].internal
|
|
466
|
+
) {
|
|
467
|
+
throw new RpcError(
|
|
468
|
+
-32602,
|
|
469
|
+
'internal category is only supported for ETH, MATIC and BASE mainnets'
|
|
470
|
+
);
|
|
471
|
+
}
|
|
472
|
+
for (const k of ['withMetadata', 'excludeZeroValue']) {
|
|
473
|
+
if (k in p && typeof p[k] !== 'boolean') throw invalid('1st', `${k} must be a boolean`);
|
|
474
|
+
}
|
|
475
|
+
for (const k of ['fromAddress', 'toAddress']) {
|
|
476
|
+
if (k in p && (typeof p[k] !== 'string' || !ADDRESS.test(p[k]))) {
|
|
477
|
+
throw invalid('1st', `${k} is not an address`);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
for (const k of ['fromBlock', 'toBlock']) {
|
|
481
|
+
if (k in p) blockOf(p[k], '1st');
|
|
482
|
+
}
|
|
483
|
+
if ('maxCount' in p) {
|
|
484
|
+
if (typeof p.maxCount !== 'string' || !QUANTITY.test(p.maxCount)) {
|
|
485
|
+
throw invalid('1st', 'maxCount must be a hex string');
|
|
486
|
+
}
|
|
487
|
+
if (BigInt(p.maxCount) > 1000n) throw invalid('1st', 'maxCount must be at most 0x3e8');
|
|
488
|
+
}
|
|
489
|
+
if ('order' in p && p.order !== 'asc' && p.order !== 'desc') {
|
|
490
|
+
throw invalid('1st', 'order must be asc or desc');
|
|
491
|
+
}
|
|
492
|
+
if ('pageKey' in p && typeof p.pageKey !== 'string') {
|
|
493
|
+
throw invalid('1st', 'pageKey must be a string');
|
|
494
|
+
}
|
|
495
|
+
const max = Number(BigInt(p.maxCount ?? '0x3e8'));
|
|
496
|
+
let offset = 0;
|
|
497
|
+
if (p.pageKey) {
|
|
498
|
+
const page = pages.get(p.pageKey);
|
|
499
|
+
if (!page) throw new RpcError(-32602, 'invalid pageKey');
|
|
500
|
+
offset = page.offset;
|
|
501
|
+
}
|
|
502
|
+
const from = String(p.fromAddress ?? '').toLowerCase();
|
|
503
|
+
const to = String(p.toAddress ?? '').toLowerCase();
|
|
504
|
+
const fromBlock = blockOf(p.fromBlock ?? '0x0', '1st');
|
|
505
|
+
const toBlock = blockOf(p.toBlock ?? 'latest', '1st');
|
|
506
|
+
const excludeZero = p.excludeZeroValue ?? true;
|
|
507
|
+
let list = transfersOf(network).filter(
|
|
508
|
+
(t) =>
|
|
509
|
+
p.category.includes(t.category) &&
|
|
510
|
+
(!from || t.from === from) &&
|
|
511
|
+
(!to || t.to === to) &&
|
|
512
|
+
Number(BigInt(t.blockNum)) >= fromBlock &&
|
|
513
|
+
Number(BigInt(t.blockNum)) <= toBlock &&
|
|
514
|
+
!(excludeZero && BigInt(t.rawContract.value) === 0n)
|
|
515
|
+
);
|
|
516
|
+
if (p.order === 'desc') list = list.reverse();
|
|
517
|
+
const slice = list.slice(offset, offset + max).map((t) => {
|
|
518
|
+
if (p.withMetadata) return t;
|
|
519
|
+
const { metadata: _m, ...rest } = t;
|
|
520
|
+
return rest;
|
|
521
|
+
});
|
|
522
|
+
/** @type {any} */
|
|
523
|
+
const result = { transfers: slice };
|
|
524
|
+
if (offset + max < list.length) {
|
|
525
|
+
const pageKey = `fake-page-${++pageSeq}`;
|
|
526
|
+
pages.set(pageKey, { filter: p, offset: offset + max });
|
|
527
|
+
result.pageKey = pageKey;
|
|
528
|
+
}
|
|
529
|
+
return result;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
/** @param {string} network @param {string} method @param {any} params */
|
|
533
|
+
function answer(network, method, params) {
|
|
534
|
+
if (!Array.isArray(params)) throw new RpcError(-32602, 'params must be an array');
|
|
535
|
+
const exact = (/** @type {number} */ n) => {
|
|
536
|
+
if (params.length !== n) throw new RpcError(-32602, `expected ${n} argument(s)`);
|
|
537
|
+
};
|
|
538
|
+
switch (method) {
|
|
539
|
+
case 'eth_chainId':
|
|
540
|
+
exact(0);
|
|
541
|
+
return hex(
|
|
542
|
+
chainIds[network] ?? NETWORKS[/** @type {keyof typeof NETWORKS} */ (network)].chainId
|
|
543
|
+
);
|
|
544
|
+
case 'eth_blockNumber':
|
|
545
|
+
exact(0);
|
|
546
|
+
return hex(head);
|
|
547
|
+
case 'eth_getBalance': {
|
|
548
|
+
exact(2);
|
|
549
|
+
if (typeof params[0] !== 'string' || !ADDRESS.test(params[0]))
|
|
550
|
+
throw invalid('1st', 'not an address');
|
|
551
|
+
blockOf(params[1], '2nd');
|
|
552
|
+
return hex(params[0].toLowerCase() === EVM.wallet ? (balances.native ?? 0n) : 0n);
|
|
553
|
+
}
|
|
554
|
+
case 'eth_getTransactionCount': {
|
|
555
|
+
exact(2);
|
|
556
|
+
if (typeof params[0] !== 'string' || !ADDRESS.test(params[0]))
|
|
557
|
+
throw invalid('1st', 'not an address');
|
|
558
|
+
const at = blockOf(params[1], '2nd');
|
|
559
|
+
const who = params[0].toLowerCase();
|
|
560
|
+
return hex(txs.filter((t) => t.from === who && t.block <= at).length);
|
|
561
|
+
}
|
|
562
|
+
case 'eth_getTransactionByHash':
|
|
563
|
+
case 'eth_getTransactionReceipt': {
|
|
564
|
+
exact(1);
|
|
565
|
+
if (typeof params[0] !== 'string' || !HASH.test(params[0]))
|
|
566
|
+
throw invalid('1st', 'not a hash');
|
|
567
|
+
const t = byHash.get(params[0].toLowerCase());
|
|
568
|
+
if (!t) return null;
|
|
569
|
+
return method === 'eth_getTransactionByHash' ? txObject(t) : receiptObject(t);
|
|
570
|
+
}
|
|
571
|
+
case 'eth_getBlockByNumber': {
|
|
572
|
+
exact(2);
|
|
573
|
+
const at = blockOf(params[0], '1st');
|
|
574
|
+
if (typeof params[1] !== 'boolean') throw invalid('2nd', 'must be a boolean');
|
|
575
|
+
if (at > head) return null;
|
|
576
|
+
const inBlock = sorted.filter((t) => t.block === at);
|
|
577
|
+
return {
|
|
578
|
+
number: hex(at),
|
|
579
|
+
hash: fakeHash(`block ${at}`, true),
|
|
580
|
+
timestamp: hex(blockTime(at)),
|
|
581
|
+
transactions: params[1] ? inBlock.map(txObject) : inBlock.map((t) => t.hash)
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
case 'alchemy_getTokenBalances': {
|
|
585
|
+
if (params.length < 1 || params.length > 3)
|
|
586
|
+
throw new RpcError(-32602, 'expected 1 to 3 arguments');
|
|
587
|
+
if (typeof params[0] !== 'string' || !ADDRESS.test(params[0]))
|
|
588
|
+
throw invalid('1st', 'not an address');
|
|
589
|
+
const spec = params[1] ?? 'erc20';
|
|
590
|
+
if (!Array.isArray(spec) && !['erc20', 'NATIVE_TOKEN', 'DEFAULT_TOKENS'].includes(spec)) {
|
|
591
|
+
throw invalid('2nd', 'token spec');
|
|
592
|
+
}
|
|
593
|
+
if (Array.isArray(spec) && spec.some((c) => typeof c !== 'string' || !ADDRESS.test(c))) {
|
|
594
|
+
throw invalid('2nd', 'not an address');
|
|
595
|
+
}
|
|
596
|
+
const mine = params[0].toLowerCase() === EVM.wallet;
|
|
597
|
+
const contracts = Array.isArray(spec)
|
|
598
|
+
? spec
|
|
599
|
+
: Object.keys(balances).filter((k) => k !== 'native');
|
|
600
|
+
return {
|
|
601
|
+
address: params[0].toLowerCase(),
|
|
602
|
+
tokenBalances: contracts.map((c) => ({
|
|
603
|
+
contractAddress: c.toLowerCase(),
|
|
604
|
+
tokenBalance: `0x${(mine ? (balances[c.toLowerCase()] ?? 0n) : 0n).toString(16).padStart(64, '0')}`
|
|
605
|
+
}))
|
|
606
|
+
};
|
|
607
|
+
}
|
|
608
|
+
case 'alchemy_getAssetTransfers':
|
|
609
|
+
return assetTransfers(network, params);
|
|
610
|
+
default:
|
|
611
|
+
throw new RpcError(-32601, `Unsupported method: ${method}.`);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
const server = http.createServer((req, res) => {
|
|
616
|
+
let raw = '';
|
|
617
|
+
req.on('data', (c) => (raw += c));
|
|
618
|
+
req.on('end', () => {
|
|
619
|
+
const send = (/** @type {number} */ status, /** @type {unknown} */ body) => {
|
|
620
|
+
res.writeHead(status, { 'Content-Type': 'application/json' });
|
|
621
|
+
res.end(body === undefined ? '' : JSON.stringify(body));
|
|
622
|
+
};
|
|
623
|
+
paths.push(req.url ?? '');
|
|
624
|
+
const m = /^\/([a-z-]+)\/v2\/([^/?#]*)$/.exec(req.url ?? '');
|
|
625
|
+
if (!m || !(m[1] in NETWORKS)) return send(404, { message: 'Not found' });
|
|
626
|
+
const [, network, given] = m;
|
|
627
|
+
if (req.method !== 'POST') return send(405, { message: 'Method not allowed' });
|
|
628
|
+
if (!String(req.headers['content-type'] ?? '').startsWith('application/json')) {
|
|
629
|
+
return send(415, { message: 'Unsupported media type' });
|
|
630
|
+
}
|
|
631
|
+
let body;
|
|
632
|
+
try {
|
|
633
|
+
body = JSON.parse(raw);
|
|
634
|
+
} catch {
|
|
635
|
+
return send(400, {
|
|
636
|
+
jsonrpc: '2.0',
|
|
637
|
+
id: null,
|
|
638
|
+
error: { code: -32700, message: 'Parse error' }
|
|
639
|
+
});
|
|
640
|
+
}
|
|
641
|
+
const id = Array.isArray(body) ? null : (body?.id ?? null);
|
|
642
|
+
if (given !== key) {
|
|
643
|
+
return send(401, {
|
|
644
|
+
jsonrpc: '2.0',
|
|
645
|
+
id,
|
|
646
|
+
error: { code: -32600, message: 'Must be authenticated!' }
|
|
647
|
+
});
|
|
648
|
+
}
|
|
649
|
+
if (deniedNetworks.includes(network)) {
|
|
650
|
+
return send(403, {
|
|
651
|
+
jsonrpc: '2.0',
|
|
652
|
+
id,
|
|
653
|
+
error: {
|
|
654
|
+
code: -32600,
|
|
655
|
+
message: `${network.toUpperCase()} is not enabled for this app. Visit this page to enable the network: https://dashboard.alchemy.com/apps/fakeapp/networks`
|
|
656
|
+
}
|
|
657
|
+
});
|
|
658
|
+
}
|
|
659
|
+
if (limitedRequests > 0) {
|
|
660
|
+
limitedRequests--;
|
|
661
|
+
return send(429, {
|
|
662
|
+
jsonrpc: '2.0',
|
|
663
|
+
id,
|
|
664
|
+
error: {
|
|
665
|
+
code: 429,
|
|
666
|
+
message: 'Your app has exceeded its compute units per second capacity.'
|
|
667
|
+
}
|
|
668
|
+
});
|
|
669
|
+
}
|
|
670
|
+
const one = (/** @type {any} */ item) => {
|
|
671
|
+
const itemId = item?.id ?? null;
|
|
672
|
+
if (
|
|
673
|
+
!item ||
|
|
674
|
+
item.jsonrpc !== '2.0' ||
|
|
675
|
+
typeof item.method !== 'string' ||
|
|
676
|
+
!(typeof itemId === 'number' || typeof itemId === 'string')
|
|
677
|
+
) {
|
|
678
|
+
return {
|
|
679
|
+
jsonrpc: '2.0',
|
|
680
|
+
id: itemId,
|
|
681
|
+
error: { code: -32600, message: 'Invalid request' }
|
|
682
|
+
};
|
|
683
|
+
}
|
|
684
|
+
calls.push({ network, method: item.method, params: item.params, url: req.url ?? '' });
|
|
685
|
+
const overBudget = !affords(item.method);
|
|
686
|
+
if (overBudget) spent.refused++;
|
|
687
|
+
else if (computeUnitsPerSecond) {
|
|
688
|
+
const second = Math.floor(now() / 1000);
|
|
689
|
+
const sum = (spent.perSecond.get(second) ?? 0) + unitsOf(item.method);
|
|
690
|
+
spent.perSecond.set(second, sum);
|
|
691
|
+
spent.peakSecond = Math.max(spent.peakSecond, sum);
|
|
692
|
+
}
|
|
693
|
+
if (overBudget || limitedItems > 0) {
|
|
694
|
+
if (!overBudget) limitedItems--;
|
|
695
|
+
return {
|
|
696
|
+
jsonrpc: '2.0',
|
|
697
|
+
id: itemId,
|
|
698
|
+
error: {
|
|
699
|
+
code: 429,
|
|
700
|
+
message: 'Your app has exceeded its compute units per second capacity.'
|
|
701
|
+
}
|
|
702
|
+
};
|
|
703
|
+
}
|
|
704
|
+
try {
|
|
705
|
+
return {
|
|
706
|
+
jsonrpc: '2.0',
|
|
707
|
+
id: itemId,
|
|
708
|
+
result: answer(network, item.method, item.params ?? [])
|
|
709
|
+
};
|
|
710
|
+
} catch (/** @type {any} */ error) {
|
|
711
|
+
if (!(error instanceof RpcError)) throw error;
|
|
712
|
+
return {
|
|
713
|
+
jsonrpc: '2.0',
|
|
714
|
+
id: itemId,
|
|
715
|
+
error: { code: error.code, message: error.message }
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
};
|
|
719
|
+
if (Array.isArray(body)) {
|
|
720
|
+
if (!body.length || body.length > 1000) {
|
|
721
|
+
return send(400, {
|
|
722
|
+
jsonrpc: '2.0',
|
|
723
|
+
id: null,
|
|
724
|
+
error: { code: -32600, message: 'Invalid batch size' }
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
// Answers come back in any order: the fake reverses them.
|
|
728
|
+
return send(200, body.map(one).reverse());
|
|
729
|
+
}
|
|
730
|
+
const single = one(body);
|
|
731
|
+
return send(200, single);
|
|
732
|
+
});
|
|
733
|
+
});
|
|
734
|
+
await new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(undefined)));
|
|
735
|
+
const { port } = /** @type {import('node:net').AddressInfo} */ (server.address());
|
|
736
|
+
const url = `http://127.0.0.1:${port}`;
|
|
737
|
+
return {
|
|
738
|
+
url,
|
|
739
|
+
baseUrl: (/** @type {string} */ network) => `${url}/${network}/v2`,
|
|
740
|
+
calls,
|
|
741
|
+
paths,
|
|
742
|
+
spent,
|
|
743
|
+
close: () =>
|
|
744
|
+
new Promise((resolve) => {
|
|
745
|
+
server.close(() => resolve(undefined));
|
|
746
|
+
server.closeAllConnections?.();
|
|
747
|
+
})
|
|
748
|
+
};
|
|
749
|
+
}
|