@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/README.md CHANGED
@@ -1,3 +1,26 @@
1
- # Temporary Holding Version
1
+ # @le-space/chains
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Own wallets on public chains, read only, by their address – for [Belege](https://github.com/Le-Space/belege) (its bridge) and the [Eigenbeleg](https://github.com/Le-Space/eigenbeleg-agent) API and web UI. Every reader hands out [`@le-space/ledger`](../ledger) entries: one per movement of value, signed from the wallet's side, the fee as an entry of its own.
4
+
5
+ Runs in a browser and in Node. The caller hands in `fetch`, the endpoints (a node, an indexer, a proxy) and the keys (an Alchemy key, a NearBlocks key, a Bitcoin zpub/xpub); nothing is read from disk, a keychain or the environment. A browser can read the keyless chains itself where the source allows CORS (or behind a proxy).
6
+
7
+ | Chain | Source | Module |
8
+ | --- | --- | --- |
9
+ | Nym (Nyx), Akash (Cosmos SDK) | CometBFT RPC + REST; Akash's older history from the Akash Console indexer; Akash deployments | `cosmos`, `akash-console`, `akash-deployments`, `bech32`, `protobuf` |
10
+ | Ethereum, Base, Arbitrum One, OP Mainnet, Polygon PoS | Blockscout, or Alchemy with a key | `evm`, `alchemy` |
11
+ | Bitcoin | Esplora; addresses derived from a zpub/ypub/xpub | `bitcoin` |
12
+ | Filecoin | Filfox | `filecoin` |
13
+ | NEAR | NearBlocks + an archival RPC (from Eigenbeleg); gives `LedgerEntry` | `near` |
14
+
15
+ - `createWalletService({ fetch, getZpub, alchemyKey, … })` – every chain behind one `history({ chain, address, endpoints })`, as Belege's bridge serves it.
16
+ - `CHAINS`, `chainOf`, `publicChains` – the chains, their assets, default endpoints and explorers (`registry`).
17
+ - `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).
18
+ - `@le-space/chains/testing/cosmos`, `@le-space/chains/testing/filfox` – fake nodes for tests (Node), with made-up addresses.
19
+
20
+ Each source sees the address and the IP address of the machine that asks; Belege's consent screen says so.
21
+
22
+ ```bash
23
+ pnpm --filter @le-space/chains test # Node, and a scenario in Chromium (no Buffer, no node:)
24
+ ```
25
+
26
+ The files came from Belege's `bridge/src/chains/` and `packages/chain-{core,cosmos,filecoin}` (moved with their history) and from Eigenbeleg's `packages/chain-near` at e56769a. AGPL-3.0-or-later.
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "@le-space/chains",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
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) – as @le-space/ledger entries. Browser and Node; fetch, endpoints and keys handed in.",
5
+ "license": "AGPL-3.0-or-later",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/Le-Space/belege.git",
10
+ "directory": "packages/chains"
11
+ },
12
+ "homepage": "https://github.com/Le-Space/belege/tree/main/packages/chains#readme",
13
+ "sideEffects": false,
14
+ "exports": {
15
+ ".": "./src/index.js",
16
+ "./core": "./src/core.js",
17
+ "./http": "./src/http.js",
18
+ "./registry": "./src/registry.js",
19
+ "./wallets": "./src/wallets.js",
20
+ "./cosmos": "./src/cosmos.js",
21
+ "./cosmos-chains": "./src/cosmos-chains.js",
22
+ "./bech32": "./src/bech32.js",
23
+ "./protobuf": "./src/protobuf.js",
24
+ "./akash-console": "./src/akash-console.js",
25
+ "./akash-deployments": "./src/akash-deployments.js",
26
+ "./evm": "./src/evm.js",
27
+ "./alchemy": "./src/alchemy.js",
28
+ "./bitcoin": "./src/bitcoin.js",
29
+ "./filecoin": "./src/filecoin.js",
30
+ "./near": "./src/near.js",
31
+ "./testing/cosmos": "./test/support/fake-cosmos.js",
32
+ "./testing/filfox": "./test/support/fake-filfox.js"
33
+ },
34
+ "files": [
35
+ "src",
36
+ "test/support"
37
+ ],
38
+ "engines": {
39
+ "node": ">=22"
40
+ },
41
+ "publishConfig": {
42
+ "access": "public",
43
+ "provenance": true
44
+ },
45
+ "dependencies": {
46
+ "@noble/hashes": "2.4.0",
47
+ "@scure/base": "2.4.0",
48
+ "@scure/bip32": "2.4.0",
49
+ "@le-space/ledger": "^0.1.0"
50
+ },
51
+ "devDependencies": {
52
+ "prettier": "3.6.2",
53
+ "@le-space/browser-test": "0.1.0"
54
+ },
55
+ "scripts": {
56
+ "test": "node --test --test-reporter=spec \"test/*.test.js\"",
57
+ "lint": "prettier --check src test"
58
+ }
6
59
  }
@@ -0,0 +1,456 @@
1
+ // Akash's older history from the Akash Console indexer (issue #105, part 4).
2
+ //
3
+ // Every public Akash node is pruned: it knows a few weeks or months of
4
+ // transactions. The indexer behind console.akash.network (run by the Akash
5
+ // team, open source: akash-network/console) knows every transaction since
6
+ // mainnet-2 (March 2021), without a key:
7
+ // - `/v1/addresses/<address>/transactions/<skip>/<limit>`: the address's
8
+ // transactions, newest first, with `hasMore` (since October 2026; before,
9
+ // with `count` – both are read);
10
+ // - `/v1/transactions/<hash>`: one transaction with its decoded messages,
11
+ // its signers and its fee (in uakt).
12
+ // It is used only for what the node no longer has: transactions below the
13
+ // node's lowest height (cosmos.js `history.earliestHeight`). The node stays
14
+ // the source for everything it knows, since its events are exact.
15
+ //
16
+ // What the indexer does not have are events, and so no amount that only an
17
+ // event carries: the rewards a withdrawal pays (the message has none), the
18
+ // rewards a delegation, undelegation or redelegation withdraws on the way,
19
+ // escrow refunds and lease payouts, whatever an authz MsgExec does. Those
20
+ // transactions are counted (`unknownAmounts`) and not booked; the balance
21
+ // check on the wallet card shows the gap. What is booked comes from the
22
+ // message: sends, multi-sends, IBC transfers out and in, delegations, escrow
23
+ // deposits from the balance, governance deposits – and the fee of every
24
+ // transaction the address signed first.
25
+ //
26
+ // Entry ids: the fee `<hash>:fee`, as cosmos.js; a message
27
+ // `<hash>:c<message>.<part>:<asset>`. When the node's window moves on, a
28
+ // transaction first read from the node is later read from here; the app
29
+ // keeps the id it was booked under (wallet-sync.js reconcileSourceIds).
30
+ //
31
+ // The log gets counts, never an address.
32
+
33
+ import { fromBase64, fromUtf8 } from '@le-space/ledger/bytes';
34
+ import { moduleAddress } from './bech32.js';
35
+ import { createJsonFetcher, txUrl, WalletError } from './core.js';
36
+ import { unitsToDecimal } from './cosmos.js';
37
+
38
+ const PER_PAGE = 100;
39
+ const HASH = /^[0-9A-F]{64}$/;
40
+
41
+ /** Messages whose effect on the balance only events tell. */
42
+ const AMOUNT_IN_EVENTS = new Set([
43
+ 'MsgWithdrawDelegatorReward',
44
+ 'MsgWithdrawValidatorCommission',
45
+ 'MsgUndelegate',
46
+ 'MsgBeginRedelegate',
47
+ 'MsgCancelUnbondingDelegation',
48
+ 'MsgExec',
49
+ 'MsgCloseDeployment',
50
+ // ACT burnt for AKT: the AKT paid out is in the events only.
51
+ 'MsgBurnACT',
52
+ 'MsgCloseGroup',
53
+ 'MsgCloseLease',
54
+ 'MsgWithdrawLease',
55
+ 'MsgCreateBid',
56
+ 'MsgCloseBid',
57
+ 'MsgAcknowledgement',
58
+ 'MsgTimeout'
59
+ ]);
60
+
61
+ /** @param {unknown} v */
62
+ const str = (v) => (typeof v === 'string' ? v : '');
63
+
64
+ /** A coin as the indexer decodes it; null unless its amount is an integer. @param {any} c */
65
+ function coin(c) {
66
+ const amount = str(c?.amount);
67
+ const denom = str(c?.denom);
68
+ return /^\d+$/.test(amount) && denom ? { denom, amount: BigInt(amount) } : null;
69
+ }
70
+
71
+ /** @param {any} list */
72
+ const coins = (list) => (Array.isArray(list) ? list : [list]).map(coin).filter((c) => c !== null);
73
+
74
+ /**
75
+ * An IBC packet's fungible-token data: `{ denom, amount, sender, receiver }`.
76
+ * A denom that starts with the packet's source port and channel is ours
77
+ * coming home; any other is a voucher of another chain.
78
+ *
79
+ * @param {any} packet
80
+ */
81
+ function packetTransfer(packet) {
82
+ try {
83
+ const data = JSON.parse(fromUtf8(fromBase64(str(packet?.data))));
84
+ const prefix = `${str(packet?.sourcePort ?? packet?.source_port)}/${str(packet?.sourceChannel ?? packet?.source_channel)}/`;
85
+ const denom = str(data?.denom);
86
+ const amount = str(data?.amount);
87
+ if (!denom || !/^\d+$/.test(amount)) return null;
88
+ return {
89
+ denom: denom.startsWith(prefix) ? denom.slice(prefix.length) : `ibc-voucher:${denom}`,
90
+ amount: BigInt(amount),
91
+ sender: str(data?.sender),
92
+ receiver: str(data?.receiver)
93
+ };
94
+ } catch {
95
+ return null;
96
+ }
97
+ }
98
+
99
+ /**
100
+ * One transaction as `/v1/transactions/<hash>` hands it out → the entries of
101
+ * `address`.
102
+ *
103
+ * @param {any} tx
104
+ * @param {{ address: string, chain: import('./cosmos-chains.js').CosmosChain }} context
105
+ * @returns {{ entries: import('./cosmos.js').WalletEntry[], unknownDenoms: string[], unknownAmount: boolean }}
106
+ */
107
+ export function normalizeConsoleTx(tx, { address, chain }) {
108
+ const hash = str(tx?.hash).toUpperCase();
109
+ if (!HASH.test(hash)) throw new WalletError('a transaction without a hash', 'WALLET_DATA');
110
+ const height = Number(tx?.height);
111
+ const ms = Date.parse(str(tx?.datetime));
112
+ if (!Number.isSafeInteger(height) || height <= 0 || Number.isNaN(ms)) {
113
+ throw new WalletError('a transaction without a height or time', 'WALLET_DATA');
114
+ }
115
+ const time = new Date(ms).toISOString();
116
+ const date = time.slice(0, 10);
117
+ const memo = str(tx?.memo);
118
+ const explorerUrl = txUrl(chain.explorer, hash);
119
+ const bonded = moduleAddress(chain.bech32Prefix, 'bonded_tokens_pool');
120
+ /** @type {import('./cosmos.js').WalletEntry[]} */
121
+ const entries = [];
122
+ /** @type {string[]} */
123
+ const unknownDenoms = [];
124
+ let unknownAmount = false;
125
+
126
+ /** @param {{ denom: string, amount: bigint }} c */
127
+ const assetOf = (c) => {
128
+ const asset = Object.hasOwn(chain.denoms, c.denom) ? chain.denoms[c.denom] : null;
129
+ if (!asset) unknownDenoms.push(c.denom);
130
+ return asset;
131
+ };
132
+
133
+ /**
134
+ * @param {string} id
135
+ * @param {{ denom: string, amount: bigint }} c
136
+ * @param {{ out: boolean, kind: import('./cosmos.js').WalletEntry['kind'], counterparty: string, counterpartyLabel?: string }} how
137
+ */
138
+ const push = (id, c, { out, kind, counterparty, counterpartyLabel = '' }) => {
139
+ const asset = assetOf(c);
140
+ if (!asset || c.amount === 0n) return;
141
+ entries.push({
142
+ id: `${id}:${asset.symbol}`,
143
+ hash,
144
+ height,
145
+ time,
146
+ date,
147
+ type: out ? 'sent' : 'received',
148
+ kind,
149
+ asset: asset.symbol,
150
+ amount: unitsToDecimal(out ? -c.amount : c.amount, asset.decimals),
151
+ decimals: asset.decimals,
152
+ counterparty,
153
+ counterpartyLabel,
154
+ memo,
155
+ success: true,
156
+ explorerUrl
157
+ });
158
+ };
159
+
160
+ // The fee: in uakt, paid by the first signer.
161
+ const signers = Array.isArray(tx?.signers) ? tx.signers.map(str) : [];
162
+ const fee = Number(tx?.fee);
163
+ if (signers[0] === address && Number.isSafeInteger(fee) && fee > 0) {
164
+ const asset = chain.denoms[chain.nativeDenom];
165
+ entries.push({
166
+ id: `${hash}:fee`,
167
+ hash,
168
+ height,
169
+ time,
170
+ date,
171
+ type: 'fee',
172
+ kind: 'fee',
173
+ asset: asset.symbol,
174
+ amount: unitsToDecimal(-BigInt(fee), asset.decimals),
175
+ decimals: asset.decimals,
176
+ counterparty: '',
177
+ counterpartyLabel: '',
178
+ memo,
179
+ success: tx?.isSuccess !== false,
180
+ explorerUrl
181
+ });
182
+ }
183
+ if (tx?.isSuccess === false) return { entries, unknownDenoms, unknownAmount };
184
+
185
+ const messages = Array.isArray(tx?.messages) ? tx.messages : [];
186
+ messages.forEach((/** @type {any} */ m, /** @type {number} */ index) => {
187
+ const type = str(m?.type).split('.').pop() ?? '';
188
+ const d = m?.data ?? {};
189
+ const at = `${hash}:c${index}`;
190
+ switch (type) {
191
+ case 'MsgSend': {
192
+ const from = str(d.from_address ?? d.fromAddress);
193
+ const to = str(d.to_address ?? d.toAddress);
194
+ if ((from === address) === (to === address)) return;
195
+ coins(d.amount).forEach((c, part) =>
196
+ push(`${at}.${part}`, c, {
197
+ out: from === address,
198
+ kind: 'transfer',
199
+ counterparty: from === address ? to : from
200
+ })
201
+ );
202
+ return;
203
+ }
204
+ case 'MsgMultiSend': {
205
+ const inputs = Array.isArray(d.inputs) ? d.inputs : [];
206
+ const outputs = Array.isArray(d.outputs) ? d.outputs : [];
207
+ const only = (/** @type {any[]} */ list) =>
208
+ list.length === 1 ? str(list[0]?.address) : '';
209
+ let part = 0;
210
+ for (const input of inputs) {
211
+ if (str(input?.address) !== address) continue;
212
+ for (const c of coins(input.coins))
213
+ push(`${at}.${part++}`, c, {
214
+ out: true,
215
+ kind: 'transfer',
216
+ counterparty: only(outputs)
217
+ });
218
+ }
219
+ for (const output of outputs) {
220
+ if (str(output?.address) !== address) continue;
221
+ for (const c of coins(output.coins))
222
+ push(`${at}.${part++}`, c, {
223
+ out: false,
224
+ kind: 'transfer',
225
+ counterparty: only(inputs)
226
+ });
227
+ }
228
+ return;
229
+ }
230
+ case 'MsgTransfer': {
231
+ if (str(d.sender) !== address) return;
232
+ const c = coin(d.token);
233
+ if (c)
234
+ push(`${at}.0`, c, {
235
+ out: true,
236
+ kind: 'ibc',
237
+ counterparty: str(d.receiver),
238
+ counterpartyLabel: 'IBC-Transfer'
239
+ });
240
+ return;
241
+ }
242
+ case 'MsgRecvPacket': {
243
+ const t = packetTransfer(d.packet);
244
+ if (!t || t.receiver !== address) return;
245
+ push(`${at}.0`, t, {
246
+ out: false,
247
+ kind: 'transfer',
248
+ counterparty: t.sender,
249
+ counterpartyLabel: 'IBC-Transfer'
250
+ });
251
+ return;
252
+ }
253
+ case 'MsgDelegate': {
254
+ if (str(d.delegator_address ?? d.delegatorAddress) !== address) return;
255
+ const c = coin(d.amount);
256
+ if (c)
257
+ push(`${at}.0`, c, {
258
+ out: true,
259
+ kind: 'stake',
260
+ counterparty: bonded,
261
+ counterpartyLabel: 'Staking (gebunden)'
262
+ });
263
+ // Rewards withdrawn on the way are in the events only.
264
+ unknownAmount = true;
265
+ return;
266
+ }
267
+ case 'MsgCreateDeployment':
268
+ case 'MsgDepositDeployment': {
269
+ const owner = str(d.depositor) || str(d.id?.owner);
270
+ if (owner !== address) return;
271
+ const c = coin(d.deposit ?? d.amount);
272
+ if (c)
273
+ push(`${at}.0`, c, {
274
+ out: true,
275
+ kind: 'transfer',
276
+ counterparty: '',
277
+ counterpartyLabel: 'Akash-Escrow (Deployment)'
278
+ });
279
+ return;
280
+ }
281
+ case 'MsgAccountDeposit': {
282
+ if (str(d.signer) !== address) return;
283
+ const sources = Array.isArray(d.deposit?.sources) ? d.deposit.sources.map(str) : [];
284
+ // From a grant, the granter paid; only a deposit from the balance is ours.
285
+ if (sources.length && !sources.includes('balance')) return;
286
+ const c = coin(d.deposit?.amount);
287
+ if (c)
288
+ push(`${at}.0`, c, {
289
+ out: true,
290
+ kind: 'transfer',
291
+ counterparty: '',
292
+ counterpartyLabel: 'Akash-Escrow (Deployment)'
293
+ });
294
+ return;
295
+ }
296
+ case 'MsgMintACT': {
297
+ // AKT burnt for ACT (BME): the AKT is in the message, the ACT minted
298
+ // in the events only – a swap whose other side has no amount here.
299
+ if (str(d.owner) !== address) return;
300
+ const c = coin(d.coins_to_burn ?? d.coinsToBurn);
301
+ if (!c) return;
302
+ const before = entries.length;
303
+ push(`${at}.0`, c, {
304
+ out: true,
305
+ kind: 'swap',
306
+ counterparty: moduleAddress(chain.bech32Prefix, 'bme'),
307
+ counterpartyLabel: 'Akash BME (AKT ↔ ACT)'
308
+ });
309
+ const leg = entries[before];
310
+ if (!leg) return;
311
+ const gas = entries.find((e) => e.type === 'fee');
312
+ const swap = {
313
+ gave: [{ asset: leg.asset, amount: leg.amount.replace(/^-/, ''), listed: true }],
314
+ got: [{ asset: 'ACT', amount: '', listed: false }],
315
+ via: 'Akash BME (AKT ↔ ACT)',
316
+ ...(gas ? { fee: { asset: gas.asset, amount: gas.amount.replace(/^-/, '') } } : {})
317
+ };
318
+ leg.swap = swap;
319
+ if (gas) gas.swap = swap;
320
+ return;
321
+ }
322
+ case 'MsgDeposit':
323
+ case 'MsgSubmitProposal': {
324
+ const who = str(d.depositor) || str(d.proposer);
325
+ if (who !== address) return;
326
+ coins(d.amount ?? d.initial_deposit ?? d.initialDeposit).forEach((c, part) =>
327
+ push(`${at}.${part}`, c, {
328
+ out: true,
329
+ kind: 'transfer',
330
+ counterparty: moduleAddress(chain.bech32Prefix, 'gov'),
331
+ counterpartyLabel: 'Governance-Einlage'
332
+ })
333
+ );
334
+ return;
335
+ }
336
+ default:
337
+ if (AMOUNT_IN_EVENTS.has(type)) unknownAmount = true;
338
+ }
339
+ });
340
+ return { entries, unknownDenoms, unknownAmount };
341
+ }
342
+
343
+ /**
344
+ * @param {object} [options]
345
+ * @param {typeof fetch} [options.fetch]
346
+ * @param {number} [options.timeoutMs] the indexer is slow for long histories
347
+ * @param {number} [options.maxTransactions] beyond that the older history is not read
348
+ * @param {(ms: number) => Promise<void>} [options.sleep]
349
+ */
350
+ export function createAkashConsoleClient({
351
+ fetch: f = fetch,
352
+ timeoutMs = 45_000,
353
+ maxTransactions = 5000,
354
+ sleep
355
+ } = {}) {
356
+ const getJson = createJsonFetcher({ fetch: f, timeoutMs, sleep });
357
+ return {
358
+ /**
359
+ * The address's transactions below `beforeHeight`, as entries.
360
+ *
361
+ * @param {object} p
362
+ * @param {import('./cosmos-chains.js').CosmosChain} p.chain
363
+ * @param {string} p.address checked by cosmos.js already
364
+ * @param {string} p.indexer base URL, checked
365
+ * @param {number} p.beforeHeight the node's lowest height
366
+ */
367
+ async history({ chain, address, indexer, beforeHeight }) {
368
+ const base = `${indexer}/v1`;
369
+ /** @type {{ hash: string, height: number }[]} */
370
+ const older = [];
371
+ for (let skip = 0; ; skip += PER_PAGE) {
372
+ const page = await getJson(
373
+ `${base}/addresses/${encodeURIComponent(address)}/transactions/${skip}/${PER_PAGE}`
374
+ );
375
+ // More to read: `hasMore` (the indexer since October 2026), or
376
+ // the total `count` it gave before.
377
+ const counted = Number.isSafeInteger(page?.count);
378
+ if (!Array.isArray(page?.results) || (!counted && typeof page?.hasMore !== 'boolean')) {
379
+ throw new WalletError('the indexer answered without transactions', 'WALLET_INDEXER');
380
+ }
381
+ const known = counted ? page.count : skip + page.results.length;
382
+ if (known > maxTransactions) {
383
+ throw new WalletError(
384
+ `more than ${maxTransactions} transactions in the indexer; older history not read`,
385
+ 'WALLET_TOO_MANY'
386
+ );
387
+ }
388
+ for (const r of page.results) {
389
+ const hash = str(r?.hash).toUpperCase();
390
+ const height = Number(r?.height);
391
+ if (HASH.test(hash) && height < beforeHeight) older.push({ hash, height });
392
+ }
393
+ const more = counted ? skip + PER_PAGE < page.count : page.hasMore;
394
+ if (!page.results.length || !more) break;
395
+ }
396
+
397
+ /** @type {import('./cosmos.js').WalletEntry[]} */
398
+ const entries = [];
399
+ /** @type {Set<string>} */
400
+ const unknown = new Set();
401
+ let unknownAmounts = 0;
402
+ /** @type {Set<string>} */
403
+ const seen = new Set();
404
+ older.sort((a, b) => a.height - b.height);
405
+ for (const { hash } of older) {
406
+ if (seen.has(hash)) continue;
407
+ seen.add(hash);
408
+ const tx = await getJson(`${base}/transactions/${hash}`);
409
+ const result = normalizeConsoleTx(tx, { address, chain });
410
+ entries.push(...result.entries);
411
+ for (const d of result.unknownDenoms) unknown.add(d);
412
+ if (result.unknownAmount) unknownAmounts++;
413
+ }
414
+ return {
415
+ entries,
416
+ transactions: seen.size,
417
+ unknownAssets: unknown.size,
418
+ unknownAmounts,
419
+ earliestTime: entries[0]?.time ?? null
420
+ };
421
+ },
422
+
423
+ /**
424
+ * Transactions by their hash, for the address: the ones another source
425
+ * names – an exchange's withdrawal to this wallet – that the address's
426
+ * own listing leaves out. Only those that move something of the
427
+ * address's count; the others are left out.
428
+ *
429
+ * @param {object} p
430
+ * @param {import('./cosmos-chains.js').CosmosChain} p.chain
431
+ * @param {string} p.address
432
+ * @param {string} p.indexer base URL, checked
433
+ * @param {string[]} p.hashes upper-case, checked
434
+ */
435
+ async byHashes({ chain, address, indexer, hashes }) {
436
+ /** @type {import('./cosmos.js').WalletEntry[]} */
437
+ const entries = [];
438
+ let found = 0;
439
+ for (const hash of hashes) {
440
+ const tx = await getJson(`${indexer}/v1/transactions/${hash}`).catch(() => null);
441
+ if (!tx) continue;
442
+ let result;
443
+ try {
444
+ result = normalizeConsoleTx(tx, { address, chain });
445
+ } catch {
446
+ continue;
447
+ }
448
+ // Only a transaction that moves something of the address's.
449
+ if (!result.entries.some((e) => e.type !== 'fee')) continue;
450
+ found++;
451
+ entries.push(...result.entries);
452
+ }
453
+ return { entries, found };
454
+ }
455
+ };
456
+ }
@@ -0,0 +1,145 @@
1
+ // An Akash wallet's deployments and what they cost (issue #305, step 2): for
2
+ // the monthly usage statement in the app.
3
+ //
4
+ // Deployments are paid in ACT (Akash's compute credit, minted from AKT by
5
+ // burn-mint, ~1 USD) through an escrow account per deployment. The node
6
+ // keeps every deployment of an owner, closed ones too, with its escrow state:
7
+ // GET <rest>/akash/deployment/v1beta4/deployments/list?filters.owner=<a>
8
+ // deployment.created_at the block it was created in
9
+ // escrow_account.state transferred (paid to the providers so far),
10
+ // funds (left), settled_at (the last settlement;
11
+ // for a closed one, its end)
12
+ // Amounts are decimal coins in uact. The blocks' times come from the Akash
13
+ // Console indexer (`/v1/blocks/<height>`), as the node is pruned. With them,
14
+ // the wallet's ACT held now (`/cosmos/bank/v1beta1/balances/<a>`, uact), for
15
+ // the ACT account (step 3): what was minted is what is held, in escrow and
16
+ // used up.
17
+ //
18
+ // What a deployment cost in a month is not kept per month on chain: the app
19
+ // spreads its transferred amount evenly over its time from creation to the
20
+ // last settlement, and says so on the statement.
21
+ //
22
+ // The log gets counts, never an address.
23
+
24
+ import { createJsonFetcher, WalletError } from './core.js';
25
+ import { unitsToDecimal } from './cosmos.js';
26
+
27
+ const LIMIT = 1000;
28
+
29
+ /**
30
+ * `49.000000000000000000` (uact, a decimal coin) → 49n, rounded half up.
31
+ *
32
+ * @param {unknown} amount
33
+ */
34
+ export function decUnits(amount) {
35
+ const m = /^(\d+)(?:\.(\d+))?$/.exec(String(amount ?? '').trim());
36
+ if (!m) return 0n;
37
+ return BigInt(m[1]) + ((m[2] ?? '0')[0] >= '5' ? 1n : 0n);
38
+ }
39
+
40
+ /** @param {any} coins @param {string} denom */
41
+ const sumOf = (coins, denom) =>
42
+ (Array.isArray(coins) ? coins : [])
43
+ .filter((c) => c?.denom === denom)
44
+ .reduce((n, c) => n + decUnits(c?.amount), 0n);
45
+
46
+ /**
47
+ * @typedef {object} AkashDeployment
48
+ * @property {string} dseq
49
+ * @property {string} state active | closed
50
+ * @property {number} createdHeight
51
+ * @property {string | null} createdAt ISO, from the indexer
52
+ * @property {number} settledHeight
53
+ * @property {string | null} settledAt ISO, from the indexer
54
+ * @property {string} transferred ACT paid to the providers, decimal
55
+ * @property {string} funds ACT left in the escrow, decimal
56
+ */
57
+
58
+ /**
59
+ * @param {object} [options]
60
+ * @param {typeof fetch} [options.fetch]
61
+ * @param {number} [options.timeoutMs]
62
+ * @param {(ms: number) => Promise<void>} [options.sleep]
63
+ */
64
+ export function createAkashDeploymentsClient({ fetch: f = fetch, timeoutMs, sleep } = {}) {
65
+ const getJson = createJsonFetcher({ fetch: f, timeoutMs, sleep });
66
+ /** @type {Map<string, string | null>} `<indexer>@<height>` → ISO time */
67
+ const times = new Map();
68
+
69
+ /** @param {string} indexer @param {number} height */
70
+ async function timeOf(indexer, height) {
71
+ const key = `${indexer}@${height}`;
72
+ if (times.has(key)) return times.get(key) ?? null;
73
+ const block = await getJson(`${indexer}/v1/blocks/${height}`).catch(() => null);
74
+ const ms = Date.parse(String(block?.datetime ?? ''));
75
+ const iso = Number.isNaN(ms) ? null : new Date(ms).toISOString();
76
+ // Only an answer is kept: an indexer that did not answer this time is
77
+ // asked again next time, not remembered as silent for the bridge's life.
78
+ if (iso) times.set(key, iso);
79
+ return iso;
80
+ }
81
+
82
+ return {
83
+ /**
84
+ * The wallet's ACT held now, decimal.
85
+ *
86
+ * @param {{ address: string, rest: string }} p checked by the caller
87
+ */
88
+ async actBalance({ address, rest }) {
89
+ const body = await getJson(
90
+ `${rest}/cosmos/bank/v1beta1/balances/${encodeURIComponent(address)}?pagination.limit=200`
91
+ );
92
+ if (!Array.isArray(body?.balances)) {
93
+ throw new WalletError('the node answered without balances', 'WALLET_DATA');
94
+ }
95
+ const uact = body.balances.find((/** @type {any} */ b) => b?.denom === 'uact');
96
+ return unitsToDecimal(decUnits(uact?.amount ?? '0'), 6);
97
+ },
98
+
99
+ /**
100
+ * @param {{ address: string, rest: string, indexer: string }} p checked by the caller
101
+ * @returns {Promise<AkashDeployment[]>}
102
+ */
103
+ async deployments({ address, rest, indexer }) {
104
+ /** @type {any[]} */
105
+ const raw = [];
106
+ let key = '';
107
+ for (let page = 0; page < 50; page++) {
108
+ const q = new URLSearchParams({
109
+ 'filters.owner': address,
110
+ 'pagination.limit': String(LIMIT),
111
+ ...(key ? { 'pagination.key': key } : {})
112
+ });
113
+ const body = await getJson(`${rest}/akash/deployment/v1beta4/deployments/list?${q}`);
114
+ if (!Array.isArray(body?.deployments)) {
115
+ throw new WalletError('the node answered without deployments', 'WALLET_DATA');
116
+ }
117
+ raw.push(...body.deployments);
118
+ key = String(body?.pagination?.next_key ?? '');
119
+ if (!key) break;
120
+ }
121
+ /** @type {AkashDeployment[]} */
122
+ const out = [];
123
+ for (const d of raw) {
124
+ const dseq = String(d?.deployment?.id?.dseq ?? '');
125
+ const createdHeight = Number(d?.deployment?.created_at);
126
+ const state = d?.escrow_account?.state ?? {};
127
+ const settledHeight = Number(state.settled_at);
128
+ if (!/^\d+$/.test(dseq) || !Number.isSafeInteger(createdHeight)) continue;
129
+ out.push({
130
+ dseq,
131
+ state: String(d?.deployment?.state ?? ''),
132
+ createdHeight,
133
+ createdAt: await timeOf(indexer, createdHeight),
134
+ settledHeight: Number.isSafeInteger(settledHeight) ? settledHeight : createdHeight,
135
+ settledAt: Number.isSafeInteger(settledHeight)
136
+ ? await timeOf(indexer, settledHeight)
137
+ : null,
138
+ transferred: unitsToDecimal(sumOf(state.transferred, 'uact'), 6),
139
+ funds: unitsToDecimal(sumOf(state.funds, 'uact'), 6)
140
+ });
141
+ }
142
+ return out.sort((a, b) => a.createdHeight - b.createdHeight);
143
+ }
144
+ };
145
+ }