@le-space/chains 0.2.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 +5 -2
- package/package.json +10 -4
- package/src/aleph.js +8 -2
- 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/registry.js +2 -25
- package/test/support/aleph.js +6 -0
- package/test/support/fake-alchemy.js +749 -0
- package/test/support/fake-blockscout.js +279 -0
package/README.md
CHANGED
|
@@ -14,9 +14,12 @@ Runs in a browser and in Node. The caller hands in `fetch`, the endpoints (a nod
|
|
|
14
14
|
| Aleph Cloud credits (no chain: Aleph's own network, by the Ethereum address) | Aleph's API, CORS open; a month's statement, `alephEntries` gives `LedgerEntry` (`usage` for consumption, with its USD price per credit) | `aleph` |
|
|
15
15
|
|
|
16
16
|
- `createWalletService({ fetch, getZpub, alchemyKey, … })` – every chain behind one `history({ chain, address, endpoints })`, as Belege's bridge serves it.
|
|
17
|
-
- `CHAINS`, `chainOf`, `publicChains` – the chains, their assets, default endpoints and explorers (`registry`).
|
|
17
|
+
- `CHAINS`, `chainOf`, `publicChains` – the chains, their assets, default endpoints and explorers (`registry`). One chain's data without the others: `FILECOIN` (`filecoin-chain`), `NYX_CHAIN`, `AKASH_CHAIN` (`cosmos-chains`), `KNOWN_EVM_CONTRACTS` (`evm-contracts`). The readers take their chain as an argument and do not import the registry.
|
|
18
|
+
- `toChecksumAddress`, `isEvmAddress` – an EVM address's EIP-55 checksum and form (`evm-address`: keccak and bytes only, so `aleph` and a browser form do not bundle the EVM reader or Alchemy; `evm` re-exports them).
|
|
18
19
|
- `createJsonFetcher`, `WalletError`, `checkEndpoint`, `txUrl`, `addressUrl`, `markSwaps` – what every reader shares (`core`). Error messages name a host at most, never a path or a query (they carry addresses).
|
|
19
|
-
-
|
|
20
|
+
- Fakes for tests, with made-up addresses, hashes, keys and amounts:
|
|
21
|
+
- `@le-space/chains/testing/cosmos`, `testing/filfox`, `testing/blockscout`, `testing/alchemy` – fake nodes on 127.0.0.1 (Node). The fake Alchemy is as strict as the real one about what it is asked; `blockscoutView` turns its made-up chain into what the fake Blockscout serves, so one history reads through both.
|
|
22
|
+
- `@le-space/chains/testing/aleph` – a fake Aleph API as a `fetch` function (Node and browser), and a made-up account and month (`ACCOUNT`, `sampleRows`, `sampleBalance`, `flatUsd`).
|
|
20
23
|
|
|
21
24
|
Each source sees the address and the IP address of the machine that asks; Belege's consent screen says so.
|
|
22
25
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@le-space/chains",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Own wallets on public chains, read only, by their address – Cosmos (Nyx, Akash), EVM (Blockscout, Alchemy), Bitcoin (Esplora, zpub), Filecoin (Filfox), NEAR (NearBlocks), Aleph Cloud credits – as @le-space/ledger entries. Browser and Node; fetch, endpoints and keys handed in.",
|
|
5
5
|
"license": "AGPL-3.0-or-later",
|
|
6
6
|
"type": "module",
|
|
@@ -24,13 +24,19 @@
|
|
|
24
24
|
"./akash-console": "./src/akash-console.js",
|
|
25
25
|
"./akash-deployments": "./src/akash-deployments.js",
|
|
26
26
|
"./evm": "./src/evm.js",
|
|
27
|
+
"./evm-address": "./src/evm-address.js",
|
|
28
|
+
"./evm-contracts": "./src/evm-contracts.js",
|
|
27
29
|
"./alchemy": "./src/alchemy.js",
|
|
28
30
|
"./bitcoin": "./src/bitcoin.js",
|
|
29
31
|
"./filecoin": "./src/filecoin.js",
|
|
32
|
+
"./filecoin-chain": "./src/filecoin-chain.js",
|
|
30
33
|
"./near": "./src/near.js",
|
|
31
34
|
"./aleph": "./src/aleph.js",
|
|
32
35
|
"./testing/cosmos": "./test/support/fake-cosmos.js",
|
|
33
|
-
"./testing/filfox": "./test/support/fake-filfox.js"
|
|
36
|
+
"./testing/filfox": "./test/support/fake-filfox.js",
|
|
37
|
+
"./testing/blockscout": "./test/support/fake-blockscout.js",
|
|
38
|
+
"./testing/alchemy": "./test/support/fake-alchemy.js",
|
|
39
|
+
"./testing/aleph": "./test/support/aleph.js"
|
|
34
40
|
},
|
|
35
41
|
"files": [
|
|
36
42
|
"src",
|
|
@@ -47,8 +53,8 @@
|
|
|
47
53
|
"@noble/hashes": "2.4.0",
|
|
48
54
|
"@scure/base": "2.4.0",
|
|
49
55
|
"@scure/bip32": "2.4.0",
|
|
50
|
-
"@le-space/ledger": "^0.
|
|
51
|
-
"@le-space/rates": "^0.
|
|
56
|
+
"@le-space/ledger": "^0.3.0",
|
|
57
|
+
"@le-space/rates": "^0.3.0"
|
|
52
58
|
},
|
|
53
59
|
"devDependencies": {
|
|
54
60
|
"prettier": "3.6.2",
|
package/src/aleph.js
CHANGED
|
@@ -57,7 +57,7 @@ import {
|
|
|
57
57
|
plain
|
|
58
58
|
} from '@le-space/rates/aleph-credits';
|
|
59
59
|
import { createJsonFetcher, WalletError } from './http.js';
|
|
60
|
-
import { toChecksumAddress } from './evm.js';
|
|
60
|
+
import { toChecksumAddress } from './evm-address.js';
|
|
61
61
|
|
|
62
62
|
export const ALEPH_API = 'https://api2.aleph.im';
|
|
63
63
|
/** Aleph's list price, USD per credit (@le-space/rates). */
|
|
@@ -286,9 +286,15 @@ export function createAlephClient({
|
|
|
286
286
|
'ALEPH_TOO_MANY'
|
|
287
287
|
);
|
|
288
288
|
}
|
|
289
|
+
// A window without rows: Aleph answers 404 in plain text (the same
|
|
290
|
+
// address without the window answers 200) – an empty page, as the
|
|
291
|
+
// balance's 404 is nothing there.
|
|
289
292
|
const body = await getJson(
|
|
290
293
|
`${base}/credit_history?page=${page}&pagination=${PER_PAGE}${query}`
|
|
291
|
-
)
|
|
294
|
+
).catch((/** @type {any} */ e) => {
|
|
295
|
+
if (e?.httpStatus === 404) return { credit_history: [], pagination_total: 0 };
|
|
296
|
+
throw e;
|
|
297
|
+
});
|
|
292
298
|
const batch = Array.isArray(body?.credit_history) ? body.credit_history : null;
|
|
293
299
|
if (!batch) throw new WalletError('Aleph answered without a history', 'ALEPH_DATA');
|
|
294
300
|
rows.push(...batch);
|
package/src/bitcoin.js
CHANGED
|
@@ -35,7 +35,7 @@ import { sha256 } from '@noble/hashes/sha2.js';
|
|
|
35
35
|
import { ripemd160 } from '@noble/hashes/legacy.js';
|
|
36
36
|
import { toHex, utf8 } from '@le-space/ledger/bytes';
|
|
37
37
|
|
|
38
|
-
import { txUrl } from './
|
|
38
|
+
import { txUrl } from './explorer.js';
|
|
39
39
|
import { createJsonFetcher, WalletError } from './http.js';
|
|
40
40
|
import { unitsToDecimal } from './cosmos.js';
|
|
41
41
|
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// An EVM address on its own: the EIP-55 checksum and the check of an
|
|
3
|
+
// address's form. Only keccak and bytes – no reader, no registry, no
|
|
4
|
+
// Alchemy – so a module that only needs an address (aleph.js, a browser
|
|
5
|
+
// form) does not bundle the EVM reader. evm.js re-exports both.
|
|
6
|
+
|
|
7
|
+
import { keccak_256 } from '@noble/hashes/sha3.js';
|
|
8
|
+
import { toHex, utf8 } from '@le-space/ledger/bytes';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* EIP-55: the mixed-case checksum of an address.
|
|
12
|
+
*
|
|
13
|
+
* @param {string} address 0x + 40 hex
|
|
14
|
+
*/
|
|
15
|
+
export function toChecksumAddress(address) {
|
|
16
|
+
const hex = address.slice(2).toLowerCase();
|
|
17
|
+
const hash = toHex(keccak_256(utf8(hex)));
|
|
18
|
+
let out = '0x';
|
|
19
|
+
for (let i = 0; i < 40; i++) {
|
|
20
|
+
out += parseInt(hash[i], 16) >= 8 ? hex[i].toUpperCase() : hex[i];
|
|
21
|
+
}
|
|
22
|
+
return out;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* 0x + 40 hex; when it mixes cases, the EIP-55 checksum must hold (a typo
|
|
27
|
+
* then shows). All lower or all upper case carries no checksum.
|
|
28
|
+
*
|
|
29
|
+
* @param {string} address
|
|
30
|
+
*/
|
|
31
|
+
export function isEvmAddress(address) {
|
|
32
|
+
if (typeof address !== 'string' || !/^0x[0-9a-fA-F]{40}$/.test(address)) return false;
|
|
33
|
+
const body = address.slice(2);
|
|
34
|
+
if (body === body.toLowerCase() || body === body.toUpperCase()) return true;
|
|
35
|
+
return toChecksumAddress(address) === address;
|
|
36
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// The EVM contracts a swap is named after, on their own so that the EVM
|
|
3
|
+
// reader does not bundle every chain's data (registry.js re-exports them).
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Contracts a wallet meets when it swaps (issue #115), by their lower-case
|
|
7
|
+
* address, and what they are called. Routers of the big aggregators and DEXes
|
|
8
|
+
* sit at the same address on most EVM chains; WETH is Ethereum's. Checked
|
|
9
|
+
* against the projects' own documentation; an address not here stays
|
|
10
|
+
* "Vertrag".
|
|
11
|
+
*/
|
|
12
|
+
export const KNOWN_EVM_CONTRACTS = /** @type {Readonly<Record<string, string>>} */ (
|
|
13
|
+
Object.freeze({
|
|
14
|
+
'0x881d40237659c251811cec9c364ef91dc08d300c': 'MetaMask Swap (Router)',
|
|
15
|
+
'0x74de5d4fcbf63e00296fd95d33236b9794016631': 'MetaMask Swap (Spender)',
|
|
16
|
+
'0x3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad': 'Uniswap (Universal Router)',
|
|
17
|
+
'0x66a9893cc07d91d95644aedd05d03f95e1dba8af': 'Uniswap (Universal Router v4)',
|
|
18
|
+
'0x7a250d5630b4cf539739df2c5dacb4c659f2488d': 'Uniswap V2 (Router)',
|
|
19
|
+
'0xe592427a0aece92de3edee1f18e0157c05861564': 'Uniswap V3 (Router)',
|
|
20
|
+
'0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45': 'Uniswap V3 (Router 2)',
|
|
21
|
+
'0x1111111254eeb25477b68fb85ed929f73a960582': '1inch (Router v5)',
|
|
22
|
+
'0x111111125421ca6dc452d289314280a0f8842a65': '1inch (Router v6)',
|
|
23
|
+
'0xdef1c0ded9bec7f1a1670819833240f027b25eff': '0x (Exchange Proxy)',
|
|
24
|
+
'0x9008d19f58aabd9ed0d60971565aa8510560ab41': 'CoW Protocol (Settlement)',
|
|
25
|
+
'0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2': 'WETH'
|
|
26
|
+
})
|
|
27
|
+
);
|
package/src/evm.js
CHANGED
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
// token is a listed one – an unlisted symbol is the token's own claim)
|
|
36
36
|
// and the router it went through, and the gas it cost (the gas entry
|
|
37
37
|
// stays a fee of its own and names the swap). Known routers and WETH are named
|
|
38
|
-
// (registry.js
|
|
38
|
+
// (evm-contracts.js, re-exported by registry.js).
|
|
39
39
|
//
|
|
40
40
|
// The log gets counts, never an address.
|
|
41
41
|
//
|
|
@@ -43,10 +43,9 @@
|
|
|
43
43
|
// own, the lists come from Alchemy instead (alchemy.js), in the same shape,
|
|
44
44
|
// and become entries here in the same way.
|
|
45
45
|
|
|
46
|
-
import {
|
|
47
|
-
import {
|
|
48
|
-
|
|
49
|
-
import { KNOWN_EVM_CONTRACTS, addressUrl, txUrl } from './registry.js';
|
|
46
|
+
import { isEvmAddress, toChecksumAddress } from './evm-address.js';
|
|
47
|
+
import { KNOWN_EVM_CONTRACTS } from './evm-contracts.js';
|
|
48
|
+
import { addressUrl, txUrl } from './explorer.js';
|
|
50
49
|
import { markSwaps } from './core.js';
|
|
51
50
|
import { createJsonFetcher, WalletError } from './http.js';
|
|
52
51
|
import { unitsToDecimal } from './cosmos.js';
|
|
@@ -68,34 +67,6 @@ const LOOKALIKE_GUARD = [
|
|
|
68
67
|
|
|
69
68
|
const PAGE = 1000;
|
|
70
69
|
|
|
71
|
-
/**
|
|
72
|
-
* EIP-55: the mixed-case checksum of an address.
|
|
73
|
-
*
|
|
74
|
-
* @param {string} address 0x + 40 hex
|
|
75
|
-
*/
|
|
76
|
-
export function toChecksumAddress(address) {
|
|
77
|
-
const hex = address.slice(2).toLowerCase();
|
|
78
|
-
const hash = toHex(keccak_256(utf8(hex)));
|
|
79
|
-
let out = '0x';
|
|
80
|
-
for (let i = 0; i < 40; i++) {
|
|
81
|
-
out += parseInt(hash[i], 16) >= 8 ? hex[i].toUpperCase() : hex[i];
|
|
82
|
-
}
|
|
83
|
-
return out;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* 0x + 40 hex; when it mixes cases, the EIP-55 checksum must hold (a typo
|
|
88
|
-
* then shows). All lower or all upper case carries no checksum.
|
|
89
|
-
*
|
|
90
|
-
* @param {string} address
|
|
91
|
-
*/
|
|
92
|
-
export function isEvmAddress(address) {
|
|
93
|
-
if (typeof address !== 'string' || !/^0x[0-9a-fA-F]{40}$/.test(address)) return false;
|
|
94
|
-
const body = address.slice(2);
|
|
95
|
-
if (body === body.toLowerCase() || body === body.toUpperCase()) return true;
|
|
96
|
-
return toChecksumAddress(address) === address;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
70
|
/** @param {unknown} v */
|
|
100
71
|
const bigintOf = (v) => (typeof v === 'string' && /^\d+$/.test(v) ? BigInt(v) : null);
|
|
101
72
|
|
|
@@ -695,3 +666,5 @@ export function createEvmClient({
|
|
|
695
666
|
}
|
|
696
667
|
|
|
697
668
|
export { markSwaps };
|
|
669
|
+
// The address helpers live in evm-address.js (no reader, no Alchemy); here as before.
|
|
670
|
+
export { isEvmAddress, toChecksumAddress };
|
package/src/http.js
CHANGED
|
@@ -93,6 +93,13 @@ export function createJsonFetcher({
|
|
|
93
93
|
continue;
|
|
94
94
|
}
|
|
95
95
|
const body = await res.json().catch(() => undefined);
|
|
96
|
+
// A refusal in plain text (Aleph's 404 for an empty window): asking
|
|
97
|
+
// again changes nothing, and the caller may tell it apart by its status.
|
|
98
|
+
if (body === undefined && res.status >= 400 && res.status < 500 && res.status !== 429) {
|
|
99
|
+
const error = new WalletError(`${host} answered ${res.status} without JSON`, 'WALLET_NODE');
|
|
100
|
+
error.httpStatus = res.status;
|
|
101
|
+
throw error;
|
|
102
|
+
}
|
|
96
103
|
if (res.status === 429 || res.status >= 500 || body === undefined) {
|
|
97
104
|
last = new WalletError(
|
|
98
105
|
res.status === 429
|
package/src/registry.js
CHANGED
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
import { addressUrl, txUrl } from './explorer.js';
|
|
25
25
|
import { AKASH_CHAIN, NYX_CHAIN } from './cosmos-chains.js';
|
|
26
26
|
import { FILECOIN } from './filecoin-chain.js';
|
|
27
|
+
import { KNOWN_EVM_CONTRACTS } from './evm-contracts.js';
|
|
27
28
|
|
|
28
29
|
/**
|
|
29
30
|
* @typedef {object} ChainAsset
|
|
@@ -108,30 +109,6 @@ const etherscanLike = (/** @type {string} */ name, /** @type {string} */ base) =
|
|
|
108
109
|
address: `${base}/address/{address}`
|
|
109
110
|
});
|
|
110
111
|
|
|
111
|
-
/**
|
|
112
|
-
* Contracts a wallet meets when it swaps (issue #115), by their lower-case
|
|
113
|
-
* address, and what they are called. Routers of the big aggregators and DEXes
|
|
114
|
-
* sit at the same address on most EVM chains; WETH is Ethereum's. Checked
|
|
115
|
-
* against the projects' own documentation; an address not here stays
|
|
116
|
-
* "Vertrag".
|
|
117
|
-
*/
|
|
118
|
-
export const KNOWN_EVM_CONTRACTS = /** @type {Readonly<Record<string, string>>} */ (
|
|
119
|
-
Object.freeze({
|
|
120
|
-
'0x881d40237659c251811cec9c364ef91dc08d300c': 'MetaMask Swap (Router)',
|
|
121
|
-
'0x74de5d4fcbf63e00296fd95d33236b9794016631': 'MetaMask Swap (Spender)',
|
|
122
|
-
'0x3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad': 'Uniswap (Universal Router)',
|
|
123
|
-
'0x66a9893cc07d91d95644aedd05d03f95e1dba8af': 'Uniswap (Universal Router v4)',
|
|
124
|
-
'0x7a250d5630b4cf539739df2c5dacb4c659f2488d': 'Uniswap V2 (Router)',
|
|
125
|
-
'0xe592427a0aece92de3edee1f18e0157c05861564': 'Uniswap V3 (Router)',
|
|
126
|
-
'0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45': 'Uniswap V3 (Router 2)',
|
|
127
|
-
'0x1111111254eeb25477b68fb85ed929f73a960582': '1inch (Router v5)',
|
|
128
|
-
'0x111111125421ca6dc452d289314280a0f8842a65': '1inch (Router v6)',
|
|
129
|
-
'0xdef1c0ded9bec7f1a1670819833240f027b25eff': '0x (Exchange Proxy)',
|
|
130
|
-
'0x9008d19f58aabd9ed0d60971565aa8510560ab41': 'CoW Protocol (Settlement)',
|
|
131
|
-
'0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2': 'WETH'
|
|
132
|
-
})
|
|
133
|
-
);
|
|
134
|
-
|
|
135
112
|
/** @type {Readonly<Record<string, Chain>>} */
|
|
136
113
|
export const CHAINS = Object.freeze({
|
|
137
114
|
nyx: NYX_CHAIN,
|
|
@@ -255,7 +232,7 @@ export function chainOf(id) {
|
|
|
255
232
|
return typeof id === 'string' && Object.hasOwn(CHAINS, id) ? CHAINS[id] : null;
|
|
256
233
|
}
|
|
257
234
|
|
|
258
|
-
export { txUrl, addressUrl };
|
|
235
|
+
export { txUrl, addressUrl, KNOWN_EVM_CONTRACTS };
|
|
259
236
|
|
|
260
237
|
/**
|
|
261
238
|
* What the app is told about the chains: everything but code.
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// @le-space/chains/testing/aleph: a fake Aleph API as a `fetch` function
|
|
3
|
+
// (Node and browser) and a made-up account and month to feed it. Every
|
|
4
|
+
// address, hash and amount is made up.
|
|
5
|
+
export * from './aleph-fetch.js';
|
|
6
|
+
export * from './aleph-sample.js';
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// A fake Blockscout on 127.0.0.1 for tests (Node): the Etherscan-compatible
|
|
3
|
+
// `/api` (txlist, txlistinternal, tokentx, balances, paging as strict as
|
|
4
|
+
// Blockscout's), its JSON-RPC proxy's eth_chainId and the v2 coin balance
|
|
5
|
+
// history, with a made-up EVM wallet's history. Every address, hash and
|
|
6
|
+
// amount here is made up: addresses are derived from test phrases, hashes
|
|
7
|
+
// from counters. fake-alchemy.js serves the same kind of chain.
|
|
8
|
+
import http from 'node:http';
|
|
9
|
+
import { createHash } from 'node:crypto';
|
|
10
|
+
|
|
11
|
+
import { fakeHash } from './fake-cosmos.js';
|
|
12
|
+
|
|
13
|
+
/** A synthetic EVM address, lower case. */
|
|
14
|
+
export const fakeEvmAddress = (/** @type {string} */ phrase) =>
|
|
15
|
+
`0x${createHash('sha256').update(`belege test ${phrase}`).digest('hex').slice(0, 40)}`;
|
|
16
|
+
|
|
17
|
+
export const EVM = {
|
|
18
|
+
wallet: fakeEvmAddress('evm wallet'),
|
|
19
|
+
exchange: fakeEvmAddress('exchange deposit address'),
|
|
20
|
+
friend: fakeEvmAddress('someone else on evm'),
|
|
21
|
+
contract: fakeEvmAddress('a contract'),
|
|
22
|
+
usdc: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
|
|
23
|
+
spamToken: fakeEvmAddress('a token calling itself USDC')
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const evmTime = (/** @type {number} */ block) =>
|
|
27
|
+
String(Math.floor(Date.parse('2026-09-01T00:00:00Z') / 1000) + (block - 100) * 12);
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* A made-up history of EVM.wallet on Ethereum: ETH in, USDC in and out to
|
|
31
|
+
* the exchange, a failed send, ETH from a contract, a spam token.
|
|
32
|
+
*/
|
|
33
|
+
export function sampleEvmHistory({ fillerTokens = 0 } = {}) {
|
|
34
|
+
const w = EVM.wallet;
|
|
35
|
+
const tx = (
|
|
36
|
+
/** @type {string} */ seed,
|
|
37
|
+
/** @type {number} */ block,
|
|
38
|
+
/** @type {Record<string, string>} */ fields
|
|
39
|
+
) => ({
|
|
40
|
+
blockNumber: String(block),
|
|
41
|
+
timeStamp: evmTime(block),
|
|
42
|
+
hash: fakeHash(seed, true),
|
|
43
|
+
transactionIndex: '0',
|
|
44
|
+
gas: '60000',
|
|
45
|
+
...fields
|
|
46
|
+
});
|
|
47
|
+
const normal = [
|
|
48
|
+
tx('eth-in', 100, {
|
|
49
|
+
from: EVM.friend,
|
|
50
|
+
to: w,
|
|
51
|
+
value: '500000000000000000',
|
|
52
|
+
gasUsed: '21000',
|
|
53
|
+
gasPrice: '1000000000',
|
|
54
|
+
isError: '0',
|
|
55
|
+
txreceipt_status: '1'
|
|
56
|
+
}),
|
|
57
|
+
// USDC to the exchange: the token moves in tokentx; here only the gas.
|
|
58
|
+
tx('usdc-out', 200, {
|
|
59
|
+
from: w,
|
|
60
|
+
to: EVM.usdc,
|
|
61
|
+
value: '0',
|
|
62
|
+
gasUsed: '50000',
|
|
63
|
+
gasPrice: '2000000000',
|
|
64
|
+
isError: '0',
|
|
65
|
+
txreceipt_status: '1'
|
|
66
|
+
}),
|
|
67
|
+
tx('failed', 300, {
|
|
68
|
+
from: w,
|
|
69
|
+
to: EVM.friend,
|
|
70
|
+
value: '100000000000000000',
|
|
71
|
+
gasUsed: '21000',
|
|
72
|
+
gasPrice: '3000000000',
|
|
73
|
+
isError: '1',
|
|
74
|
+
txreceipt_status: '0'
|
|
75
|
+
}),
|
|
76
|
+
tx('eth-out', 400, {
|
|
77
|
+
from: w,
|
|
78
|
+
to: EVM.friend,
|
|
79
|
+
value: '100000000000000000',
|
|
80
|
+
gasUsed: '21000',
|
|
81
|
+
gasPrice: '1000000000',
|
|
82
|
+
isError: '0',
|
|
83
|
+
txreceipt_status: '1'
|
|
84
|
+
})
|
|
85
|
+
];
|
|
86
|
+
const internal = [
|
|
87
|
+
{
|
|
88
|
+
blockNumber: '500',
|
|
89
|
+
timeStamp: evmTime(500),
|
|
90
|
+
transactionHash: fakeHash('contract-pays', true),
|
|
91
|
+
index: '1',
|
|
92
|
+
from: EVM.contract,
|
|
93
|
+
to: w,
|
|
94
|
+
value: '20000000000000000',
|
|
95
|
+
isError: '0',
|
|
96
|
+
type: 'call'
|
|
97
|
+
}
|
|
98
|
+
];
|
|
99
|
+
const tokens = [
|
|
100
|
+
tx('usdc-in', 150, {
|
|
101
|
+
from: EVM.friend,
|
|
102
|
+
to: w,
|
|
103
|
+
value: '750000000',
|
|
104
|
+
contractAddress: EVM.usdc,
|
|
105
|
+
tokenSymbol: 'USDC',
|
|
106
|
+
tokenDecimal: '6'
|
|
107
|
+
}),
|
|
108
|
+
tx('usdc-out', 200, {
|
|
109
|
+
from: w,
|
|
110
|
+
to: EVM.exchange,
|
|
111
|
+
value: '300000000',
|
|
112
|
+
contractAddress: EVM.usdc,
|
|
113
|
+
tokenSymbol: 'USDC',
|
|
114
|
+
tokenDecimal: '6'
|
|
115
|
+
}),
|
|
116
|
+
tx('spam', 250, {
|
|
117
|
+
from: EVM.friend,
|
|
118
|
+
to: w,
|
|
119
|
+
value: '1000000000000',
|
|
120
|
+
contractAddress: EVM.spamToken,
|
|
121
|
+
tokenSymbol: 'USDC',
|
|
122
|
+
tokenDecimal: '6'
|
|
123
|
+
})
|
|
124
|
+
];
|
|
125
|
+
for (let i = 0; i < fillerTokens; i++) {
|
|
126
|
+
tokens.push(
|
|
127
|
+
tx(`filler-${i}`, 1000 + Math.floor(i / 3), {
|
|
128
|
+
from: EVM.friend,
|
|
129
|
+
to: w,
|
|
130
|
+
value: '1',
|
|
131
|
+
contractAddress: EVM.usdc,
|
|
132
|
+
tokenSymbol: 'USDC',
|
|
133
|
+
tokenDecimal: '6'
|
|
134
|
+
})
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
return { normal, internal, tokens };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* @param {object} [options]
|
|
142
|
+
* @param {{ normal: Record<string, string>[], internal: Record<string, string>[], tokens: Record<string, string>[] }} [options.history]
|
|
143
|
+
* as sampleEvmHistory, or fake-alchemy.js's blockscoutView
|
|
144
|
+
* @param {Record<string, string>} [options.balances] `native` and contract → units
|
|
145
|
+
* @param {number} [options.rateLimitedCalls] this many answer Blockscout's "rate limit" first
|
|
146
|
+
* @param {number} [options.maxOffset] page × offset beyond this is refused, as Blockscout does
|
|
147
|
+
* @param {string | null} [options.chainId] what `…/api/eth-rpc` answers to eth_chainId; null: 404
|
|
148
|
+
* @param {{ block_number: number, block_timestamp: string, value: string }[] | null} [options.coinBalanceHistory]
|
|
149
|
+
* `…/api/v2/addresses/<a>/coin-balance-history`, newest first; null: 404
|
|
150
|
+
*/
|
|
151
|
+
export async function startFakeBlockscout({
|
|
152
|
+
history = sampleEvmHistory(),
|
|
153
|
+
balances = { native: '310000000000000000', [EVM.usdc]: '450000000' },
|
|
154
|
+
rateLimitedCalls = 0,
|
|
155
|
+
maxOffset = 10_000,
|
|
156
|
+
chainId = '0x1',
|
|
157
|
+
// The native coin's balance after each change (#287), newest first as Blockscout gives it;
|
|
158
|
+
// null: the v2 endpoint is not there.
|
|
159
|
+
coinBalanceHistory = [
|
|
160
|
+
{
|
|
161
|
+
block_number: 19_500_000,
|
|
162
|
+
block_timestamp: '2026-03-20T09:00:00.000000Z',
|
|
163
|
+
value: '310000000000000000'
|
|
164
|
+
},
|
|
165
|
+
{
|
|
166
|
+
block_number: 19_400_000,
|
|
167
|
+
block_timestamp: '2026-02-10T12:00:00.000000Z',
|
|
168
|
+
value: '500000000000000000'
|
|
169
|
+
}
|
|
170
|
+
]
|
|
171
|
+
} = {}) {
|
|
172
|
+
/** @type {Record<string, string>[]} */
|
|
173
|
+
const calls = [];
|
|
174
|
+
let limited = rateLimitedCalls;
|
|
175
|
+
const server = http.createServer((req, res) => {
|
|
176
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
177
|
+
if (url.pathname === '/api/eth-rpc' && req.method === 'POST') {
|
|
178
|
+
let raw = '';
|
|
179
|
+
req.on('data', (c) => (raw += c));
|
|
180
|
+
req.on('end', () => {
|
|
181
|
+
calls.push({ rpc: JSON.parse(raw).method });
|
|
182
|
+
if (chainId === null) {
|
|
183
|
+
res.writeHead(404, { 'Content-Type': 'application/json' });
|
|
184
|
+
return res.end(JSON.stringify({ message: 'Not found' }));
|
|
185
|
+
}
|
|
186
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
187
|
+
res.end(JSON.stringify({ jsonrpc: '2.0', id: 1, result: chainId }));
|
|
188
|
+
});
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
const reply = (/** @type {unknown} */ body) => {
|
|
192
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
193
|
+
res.end(JSON.stringify(body));
|
|
194
|
+
};
|
|
195
|
+
const v2 = /^\/api\/v2\/addresses\/(0x[0-9a-f]{40})\/coin-balance-history$/.exec(url.pathname);
|
|
196
|
+
if (v2) {
|
|
197
|
+
calls.push({
|
|
198
|
+
v2: 'coin-balance-history',
|
|
199
|
+
address: v2[1],
|
|
200
|
+
...Object.fromEntries(url.searchParams)
|
|
201
|
+
});
|
|
202
|
+
if (coinBalanceHistory === null) {
|
|
203
|
+
res.writeHead(404, { 'Content-Type': 'application/json' });
|
|
204
|
+
return res.end(JSON.stringify({ message: 'Not found' }));
|
|
205
|
+
}
|
|
206
|
+
// One item a page, to prove the paging.
|
|
207
|
+
const from = Number(url.searchParams.get('n') ?? 0);
|
|
208
|
+
const item = coinBalanceHistory[from];
|
|
209
|
+
return reply({
|
|
210
|
+
items: item ? [item] : [],
|
|
211
|
+
next_page_params: from + 1 < coinBalanceHistory.length ? { n: from + 1 } : null
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
const p = Object.fromEntries(url.searchParams);
|
|
215
|
+
calls.push(p);
|
|
216
|
+
if (url.pathname !== '/api')
|
|
217
|
+
return reply({ status: '0', message: 'Unknown path', result: null });
|
|
218
|
+
if (limited > 0) {
|
|
219
|
+
limited--;
|
|
220
|
+
return reply({ status: '0', message: 'NOTOK', result: 'Max rate limit reached' });
|
|
221
|
+
}
|
|
222
|
+
if (!/^0x[0-9a-f]{40}$/.test(p.address ?? '')) {
|
|
223
|
+
return reply({ status: '0', message: 'Invalid address format', result: null });
|
|
224
|
+
}
|
|
225
|
+
if (p.action === 'balance')
|
|
226
|
+
return reply({ status: '1', message: 'OK', result: balances.native ?? '0' });
|
|
227
|
+
if (p.action === 'tokenbalance') {
|
|
228
|
+
return reply({
|
|
229
|
+
status: '1',
|
|
230
|
+
message: 'OK',
|
|
231
|
+
result: balances[String(p.contractaddress).toLowerCase()] ?? '0'
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
const lists = /** @type {Record<string, any[]>} */ ({
|
|
235
|
+
txlist: history.normal,
|
|
236
|
+
txlistinternal: history.internal,
|
|
237
|
+
tokentx: history.tokens
|
|
238
|
+
});
|
|
239
|
+
const list = lists[p.action];
|
|
240
|
+
if (!list) return reply({ status: '0', message: 'Unknown action', result: null });
|
|
241
|
+
const page = Number(p.page ?? 1);
|
|
242
|
+
const offset = Number(p.offset ?? 10);
|
|
243
|
+
if (page * offset > maxOffset) {
|
|
244
|
+
return reply({
|
|
245
|
+
status: '0',
|
|
246
|
+
message: `Result window is too large, PageNo x Offset size must be less than or equal to ${maxOffset}`,
|
|
247
|
+
result: null
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
const start = Number(p.startblock ?? 0);
|
|
251
|
+
const mine = list
|
|
252
|
+
.filter((r) => [r.from, r.to].includes(p.address) && Number(r.blockNumber) >= start)
|
|
253
|
+
.sort((a, b) => Number(a.blockNumber) - Number(b.blockNumber));
|
|
254
|
+
const slice = mine.slice((page - 1) * offset, page * offset);
|
|
255
|
+
// Blockscout's tokentx carries no logIndex.
|
|
256
|
+
const shaped = slice.map(({ logIndex: _l, ...r }) => r);
|
|
257
|
+
if (!shaped.length) {
|
|
258
|
+
return reply({
|
|
259
|
+
status: '0',
|
|
260
|
+
message: p.action === 'tokentx' ? 'No token transfers found' : 'No transactions found',
|
|
261
|
+
result: []
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
return reply({ status: '1', message: 'OK', result: shaped });
|
|
265
|
+
});
|
|
266
|
+
await new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(undefined)));
|
|
267
|
+
const { port } = /** @type {import('node:net').AddressInfo} */ (server.address());
|
|
268
|
+
const url = `http://127.0.0.1:${port}`;
|
|
269
|
+
return {
|
|
270
|
+
url,
|
|
271
|
+
endpoints: { api: `${url}/api` },
|
|
272
|
+
calls,
|
|
273
|
+
close: () =>
|
|
274
|
+
new Promise((resolve) => {
|
|
275
|
+
server.close(() => resolve(undefined));
|
|
276
|
+
server.closeAllConnections?.();
|
|
277
|
+
})
|
|
278
|
+
};
|
|
279
|
+
}
|