@le-space/chains 0.2.0 → 0.4.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
@@ -7,16 +7,21 @@ Runs in a browser and in Node. The caller hands in `fetch`, the endpoints (a nod
7
7
  | Chain | Source | Module |
8
8
  | --- | --- | --- |
9
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 (USDC listed; ALEPH on Ethereum and Base) | Blockscout, or Alchemy with a key | `evm`, `alchemy` |
10
+ | Akash as `LedgerEntry` (`readAkash`, `statementAkash`: the fee to the network, escrow its own kind) | the Cosmos reader and the Akash Console indexer | `akash` |
11
+ | Ethereum, Base, Arbitrum One, OP Mainnet, Polygon PoS (USDC listed; ALEPH on Ethereum and Base) | Blockscout, or Alchemy with a key; `evmReader(chain)` gives `LedgerEntry` through Alchemy (the key handed to each read) | `evm`, `alchemy` |
11
12
  | Bitcoin | Esplora; addresses derived from a zpub/ypub/xpub | `bitcoin` |
12
- | Filecoin | Filfox | `filecoin` |
13
+ | Filecoin | Filfox; `readFilecoin`/`statementFilecoin` give `LedgerEntry` | `filecoin` |
13
14
  | NEAR | NearBlocks + an archival RPC (from Eigenbeleg); gives `LedgerEntry` | `near` |
14
15
  | Aleph Cloud credits (no chain: Aleph's own network, by the Ethereum address) | Aleph's API, CORS open; a month's statement, `alephEntries` gives `LedgerEntry` (`usage` for consumption, with its USD price per credit) | `aleph` |
15
16
 
16
17
  - `createWalletService({ fetch, getZpub, alchemyKey, … })` – every chain behind one `history({ chain, address, endpoints })`, as Belege's bridge serves it.
17
- - `CHAINS`, `chainOf`, `publicChains` – the chains, their assets, default endpoints and explorers (`registry`).
18
+ - `CHAINS`, `chainOf`, `publicChains` – the chains, their assets, default endpoints and explorers (`registry`). One chain's data without the others: `FILECOIN` (`filecoin-chain`), `NYX_CHAIN`, `AKASH_CHAIN` (`cosmos-chains`), `KNOWN_EVM_CONTRACTS` (`evm-contracts`). The readers take their chain as an argument and do not import the registry.
19
+ - The `LedgerEntry` readers (`near`, `akash`, `filecoin`, `evmReader`, `aleph`) each give `read…`/`statement…` for a period (`statement`: the entries and the balances before and after, `method: 'archive'` on NEAR, `'derived'` from today's balance elsewhere), `probe` as a live check against public data, `isAddress`, and for Aleph `purchaseEntries`: the payment behind each credit purchase. From the Eigenbeleg agent's pipeline readers; its blocks are built on them.
20
+ - `toChecksumAddress`, `isEvmAddress` – an EVM address's EIP-55 checksum and form (`evm-address`: keccak and bytes only, so `aleph` and a browser form do not bundle the EVM reader or Alchemy; `evm` re-exports them).
18
21
  - `createJsonFetcher`, `WalletError`, `checkEndpoint`, `txUrl`, `addressUrl`, `markSwaps` – what every reader shares (`core`). Error messages name a host at most, never a path or a query (they carry addresses).
19
- - `@le-space/chains/testing/cosmos`, `@le-space/chains/testing/filfox` – fake nodes for tests (Node), with made-up addresses.
22
+ - Fakes for tests, with made-up addresses, hashes, keys and amounts:
23
+ - `@le-space/chains/testing/cosmos`, `testing/filfox`, `testing/blockscout`, `testing/alchemy` – fake nodes on 127.0.0.1 (Node). The fake Alchemy is as strict as the real one about what it is asked; `blockscoutView` turns its made-up chain into what the fake Blockscout serves, so one history reads through both.
24
+ - `@le-space/chains/testing/aleph` – a fake Aleph API as a `fetch` function (Node and browser), and a made-up account and month (`ACCOUNT`, `sampleRows`, `sampleBalance`, `flatUsd`).
20
25
 
21
26
  Each source sees the address and the IP address of the machine that asks; Belege's consent screen says so.
22
27
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@le-space/chains",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Own wallets on public chains, read only, by their address – Cosmos (Nyx, Akash), EVM (Blockscout, Alchemy), Bitcoin (Esplora, zpub), Filecoin (Filfox), NEAR (NearBlocks), Aleph Cloud credits – as @le-space/ledger entries. Browser and Node; fetch, endpoints and keys handed in.",
5
5
  "license": "AGPL-3.0-or-later",
6
6
  "type": "module",
@@ -21,16 +21,23 @@
21
21
  "./cosmos-chains": "./src/cosmos-chains.js",
22
22
  "./bech32": "./src/bech32.js",
23
23
  "./protobuf": "./src/protobuf.js",
24
+ "./akash": "./src/akash.js",
24
25
  "./akash-console": "./src/akash-console.js",
25
26
  "./akash-deployments": "./src/akash-deployments.js",
26
27
  "./evm": "./src/evm.js",
28
+ "./evm-address": "./src/evm-address.js",
29
+ "./evm-contracts": "./src/evm-contracts.js",
27
30
  "./alchemy": "./src/alchemy.js",
28
31
  "./bitcoin": "./src/bitcoin.js",
29
32
  "./filecoin": "./src/filecoin.js",
33
+ "./filecoin-chain": "./src/filecoin-chain.js",
30
34
  "./near": "./src/near.js",
31
35
  "./aleph": "./src/aleph.js",
32
36
  "./testing/cosmos": "./test/support/fake-cosmos.js",
33
- "./testing/filfox": "./test/support/fake-filfox.js"
37
+ "./testing/filfox": "./test/support/fake-filfox.js",
38
+ "./testing/blockscout": "./test/support/fake-blockscout.js",
39
+ "./testing/alchemy": "./test/support/fake-alchemy.js",
40
+ "./testing/aleph": "./test/support/aleph.js"
34
41
  },
35
42
  "files": [
36
43
  "src",
@@ -47,8 +54,8 @@
47
54
  "@noble/hashes": "2.4.0",
48
55
  "@scure/base": "2.4.0",
49
56
  "@scure/bip32": "2.4.0",
50
- "@le-space/ledger": "^0.2.0",
51
- "@le-space/rates": "^0.2.0"
57
+ "@le-space/ledger": "^0.3.0",
58
+ "@le-space/rates": "^0.3.0"
52
59
  },
53
60
  "devDependencies": {
54
61
  "prettier": "3.6.2",
package/src/akash.js ADDED
@@ -0,0 +1,132 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Akash as ledger entries, for an Eigenbeleg or a Kontoauszug (from the
3
+ // Eigenbeleg agent's readers/akash.js). The reading is cosmos.js: the node's
4
+ // `tx_search` for everything it still has, the Akash Console indexer for what
5
+ // the pruned node has forgotten. This file keeps what a document reads
6
+ // differently from a wallet view: the fee goes to the network, an escrow
7
+ // deposit is a kind of its own, only AKT is priced; and the period.
8
+
9
+ import { derivedStatement, fromWalletEntry, sortEntries } from '@le-space/ledger';
10
+ import { createCosmosClient } from './cosmos.js';
11
+ import { AKASH_CHAIN } from './cosmos-chains.js';
12
+ import { createAkashConsoleClient } from './akash-console.js';
13
+ import { isCosmosAddress } from './bech32.js';
14
+
15
+ /** Market prices for the native assets. */
16
+ const PRICE_AS = { AKT: 'AKT' };
17
+ const NETWORK_LABEL = 'Akash-Netzwerk (Gebühr an Validatoren)';
18
+
19
+ /**
20
+ * A WalletEntry → the ledger entry a document books.
21
+ *
22
+ * @param {import('@le-space/ledger/wallet-entry').WalletEntry} e
23
+ * @param {{ chain: typeof AKASH_CHAIN, account: string }} c
24
+ */
25
+ export function toLedger(e, { chain, account }) {
26
+ const escrow = /Escrow/i.test(String(e.counterpartyLabel ?? ''));
27
+ const kind =
28
+ e.type === 'fee'
29
+ ? 'fee'
30
+ : e.kind === 'ibc'
31
+ ? 'transfer'
32
+ : escrow
33
+ ? 'escrow'
34
+ : e.kind === 'swap'
35
+ ? 'swap'
36
+ : ['reward', 'stake'].includes(e.kind)
37
+ ? e.kind
38
+ : 'transfer';
39
+ const fee = e.type === 'fee';
40
+ return fromWalletEntry(
41
+ e,
42
+ {
43
+ chain: chain.id,
44
+ network: 'mainnet',
45
+ account,
46
+ priceAs: PRICE_AS[/** @type {keyof typeof PRICE_AS} */ (e.asset)] ?? ''
47
+ },
48
+ {
49
+ kind,
50
+ counterparty: fee ? chain.id : String(e.counterparty ?? ''),
51
+ counterpartyLabel: fee ? NETWORK_LABEL : String(e.counterpartyLabel ?? ''),
52
+ memo: String(e.memo ?? ''),
53
+ // A failed transaction still pays its fee: the fee is a real payment.
54
+ success: fee ? true : e.success !== false
55
+ }
56
+ );
57
+ }
58
+
59
+ /**
60
+ * @param {object} p
61
+ * @param {string} p.account bech32 address
62
+ * @param {string} [p.network] mainnet only
63
+ * @param {string} p.from YYYY-MM-DD
64
+ * @param {string} p.to YYYY-MM-DD
65
+ * @param {typeof fetch} [p.fetch]
66
+ * @param {Record<string, string>} [p.endpoints] instead of the chain's own, e.g. `indexer` behind a CORS proxy in a browser
67
+ */
68
+ async function history({ account, from, fetch = globalThis.fetch, endpoints: own }) {
69
+ const chain = AKASH_CHAIN;
70
+ if (!isCosmosAddress(account, chain.bech32Prefix))
71
+ throw new Error(`not a valid ${chain.name} address`);
72
+ const endpoints = { ...chain.endpoints, ...own };
73
+ const node = createCosmosClient({ fetch });
74
+ const result = await node.history({ chain, address: account, endpoints });
75
+ let entries = result.entries;
76
+ if (
77
+ result.history.pruned &&
78
+ endpoints.indexer &&
79
+ result.history.earliestTime &&
80
+ result.history.earliestTime.slice(0, 10) > from
81
+ ) {
82
+ const older = await createAkashConsoleClient({ fetch }).history({
83
+ chain,
84
+ address: account,
85
+ indexer: endpoints.indexer,
86
+ beforeHeight: result.history.earliestHeight
87
+ });
88
+ entries = [...older.entries, ...entries];
89
+ }
90
+ return {
91
+ chain,
92
+ all: sortEntries(entries.map((e) => toLedger(e, { chain, account }))),
93
+ balances: result.balances
94
+ };
95
+ }
96
+
97
+ /** Ledger entries for an account and period. @param {Parameters<typeof history>[0]} p */
98
+ export async function readAkash(p) {
99
+ const { all } = await history(p);
100
+ return all.filter((e) => e.date >= p.from && e.date <= p.to);
101
+ }
102
+
103
+ /**
104
+ * For a Kontoauszug: the bookings of the period, and the balances before and
105
+ * after it, derived from today's balance less every movement since. (Pruned
106
+ * nodes keep no old balances.) What the reader cannot see – tokens coming back
107
+ * when an unbonding ends, vesting – shifts the derived balances; the
108
+ * statement says how they were made.
109
+ *
110
+ * @param {Parameters<typeof history>[0]} p
111
+ */
112
+ export async function statementAkash(p) {
113
+ const { all, balances } = await history(p);
114
+ return derivedStatement(all, balances, p.from, p.to);
115
+ }
116
+
117
+ /** The public node must answer for Akash's own chain id. @param {{ fetch?: typeof fetch, endpoints?: { rpc?: string } }} [o] */
118
+ export async function probe({ fetch = globalThis.fetch, endpoints } = {}) {
119
+ const rpc = endpoints?.rpc ?? AKASH_CHAIN.endpoints.rpc;
120
+ const res = await fetch(`${rpc}/status`);
121
+ if (!res.ok) throw new Error(`Akash RPC answered ${res.status}`);
122
+ const body = await res.json();
123
+ if (body?.result?.node_info?.network !== AKASH_CHAIN.chainId)
124
+ throw new Error('the Akash RPC belongs to another chain');
125
+ return {
126
+ sample: `${rpc} status`,
127
+ entries: Number(body.result.sync_info?.latest_block_height ?? 0) > 0 ? 1 : 0
128
+ };
129
+ }
130
+
131
+ /** @param {string} a */
132
+ export const isAddress = (a) => isCosmosAddress(a, AKASH_CHAIN.bech32Prefix);
package/src/aleph.js CHANGED
@@ -49,7 +49,7 @@
49
49
  // Times are UTC; the month is the UTC month. The log gets counts, never an
50
50
  // address.
51
51
 
52
- import { entry, sortEntries } from '@le-space/ledger';
52
+ import { entry, multiply, normalize, sortEntries } from '@le-space/ledger';
53
53
  import {
54
54
  ALEPH_LIST_PRICE_USD,
55
55
  alephCreditPrice,
@@ -57,7 +57,8 @@ import {
57
57
  plain
58
58
  } from '@le-space/rates/aleph-credits';
59
59
  import { createJsonFetcher, WalletError } from './http.js';
60
- import { toChecksumAddress } from './evm.js';
60
+ import { toChecksumAddress } from './evm-address.js';
61
+ import { txUrl } from './explorer.js';
61
62
 
62
63
  export const ALEPH_API = 'https://api2.aleph.im';
63
64
  /** Aleph's list price, USD per credit (@le-space/rates). */
@@ -286,9 +287,15 @@ export function createAlephClient({
286
287
  'ALEPH_TOO_MANY'
287
288
  );
288
289
  }
290
+ // A window without rows: Aleph answers 404 in plain text (the same
291
+ // address without the window answers 200) – an empty page, as the
292
+ // balance's 404 is nothing there.
289
293
  const body = await getJson(
290
294
  `${base}/credit_history?page=${page}&pagination=${PER_PAGE}${query}`
291
- );
295
+ ).catch((/** @type {any} */ e) => {
296
+ if (e?.httpStatus === 404) return { credit_history: [], pagination_total: 0 };
297
+ throw e;
298
+ });
292
299
  const batch = Array.isArray(body?.credit_history) ? body.credit_history : null;
293
300
  if (!batch) throw new WalletError('Aleph answered without a history', 'ALEPH_DATA');
294
301
  rows.push(...batch);
@@ -446,3 +453,68 @@ export function alephEntries(statement) {
446
453
  ];
447
454
  return sortEntries(out);
448
455
  }
456
+
457
+ /**
458
+ * Aleph's name for the chain a purchase was paid on → the explorer's transaction
459
+ * link there. The same templates as the registry's `ethereum` and `base`
460
+ * (the test checks); spelled out here so that `/aleph` bundles without the
461
+ * registry.
462
+ */
463
+ export const PURCHASE_EXPLORERS = /** @type {Record<string, import('./explorer.js').Explorer>} */ ({
464
+ ETH: {
465
+ name: 'Etherscan',
466
+ tx: 'https://etherscan.io/tx/{tx}',
467
+ address: 'https://etherscan.io/address/{address}'
468
+ },
469
+ BASE: {
470
+ name: 'Basescan',
471
+ tx: 'https://basescan.org/tx/{tx}',
472
+ address: 'https://basescan.org/address/{address}'
473
+ }
474
+ });
475
+
476
+ /**
477
+ * The payments behind a month's credit purchases: one `sent` entry per
478
+ * purchase, in USD (credits × the purchase's USD price per credit), of kind
479
+ * `swap` – a token for credits; the ledger has no `purchase` kind. The token
480
+ * amount paid is not in Aleph's data; it is checked through the paying
481
+ * transaction's hash, whose explorer link is on the chain it was paid on
482
+ * (Ethereum or Base), else Aleph's explorer page of the account. The credits
483
+ * bought stay the `received` row of `alephEntries`, with the same hash, so an
484
+ * Eigenbeleg shows both sides.
485
+ *
486
+ * @param {Awaited<ReturnType<ReturnType<typeof createAlephClient>['statement']>>} statement
487
+ * @param {{ explorers?: Record<string, import('./explorer.js').Explorer> }} [o] by Aleph's chain code (`ETH`, `BASE`)
488
+ * @returns {import('@le-space/ledger').LedgerEntry[]}
489
+ */
490
+ export function purchaseEntries(statement, { explorers = PURCHASE_EXPLORERS } = {}) {
491
+ const { address, topUps } = statement;
492
+ return topUps
493
+ .filter((t) => t.how === 'purchase' && t.price)
494
+ .map((t, i) => {
495
+ const explorer = t.chain ? explorers[t.chain.toUpperCase()] : undefined;
496
+ return entry({
497
+ id: `aleph:${address}:purchase:${t.time}:${i}`,
498
+ chain: 'aleph',
499
+ network: 'mainnet',
500
+ account: address,
501
+ hash: t.txHash ?? '',
502
+ height: 0,
503
+ time: t.time,
504
+ type: 'sent',
505
+ kind: 'swap',
506
+ asset: 'USD',
507
+ contract: 'native',
508
+ decimals: 6,
509
+ amount: `-${normalize(multiply(credits(t.credits), /** @type {string} */ (t.price), 8))}`,
510
+ counterparty: 'aleph',
511
+ method: '',
512
+ counterpartyLabel: `Aleph Cloud (Kauf von ${credits(t.credits)} Credits${t.token ? ` mit ${t.token}` : ''}${t.chain ? ` auf ${t.chain}` : ''})`,
513
+ memo: `${credits(t.credits)} Credits × ${t.price} USD`,
514
+ success: true,
515
+ explorerUrl:
516
+ explorer && t.txHash ? txUrl(explorer, t.txHash) : `${ALEPH_EXPLORER}${address}`,
517
+ priceAs: 'USD'
518
+ });
519
+ });
520
+ }
package/src/bitcoin.js CHANGED
@@ -35,7 +35,7 @@ import { sha256 } from '@noble/hashes/sha2.js';
35
35
  import { ripemd160 } from '@noble/hashes/legacy.js';
36
36
  import { toHex, utf8 } from '@le-space/ledger/bytes';
37
37
 
38
- import { txUrl } from './registry.js';
38
+ import { txUrl } from './explorer.js';
39
39
  import { createJsonFetcher, WalletError } from './http.js';
40
40
  import { unitsToDecimal } from './cosmos.js';
41
41
 
@@ -0,0 +1,36 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // An EVM address on its own: the EIP-55 checksum and the check of an
3
+ // address's form. Only keccak and bytes – no reader, no registry, no
4
+ // Alchemy – so a module that only needs an address (aleph.js, a browser
5
+ // form) does not bundle the EVM reader. evm.js re-exports both.
6
+
7
+ import { keccak_256 } from '@noble/hashes/sha3.js';
8
+ import { toHex, utf8 } from '@le-space/ledger/bytes';
9
+
10
+ /**
11
+ * EIP-55: the mixed-case checksum of an address.
12
+ *
13
+ * @param {string} address 0x + 40 hex
14
+ */
15
+ export function toChecksumAddress(address) {
16
+ const hex = address.slice(2).toLowerCase();
17
+ const hash = toHex(keccak_256(utf8(hex)));
18
+ let out = '0x';
19
+ for (let i = 0; i < 40; i++) {
20
+ out += parseInt(hash[i], 16) >= 8 ? hex[i].toUpperCase() : hex[i];
21
+ }
22
+ return out;
23
+ }
24
+
25
+ /**
26
+ * 0x + 40 hex; when it mixes cases, the EIP-55 checksum must hold (a typo
27
+ * then shows). All lower or all upper case carries no checksum.
28
+ *
29
+ * @param {string} address
30
+ */
31
+ export function isEvmAddress(address) {
32
+ if (typeof address !== 'string' || !/^0x[0-9a-fA-F]{40}$/.test(address)) return false;
33
+ const body = address.slice(2);
34
+ if (body === body.toLowerCase() || body === body.toUpperCase()) return true;
35
+ return toChecksumAddress(address) === address;
36
+ }
@@ -0,0 +1,27 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // The EVM contracts a swap is named after, on their own so that the EVM
3
+ // reader does not bundle every chain's data (registry.js re-exports them).
4
+
5
+ /**
6
+ * Contracts a wallet meets when it swaps (issue #115), by their lower-case
7
+ * address, and what they are called. Routers of the big aggregators and DEXes
8
+ * sit at the same address on most EVM chains; WETH is Ethereum's. Checked
9
+ * against the projects' own documentation; an address not here stays
10
+ * "Vertrag".
11
+ */
12
+ export const KNOWN_EVM_CONTRACTS = /** @type {Readonly<Record<string, string>>} */ (
13
+ Object.freeze({
14
+ '0x881d40237659c251811cec9c364ef91dc08d300c': 'MetaMask Swap (Router)',
15
+ '0x74de5d4fcbf63e00296fd95d33236b9794016631': 'MetaMask Swap (Spender)',
16
+ '0x3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad': 'Uniswap (Universal Router)',
17
+ '0x66a9893cc07d91d95644aedd05d03f95e1dba8af': 'Uniswap (Universal Router v4)',
18
+ '0x7a250d5630b4cf539739df2c5dacb4c659f2488d': 'Uniswap V2 (Router)',
19
+ '0xe592427a0aece92de3edee1f18e0157c05861564': 'Uniswap V3 (Router)',
20
+ '0x68b3465833fb72a70ecdf485e0e4c7bd8665fc45': 'Uniswap V3 (Router 2)',
21
+ '0x1111111254eeb25477b68fb85ed929f73a960582': '1inch (Router v5)',
22
+ '0x111111125421ca6dc452d289314280a0f8842a65': '1inch (Router v6)',
23
+ '0xdef1c0ded9bec7f1a1670819833240f027b25eff': '0x (Exchange Proxy)',
24
+ '0x9008d19f58aabd9ed0d60971565aa8510560ab41': 'CoW Protocol (Settlement)',
25
+ '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2': 'WETH'
26
+ })
27
+ );
package/src/evm.js CHANGED
@@ -35,7 +35,7 @@
35
35
  // token is a listed one – an unlisted symbol is the token's own claim)
36
36
  // and the router it went through, and the gas it cost (the gas entry
37
37
  // stays a fee of its own and names the swap). Known routers and WETH are named
38
- // (registry.js KNOWN_EVM_CONTRACTS).
38
+ // (evm-contracts.js, re-exported by registry.js).
39
39
  //
40
40
  // The log gets counts, never an address.
41
41
  //
@@ -43,14 +43,14 @@
43
43
  // own, the lists come from Alchemy instead (alchemy.js), in the same shape,
44
44
  // and become entries here in the same way.
45
45
 
46
- import { 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';
46
+ import { isEvmAddress, toChecksumAddress } from './evm-address.js';
47
+ import { KNOWN_EVM_CONTRACTS } from './evm-contracts.js';
48
+ import { addressUrl, txUrl } from './explorer.js';
50
49
  import { markSwaps } from './core.js';
51
50
  import { createJsonFetcher, WalletError } from './http.js';
52
51
  import { unitsToDecimal } from './cosmos.js';
53
- import { alchemyBaseUrl, createAlchemyReader } from './alchemy.js';
52
+ import { alchemyBaseUrl, createAlchemyReader, isAlchemyKey } from './alchemy.js';
53
+ import { derivedStatement, fromWalletEntry, sortEntries } from '@le-space/ledger';
54
54
 
55
55
  /** Symbols an unlisted token may never be booked under: the big ones a fake would copy. */
56
56
  const LOOKALIKE_GUARD = [
@@ -68,34 +68,6 @@ const LOOKALIKE_GUARD = [
68
68
 
69
69
  const PAGE = 1000;
70
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
71
  /** @param {unknown} v */
100
72
  const bigintOf = (v) => (typeof v === 'string' && /^\d+$/.test(v) ? BigInt(v) : null);
101
73
 
@@ -695,3 +667,109 @@ export function createEvmClient({
695
667
  }
696
668
 
697
669
  export { markSwaps };
670
+ // The address helpers live in evm-address.js (no reader, no Alchemy); here as before.
671
+ export { isEvmAddress, toChecksumAddress };
672
+
673
+ // ---- as ledger entries, for an Eigenbeleg or a Kontoauszug (from the
674
+ // Eigenbeleg agent's readers/evm.js): what an own address paid and received
675
+ // – the native coin and the tokens the chain lists – and the gas of every
676
+ // transaction it sent, also a failed one's; and the period. Through Alchemy
677
+ // only: the key is handed to each read (never kept, never in an answer or a
678
+ // log). Without a key the client would fall back to Blockscout, which answers
679
+ // only a few requests per half hour and IP; the reader refuses instead.
680
+
681
+ /** Market prices for the assets the chains list (ETH, USDC, ALEPH). */
682
+ const LEDGER_PRICE_AS = /** @type {Record<string, string>} */ ({
683
+ ETH: 'ETH',
684
+ USDC: 'USDC',
685
+ ALEPH: 'ALEPH'
686
+ });
687
+
688
+ /** @param {unknown} key @returns {string} */
689
+ function needKey(key) {
690
+ if (!isAlchemyKey(key)) throw new Error('this reader needs an Alchemy key');
691
+ return /** @type {string} */ (key);
692
+ }
693
+
694
+ /**
695
+ * The ledger reader for one EVM chain of the registry that Alchemy serves
696
+ * (`CHAINS.ethereum`, `CHAINS.base`). The chain is handed in, so this module
697
+ * stays free of the registry.
698
+ *
699
+ * @param {import('./registry.js').EvmChain} chain
700
+ * @param {{ baseUrl?: (network: string) => string }} [o] tests: a fake Alchemy on 127.0.0.1
701
+ */
702
+ export function evmReader(chain, { baseUrl } = {}) {
703
+ if (chain?.kind !== 'evm' || !chain.alchemy)
704
+ throw new Error(`no EVM chain ${chain?.id} with Alchemy`);
705
+ const network = `${chain.name}-Netzwerk (Gas)`;
706
+
707
+ /**
708
+ * A WalletEntry → the ledger entry a document books; the gas goes to the network,
709
+ * and is paid also when the transaction failed.
710
+ *
711
+ * @param {import('@le-space/ledger/wallet-entry').WalletEntry} e
712
+ * @param {string} account
713
+ */
714
+ const toLedger = (e, account) => {
715
+ const fee = e.type === 'fee';
716
+ return fromWalletEntry(
717
+ e,
718
+ { chain: chain.id, network: 'mainnet', account, priceAs: LEDGER_PRICE_AS[e.asset] ?? '' },
719
+ {
720
+ counterparty: fee ? chain.id : String(e.counterparty ?? ''),
721
+ counterpartyLabel: fee ? network : String(e.counterpartyLabel ?? ''),
722
+ success: fee ? true : e.success !== false
723
+ }
724
+ );
725
+ };
726
+
727
+ /** @param {{ account: string, fetch?: typeof fetch, alchemyKey?: string }} p */
728
+ const history = async ({ account, fetch: f = globalThis.fetch, alchemyKey }) => {
729
+ if (!isEvmAddress(account))
730
+ throw new Error(`not an ${chain.name} address (0x and 40 hex digits)`);
731
+ const key = needKey(alchemyKey);
732
+ const client = createEvmClient({
733
+ fetch: f,
734
+ alchemy: { key: async () => key, ...(baseUrl ? { baseUrl } : {}) }
735
+ });
736
+ const r = await client.history({ chain, address: account, endpoints: chain.endpoints });
737
+ return { all: sortEntries(r.entries.map((e) => toLedger(e, account))), balances: r.balances };
738
+ };
739
+
740
+ return {
741
+ chain,
742
+ toLedger,
743
+ /** Ledger entries for an account and period. @param {{ account: string, from: string, to: string, fetch?: typeof fetch, alchemyKey?: string }} p */
744
+ read: async (p) => (await history(p)).all.filter((e) => e.date >= p.from && e.date <= p.to),
745
+ /** For a Kontoauszug: balances derived from today's balance less the movements since, as for Akash. @param {{ account: string, from: string, to: string, fetch?: typeof fetch, alchemyKey?: string }} p */
746
+ statement: async (p) => {
747
+ const { all, balances } = await history(p);
748
+ return derivedStatement(all, balances, p.from, p.to);
749
+ },
750
+ /** Alchemy answers for the chain with this key. @param {{ fetch?: typeof fetch, alchemyKey?: string }} [p] */
751
+ probe: async ({ fetch: f = globalThis.fetch, alchemyKey } = {}) => {
752
+ const key = needKey(alchemyKey);
753
+ const alchemyNetwork = /** @type {import('./registry.js').AlchemyNetwork} */ (chain.alchemy);
754
+ // The key is in the URL: no message here names the URL or passes on fetch's own.
755
+ const res = await f(`${(baseUrl ?? alchemyBaseUrl)(alchemyNetwork.network)}/${key}`, {
756
+ method: 'POST',
757
+ headers: { 'content-type': 'application/json' },
758
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_chainId', params: [] })
759
+ }).catch(() => null);
760
+ if (!res) throw new Error('Alchemy is not reachable');
761
+ if (!res.ok) throw new Error(`Alchemy answered ${res.status}`);
762
+ const body = await res.json().catch(() => null);
763
+ const served =
764
+ typeof body?.result === 'string' && /^0x[0-9a-f]+$/i.test(body.result)
765
+ ? Number(BigInt(body.result))
766
+ : null;
767
+ if (served !== chain.chainId)
768
+ throw new Error(`Alchemy does not serve ${chain.name} (${chain.chainId}) here`);
769
+ return { sample: `${alchemyNetwork.network} eth_chainId`, entries: 1 };
770
+ },
771
+ isAddress: isEvmAddress,
772
+ /** One spelling per account: the EIP-55 checksum. @param {string} a */
773
+ canonical: (a) => toChecksumAddress(a)
774
+ };
775
+ }
package/src/filecoin.js CHANGED
@@ -37,6 +37,8 @@
37
37
  import { base32nopad } from '@scure/base';
38
38
  import { blake2b } from '@noble/hashes/blake2.js';
39
39
  import { fromHex } from '@le-space/ledger/bytes';
40
+ import { derivedStatement, fromWalletEntry, sortEntries } from '@le-space/ledger';
41
+ import { FILECOIN } from './filecoin-chain.js';
40
42
 
41
43
  import {
42
44
  addressUrl,
@@ -396,3 +398,76 @@ export function createFilecoinClient({ fetch: f, timeoutMs, sleep }) {
396
398
  }
397
399
  };
398
400
  }
401
+
402
+ // ---- as ledger entries, for an Eigenbeleg or a Kontoauszug (from the
403
+ // Eigenbeleg agent's readers/filecoin.js): the fee goes to the network, FIL
404
+ // and USDFC are priced; and the period.
405
+
406
+ const PRICE_AS = { FIL: 'FIL', USDFC: 'USDC' };
407
+
408
+ /**
409
+ * A WalletEntry → the ledger entry a document books.
410
+ *
411
+ * @param {import('@le-space/ledger/wallet-entry').WalletEntry} e
412
+ * @param {string} account
413
+ */
414
+ export function toLedger(e, account) {
415
+ const fee = e.type === 'fee';
416
+ return fromWalletEntry(
417
+ e,
418
+ {
419
+ chain: 'filecoin',
420
+ network: 'mainnet',
421
+ account,
422
+ priceAs: PRICE_AS[/** @type {keyof typeof PRICE_AS} */ (e.asset)] ?? ''
423
+ },
424
+ {
425
+ kind: fee ? 'fee' : e.kind === 'swap' ? 'swap' : 'transfer',
426
+ contract: e.contract ?? 'native',
427
+ counterparty: fee ? 'filecoin' : String(e.counterparty ?? ''),
428
+ counterpartyLabel: fee
429
+ ? 'Filecoin-Netzwerk (Miner-Tip und verbrannte Gebühr)'
430
+ : String(e.counterpartyLabel ?? ''),
431
+ memo: '',
432
+ success: fee ? true : e.success !== false
433
+ }
434
+ );
435
+ }
436
+
437
+ /**
438
+ * @param {object} p
439
+ * @param {string} p.account f0/f1/f3/f410f or 0x
440
+ * @param {typeof fetch} [p.fetch]
441
+ * @param {{ api?: string }} [p.endpoints] instead of Filfox, e.g. behind a proxy
442
+ */
443
+ async function ledgerHistory({ account, fetch = globalThis.fetch, endpoints }) {
444
+ if (!isFilecoinAddress(account)) throw new Error('not a valid Filecoin address');
445
+ const address = toFilecoinAddress(account) ?? account;
446
+ const { entries, balances } = await createFilecoinClient({ fetch }).history({
447
+ chain: FILECOIN,
448
+ address,
449
+ endpoints: { ...FILECOIN.endpoints, ...endpoints }
450
+ });
451
+ return { all: sortEntries(entries.map((e) => toLedger(e, address))), balances };
452
+ }
453
+
454
+ /** Ledger entries for an account and period. @param {Parameters<typeof ledgerHistory>[0] & { from: string, to: string }} p */
455
+ export async function readFilecoin(p) {
456
+ const { all } = await ledgerHistory(p);
457
+ return all.filter((e) => e.date >= p.from && e.date <= p.to);
458
+ }
459
+
460
+ /** For a Kontoauszug: balances derived from today's balance less the movements since (as for Akash). @param {Parameters<typeof readFilecoin>[0]} p */
461
+ export async function statementFilecoin(p) {
462
+ const { all, balances } = await ledgerHistory(p);
463
+ return derivedStatement(all, balances, p.from, p.to);
464
+ }
465
+
466
+ /** The storage market actor always exists: Filfox answers for it when the source is up. @param {{ fetch?: typeof fetch, endpoints?: { api?: string } }} [o] */
467
+ export async function probe({ fetch = globalThis.fetch, endpoints } = {}) {
468
+ const res = await fetch(`${endpoints?.api ?? FILECOIN.endpoints.api}/address/f05`);
469
+ if (!res.ok) throw new Error(`Filfox answered ${res.status}`);
470
+ const body = await res.json();
471
+ if (!body?.balance) throw new Error('Filfox answered without a balance');
472
+ return { sample: 'Filfox f05 (storage market actor)', entries: 1 };
473
+ }
package/src/http.js CHANGED
@@ -93,6 +93,13 @@ export function createJsonFetcher({
93
93
  continue;
94
94
  }
95
95
  const body = await res.json().catch(() => undefined);
96
+ // A refusal in plain text (Aleph's 404 for an empty window): asking
97
+ // again changes nothing, and the caller may tell it apart by its status.
98
+ if (body === undefined && res.status >= 400 && res.status < 500 && res.status !== 429) {
99
+ const error = new WalletError(`${host} answered ${res.status} without JSON`, 'WALLET_NODE');
100
+ error.httpStatus = res.status;
101
+ throw error;
102
+ }
96
103
  if (res.status === 429 || res.status >= 500 || body === undefined) {
97
104
  last = new WalletError(
98
105
  res.status === 429