@le-space/chains 0.0.0-stage → 0.2.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/src/cosmos.js ADDED
@@ -0,0 +1,591 @@
1
+ // A Cosmos SDK wallet, read only, by its address: every transfer in or out,
2
+ // the fees it paid, and its balance. Nyx (Nym) first; any chain in
3
+ // registry.js with kind `cosmos`.
4
+ //
5
+ // Where the data comes from:
6
+ // - CometBFT RPC `tx_search` (JSON-RPC over POST), twice: once for
7
+ // `transfer.sender='<address>'` and once for `transfer.recipient='…'`,
8
+ // 100 a page, oldest first, until `total_count`; merged by hash. A send,
9
+ // a fee, a reward are `transfer` events; a delegation is not (see below),
10
+ // but it pays its fee with one, so the first query finds it too. A failed
11
+ // transaction still paid its fee.
12
+ // - `header?height=` for the time of each block (cached per height).
13
+ // - `status` for the oldest block the node still has: a pruned node does
14
+ // not know older transactions, and the sync says so instead of
15
+ // pretending the wallet was empty.
16
+ // - REST `/cosmos/bank/v1beta1/balances/<address>` for the balance.
17
+ // - the transaction's bytes for its memo (protobuf.js).
18
+ //
19
+ // How a transaction becomes entries:
20
+ // - the fee: the `tx` event's `fee` and `fee_payer` (cosmos-sdk ≥ 0.46),
21
+ // else the fee from the transaction's AuthInfo and the sender of the
22
+ // transfer to the fee collector. It is an entry of its own, only when
23
+ // this address paid it, and the transfer to the fee collector is not
24
+ // counted a second time.
25
+ // - a failed transaction (code ≠ 0) moved nothing but the fee.
26
+ // - every other `transfer` event from or to the address, one entry per
27
+ // coin, with the other side as counterparty. Several messages in one
28
+ // transaction give several entries. A transfer to itself is none.
29
+ // Events of cosmos-sdk < 0.47 that pack several transfers into one
30
+ // event, and base64-encoded attributes (CometBFT 0.34), are read too.
31
+ // - a delegation: the bank keeper's DelegateCoins spends from the address
32
+ // and credits the bonded pool with `coin_spent` and `coin_received` but
33
+ // no `transfer` (issue #135). Such a pair that no transfer follows is a
34
+ // movement too. Chains older than cosmos-sdk 0.44 have no `coin_spent`;
35
+ // there the `delegate` event says it, its amount maybe without a denom.
36
+ // - the other side named when it is a module: rewards come from
37
+ // `distribution`, a delegation goes to `bonded_tokens_pool`; an IBC
38
+ // transfer names its receiver on the other chain.
39
+ // Denoms that are not in the chain's list (IBC vouchers `ibc/…`, factory
40
+ // tokens) are counted and left out.
41
+ //
42
+ // Not seen: tokens that come back when an unbonding ends (the chain does
43
+ // that in its end-block, not in a transaction) and vesting. The balance
44
+ // shows them; the difference is for a person to look at.
45
+ //
46
+ // The log gets counts, never an address.
47
+
48
+ import { fromBase64, fromUtf8 } from '@le-space/ledger/bytes';
49
+ import { isCosmosAddress, moduleAddress } from './bech32.js';
50
+ import { decodeTx } from './protobuf.js';
51
+ import { addressUrl, createJsonFetcher, txUrl, unitsToDecimal, WalletError } from './core.js';
52
+
53
+ /** Module accounts a transfer may go to or come from, and how they are named. */
54
+ const MODULES = /** @type {const} */ ({
55
+ fee_collector: 'Gebührensammler der Chain',
56
+ distribution: 'Staking-Belohnungen (distribution)',
57
+ bonded_tokens_pool: 'Staking (gebunden)',
58
+ not_bonded_tokens_pool: 'Staking (ungebunden)',
59
+ gov: 'Governance-Einlage',
60
+ mint: 'Neu geprägt (mint)',
61
+ // Akash: deployments' escrow, and burn-mint (BME) – AKT burnt for ACT, the
62
+ // compute credit deployments are paid in, and back.
63
+ escrow: 'Akash-Escrow (Deployment)',
64
+ bme: 'Akash BME (AKT ↔ ACT)'
65
+ });
66
+
67
+ /** How an unlisted denom is named in a swap's text: `uact` → `ACT`. @param {string} denom */
68
+ export const denomLabel = (denom) =>
69
+ /^u[a-z]{2,10}$/.test(denom) ? denom.slice(1).toUpperCase() : denom.slice(0, 20);
70
+
71
+ /**
72
+ * A swap with the BME module (Akash burn-mint): what the wallet gave and got
73
+ * in one transaction, one side a listed asset and the other usually ACT,
74
+ * which is not listed. The listed legs become kind `swap`, as on the EVM
75
+ * chains (evm.js markSwaps), and the fee names it. Changes the entries in place.
76
+ *
77
+ * @param {WalletEntry[]} entries one transaction's
78
+ * @param {{ asset: string, amount: string, listed: false }[]} unlisted its unlisted moves, signed
79
+ * @param {string} via
80
+ */
81
+ export function markBmeSwap(entries, unlisted, via) {
82
+ const legs = entries.filter((e) => e.kind === 'transfer');
83
+ const side = (/** @type {boolean} */ out) => [
84
+ ...legs
85
+ .filter((e) => e.amount.startsWith('-') === out)
86
+ .map((e) => ({ asset: e.asset, amount: e.amount.replace(/^-/, ''), listed: true })),
87
+ ...unlisted
88
+ .filter((u) => u.amount.startsWith('-') === out)
89
+ .map((u) => ({ asset: u.asset, amount: u.amount.replace(/^-/, ''), listed: false }))
90
+ ];
91
+ const gave = side(true);
92
+ const got = side(false);
93
+ if (!legs.length || !gave.length || !got.length) return;
94
+ if (got.every((g) => gave.some((x) => x.asset === g.asset))) return;
95
+ const gas = entries.find((e) => e.type === 'fee');
96
+ const swap = {
97
+ gave,
98
+ got,
99
+ via,
100
+ ...(gas ? { fee: { asset: gas.asset, amount: gas.amount.replace(/^-/, '') } } : {})
101
+ };
102
+ for (const e of legs) {
103
+ e.kind = 'swap';
104
+ e.swap = swap;
105
+ }
106
+ if (gas) gas.swap = swap;
107
+ }
108
+
109
+ const PER_PAGE = 100;
110
+ const COIN = /^(\d+)([a-zA-Z][a-zA-Z0-9/:._-]{1,127})$/;
111
+
112
+ /** @typedef {import('@le-space/ledger/wallet-entry').WalletEntry} WalletEntry */
113
+
114
+ /**
115
+ * `1500unym,20unyx` → coins; null when it does not parse.
116
+ *
117
+ * @param {string} text
118
+ * @returns {{ denom: string, amount: bigint }[] | null}
119
+ */
120
+ export function parseCoins(text) {
121
+ if (typeof text !== 'string') return null;
122
+ if (!text.trim()) return [];
123
+ /** @type {{ denom: string, amount: bigint }[]} */
124
+ const coins = [];
125
+ for (const part of text.split(',')) {
126
+ const m = COIN.exec(part.trim());
127
+ if (!m) return null;
128
+ coins.push({ denom: m[2], amount: BigInt(m[1]) });
129
+ }
130
+ return coins;
131
+ }
132
+
133
+ export { unitsToDecimal };
134
+
135
+ /**
136
+ * CometBFT 0.34 hands out event keys and values in base64; 0.37 and later
137
+ * as text. Keys are short lower-case words, so text keys tell.
138
+ *
139
+ * @param {any[]} events
140
+ * @returns {{ type: string, attributes: { key: string, value: string }[] }[]}
141
+ */
142
+ export function readEvents(events) {
143
+ const list = Array.isArray(events) ? events : [];
144
+ const keys = list.flatMap((e) => (Array.isArray(e?.attributes) ? e.attributes : []));
145
+ const plain = keys.every((a) => typeof a?.key === 'string' && /^[a-z_.]+$/.test(a.key));
146
+ const read = (/** @type {unknown} */ v) =>
147
+ typeof v !== 'string' ? '' : plain ? v : fromUtf8(fromBase64(v));
148
+ return list.map((e) => ({
149
+ type: String(e?.type ?? ''),
150
+ attributes: (Array.isArray(e?.attributes) ? e.attributes : []).map((/** @type {any} */ a) => ({
151
+ key: read(a?.key),
152
+ value: read(a?.value)
153
+ }))
154
+ }));
155
+ }
156
+
157
+ /**
158
+ * The transfers of a transaction's events: `{ sender, recipient, amount }`,
159
+ * with where they stand – the event's index in the transaction and the
160
+ * triple's within the event – so an entry keeps its id however the rest of
161
+ * the transaction is read. One event may hold several (cosmos-sdk < 0.47); a
162
+ * triple ends with its amount.
163
+ *
164
+ * @param {ReturnType<typeof readEvents>} events
165
+ */
166
+ export function transfersOf(events) {
167
+ /** @type {{ sender: string, recipient: string, amount: string, msgIndex: string | null, event: number, part: number }[]} */
168
+ const out = [];
169
+ events.forEach((event, index) => {
170
+ if (event.type !== 'transfer') return;
171
+ /** @type {Record<string, string>} */
172
+ let current = {};
173
+ let part = 0;
174
+ const msgIndex = event.attributes.find((a) => a.key === 'msg_index')?.value ?? null;
175
+ for (const { key, value } of event.attributes) {
176
+ if (key === 'recipient' || key === 'sender') current[key] = value;
177
+ if (key === 'amount') {
178
+ out.push({
179
+ sender: current.sender ?? '',
180
+ recipient: current.recipient ?? '',
181
+ amount: value,
182
+ msgIndex,
183
+ event: index,
184
+ part: part++
185
+ });
186
+ current = {};
187
+ }
188
+ }
189
+ });
190
+ return out;
191
+ }
192
+
193
+ /**
194
+ * Movements the bank keeper made without a `transfer` event – a delegation
195
+ * (DelegateCoins) – in the same shape as `transfersOf`: a `coin_spent`
196
+ * followed by a `coin_received` of the same amount, and then no `transfer`
197
+ * (a send, a fee, a reward are followed by theirs). Without any `coin_spent`
198
+ * in the transaction (cosmos-sdk < 0.44) the `delegate` events instead, the
199
+ * delegator named in the event or as the staking message's only sender.
200
+ *
201
+ * @param {ReturnType<typeof readEvents>} events
202
+ * @param {{ nativeDenom: string, bonded: string }} chain
203
+ */
204
+ export function untransferredOf(events, { nativeDenom, bonded }) {
205
+ /** @type {ReturnType<typeof transfersOf>} */
206
+ const out = [];
207
+ const value = (/** @type {typeof events[number] | undefined} */ e, /** @type {string} */ key) =>
208
+ e?.attributes.find((a) => a.key === key)?.value;
209
+ if (events.some((e) => e.type === 'coin_spent')) {
210
+ events.forEach((spent, index) => {
211
+ const received = events[index + 1];
212
+ if (spent.type !== 'coin_spent' || received?.type !== 'coin_received') return;
213
+ if (events[index + 2]?.type === 'transfer') return;
214
+ const amount = value(spent, 'amount') ?? '';
215
+ if (!amount || value(received, 'amount') !== amount) return;
216
+ out.push({
217
+ sender: value(spent, 'spender') ?? '',
218
+ recipient: value(received, 'receiver') ?? '',
219
+ amount,
220
+ msgIndex: value(spent, 'msg_index') ?? null,
221
+ event: index,
222
+ part: 0
223
+ });
224
+ });
225
+ return out;
226
+ }
227
+ const stakingSenders = [
228
+ ...new Set(
229
+ events
230
+ .filter((e) => e.type === 'message' && value(e, 'module') === 'staking')
231
+ .flatMap((e) => e.attributes.filter((a) => a.key === 'sender').map((a) => a.value))
232
+ )
233
+ ];
234
+ events.forEach((e, index) => {
235
+ if (e.type !== 'delegate') return;
236
+ const delegator =
237
+ value(e, 'delegator') ?? (stakingSenders.length === 1 ? stakingSenders[0] : '');
238
+ const raw = value(e, 'amount') ?? '';
239
+ if (!delegator || !raw) return;
240
+ out.push({
241
+ sender: delegator,
242
+ recipient: bonded,
243
+ amount: /^\d+$/.test(raw) ? `${raw}${nativeDenom}` : raw,
244
+ msgIndex: value(e, 'msg_index') ?? null,
245
+ event: index,
246
+ part: 0
247
+ });
248
+ });
249
+ return out;
250
+ }
251
+
252
+ /**
253
+ * One transaction from tx_search → the entries of `address`.
254
+ *
255
+ * @param {any} raw an item of `result.txs`
256
+ * @param {object} context
257
+ * @param {string} context.address
258
+ * @param {import('./cosmos-chains.js').CosmosChain} context.chain
259
+ * @param {string} context.time ISO 8601 of its block
260
+ * @returns {{ entries: WalletEntry[], unknownDenoms: string[] }}
261
+ */
262
+ export function normalizeCosmosTx(raw, { address, chain, time }) {
263
+ const hash = String(raw?.hash ?? '').toUpperCase();
264
+ if (!/^[0-9A-F]{64}$/.test(hash))
265
+ throw new WalletError('a transaction without a hash', 'WALLET_DATA');
266
+ const height = Number(raw?.height);
267
+ const code = Number(raw?.tx_result?.code ?? 0);
268
+ const events = readEvents(raw?.tx_result?.events);
269
+ const decoded = decodeTx(raw?.tx);
270
+ const memo = decoded?.memo ?? '';
271
+ const feeCollector = moduleAddress(chain.bech32Prefix, 'fee_collector');
272
+ /** @type {Map<string, string>} */
273
+ const modules = new Map(
274
+ Object.entries(MODULES).map(([name, label]) => [moduleAddress(chain.bech32Prefix, name), label])
275
+ );
276
+ const pools = {
277
+ distribution: moduleAddress(chain.bech32Prefix, 'distribution'),
278
+ bonded: moduleAddress(chain.bech32Prefix, 'bonded_tokens_pool'),
279
+ notBonded: moduleAddress(chain.bech32Prefix, 'not_bonded_tokens_pool')
280
+ };
281
+ const explorerUrl = txUrl(chain.explorer, hash);
282
+ const date = time.slice(0, 10);
283
+ /** @type {WalletEntry[]} */
284
+ const entries = [];
285
+ /** @type {string[]} */
286
+ const unknownDenoms = [];
287
+ /** @type {{ asset: string, amount: string, listed: false }[]} moves of unlisted denoms (a BME swap's ACT) */
288
+ const unlisted = [];
289
+ const bme = moduleAddress(chain.bech32Prefix, 'bme');
290
+ let withBme = false;
291
+
292
+ const txEvent = (/** @type {string} */ key) =>
293
+ events
294
+ .find((e) => e.type === 'tx' && e.attributes.some((a) => a.key === key))
295
+ ?.attributes.find((a) => a.key === key)?.value;
296
+
297
+ let transfers = transfersOf(events);
298
+ // The fee and who paid it. The fee transfer is the ante handler's: to the
299
+ // fee collector, outside any message (no msg_index), from the payer the
300
+ // `tx` event names – recognised by where it stands, not by its amount
301
+ // text, which need not be spelt as the fee is.
302
+ const namedPayer = txEvent('fee_payer') ?? null;
303
+ const feeTransfer = transfers.find(
304
+ (t) =>
305
+ t.recipient === feeCollector &&
306
+ t.msgIndex === null &&
307
+ (namedPayer === null || t.sender === namedPayer)
308
+ );
309
+ const payer = namedPayer ?? feeTransfer?.sender ?? '';
310
+ if (feeTransfer) transfers = transfers.filter((t) => t !== feeTransfer);
311
+ const feeText =
312
+ txEvent('fee') ??
313
+ ((decoded?.fee ?? []).map((c) => `${c.amount}${c.denom}`).join(',') ||
314
+ feeTransfer?.amount ||
315
+ '');
316
+ const feeCoins = parseCoins(feeText) ?? [];
317
+
318
+ /**
319
+ * Ids that stay what they are when the rest of the transaction is read
320
+ * differently (a denom listed later, another entry found): the fee
321
+ * `<hash>:fee` (in another denom than the chain's own `<hash>:fee:<asset>`),
322
+ * a transfer `<hash>:m<msg_index>:e<event>.<triple>:<asset>`.
323
+ *
324
+ * @param {string} id
325
+ * @param {Omit<WalletEntry, 'id' | 'hash' | 'height' | 'time' | 'date' | 'explorerUrl' | 'memo'>} e
326
+ */
327
+ const push = (id, e) => {
328
+ entries.push({ id, hash, height, time, date, memo, explorerUrl, ...e });
329
+ };
330
+
331
+ /** @param {{ denom: string, amount: bigint }} coin */
332
+ const assetOf = (coin) => {
333
+ const asset = Object.hasOwn(chain.denoms, coin.denom) ? chain.denoms[coin.denom] : null;
334
+ if (!asset) unknownDenoms.push(coin.denom);
335
+ return asset;
336
+ };
337
+
338
+ if (payer === address) {
339
+ for (const coin of feeCoins) {
340
+ const asset = assetOf(coin);
341
+ if (!asset || coin.amount === 0n) continue;
342
+ push(coin.denom === chain.nativeDenom ? `${hash}:fee` : `${hash}:fee:${asset.symbol}`, {
343
+ type: 'fee',
344
+ kind: 'fee',
345
+ asset: asset.symbol,
346
+ amount: unitsToDecimal(-coin.amount, asset.decimals),
347
+ decimals: asset.decimals,
348
+ counterparty: '',
349
+ counterpartyLabel: '',
350
+ success: code === 0
351
+ });
352
+ }
353
+ }
354
+ if (code !== 0) return { entries, unknownDenoms };
355
+
356
+ const ibcEvent = events.find((e) => e.type === 'ibc_transfer');
357
+ const ibcReceiver = ibcEvent?.attributes.find((a) => a.key === 'receiver')?.value ?? '';
358
+ // The IBC message's own memo (MsgTransfer.memo, in the event too) – where a
359
+ // wallet's swap puts its plan; the transaction's memo stays empty (#170).
360
+ const ibcMemo = ibcEvent?.attributes.find((a) => a.key === 'memo')?.value ?? '';
361
+ for (const t of [
362
+ ...transfers,
363
+ ...untransferredOf(events, { nativeDenom: chain.nativeDenom, bonded: pools.bonded })
364
+ ]) {
365
+ const out = t.sender === address;
366
+ const into = t.recipient === address;
367
+ if (out === into) continue; // not ours, or to itself
368
+ const other = out ? t.recipient : t.sender;
369
+ const label = modules.get(other) ?? '';
370
+ const coins = parseCoins(t.amount);
371
+ if (!coins) throw new WalletError('a transfer amount that does not parse', 'WALLET_DATA');
372
+ const kind =
373
+ !out && other === pools.distribution
374
+ ? 'reward'
375
+ : other === pools.bonded || other === pools.notBonded
376
+ ? 'stake'
377
+ : out && ibcReceiver && !label
378
+ ? 'ibc'
379
+ : 'transfer';
380
+ if (other === bme) withBme = true;
381
+ for (const coin of coins) {
382
+ const asset = assetOf(coin);
383
+ if (!asset && coin.amount > 0n) {
384
+ unlisted.push({
385
+ asset: denomLabel(coin.denom),
386
+ amount: unitsToDecimal(out ? -coin.amount : coin.amount, 6),
387
+ listed: false
388
+ });
389
+ }
390
+ if (!asset || coin.amount === 0n) continue;
391
+ push(`${hash}:m${t.msgIndex ?? 'x'}:e${t.event}.${t.part}:${asset.symbol}`, {
392
+ type: out ? 'sent' : 'received',
393
+ kind,
394
+ asset: asset.symbol,
395
+ amount: unitsToDecimal(out ? -coin.amount : coin.amount, asset.decimals),
396
+ decimals: asset.decimals,
397
+ counterparty: kind === 'ibc' ? ibcReceiver : other,
398
+ counterpartyLabel: kind === 'ibc' ? 'IBC-Transfer' : label,
399
+ ...(kind === 'ibc' && ibcMemo ? { ibcMemo: ibcMemo.slice(0, 20_000) } : {}),
400
+ success: true
401
+ });
402
+ }
403
+ }
404
+ if (withBme) markBmeSwap(entries, unlisted, MODULES.bme);
405
+ return { entries, unknownDenoms };
406
+ }
407
+
408
+ /**
409
+ * @param {object} [options]
410
+ * @param {typeof fetch} [options.fetch]
411
+ * @param {number} [options.timeoutMs]
412
+ * @param {number} [options.maxPages] per query; beyond that the sync stops with an error
413
+ * @param {(ms: number) => Promise<void>} [options.sleep]
414
+ */
415
+ export function createCosmosClient({ fetch: f = fetch, timeoutMs, maxPages = 200, sleep } = {}) {
416
+ const getJson = createJsonFetcher({ fetch: f, timeoutMs, sleep });
417
+
418
+ /**
419
+ * @param {string} rpc
420
+ * @param {string} method
421
+ * @param {Record<string, string | boolean>} params CometBFT: integers as strings, bools as bools
422
+ */
423
+ async function rpcCall(rpc, method, params) {
424
+ const body = await getJson(
425
+ `${rpc}/`,
426
+ {
427
+ method: 'POST',
428
+ headers: { 'content-type': 'application/json' },
429
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params })
430
+ },
431
+ // "Internal error" with a timeout inside is a busy node, not a bad question.
432
+ { retryIf: (b) => /timed out|timeout|too many/i.test(String(b?.error?.data ?? '')) }
433
+ );
434
+ if (body?.error) {
435
+ // A message may quote the query, and with it the address: bech32 strings go.
436
+ const detail = String(body.error.data ?? body.error.message ?? '')
437
+ .replace(/[a-z]{1,20}1[02-9ac-hj-np-z]{20,}/gi, '…')
438
+ .slice(0, 120);
439
+ throw new WalletError(`the node refused ${method}: ${detail}`, 'WALLET_RPC');
440
+ }
441
+ if (!body || typeof body !== 'object' || !('result' in body)) {
442
+ throw new WalletError(`the node answered ${method} without a result`, 'WALLET_RPC');
443
+ }
444
+ return body.result;
445
+ }
446
+
447
+ return {
448
+ /**
449
+ * @param {object} params
450
+ * @param {import('./cosmos-chains.js').CosmosChain} params.chain
451
+ * @param {string} params.address
452
+ * @param {{ rpc: string, rest: string }} params.endpoints already checked
453
+ */
454
+ async history({ chain, address, endpoints }) {
455
+ if (!isCosmosAddress(address, chain.bech32Prefix)) {
456
+ throw new WalletError(
457
+ `not a ${chain.name} address (bech32, prefix ${chain.bech32Prefix}1…)`,
458
+ 'WALLET_ADDRESS',
459
+ 400
460
+ );
461
+ }
462
+ const status = await rpcCall(endpoints.rpc, 'status', {});
463
+ const network = String(status?.node_info?.network ?? '');
464
+ if (network !== chain.chainId) {
465
+ throw new WalletError(
466
+ `the node belongs to chain "${network.slice(0, 40)}", not ${chain.chainId}`,
467
+ 'WALLET_WRONG_CHAIN',
468
+ 400
469
+ );
470
+ }
471
+ // `/status` is not to be trusted here: a node restored from a snapshot
472
+ // says 0 and still refuses old blocks. Asking for block 1 tells: "height 1
473
+ // is not available, lowest height is N" (issue #105).
474
+ let earliestHeight = Number(status?.sync_info?.earliest_block_height ?? 0);
475
+ let earliestTime = String(status?.sync_info?.earliest_block_time ?? '') || null;
476
+ if (earliestHeight <= 1) {
477
+ try {
478
+ await rpcCall(endpoints.rpc, 'header', { height: '1' });
479
+ earliestHeight = 1;
480
+ } catch (/** @type {any} */ error) {
481
+ const lowest = /lowest height is (\d+)/.exec(String(error?.message ?? ''));
482
+ if (lowest) {
483
+ earliestHeight = Number(lowest[1]);
484
+ earliestTime = null;
485
+ }
486
+ }
487
+ }
488
+
489
+ /** @type {Map<string, any>} */
490
+ const txs = new Map();
491
+ for (const key of ['transfer.sender', 'transfer.recipient']) {
492
+ for (let page = 1; ; page++) {
493
+ if (page > maxPages) {
494
+ throw new WalletError(
495
+ `more than ${maxPages * PER_PAGE} transactions; not synchronised`,
496
+ 'WALLET_TOO_MANY'
497
+ );
498
+ }
499
+ const result = await rpcCall(endpoints.rpc, 'tx_search', {
500
+ query: `${key}='${address}'`,
501
+ // CometBFT's JSON-RPC takes integers as strings, but a bool must be a
502
+ // JSON bool: "false" is refused ("cannot unmarshal string into Go
503
+ // value of type bool").
504
+ prove: false,
505
+ page: String(page),
506
+ per_page: String(PER_PAGE),
507
+ order_by: 'asc'
508
+ });
509
+ const batch = Array.isArray(result?.txs) ? result.txs : [];
510
+ for (const tx of batch) txs.set(String(tx.hash).toUpperCase(), tx);
511
+ const total = Number(result?.total_count ?? 0);
512
+ if (!batch.length || page * PER_PAGE >= total) break;
513
+ }
514
+ }
515
+
516
+ /** @type {Map<number, string>} */
517
+ const times = new Map();
518
+ const timeOf = async (/** @type {number} */ height) => {
519
+ const known = times.get(height);
520
+ if (known) return known;
521
+ let header;
522
+ try {
523
+ header = (await rpcCall(endpoints.rpc, 'header', { height: String(height) }))?.header;
524
+ } catch {
525
+ header = (await rpcCall(endpoints.rpc, 'block', { height: String(height) }))?.block
526
+ ?.header;
527
+ }
528
+ const time = Date.parse(String(header?.time ?? ''));
529
+ if (Number.isNaN(time)) {
530
+ throw new WalletError(`no time for block ${height}`, 'WALLET_DATA');
531
+ }
532
+ const iso = new Date(time).toISOString();
533
+ times.set(height, iso);
534
+ return iso;
535
+ };
536
+
537
+ /** @type {WalletEntry[]} */
538
+ const entries = [];
539
+ /** @type {Set<string>} */
540
+ const unknown = new Set();
541
+ const ordered = [...txs.values()].sort(
542
+ (a, b) => Number(a.height) - Number(b.height) || Number(a.index ?? 0) - Number(b.index ?? 0)
543
+ );
544
+ for (const raw of ordered) {
545
+ const height = Number(raw.height);
546
+ if (!Number.isSafeInteger(height) || height <= 0) {
547
+ throw new WalletError('a transaction without a height', 'WALLET_DATA');
548
+ }
549
+ const result = normalizeCosmosTx(raw, { address, chain, time: await timeOf(height) });
550
+ entries.push(...result.entries);
551
+ for (const d of result.unknownDenoms) unknown.add(d);
552
+ }
553
+
554
+ const bank = await getJson(
555
+ `${endpoints.rest}/cosmos/bank/v1beta1/balances/${encodeURIComponent(address)}?pagination.limit=1000`
556
+ );
557
+ if (!Array.isArray(bank?.balances)) {
558
+ throw new WalletError('the REST API answered the balance without balances', 'WALLET_NODE');
559
+ }
560
+ const balances = bank.balances.flatMap((/** @type {any} */ b) => {
561
+ const asset = Object.hasOwn(chain.denoms, b?.denom) ? chain.denoms[b.denom] : null;
562
+ if (!asset || !/^\d+$/.test(String(b.amount))) return [];
563
+ return [
564
+ {
565
+ asset: asset.symbol,
566
+ amount: unitsToDecimal(BigInt(b.amount), asset.decimals),
567
+ decimals: asset.decimals
568
+ }
569
+ ];
570
+ });
571
+
572
+ if (earliestHeight > 1 && !earliestTime) {
573
+ earliestTime = await timeOf(earliestHeight).catch(() => null);
574
+ }
575
+
576
+ return {
577
+ entries,
578
+ balances,
579
+ transactions: txs.size,
580
+ unknownAssets: unknown.size,
581
+ history: {
582
+ earliestHeight,
583
+ earliestTime,
584
+ // A node that starts after block 1 has forgotten older transactions.
585
+ pruned: earliestHeight > 1
586
+ },
587
+ addressUrl: addressUrl(chain.explorer, address)
588
+ };
589
+ }
590
+ };
591
+ }