@le-space/chains 0.0.0-stage → 0.1.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/LICENSE +662 -0
- package/README.md +25 -2
- package/package.json +56 -3
- package/src/akash-console.js +456 -0
- package/src/akash-deployments.js +145 -0
- package/src/alchemy.js +648 -0
- package/src/bech32.js +126 -0
- package/src/bitcoin.js +366 -0
- package/src/core.js +8 -0
- package/src/cosmos-chains.js +80 -0
- package/src/cosmos.js +591 -0
- package/src/evm.js +697 -0
- package/src/explorer.js +14 -0
- package/src/filecoin-chain.js +45 -0
- package/src/filecoin.js +398 -0
- package/src/http.js +121 -0
- package/src/index.js +63 -0
- package/src/near.js +655 -0
- package/src/protobuf.js +130 -0
- package/src/registry.js +279 -0
- package/src/swaps.js +61 -0
- package/src/wallets.js +236 -0
- package/test/support/fake-cosmos.js +650 -0
- package/test/support/fake-filfox.js +87 -0
package/src/evm.js
ADDED
|
@@ -0,0 +1,697 @@
|
|
|
1
|
+
// An EVM wallet (Ethereum, Base, Arbitrum, Optimism, Polygon), read only, by
|
|
2
|
+
// its address: ETH (or the chain's native coin) in and out, the ERC-20
|
|
3
|
+
// tokens listed in registry.js, and the gas it paid.
|
|
4
|
+
//
|
|
5
|
+
// Source: Blockscout's Etherscan-compatible API, no key needed, after its
|
|
6
|
+
// JSON-RPC proxy (`…/api/eth-rpc`, eth_chainId) has said it serves the chain:
|
|
7
|
+
// module=account&action=txlist normal transactions
|
|
8
|
+
// module=account&action=txlistinternal ETH a contract sent (a withdrawal
|
|
9
|
+
// from an exchange's hot wallet contract, say)
|
|
10
|
+
// module=account&action=tokentx ERC-20 transfers
|
|
11
|
+
// module=account&action=balance / tokenbalance
|
|
12
|
+
// /api/v2/addresses/{address}/coin-balance-history the native coin's
|
|
13
|
+
// balance after each change, for the
|
|
14
|
+
// month balances of a statement (#287)
|
|
15
|
+
// Lists come oldest first, 1000 a page. Blockscout refuses page × offset
|
|
16
|
+
// beyond 10 000, so paging goes on by `startblock`: the next request starts
|
|
17
|
+
// at the last block seen, and what was seen twice is dropped.
|
|
18
|
+
//
|
|
19
|
+
// How a transaction becomes entries:
|
|
20
|
+
// - gas: every transaction this address sent costs gasUsed × gasPrice,
|
|
21
|
+
// also a failed one; an entry of its own (type fee). On rollups
|
|
22
|
+
// (Optimism, Base, Arbitrum) the L1 data fee is not in this API and is
|
|
23
|
+
// missing – see docs/wallets.md.
|
|
24
|
+
// - a failed transaction (isError 1 or txreceipt_status 0) moved nothing
|
|
25
|
+
// but its gas.
|
|
26
|
+
// - value out or in: an entry sent or received; to itself: none.
|
|
27
|
+
// - ERC-20: only the contracts listed for the chain, with the symbol and
|
|
28
|
+
// decimals from the list, never from the token (anyone can deploy a
|
|
29
|
+
// contract called "USDC"). Others are counted and left out as bookings,
|
|
30
|
+
// but a swap names them (below).
|
|
31
|
+
// - a swap (issue #115): in one transaction the wallet gives one asset and
|
|
32
|
+
// gets another – a token to a router and ETH back as an internal
|
|
33
|
+
// transfer, say. Its booked legs become kind `swap` and carry what went
|
|
34
|
+
// each way (`swap.gave`, `swap.got`: symbol, amount, and whether the
|
|
35
|
+
// token is a listed one – an unlisted symbol is the token's own claim)
|
|
36
|
+
// and the router it went through, and the gas it cost (the gas entry
|
|
37
|
+
// stays a fee of its own and names the swap). Known routers and WETH are named
|
|
38
|
+
// (registry.js KNOWN_EVM_CONTRACTS).
|
|
39
|
+
//
|
|
40
|
+
// The log gets counts, never an address.
|
|
41
|
+
//
|
|
42
|
+
// With an Alchemy key (`pnpm setup:alchemy`) and no endpoint of the wallet's
|
|
43
|
+
// own, the lists come from Alchemy instead (alchemy.js), in the same shape,
|
|
44
|
+
// and become entries here in the same way.
|
|
45
|
+
|
|
46
|
+
import { keccak_256 } from '@noble/hashes/sha3.js';
|
|
47
|
+
import { toHex, utf8 } from '@le-space/ledger/bytes';
|
|
48
|
+
|
|
49
|
+
import { KNOWN_EVM_CONTRACTS, addressUrl, txUrl } from './registry.js';
|
|
50
|
+
import { markSwaps } from './core.js';
|
|
51
|
+
import { createJsonFetcher, WalletError } from './http.js';
|
|
52
|
+
import { unitsToDecimal } from './cosmos.js';
|
|
53
|
+
import { alchemyBaseUrl, createAlchemyReader } from './alchemy.js';
|
|
54
|
+
|
|
55
|
+
/** Symbols an unlisted token may never be booked under: the big ones a fake would copy. */
|
|
56
|
+
const LOOKALIKE_GUARD = [
|
|
57
|
+
'ETH',
|
|
58
|
+
'WETH',
|
|
59
|
+
'USDC',
|
|
60
|
+
'USDT',
|
|
61
|
+
'DAI',
|
|
62
|
+
'WBTC',
|
|
63
|
+
'BTC',
|
|
64
|
+
'POL',
|
|
65
|
+
'MATIC',
|
|
66
|
+
'EURC'
|
|
67
|
+
];
|
|
68
|
+
|
|
69
|
+
const PAGE = 1000;
|
|
70
|
+
|
|
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
|
+
/** @param {unknown} v */
|
|
100
|
+
const bigintOf = (v) => (typeof v === 'string' && /^\d+$/.test(v) ? BigInt(v) : null);
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* @param {unknown} seconds
|
|
104
|
+
* @returns {string} ISO 8601
|
|
105
|
+
*/
|
|
106
|
+
function isoOf(seconds) {
|
|
107
|
+
const n = Number(seconds);
|
|
108
|
+
if (!Number.isFinite(n) || n <= 0)
|
|
109
|
+
throw new WalletError('a transfer without a time', 'WALLET_DATA');
|
|
110
|
+
return new Date(n * 1000).toISOString();
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* The three lists → entries of `address` (lower case).
|
|
115
|
+
*
|
|
116
|
+
* @param {object} lists
|
|
117
|
+
* @param {any[]} lists.normal
|
|
118
|
+
* @param {any[]} lists.internal
|
|
119
|
+
* @param {any[]} lists.tokens
|
|
120
|
+
* @param {Record<string, string>} [lists.senders] Alchemy: the sender of a transaction that moved
|
|
121
|
+
* this address's tokens out, where it was not this address (#162)
|
|
122
|
+
* @param {object} context
|
|
123
|
+
* @param {string} context.address lower case
|
|
124
|
+
* @param {import('./registry.js').EvmChain} context.chain
|
|
125
|
+
* @returns {{ entries: import('./cosmos.js').WalletEntry[], unknownTokens: string[] }}
|
|
126
|
+
*/
|
|
127
|
+
export function normalizeEvm({ normal, internal, tokens, senders = {} }, { address, chain }) {
|
|
128
|
+
// The transactions this address sent itself; a token that left in any other
|
|
129
|
+
// was moved by someone else – a burn by the token's project (issue #162).
|
|
130
|
+
/** @type {Set<string>} */
|
|
131
|
+
const ownSent = new Set(
|
|
132
|
+
normal
|
|
133
|
+
.filter((/** @type {any} */ r) => String(r.from ?? '').toLowerCase() === address)
|
|
134
|
+
.map((/** @type {any} */ r) => String(r.hash ?? '').toLowerCase())
|
|
135
|
+
);
|
|
136
|
+
/** @type {(import('./cosmos.js').WalletEntry & { order: string })[]} */
|
|
137
|
+
const entries = [];
|
|
138
|
+
/** @type {Set<string>} */
|
|
139
|
+
const unknownTokens = new Set();
|
|
140
|
+
const native = chain.native;
|
|
141
|
+
/** @type {Map<string, number>} token transfers without a log index, counted per same transfer */
|
|
142
|
+
const repeats = new Map();
|
|
143
|
+
/** @type {Map<string, string>} hash → the contract the wallet called */
|
|
144
|
+
const calledOf = new Map();
|
|
145
|
+
/** @type {{ hash: string, asset: string, amount: string, listed: false }[]} own moves of unlisted tokens */
|
|
146
|
+
const unlisted = [];
|
|
147
|
+
/** @param {string} address @param {string} [fallback] */
|
|
148
|
+
const known = (address, fallback = '') =>
|
|
149
|
+
Object.hasOwn(KNOWN_EVM_CONTRACTS, address) ? KNOWN_EVM_CONTRACTS[address] : fallback;
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Ids stay what they are whatever else the lists hold (an internal
|
|
153
|
+
* transaction indexed late, a token listed later): the gas `<hash>:fee`,
|
|
154
|
+
* the value of the transaction `<hash>:value`, an internal transfer
|
|
155
|
+
* `<hash>:internal:<index>`, a token transfer `<hash>:log:<logIndex>` – or,
|
|
156
|
+
* where the API gives no log index (Blockscout's tokentx),
|
|
157
|
+
* `<hash>:erc20:<contract>:<from>:<to>:<value>:<n>`.
|
|
158
|
+
*
|
|
159
|
+
* @param {any} raw
|
|
160
|
+
* @param {string} hash
|
|
161
|
+
* @param {string} order sorts the entries: block, position, kind
|
|
162
|
+
* @param {string} id
|
|
163
|
+
* @param {Omit<import('./cosmos.js').WalletEntry, 'id' | 'hash' | 'height' | 'time' | 'date' | 'explorerUrl' | 'memo'>} e
|
|
164
|
+
*/
|
|
165
|
+
const push = (raw, hash, order, id, e) => {
|
|
166
|
+
const time = isoOf(raw.timeStamp);
|
|
167
|
+
entries.push({
|
|
168
|
+
id,
|
|
169
|
+
hash,
|
|
170
|
+
height: Number(raw.blockNumber),
|
|
171
|
+
time,
|
|
172
|
+
date: time.slice(0, 10),
|
|
173
|
+
memo: '',
|
|
174
|
+
explorerUrl: txUrl(chain.explorer, hash),
|
|
175
|
+
order,
|
|
176
|
+
...e
|
|
177
|
+
});
|
|
178
|
+
};
|
|
179
|
+
const hashOf = (/** @type {any} */ raw) => {
|
|
180
|
+
const hash = String(raw?.hash ?? raw?.transactionHash ?? '').toLowerCase();
|
|
181
|
+
if (!/^0x[0-9a-f]{64}$/.test(hash)) {
|
|
182
|
+
throw new WalletError('a transaction without a hash', 'WALLET_DATA');
|
|
183
|
+
}
|
|
184
|
+
return hash;
|
|
185
|
+
};
|
|
186
|
+
const pad = (/** @type {unknown} */ n) => String(Number(n) || 0).padStart(12, '0');
|
|
187
|
+
|
|
188
|
+
for (const raw of normal) {
|
|
189
|
+
const hash = hashOf(raw);
|
|
190
|
+
const from = String(raw.from ?? '').toLowerCase();
|
|
191
|
+
const to = String(raw.to ?? '').toLowerCase();
|
|
192
|
+
const failed = raw.isError === '1' || raw.txreceipt_status === '0';
|
|
193
|
+
// Alchemy, a receipt from before Byzantium: no status, so no value; the gas was paid.
|
|
194
|
+
const unknown = raw.statusUnknown === true;
|
|
195
|
+
const order = `${pad(raw.blockNumber)}:${pad(raw.transactionIndex)}`;
|
|
196
|
+
if (from === address && !failed && to) calledOf.set(hash, to);
|
|
197
|
+
if (from === address) {
|
|
198
|
+
const gasUsed = bigintOf(raw.gasUsed);
|
|
199
|
+
const gasPrice = bigintOf(raw.gasPrice);
|
|
200
|
+
if (gasUsed === null || gasPrice === null) {
|
|
201
|
+
throw new WalletError('a transaction without gas figures', 'WALLET_DATA');
|
|
202
|
+
}
|
|
203
|
+
const fee = gasUsed * gasPrice;
|
|
204
|
+
if (fee > 0n) {
|
|
205
|
+
push(raw, hash, `${order}:0`, `${hash}:fee`, {
|
|
206
|
+
type: 'fee',
|
|
207
|
+
kind: 'fee',
|
|
208
|
+
asset: native.symbol,
|
|
209
|
+
amount: unitsToDecimal(-fee, native.decimals),
|
|
210
|
+
decimals: native.decimals,
|
|
211
|
+
counterparty: '',
|
|
212
|
+
counterpartyLabel: '',
|
|
213
|
+
success: !failed
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
const value = bigintOf(raw.value) ?? 0n;
|
|
218
|
+
if (failed || unknown || value === 0n || (from === address) === (to === address)) continue;
|
|
219
|
+
const out = from === address;
|
|
220
|
+
push(raw, hash, `${order}:1`, `${hash}:value`, {
|
|
221
|
+
type: out ? 'sent' : 'received',
|
|
222
|
+
kind: 'transfer',
|
|
223
|
+
asset: native.symbol,
|
|
224
|
+
amount: unitsToDecimal(out ? -value : value, native.decimals),
|
|
225
|
+
decimals: native.decimals,
|
|
226
|
+
counterparty: out ? to : from,
|
|
227
|
+
counterpartyLabel: known(out ? to : from),
|
|
228
|
+
success: true
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
for (const raw of internal) {
|
|
233
|
+
const hash = hashOf(raw);
|
|
234
|
+
const from = String(raw.from ?? '').toLowerCase();
|
|
235
|
+
const to = String(raw.to ?? '').toLowerCase();
|
|
236
|
+
const value = bigintOf(raw.value) ?? 0n;
|
|
237
|
+
if (raw.isError === '1' || value === 0n || (from === address) === (to === address)) continue;
|
|
238
|
+
const out = from === address;
|
|
239
|
+
const at = raw.index ?? raw.traceId;
|
|
240
|
+
// Alchemy names an internal transfer by its trace address, which is not
|
|
241
|
+
// Blockscout's index: a prefix of its own, so the two never collide.
|
|
242
|
+
const internalId = raw.alchemyTrace
|
|
243
|
+
? `${hash}:internal:trace:${raw.alchemyTrace}`
|
|
244
|
+
: at !== undefined && at !== ''
|
|
245
|
+
? `${hash}:internal:${at}`
|
|
246
|
+
: `${hash}:internal:${from}:${to}:${value}`;
|
|
247
|
+
push(
|
|
248
|
+
raw,
|
|
249
|
+
hash,
|
|
250
|
+
`${pad(raw.blockNumber)}:${pad(raw.transactionIndex)}:2:${pad(at)}`,
|
|
251
|
+
internalId,
|
|
252
|
+
{
|
|
253
|
+
type: out ? 'sent' : 'received',
|
|
254
|
+
kind: 'transfer',
|
|
255
|
+
asset: native.symbol,
|
|
256
|
+
amount: unitsToDecimal(out ? -value : value, native.decimals),
|
|
257
|
+
decimals: native.decimals,
|
|
258
|
+
counterparty: out ? to : from,
|
|
259
|
+
counterpartyLabel: known(out ? to : from, 'Vertrag (interne Transaktion)'),
|
|
260
|
+
success: true
|
|
261
|
+
}
|
|
262
|
+
);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// Tokens not in the list (issue #115): booked in an account of their own
|
|
266
|
+
// once the wallet has sent them itself – an airdrop it never touched is
|
|
267
|
+
// not booked. Never under a symbol that is a listed asset's or another
|
|
268
|
+
// token's already (a contract can call itself anything): those stay out.
|
|
269
|
+
const reserved = new Set([
|
|
270
|
+
native.symbol,
|
|
271
|
+
...Object.values(chain.tokens).map((t) => t.symbol),
|
|
272
|
+
...LOOKALIKE_GUARD
|
|
273
|
+
]);
|
|
274
|
+
/** @type {Map<string, { symbol: string, decimals: number }>} contract → how it is booked */
|
|
275
|
+
const used = new Map();
|
|
276
|
+
/** @type {Set<string>} */
|
|
277
|
+
const takenSymbols = new Set();
|
|
278
|
+
for (const raw of tokens) {
|
|
279
|
+
const contract = String(raw.contractAddress ?? '').toLowerCase();
|
|
280
|
+
if (Object.hasOwn(chain.tokens, contract) || used.has(contract)) continue;
|
|
281
|
+
if (String(raw.from ?? '').toLowerCase() !== address) continue;
|
|
282
|
+
const symbol = String(raw.tokenSymbol ?? '').toUpperCase();
|
|
283
|
+
const decimals = Number(raw.tokenDecimal);
|
|
284
|
+
if (
|
|
285
|
+
!/^[A-Z0-9]{2,10}$/.test(symbol) ||
|
|
286
|
+
reserved.has(symbol) ||
|
|
287
|
+
takenSymbols.has(symbol) ||
|
|
288
|
+
!Number.isInteger(decimals) ||
|
|
289
|
+
decimals < 0 ||
|
|
290
|
+
decimals > 36
|
|
291
|
+
) {
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
used.set(contract, { symbol, decimals });
|
|
295
|
+
takenSymbols.add(symbol);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
for (const raw of tokens) {
|
|
299
|
+
const hash = hashOf(raw);
|
|
300
|
+
const contract = String(raw.contractAddress ?? '').toLowerCase();
|
|
301
|
+
const listedToken = Object.hasOwn(chain.tokens, contract) ? chain.tokens[contract] : null;
|
|
302
|
+
const token = listedToken ?? used.get(contract) ?? null;
|
|
303
|
+
if (!token) {
|
|
304
|
+
unknownTokens.add(contract);
|
|
305
|
+
// Not booked, but a swap names it: symbol and decimals as the token
|
|
306
|
+
// says (unverified), only for a transfer from or to this wallet.
|
|
307
|
+
const from = String(raw.from ?? '').toLowerCase();
|
|
308
|
+
const to = String(raw.to ?? '').toLowerCase();
|
|
309
|
+
const value = bigintOf(raw.value) ?? 0n;
|
|
310
|
+
const decimals = Number(raw.tokenDecimal);
|
|
311
|
+
const symbol = String(raw.tokenSymbol ?? '')
|
|
312
|
+
.replace(/[^\p{L}\p{N}._-]/gu, '')
|
|
313
|
+
.slice(0, 12);
|
|
314
|
+
if (
|
|
315
|
+
value !== 0n &&
|
|
316
|
+
(from === address) !== (to === address) &&
|
|
317
|
+
Number.isInteger(decimals) &&
|
|
318
|
+
decimals >= 0 &&
|
|
319
|
+
decimals <= 36
|
|
320
|
+
) {
|
|
321
|
+
unlisted.push({
|
|
322
|
+
hash,
|
|
323
|
+
asset: symbol || '?',
|
|
324
|
+
amount: unitsToDecimal(from === address ? -value : value, decimals),
|
|
325
|
+
listed: false
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
const from = String(raw.from ?? '').toLowerCase();
|
|
331
|
+
const to = String(raw.to ?? '').toLowerCase();
|
|
332
|
+
const value = bigintOf(raw.value) ?? 0n;
|
|
333
|
+
if (value === 0n || (from === address) === (to === address)) continue;
|
|
334
|
+
const out = from === address;
|
|
335
|
+
let tokenId;
|
|
336
|
+
if (raw.logIndex !== undefined && raw.logIndex !== '') {
|
|
337
|
+
tokenId = `${hash}:log:${raw.logIndex}`;
|
|
338
|
+
} else {
|
|
339
|
+
const same = `${hash}:erc20:${contract}:${from}:${to}:${value}`;
|
|
340
|
+
const n = repeats.get(same) ?? 0;
|
|
341
|
+
repeats.set(same, n + 1);
|
|
342
|
+
tokenId = `${same}:${n}`;
|
|
343
|
+
}
|
|
344
|
+
push(
|
|
345
|
+
raw,
|
|
346
|
+
hash,
|
|
347
|
+
`${pad(raw.blockNumber)}:${pad(raw.transactionIndex)}:3:${pad(raw.logIndex ?? raw.position)}`,
|
|
348
|
+
tokenId,
|
|
349
|
+
{
|
|
350
|
+
type: out ? 'sent' : 'received',
|
|
351
|
+
kind: 'transfer',
|
|
352
|
+
asset: token.symbol,
|
|
353
|
+
amount: unitsToDecimal(out ? -value : value, token.decimals),
|
|
354
|
+
decimals: token.decimals,
|
|
355
|
+
counterparty: out ? to : from,
|
|
356
|
+
counterpartyLabel: known(out ? to : from),
|
|
357
|
+
success: true,
|
|
358
|
+
// Sent out in a transaction this address did not send: who did, where known.
|
|
359
|
+
...(out && !ownSent.has(hash)
|
|
360
|
+
? { byOther: true, ...(senders[hash] ? { txFrom: senders[hash] } : {}) }
|
|
361
|
+
: {}),
|
|
362
|
+
// Not in the list: priced by its contract, marked as the token's own claim.
|
|
363
|
+
...(listedToken ? {} : { contract, listed: false })
|
|
364
|
+
}
|
|
365
|
+
);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
markSwaps(entries, unlisted, (hash) => {
|
|
369
|
+
const called = calledOf.get(hash) ?? '';
|
|
370
|
+
return called ? known(called) : '';
|
|
371
|
+
});
|
|
372
|
+
|
|
373
|
+
entries.sort((a, b) => (a.order < b.order ? -1 : a.order > b.order ? 1 : 0));
|
|
374
|
+
const result = entries.map(({ order: _order, ...e }) => e);
|
|
375
|
+
return { entries: result, unknownTokens: [...unknownTokens] };
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* @param {object} [options]
|
|
380
|
+
* @param {typeof fetch} [options.fetch]
|
|
381
|
+
* @param {number} [options.timeoutMs]
|
|
382
|
+
* @param {number} [options.maxPages] per list
|
|
383
|
+
* @param {(ms: number) => Promise<void>} [options.sleep]
|
|
384
|
+
* @param {object} [options.alchemy]
|
|
385
|
+
* @param {() => Promise<string | null>} options.alchemy.key the key, or null when none is set up
|
|
386
|
+
* @param {(network: string) => string} [options.alchemy.baseUrl] tests: a fake on 127.0.0.1
|
|
387
|
+
* @param {number} [options.alchemy.maxHiddenBlocks]
|
|
388
|
+
* @param {number} [options.alchemy.computeUnitsPerSecond]
|
|
389
|
+
* @param {() => number} [options.alchemy.now] tests: a clock that `sleep` moves
|
|
390
|
+
*/
|
|
391
|
+
export function createEvmClient({
|
|
392
|
+
fetch: f = fetch,
|
|
393
|
+
timeoutMs,
|
|
394
|
+
maxPages = 50,
|
|
395
|
+
sleep,
|
|
396
|
+
alchemy
|
|
397
|
+
} = {}) {
|
|
398
|
+
const alchemyReader = createAlchemyReader({
|
|
399
|
+
fetch: f,
|
|
400
|
+
timeoutMs,
|
|
401
|
+
sleep,
|
|
402
|
+
maxPages,
|
|
403
|
+
maxHiddenBlocks: alchemy?.maxHiddenBlocks,
|
|
404
|
+
computeUnitsPerSecond: alchemy?.computeUnitsPerSecond,
|
|
405
|
+
now: alchemy?.now
|
|
406
|
+
});
|
|
407
|
+
const getJson = createJsonFetcher({
|
|
408
|
+
fetch: f,
|
|
409
|
+
timeoutMs,
|
|
410
|
+
sleep,
|
|
411
|
+
retries: 3
|
|
412
|
+
});
|
|
413
|
+
/** Blockscout says "rate limit" in a 200 as well. */
|
|
414
|
+
const limited = (/** @type {any} */ b) =>
|
|
415
|
+
b?.status === '0' && /rate limit|too many/i.test(`${b?.message ?? ''} ${b?.result ?? ''}`);
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* @param {string} api
|
|
419
|
+
* @param {Record<string, string>} params
|
|
420
|
+
*/
|
|
421
|
+
async function call(api, params) {
|
|
422
|
+
const body = await getJson(`${api}?${new URLSearchParams(params)}`, {}, { retryIf: limited });
|
|
423
|
+
if (body?.status === '1' || body?.status === '2') return body.result;
|
|
424
|
+
const message = String(body?.message ?? '');
|
|
425
|
+
if (/no (transactions|token transfers|internal transactions|records) found/i.test(message))
|
|
426
|
+
return [];
|
|
427
|
+
if (/invalid address/i.test(message)) {
|
|
428
|
+
throw new WalletError('the API refused the address', 'WALLET_ADDRESS', 400);
|
|
429
|
+
}
|
|
430
|
+
// Only the API's words: no address or hash (0x…) goes into a message, which the bridge logs.
|
|
431
|
+
const words = message.replace(/0x[0-9a-fA-F]{8,}/g, '0x…').slice(0, 80);
|
|
432
|
+
throw new WalletError(`the API answered: ${words || 'no result'}`, 'WALLET_NODE');
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* The API belongs to the chain it is meant for: Blockscout's JSON-RPC
|
|
437
|
+
* proxy (`…/api/eth-rpc`) names its chain id, as a Cosmos node names its
|
|
438
|
+
* network. Another chain, or no answer to that question, and nothing is read.
|
|
439
|
+
*
|
|
440
|
+
* @param {string} api
|
|
441
|
+
* @param {import('./registry.js').EvmChain} chain
|
|
442
|
+
*/
|
|
443
|
+
async function checkChain(api, chain) {
|
|
444
|
+
let body;
|
|
445
|
+
try {
|
|
446
|
+
body = await getJson(`${api}/eth-rpc`, {
|
|
447
|
+
method: 'POST',
|
|
448
|
+
headers: { 'content-type': 'application/json' },
|
|
449
|
+
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_chainId', params: [] })
|
|
450
|
+
});
|
|
451
|
+
} catch (/** @type {any} */ error) {
|
|
452
|
+
if (error?.code !== 'WALLET_NODE') throw error;
|
|
453
|
+
body = null;
|
|
454
|
+
}
|
|
455
|
+
const id =
|
|
456
|
+
typeof body?.result === 'string' && /^0x[0-9a-f]+$/i.test(body.result)
|
|
457
|
+
? BigInt(body.result)
|
|
458
|
+
: null;
|
|
459
|
+
if (id === null) {
|
|
460
|
+
throw new WalletError(
|
|
461
|
+
'the API does not say which chain it serves (no eth_chainId at …/api/eth-rpc)',
|
|
462
|
+
'WALLET_CHAIN_UNVERIFIED'
|
|
463
|
+
);
|
|
464
|
+
}
|
|
465
|
+
if (id !== BigInt(chain.chainId)) {
|
|
466
|
+
throw new WalletError(
|
|
467
|
+
`the API serves chain ${id}, not ${chain.name} (${chain.chainId})`,
|
|
468
|
+
'WALLET_WRONG_CHAIN',
|
|
469
|
+
400
|
|
470
|
+
);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/**
|
|
475
|
+
* @param {string} api
|
|
476
|
+
* @param {string} action
|
|
477
|
+
* @param {string} address
|
|
478
|
+
* @param {(raw: any, counts: Map<string, number>) => string} keyOf `counts` is per page:
|
|
479
|
+
* pages overlap by a block, and what repeats there must get the same key
|
|
480
|
+
*/
|
|
481
|
+
async function list(api, action, address, keyOf) {
|
|
482
|
+
/** @type {Map<string, any>} */
|
|
483
|
+
const seen = new Map();
|
|
484
|
+
let startblock = 0;
|
|
485
|
+
for (let page = 0; ; page++) {
|
|
486
|
+
if (page >= maxPages) {
|
|
487
|
+
throw new WalletError(`more than ${maxPages * PAGE} ${action} entries`, 'WALLET_TOO_MANY');
|
|
488
|
+
}
|
|
489
|
+
const batch = await call(api, {
|
|
490
|
+
module: 'account',
|
|
491
|
+
action,
|
|
492
|
+
address,
|
|
493
|
+
startblock: String(startblock),
|
|
494
|
+
endblock: '999999999',
|
|
495
|
+
page: '1',
|
|
496
|
+
offset: String(PAGE),
|
|
497
|
+
sort: 'asc'
|
|
498
|
+
});
|
|
499
|
+
if (!Array.isArray(batch)) throw new WalletError(`${action} without a list`, 'WALLET_NODE');
|
|
500
|
+
const before = seen.size;
|
|
501
|
+
/** @type {Map<string, number>} */
|
|
502
|
+
const counts = new Map();
|
|
503
|
+
for (const raw of batch) seen.set(keyOf(raw, counts), raw);
|
|
504
|
+
if (batch.length < PAGE) break;
|
|
505
|
+
const last = Number(batch[batch.length - 1]?.blockNumber);
|
|
506
|
+
// A full page that brought nothing new: one block holds more than a page.
|
|
507
|
+
if (seen.size === before || !Number.isSafeInteger(last)) {
|
|
508
|
+
throw new WalletError(
|
|
509
|
+
`${action}: more entries in one block than a page`,
|
|
510
|
+
'WALLET_TOO_MANY'
|
|
511
|
+
);
|
|
512
|
+
}
|
|
513
|
+
startblock = last;
|
|
514
|
+
}
|
|
515
|
+
return [...seen.values()];
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* The native coin's balance after each change (#287), from Blockscout's own
|
|
520
|
+
* API (`/api/v2/addresses/{address}/coin-balance-history`), newest first,
|
|
521
|
+
* paged by `next_page_params`. A source of its own, independent of the
|
|
522
|
+
* transaction lists: it carries what they lack, a rollup's L1 data fee
|
|
523
|
+
* say. Where the API has no such endpoint or refuses, there is none – not
|
|
524
|
+
* an error.
|
|
525
|
+
*
|
|
526
|
+
* @param {string} api the Etherscan-compatible base, `…/api`
|
|
527
|
+
* @param {string} address lower case
|
|
528
|
+
* @returns {Promise<{ time: string, value: string }[] | null>} oldest first; value in units
|
|
529
|
+
*/
|
|
530
|
+
async function coinBalanceHistory(api, address) {
|
|
531
|
+
/** @type {{ time: string, value: string }[]} */
|
|
532
|
+
const points = [];
|
|
533
|
+
/** @type {Record<string, string> | null} */
|
|
534
|
+
let next = {};
|
|
535
|
+
try {
|
|
536
|
+
for (let page = 0; next; page++) {
|
|
537
|
+
if (page >= maxPages) return null;
|
|
538
|
+
const query = new URLSearchParams(next).toString();
|
|
539
|
+
/** @type {any} */
|
|
540
|
+
const body = await getJson(
|
|
541
|
+
`${api.replace(/\/+$/, '')}/v2/addresses/${address}/coin-balance-history${query ? `?${query}` : ''}`
|
|
542
|
+
);
|
|
543
|
+
if (!Array.isArray(body?.items)) return null;
|
|
544
|
+
for (const item of body.items) {
|
|
545
|
+
const value = String(item?.value ?? '');
|
|
546
|
+
const time = String(item?.block_timestamp ?? '');
|
|
547
|
+
if (!/^\d+$/.test(value) || Number.isNaN(Date.parse(time))) return null;
|
|
548
|
+
points.push({ time: new Date(time).toISOString(), value });
|
|
549
|
+
}
|
|
550
|
+
next =
|
|
551
|
+
body.next_page_params && typeof body.next_page_params === 'object'
|
|
552
|
+
? Object.fromEntries(
|
|
553
|
+
Object.entries(body.next_page_params).map(([k, v]) => [k, String(v)])
|
|
554
|
+
)
|
|
555
|
+
: null;
|
|
556
|
+
}
|
|
557
|
+
} catch {
|
|
558
|
+
return null;
|
|
559
|
+
}
|
|
560
|
+
return points.sort((a, b) => a.time.localeCompare(b.time));
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/** @param {any} r */
|
|
564
|
+
const internalKey = (r) =>
|
|
565
|
+
`${String(r.transactionHash ?? r.hash).toLowerCase()}:${r.index ?? r.traceId ?? ''}:${r.from}:${r.to}:${r.value}`;
|
|
566
|
+
|
|
567
|
+
return {
|
|
568
|
+
/**
|
|
569
|
+
* @param {object} params
|
|
570
|
+
* @param {import('./registry.js').EvmChain} params.chain
|
|
571
|
+
* @param {string} params.address
|
|
572
|
+
* @param {{ api: string }} params.endpoints already checked
|
|
573
|
+
* @param {boolean} [params.ownEndpoint] the wallet names its own API: that one is asked,
|
|
574
|
+
* never Alchemy
|
|
575
|
+
*/
|
|
576
|
+
async history({ chain, address, endpoints, ownEndpoint = false }) {
|
|
577
|
+
if (!isEvmAddress(address)) {
|
|
578
|
+
throw new WalletError(
|
|
579
|
+
'not an EVM address (0x and 40 hex digits; mixed case must match its EIP-55 checksum)',
|
|
580
|
+
'WALLET_ADDRESS',
|
|
581
|
+
400
|
|
582
|
+
);
|
|
583
|
+
}
|
|
584
|
+
const lower = address.toLowerCase();
|
|
585
|
+
const key = chain.alchemy && !ownEndpoint && alchemy ? await alchemy.key() : null;
|
|
586
|
+
if (key) {
|
|
587
|
+
const network = /** @type {import('./registry.js').AlchemyNetwork} */ (chain.alchemy);
|
|
588
|
+
const read = await alchemyReader.read({
|
|
589
|
+
chain,
|
|
590
|
+
address: lower,
|
|
591
|
+
key,
|
|
592
|
+
baseUrl: (alchemy?.baseUrl ?? alchemyBaseUrl)(network.network),
|
|
593
|
+
// Arbitrum and Optimism: Alchemy has no internal transfers there.
|
|
594
|
+
blockscoutInternal: network.internal
|
|
595
|
+
? undefined
|
|
596
|
+
: async () => {
|
|
597
|
+
await checkChain(endpoints.api, chain);
|
|
598
|
+
return list(endpoints.api, 'txlistinternal', lower, internalKey);
|
|
599
|
+
}
|
|
600
|
+
});
|
|
601
|
+
const { entries, unknownTokens } = normalizeEvm(read, { address: lower, chain });
|
|
602
|
+
/** @type {{ asset: string, amount: string, decimals: number }[]} */
|
|
603
|
+
const balances = [];
|
|
604
|
+
for (const [what, units] of read.balances) {
|
|
605
|
+
const asset = what === 'native' ? chain.native : chain.tokens[what];
|
|
606
|
+
balances.push({
|
|
607
|
+
asset: asset.symbol,
|
|
608
|
+
amount: unitsToDecimal(units, asset.decimals),
|
|
609
|
+
decimals: asset.decimals
|
|
610
|
+
});
|
|
611
|
+
}
|
|
612
|
+
return {
|
|
613
|
+
source: /** @type {const} */ ('alchemy'),
|
|
614
|
+
internalSource: network.internal ? 'alchemy' : 'blockscout',
|
|
615
|
+
entries,
|
|
616
|
+
balances,
|
|
617
|
+
transactions: new Set(entries.map((e) => e.hash)).size,
|
|
618
|
+
unknownAssets: unknownTokens.length,
|
|
619
|
+
// transactions whose receipt has no status (before Byzantium): gas booked, value not
|
|
620
|
+
unknownStatus: read.unknownStatus,
|
|
621
|
+
history: { earliestHeight: 0, earliestTime: null, pruned: false },
|
|
622
|
+
addressUrl: addressUrl(chain.explorer, address)
|
|
623
|
+
};
|
|
624
|
+
}
|
|
625
|
+
await checkChain(endpoints.api, chain);
|
|
626
|
+
const normal = await list(endpoints.api, 'txlist', lower, (r) =>
|
|
627
|
+
String(r.hash).toLowerCase()
|
|
628
|
+
);
|
|
629
|
+
const internal = await list(endpoints.api, 'txlistinternal', lower, internalKey);
|
|
630
|
+
const tokens = await list(endpoints.api, 'tokentx', lower, (r, occurrences) => {
|
|
631
|
+
if (r.logIndex !== undefined && r.logIndex !== '') {
|
|
632
|
+
return `${String(r.hash).toLowerCase()}:${r.logIndex}`;
|
|
633
|
+
}
|
|
634
|
+
// No log index in this API's answer: the same transfer twice in one
|
|
635
|
+
// transaction is told apart by its order.
|
|
636
|
+
const base = `${String(r.hash).toLowerCase()}:${r.contractAddress}:${r.from}:${r.to}:${r.value}`;
|
|
637
|
+
const n = occurrences.get(base) ?? 0;
|
|
638
|
+
occurrences.set(base, n + 1);
|
|
639
|
+
return `${base}:${n}`;
|
|
640
|
+
});
|
|
641
|
+
const { entries, unknownTokens } = normalizeEvm(
|
|
642
|
+
{ normal, internal, tokens },
|
|
643
|
+
{ address: lower, chain }
|
|
644
|
+
);
|
|
645
|
+
|
|
646
|
+
const nativeBalance = bigintOf(
|
|
647
|
+
await call(endpoints.api, { module: 'account', action: 'balance', address: lower })
|
|
648
|
+
);
|
|
649
|
+
/** @type {{ asset: string, amount: string, decimals: number }[]} */
|
|
650
|
+
const balances = [];
|
|
651
|
+
if (nativeBalance !== null) {
|
|
652
|
+
balances.push({
|
|
653
|
+
asset: chain.native.symbol,
|
|
654
|
+
amount: unitsToDecimal(nativeBalance, chain.native.decimals),
|
|
655
|
+
decimals: chain.native.decimals
|
|
656
|
+
});
|
|
657
|
+
}
|
|
658
|
+
for (const [contract, token] of Object.entries(chain.tokens)) {
|
|
659
|
+
const amount = bigintOf(
|
|
660
|
+
await call(endpoints.api, {
|
|
661
|
+
module: 'account',
|
|
662
|
+
action: 'tokenbalance',
|
|
663
|
+
contractaddress: contract,
|
|
664
|
+
address: lower
|
|
665
|
+
})
|
|
666
|
+
);
|
|
667
|
+
if (amount !== null) {
|
|
668
|
+
balances.push({
|
|
669
|
+
asset: token.symbol,
|
|
670
|
+
amount: unitsToDecimal(amount, token.decimals),
|
|
671
|
+
decimals: token.decimals
|
|
672
|
+
});
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
const history = await coinBalanceHistory(endpoints.api, lower);
|
|
676
|
+
return {
|
|
677
|
+
source: /** @type {const} */ ('blockscout'),
|
|
678
|
+
entries,
|
|
679
|
+
balances,
|
|
680
|
+
// The native coin's balance after each change, from the explorer (#287).
|
|
681
|
+
...(history
|
|
682
|
+
? {
|
|
683
|
+
balanceHistory: [
|
|
684
|
+
{ asset: chain.native.symbol, decimals: chain.native.decimals, points: history }
|
|
685
|
+
]
|
|
686
|
+
}
|
|
687
|
+
: {}),
|
|
688
|
+
transactions: new Set(entries.map((e) => e.hash)).size,
|
|
689
|
+
unknownAssets: unknownTokens.length,
|
|
690
|
+
history: { earliestHeight: 0, earliestTime: null, pruned: false },
|
|
691
|
+
addressUrl: addressUrl(chain.explorer, address)
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
};
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
export { markSwaps };
|