@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.
@@ -0,0 +1,650 @@
1
+ // Fake Cosmos services on 127.0.0.1 for tests: a Cosmos node (CometBFT
2
+ // JSON-RPC `status`, `tx_search`, `header`, and the REST balance) and the
3
+ // Akash Console indexer. Every address, hash and amount here is made up:
4
+ // addresses are derived from test phrases, hashes from counters.
5
+ import http from 'node:http';
6
+ import { createHash } from 'node:crypto';
7
+
8
+ import { bech32Encode, moduleAddress } from '../../src/bech32.js';
9
+ import { encodeTx } from '../../src/protobuf.js';
10
+
11
+ /** A synthetic bech32 address: the first 20 bytes of SHA-256 of a phrase. */
12
+ export const fakeCosmosAddress = (/** @type {string} */ phrase, prefix = 'n') =>
13
+ bech32Encode(
14
+ prefix,
15
+ createHash('sha256').update(`belege test ${phrase}`).digest().subarray(0, 20)
16
+ );
17
+
18
+ /** A synthetic 32-byte hash, upper-case hex (Cosmos) or 0x-lower (EVM). */
19
+ export const fakeHash = (/** @type {string} */ seed, evm = false) => {
20
+ const hex = createHash('sha256').update(`belege test tx ${seed}`).digest('hex');
21
+ return evm ? `0x${hex}` : hex.toUpperCase();
22
+ };
23
+
24
+ /** The addresses the samples use. */
25
+ export const NYX = {
26
+ wallet: fakeCosmosAddress('wallet'),
27
+ exchange: fakeCosmosAddress('exchange hot wallet'),
28
+ friend: fakeCosmosAddress('someone else'),
29
+ feeCollector: moduleAddress('n', 'fee_collector'),
30
+ distribution: moduleAddress('n', 'distribution'),
31
+ bonded: moduleAddress('n', 'bonded_tokens_pool')
32
+ };
33
+
34
+ /**
35
+ * One transaction as tx_search hands it out (cosmos-sdk 0.53, CometBFT 0.38).
36
+ *
37
+ * @param {object} t
38
+ * @param {string} t.seed makes the hash
39
+ * @param {number} t.height
40
+ * @param {number} [t.code] 0 = success
41
+ * @param {string} [t.memo]
42
+ * @param {{ payer: string, amount: string } | null} [t.fee] e.g. { payer, amount: '5000unym' }
43
+ * @param {{ sender: string, recipient: string, amount: string }[]} [t.transfers] one per message
44
+ * @param {string} [t.ibcReceiver] an IBC transfer's receiver on the other chain
45
+ * @param {string} [t.ibcMemo] the IBC message's own memo, as ibc-go puts it into the event
46
+ * @param {boolean} [t.legacyEvents] cosmos-sdk < 0.47 with CometBFT 0.34: one transfer
47
+ * event holding every triple, base64 keys and values, no fee event
48
+ * @param {boolean} [t.coinEvents] also the bank keeper's coin_spent / coin_received before each transfer, as real chains emit them
49
+ * @param {{ delegator: string, amount: string, validator?: string }[]} [t.delegations] MsgDelegate, one message each, after the transfers
50
+ * @param {string} [t.prefix] the chain's bech32 prefix, for its fee collector
51
+ */
52
+ export function cosmosTx({
53
+ seed,
54
+ height,
55
+ code = 0,
56
+ memo = '',
57
+ fee = null,
58
+ transfers = [],
59
+ ibcReceiver,
60
+ ibcMemo,
61
+ legacyEvents = false,
62
+ coinEvents = false,
63
+ delegations = [],
64
+ prefix = 'n'
65
+ }) {
66
+ /** @type {{ type: string, attributes: { key: string, value: string, index?: boolean }[] }[]} */
67
+ const events = [];
68
+ const attr = (/** @type {string} */ key, /** @type {string} */ value) => ({
69
+ key,
70
+ value,
71
+ index: true
72
+ });
73
+ if (fee) {
74
+ events.push({
75
+ type: 'transfer',
76
+ attributes: [
77
+ attr('recipient', moduleAddress(prefix, 'fee_collector')),
78
+ attr('sender', fee.payer),
79
+ attr('amount', fee.amount)
80
+ ]
81
+ });
82
+ if (!legacyEvents) {
83
+ events.push({
84
+ type: 'tx',
85
+ attributes: [attr('fee', fee.amount), attr('fee_payer', fee.payer)]
86
+ });
87
+ }
88
+ }
89
+ if (code === 0) {
90
+ if (legacyEvents && transfers.length) {
91
+ events.push({
92
+ type: 'transfer',
93
+ attributes: transfers.flatMap((t) => [
94
+ attr('recipient', t.recipient),
95
+ attr('sender', t.sender),
96
+ attr('amount', t.amount)
97
+ ])
98
+ });
99
+ } else {
100
+ transfers.forEach((t, i) => {
101
+ events.push({
102
+ type: 'message',
103
+ attributes: [attr('sender', t.sender), attr('msg_index', String(i))]
104
+ });
105
+ // The bank keeper's own events, before the transfer they belong to.
106
+ if (coinEvents) {
107
+ events.push({
108
+ type: 'coin_spent',
109
+ attributes: [
110
+ attr('spender', t.sender),
111
+ attr('amount', t.amount),
112
+ attr('msg_index', String(i))
113
+ ]
114
+ });
115
+ events.push({
116
+ type: 'coin_received',
117
+ attributes: [
118
+ attr('receiver', t.recipient),
119
+ attr('amount', t.amount),
120
+ attr('msg_index', String(i))
121
+ ]
122
+ });
123
+ }
124
+ events.push({
125
+ type: 'transfer',
126
+ attributes: [
127
+ attr('recipient', t.recipient),
128
+ attr('sender', t.sender),
129
+ attr('amount', t.amount),
130
+ attr('msg_index', String(i))
131
+ ]
132
+ });
133
+ });
134
+ }
135
+ // A delegation: the bank keeper's DelegateCoins spends and credits the
136
+ // bonded pool without a transfer event (cosmos-sdk ≥ 0.44). Before that,
137
+ // only the `delegate` event, its amount without a denom.
138
+ delegations.forEach((d, n) => {
139
+ const i = String(transfers.length + n);
140
+ const denom = d.amount.replace(/^\d+/, '');
141
+ if (!legacyEvents) {
142
+ events.push({
143
+ type: 'coin_spent',
144
+ attributes: [attr('spender', d.delegator), attr('amount', d.amount), attr('msg_index', i)]
145
+ });
146
+ events.push({
147
+ type: 'coin_received',
148
+ attributes: [
149
+ attr('receiver', moduleAddress(prefix, 'bonded_tokens_pool')),
150
+ attr('amount', d.amount),
151
+ attr('msg_index', i)
152
+ ]
153
+ });
154
+ }
155
+ events.push({
156
+ type: 'delegate',
157
+ attributes: [
158
+ attr('validator', d.validator ?? `${prefix}valoper1example`),
159
+ ...(legacyEvents ? [] : [attr('delegator', d.delegator)]),
160
+ attr('amount', legacyEvents ? d.amount.slice(0, -denom.length || undefined) : d.amount),
161
+ ...(legacyEvents ? [] : [attr('msg_index', i)])
162
+ ]
163
+ });
164
+ if (legacyEvents) {
165
+ events.push({
166
+ type: 'message',
167
+ attributes: [
168
+ attr('action', 'delegate'),
169
+ attr('module', 'staking'),
170
+ attr('sender', d.delegator)
171
+ ]
172
+ });
173
+ }
174
+ });
175
+ if (ibcReceiver) {
176
+ events.push({
177
+ type: 'ibc_transfer',
178
+ attributes: [attr('receiver', ibcReceiver), ...(ibcMemo ? [attr('memo', ibcMemo)] : [])]
179
+ });
180
+ }
181
+ }
182
+ const b64 = (/** @type {string} */ s) => Buffer.from(s).toString('base64');
183
+ return {
184
+ hash: fakeHash(seed),
185
+ height: String(height),
186
+ index: 0,
187
+ tx: encodeTx({
188
+ memo,
189
+ messageTypes: [
190
+ ...transfers.map(() => '/cosmos.bank.v1beta1.MsgSend'),
191
+ ...delegations.map(() => '/cosmos.staking.v1beta1.MsgDelegate')
192
+ ],
193
+ fee: fee
194
+ ? [{ denom: fee.amount.replace(/^\d+/, ''), amount: fee.amount.match(/^\d+/)?.[0] ?? '0' }]
195
+ : []
196
+ }),
197
+ tx_result: {
198
+ code,
199
+ log: code ? 'out of gas' : '',
200
+ events: legacyEvents
201
+ ? events.map((e) => ({
202
+ type: e.type,
203
+ attributes: e.attributes.map((a) => ({ key: b64(a.key), value: b64(a.value) }))
204
+ }))
205
+ : events
206
+ }
207
+ };
208
+ }
209
+
210
+ /** Block heights → times: one block a minute from a made-up start. */
211
+ export const blockTime = (/** @type {number} */ height) =>
212
+ new Date(Date.parse('2026-09-01T00:00:00Z') + (height - 1000) * 60_000).toISOString();
213
+
214
+ /**
215
+ * A made-up history of NYX.wallet: bought on an exchange and withdrawn to
216
+ * the wallet, sent on, a failed send, a delegation with its reward, an IBC
217
+ * voucher, a multi-message send, a transaction from the old event format,
218
+ * and many small incoming ones, so tx_search needs more than one page.
219
+ *
220
+ * @param {object} [options]
221
+ * @param {number} [options.filler] how many small incoming ones
222
+ * @param {(height: number) => string} [options.time]
223
+ */
224
+ export function sampleNyxHistory({ filler = 110 } = {}) {
225
+ const w = NYX.wallet;
226
+ const fee = (/** @type {string} */ amount) => ({ payer: w, amount });
227
+ const txs = [
228
+ // The exchange withdraws 250 NYM to the wallet; the exchange pays the fee.
229
+ cosmosTx({
230
+ seed: 'withdrawal',
231
+ height: 1000,
232
+ memo: 'Test-Memo Auszahlung',
233
+ fee: { payer: NYX.exchange, amount: '4000unym' },
234
+ transfers: [{ sender: NYX.exchange, recipient: w, amount: '250000000unym' }]
235
+ }),
236
+ // The wallet sends 12.5 NYM to someone and pays 5000 unym fee.
237
+ cosmosTx({
238
+ seed: 'send',
239
+ height: 2000,
240
+ memo: 'Rechnung Test 1',
241
+ fee: fee('5000unym'),
242
+ transfers: [{ sender: w, recipient: NYX.friend, amount: '12500000unym' }]
243
+ }),
244
+ // A failed send: only the fee leaves.
245
+ cosmosTx({
246
+ seed: 'failed',
247
+ height: 2100,
248
+ code: 5,
249
+ fee: fee('3000unym'),
250
+ transfers: [{ sender: w, recipient: NYX.friend, amount: '999000000unym' }]
251
+ }),
252
+ // A delegation, with the rewards withdrawn in the same transaction.
253
+ cosmosTx({
254
+ seed: 'delegate',
255
+ height: 2200,
256
+ fee: fee('6000unym'),
257
+ transfers: [
258
+ { sender: NYX.distribution, recipient: w, amount: '1234567unym' },
259
+ { sender: w, recipient: NYX.bonded, amount: '100000000unym' }
260
+ ]
261
+ }),
262
+ // An IBC voucher arrives next to NYX: the voucher is not booked.
263
+ cosmosTx({
264
+ seed: 'ibc-in',
265
+ height: 2300,
266
+ fee: { payer: NYX.friend, amount: '2000unym' },
267
+ transfers: [
268
+ { sender: NYX.friend, recipient: w, amount: '7000000ibc/ABCDEF0123456789,2000000unyx' }
269
+ ]
270
+ }),
271
+ // Two sends in one transaction.
272
+ cosmosTx({
273
+ seed: 'multi',
274
+ height: 2400,
275
+ memo: 'Zwei Empfänger',
276
+ fee: fee('8000unym'),
277
+ transfers: [
278
+ { sender: w, recipient: NYX.friend, amount: '1000000unym' },
279
+ { sender: w, recipient: NYX.exchange, amount: '2000000unym' }
280
+ ]
281
+ }),
282
+ // A fee-only transaction (a vote, say): nothing moves but the fee.
283
+ cosmosTx({ seed: 'fee-only', height: 2500, fee: fee('1500unym') }),
284
+ // The old format: base64 attributes, triples in one event, no fee event.
285
+ cosmosTx({
286
+ seed: 'legacy',
287
+ height: 2600,
288
+ fee: fee('2500unym'),
289
+ legacyEvents: true,
290
+ transfers: [{ sender: NYX.friend, recipient: w, amount: '3000000unym' }]
291
+ }),
292
+ // To itself: nothing but the fee.
293
+ cosmosTx({
294
+ seed: 'self',
295
+ height: 2700,
296
+ fee: fee('1000unym'),
297
+ transfers: [{ sender: w, recipient: w, amount: '5000000unym' }]
298
+ })
299
+ ];
300
+ for (let i = 0; i < filler; i++) {
301
+ txs.push(
302
+ cosmosTx({
303
+ seed: `filler-${i}`,
304
+ height: 3000 + i,
305
+ fee: { payer: NYX.friend, amount: '1000unym' },
306
+ transfers: [{ sender: NYX.friend, recipient: w, amount: '1000unym' }]
307
+ })
308
+ );
309
+ }
310
+ return txs;
311
+ }
312
+
313
+ /**
314
+ * @param {object} [options]
315
+ * @param {string} [options.network] the chain id `status` names
316
+ * @param {any[]} [options.txs]
317
+ * @param {Record<string, { denom: string, amount: string }[]>} [options.balances]
318
+ * @param {number} [options.earliestHeight]
319
+ * @param {boolean} [options.statusSaysZero] `status` claims 0 though older blocks are gone (a node restored from a snapshot)
320
+ * @param {number} [options.failFirst] this many requests answer 503 first
321
+ * @param {(height: number) => string} [options.time]
322
+ * @param {any[]} [options.deployments] Akash: deployments as the node lists them (akashDeployment)
323
+ */
324
+ export async function startFakeCosmos({
325
+ network = 'nyx',
326
+ txs = sampleNyxHistory(),
327
+ balances = {
328
+ [NYX.wallet]: [
329
+ { denom: 'unym', amount: '137000000' },
330
+ { denom: 'unyx', amount: '2000000' },
331
+ { denom: 'ibc/ABCDEF0123456789', amount: '7000000' }
332
+ ]
333
+ },
334
+ earliestHeight = 1,
335
+ statusSaysZero = false,
336
+ failFirst = 0,
337
+ time = blockTime,
338
+ deployments = []
339
+ } = {}) {
340
+ /** @type {{ method: string, params: any }[]} */
341
+ const calls = [];
342
+ let failing = failFirst;
343
+ const server = http.createServer((req, res) => {
344
+ let raw = '';
345
+ req.on('data', (c) => (raw += c));
346
+ req.on('end', () => {
347
+ const reply = (/** @type {number} */ status, /** @type {unknown} */ body) => {
348
+ res.writeHead(status, { 'Content-Type': 'application/json' });
349
+ res.end(JSON.stringify(body));
350
+ };
351
+ if (failing > 0) {
352
+ failing--;
353
+ res.writeHead(503, { 'Content-Type': 'text/html' });
354
+ return res.end('<html>busy</html>');
355
+ }
356
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1');
357
+ const bank = /^\/cosmos\/bank\/v1beta1\/balances\/([^/]+)$/.exec(url.pathname);
358
+ if (req.method === 'GET' && bank) {
359
+ calls.push({ method: 'balances', params: {} });
360
+ return reply(200, {
361
+ balances: balances[decodeURIComponent(bank[1])] ?? [],
362
+ pagination: { next_key: null, total: '0' }
363
+ });
364
+ }
365
+ // Akash: an owner's deployments with their escrow (#305).
366
+ if (req.method === 'GET' && url.pathname === '/akash/deployment/v1beta4/deployments/list') {
367
+ const owner = url.searchParams.get('filters.owner');
368
+ const mine = deployments.filter((/** @type {any} */ d) => d.deployment.id.owner === owner);
369
+ return reply(200, {
370
+ deployments: mine,
371
+ pagination: { next_key: null, total: String(mine.length) }
372
+ });
373
+ }
374
+ if (req.method !== 'POST') return reply(404, { code: 5, message: 'not found' });
375
+ /** @type {any} */ let body;
376
+ try {
377
+ body = JSON.parse(raw);
378
+ } catch {
379
+ return reply(200, {
380
+ jsonrpc: '2.0',
381
+ id: -1,
382
+ error: { code: -32700, message: 'Parse error' }
383
+ });
384
+ }
385
+ const { method, params = {} } = body;
386
+ calls.push({ method, params });
387
+ const ok = (/** @type {unknown} */ result) =>
388
+ reply(200, { jsonrpc: '2.0', id: body.id, result });
389
+ if (method === 'status') {
390
+ return ok({
391
+ node_info: { network, version: '0.38.17' },
392
+ sync_info: {
393
+ earliest_block_height: statusSaysZero ? '0' : String(earliestHeight),
394
+ earliest_block_time: statusSaysZero
395
+ ? '1970-01-01T00:00:00Z'
396
+ : time(Math.max(earliestHeight, 1000)),
397
+ latest_block_height: '99999'
398
+ }
399
+ });
400
+ }
401
+ if (method === 'header') {
402
+ if (Number(params.height) < earliestHeight) {
403
+ return reply(200, {
404
+ jsonrpc: '2.0',
405
+ id: body.id,
406
+ error: {
407
+ code: -32603,
408
+ message: 'Internal error',
409
+ data: `height ${params.height} is not available, lowest height is ${earliestHeight}`
410
+ }
411
+ });
412
+ }
413
+ return ok({ header: { height: String(params.height), time: time(Number(params.height)) } });
414
+ }
415
+ if (method === 'tx_search') {
416
+ // As strict as CometBFT 0.38: `prove` a JSON bool, page and per_page
417
+ // integers or strings of digits.
418
+ const badParam =
419
+ ('prove' in params && typeof params.prove !== 'boolean') ||
420
+ ['page', 'per_page'].some(
421
+ (k) => k in params && !(Number.isInteger(params[k]) || /^\d+$/.test(String(params[k])))
422
+ );
423
+ if (badParam) {
424
+ return reply(200, {
425
+ jsonrpc: '2.0',
426
+ id: body.id,
427
+ error: {
428
+ code: -32602,
429
+ message: 'Invalid params',
430
+ data: 'error converting json params to arguments: json: cannot unmarshal string into Go value of type bool'
431
+ }
432
+ });
433
+ }
434
+ const m = /^(transfer\.sender|transfer\.recipient)='([a-z0-9]+)'$/.exec(
435
+ String(params.query)
436
+ );
437
+ if (!m) {
438
+ return reply(200, {
439
+ jsonrpc: '2.0',
440
+ id: body.id,
441
+ error: { code: -32603, message: 'Internal error', data: `bad query ${params.query}` }
442
+ });
443
+ }
444
+ const [, key, who] = m;
445
+ const attr = key === 'transfer.sender' ? 'sender' : 'recipient';
446
+ const b64 = (/** @type {string} */ s) => Buffer.from(s).toString('base64');
447
+ const matching = txs.filter(
448
+ (tx) =>
449
+ Number(tx.height) >= earliestHeight &&
450
+ tx.tx_result.events.some(
451
+ (/** @type {any} */ e) =>
452
+ (e.type === 'transfer' || e.type === b64('transfer')) &&
453
+ e.attributes.some(
454
+ (/** @type {any} */ a) =>
455
+ (a.key === attr && a.value === who) ||
456
+ (a.key === b64(attr) && a.value === b64(who))
457
+ )
458
+ )
459
+ );
460
+ const perPage = Math.min(Number(params.per_page ?? 30), 100);
461
+ const page = Number(params.page ?? 1);
462
+ const sorted = [...matching].sort((a, b) =>
463
+ params.order_by === 'desc' ? b.height - a.height : a.height - b.height
464
+ );
465
+ return ok({
466
+ txs: sorted.slice((page - 1) * perPage, page * perPage),
467
+ total_count: String(matching.length)
468
+ });
469
+ }
470
+ return reply(200, {
471
+ jsonrpc: '2.0',
472
+ id: body.id,
473
+ error: { code: -32601, message: 'Method not found' }
474
+ });
475
+ });
476
+ });
477
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(undefined)));
478
+ const { port } = /** @type {import('node:net').AddressInfo} */ (server.address());
479
+ const url = `http://127.0.0.1:${port}`;
480
+ return {
481
+ url,
482
+ endpoints: { rpc: url, rest: url },
483
+ calls,
484
+ close: () =>
485
+ new Promise((resolve) => {
486
+ server.close(() => resolve(undefined));
487
+ server.closeAllConnections?.();
488
+ })
489
+ };
490
+ }
491
+
492
+ /** The addresses and contracts the EVM samples use. */
493
+ /**
494
+ * One transaction as the Akash Console indexer's `/v1/transactions/<hash>`
495
+ * hands it out, and its row in an address's list.
496
+ *
497
+ * @param {object} t
498
+ * @param {string} t.seed makes the hash
499
+ * @param {number} t.height
500
+ * @param {string[]} t.signers the first pays the fee
501
+ * @param {number} [t.fee] uakt
502
+ * @param {boolean} [t.success]
503
+ * @param {{ type: string, data: Record<string, unknown> }[]} [t.messages] type without its package, e.g. `MsgSend`
504
+ */
505
+ export function consoleTx({ seed, height, signers, fee = 0, success = true, messages = [] }) {
506
+ const packages = /** @type {Record<string, string>} */ ({
507
+ MsgSend: '/cosmos.bank.v1beta1.',
508
+ MsgMultiSend: '/cosmos.bank.v1beta1.',
509
+ MsgDelegate: '/cosmos.staking.v1beta1.',
510
+ MsgWithdrawDelegatorReward: '/cosmos.distribution.v1beta1.',
511
+ MsgTransfer: '/ibc.applications.transfer.v1.',
512
+ MsgRecvPacket: '/ibc.core.channel.v1.',
513
+ MsgCreateDeployment: '/akash.deployment.v1beta3.',
514
+ MsgAccountDeposit: '/akash.escrow.v1.',
515
+ MsgMintACT: '/akash.bme.v1.',
516
+ MsgBurnACT: '/akash.bme.v1.'
517
+ });
518
+ return {
519
+ height,
520
+ datetime: blockTime(height),
521
+ hash: fakeHash(seed),
522
+ isSuccess: success,
523
+ multisigThreshold: null,
524
+ signers,
525
+ error: success ? null : 'out of gas',
526
+ gasUsed: 90000,
527
+ gasWanted: 100000,
528
+ fee,
529
+ memo: '',
530
+ messages: messages.map((m, i) => ({
531
+ id: `msg-${seed}-${i}`,
532
+ type: `${packages[m.type] ?? '/x.'}${m.type}`,
533
+ data: m.data,
534
+ relatedDeploymentId: null
535
+ }))
536
+ };
537
+ }
538
+
539
+ /**
540
+ * One Akash deployment as the node lists it (#305): its escrow with what it
541
+ * paid its providers, in decimal uact.
542
+ *
543
+ * @param {{ owner: string, dseq: string, created: number, settled: number, uact: string, state?: string }} d
544
+ */
545
+ export function akashDeployment({ owner, dseq, created, settled, uact, state = 'closed' }) {
546
+ return {
547
+ deployment: {
548
+ id: { owner, dseq },
549
+ state,
550
+ hash: '',
551
+ created_at: String(created),
552
+ reclamation: null
553
+ },
554
+ escrow_account: {
555
+ id: { scope: 'deployment', xid: `${owner}/${dseq}` },
556
+ state: {
557
+ owner,
558
+ state,
559
+ transferred: [{ denom: 'uact', amount: `${uact}.000000000000000000` }],
560
+ settled_at: String(settled),
561
+ funds: [{ denom: 'uact', amount: '0.000000000000000000' }],
562
+ deposits: []
563
+ }
564
+ }
565
+ };
566
+ }
567
+
568
+ /**
569
+ * The Akash Console indexer: an address's transactions, newest first, and
570
+ * one transaction by hash. Every address named in a transaction's data or
571
+ * signers finds it.
572
+ *
573
+ * @param {object} [options]
574
+ * @param {ReturnType<typeof consoleTx>[]} [options.txs]
575
+ * @param {boolean} [options.broken] every request answers 500
576
+ * @param {boolean} [options.withCount] the listing as before October 2026: the total
577
+ * `count` instead of `hasMore`
578
+ * @param {string[]} [options.unlisted] hashes found by hash only, not in any address's
579
+ * listing (as the real indexer leaves some out)
580
+ */
581
+ export async function startFakeAkashConsole({
582
+ txs = [],
583
+ broken = false,
584
+ withCount = false,
585
+ unlisted = []
586
+ } = {}) {
587
+ /** @type {string[]} */
588
+ const calls = [];
589
+ const server = http.createServer((req, res) => {
590
+ const reply = (/** @type {number} */ status, /** @type {unknown} */ body) => {
591
+ res.writeHead(status, { 'Content-Type': 'application/json' });
592
+ res.end(JSON.stringify(body));
593
+ };
594
+ const path = String(req.url ?? '');
595
+ calls.push(path.replace(/akash1[02-9ac-hj-np-z]+/g, '<address>'));
596
+ if (broken) return reply(500, { error: 'down' });
597
+ const list = /^\/v1\/addresses\/([^/]+)\/transactions\/(\d+)\/(\d+)$/.exec(path);
598
+ if (list) {
599
+ const address = decodeURIComponent(list[1]);
600
+ const mine = txs
601
+ .filter((t) => !unlisted.includes(t.hash))
602
+ .filter((t) => JSON.stringify([t.signers, t.messages]).includes(address))
603
+ .sort((a, b) => b.height - a.height);
604
+ const skip = Number(list[2]);
605
+ const limit = Number(list[3]);
606
+ return reply(200, {
607
+ ...(withCount ? { count: mine.length } : { hasMore: skip + limit < mine.length }),
608
+ results: mine.slice(skip, skip + limit).map((t) => ({
609
+ height: t.height,
610
+ datetime: t.datetime,
611
+ hash: t.hash,
612
+ isSuccess: t.isSuccess,
613
+ error: t.error,
614
+ gasUsed: t.gasUsed,
615
+ gasWanted: t.gasWanted,
616
+ fee: t.fee,
617
+ memo: t.memo,
618
+ isSigner: t.signers.includes(address),
619
+ messages: t.messages.map((m) => ({
620
+ id: m.id,
621
+ type: m.type,
622
+ amount: 0,
623
+ isReceiver: false
624
+ }))
625
+ }))
626
+ });
627
+ }
628
+ const block = /^\/v1\/blocks\/(\d+)$/.exec(path);
629
+ if (block)
630
+ return reply(200, { height: Number(block[1]), datetime: blockTime(Number(block[1])) });
631
+ const one = /^\/v1\/transactions\/([0-9A-Fa-f]{64})$/.exec(path);
632
+ if (one) {
633
+ const tx = txs.find((t) => t.hash === one[1].toUpperCase());
634
+ return tx ? reply(200, tx) : reply(404, { error: 'not found' });
635
+ }
636
+ return reply(404, { error: 'not found' });
637
+ });
638
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(undefined)));
639
+ const { port } = /** @type {import('node:net').AddressInfo} */ (server.address());
640
+ const url = `http://127.0.0.1:${port}`;
641
+ return {
642
+ url,
643
+ calls,
644
+ close: () =>
645
+ new Promise((resolve) => {
646
+ server.close(() => resolve(undefined));
647
+ server.closeAllConnections?.();
648
+ })
649
+ };
650
+ }