@le-space/chains 0.1.0 → 0.3.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,15 +7,19 @@ 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 | Blockscout, or Alchemy with a key | `evm`, `alchemy` |
10
+ | Ethereum, Base, Arbitrum One, OP Mainnet, Polygon PoS (USDC listed; ALEPH on Ethereum and Base) | Blockscout, or Alchemy with a key | `evm`, `alchemy` |
11
11
  | Bitcoin | Esplora; addresses derived from a zpub/ypub/xpub | `bitcoin` |
12
12
  | Filecoin | Filfox | `filecoin` |
13
13
  | NEAR | NearBlocks + an archival RPC (from Eigenbeleg); gives `LedgerEntry` | `near` |
14
+ | 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` |
14
15
 
15
16
  - `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
+ - `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.
18
+ - `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).
17
19
  - `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.
20
+ - Fakes for tests, with made-up addresses, hashes, keys and amounts:
21
+ - `@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.
22
+ - `@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`).
19
23
 
20
24
  Each source sees the address and the IP address of the machine that asks; Belege's consent screen says so.
21
25
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@le-space/chains",
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.",
3
+ "version": "0.3.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), 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",
7
7
  "repository": {
@@ -24,12 +24,19 @@
24
24
  "./akash-console": "./src/akash-console.js",
25
25
  "./akash-deployments": "./src/akash-deployments.js",
26
26
  "./evm": "./src/evm.js",
27
+ "./evm-address": "./src/evm-address.js",
28
+ "./evm-contracts": "./src/evm-contracts.js",
27
29
  "./alchemy": "./src/alchemy.js",
28
30
  "./bitcoin": "./src/bitcoin.js",
29
31
  "./filecoin": "./src/filecoin.js",
32
+ "./filecoin-chain": "./src/filecoin-chain.js",
30
33
  "./near": "./src/near.js",
34
+ "./aleph": "./src/aleph.js",
31
35
  "./testing/cosmos": "./test/support/fake-cosmos.js",
32
- "./testing/filfox": "./test/support/fake-filfox.js"
36
+ "./testing/filfox": "./test/support/fake-filfox.js",
37
+ "./testing/blockscout": "./test/support/fake-blockscout.js",
38
+ "./testing/alchemy": "./test/support/fake-alchemy.js",
39
+ "./testing/aleph": "./test/support/aleph.js"
33
40
  },
34
41
  "files": [
35
42
  "src",
@@ -46,7 +53,8 @@
46
53
  "@noble/hashes": "2.4.0",
47
54
  "@scure/base": "2.4.0",
48
55
  "@scure/bip32": "2.4.0",
49
- "@le-space/ledger": "^0.1.0"
56
+ "@le-space/ledger": "^0.3.0",
57
+ "@le-space/rates": "^0.3.0"
50
58
  },
51
59
  "devDependencies": {
52
60
  "prettier": "3.6.2",
package/src/aleph.js ADDED
@@ -0,0 +1,454 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Aleph Cloud, read only: what an account's credits did in one month – the
3
+ // source of the monthly consumption statement (issue #113). No key, no
4
+ // signing, no transfer or forget: only the public API that the official
5
+ // client (aleph-im/aleph-rs, `aleph credit history|summary`) reads too.
6
+ //
7
+ // GET /api/v0/addresses/<a>/balance `credit_balance` now
8
+ // GET /api/v0/addresses/<a>/credit_history one row per entry, newest
9
+ // ?page=&pagination=&startDate=&endDate= first; filters in Unix
10
+ // seconds, inclusive
11
+ // GET /api/v0/addresses/<a>/credit_history/summary net, in and out of a window
12
+ //
13
+ // A row with a positive amount brings credits in: a purchase (with its
14
+ // per-credit `price` in USD, token, chain and transaction hash) or a transfer
15
+ // from another account. A negative one takes them out: `credit_expense` is
16
+ // consumption, billed about hourly per kind of resource (`origin_ref`:
17
+ // `storage`, `execution`, …) with the number of resources and their size;
18
+ // anything else is a transfer out. Storage is billed as one line for all
19
+ // stores (`origin_ref: storage`, with their number and size); compute per
20
+ // resource: `origin` is the instance's or program's item hash, `origin_ref`
21
+ // the billing message. The statement lists consumption per day, storage in
22
+ // one line and each instance in its own, named from its message
23
+ // (`/api/v0/messages/<hash>`, `content.metadata.name`).
24
+ //
25
+ // Opening and closing balance: the balance now, less what came and went
26
+ // since the month began or ended (the summary endpoint), so they are exact
27
+ // and need no history before the month.
28
+ //
29
+ // Euro value (a choice for the tax adviser, documented on the statement):
30
+ // credits are priced in USD; a day's consumption is valued at the per-credit
31
+ // price of the last purchase on or before that day, or Aleph's list price of
32
+ // 1 USD per 1,000,000 credits when the account never bought any (credits
33
+ // moved in from another account), then converted at that day's ECB
34
+ // reference rate – the rule is @le-space/rates' (aleph-credits.js).
35
+ //
36
+ // Aleph is no blockchain: the credits live in Aleph's own network, keyed by
37
+ // the account's Ethereum address. `alephEntries` gives a statement's lines as
38
+ // @le-space/ledger entries (`chain: 'aleph'`): purchases and transfers in,
39
+ // transfers out, and a day's consumption per resource as `usage`. The ALEPH
40
+ // token itself is an ERC-20 on Ethereum and Base, read by the EVM reader.
41
+ //
42
+ // In a browser: Aleph's API answers with CORS headers for the origins that
43
+ // read it (checked 2026-11-06 for eigenbelege.le-space.de), so no proxy.
44
+ //
45
+ // Aleph keys accounts by their EIP-55 checksummed address: asked in lower
46
+ // case, it answers a balance of 0 and no history. Every address is
47
+ // checksummed before it is asked about.
48
+ //
49
+ // Times are UTC; the month is the UTC month. The log gets counts, never an
50
+ // address.
51
+
52
+ import { entry, sortEntries } from '@le-space/ledger';
53
+ import {
54
+ ALEPH_LIST_PRICE_USD,
55
+ alephCreditPrice,
56
+ alephCreditsInEur,
57
+ plain
58
+ } from '@le-space/rates/aleph-credits';
59
+ import { createJsonFetcher, WalletError } from './http.js';
60
+ import { toChecksumAddress } from './evm-address.js';
61
+
62
+ export const ALEPH_API = 'https://api2.aleph.im';
63
+ /** Aleph's list price, USD per credit (@le-space/rates). */
64
+ export const LIST_PRICE_USD = ALEPH_LIST_PRICE_USD;
65
+ /** Where an Aleph message (an instance, a program, a purchase) can be looked at. */
66
+ export const ALEPH_EXPLORER = 'https://explorer.aleph.cloud/address/ETH/';
67
+ const PER_PAGE = 100;
68
+
69
+ /** @param {unknown} v */
70
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : Number(v ?? NaN));
71
+
72
+ /**
73
+ * `YYYY-MM` → its first and last second, Unix, UTC.
74
+ *
75
+ * @param {string} month
76
+ */
77
+ export function monthWindow(month) {
78
+ const m = /^(\d{4})-(0[1-9]|1[0-2])$/.exec(month);
79
+ if (!m) throw new WalletError('month must be YYYY-MM', 'ALEPH_MONTH', 400);
80
+ const start = Date.UTC(Number(m[1]), Number(m[2]) - 1, 1) / 1000;
81
+ const next = Date.UTC(Number(m[1]), Number(m[2]), 1) / 1000;
82
+ return { start, end: next - 1, next };
83
+ }
84
+
85
+ /**
86
+ * @typedef {object} TopUp
87
+ * @property {string} time ISO
88
+ * @property {number} credits
89
+ * @property {number} bonus credits given on top
90
+ * @property {'purchase' | 'transfer'} how
91
+ * @property {string | null} price USD per credit, a purchase's
92
+ * @property {string | null} token
93
+ * @property {string | null} chain
94
+ * @property {string | null} txHash the paying transaction
95
+ * @property {string} from for a transfer, the account it came from ('' when not said)
96
+ */
97
+
98
+ /**
99
+ * @typedef {object} UsageLine one day's consumption of one kind of resource
100
+ * @property {string} date YYYY-MM-DD (UTC)
101
+ * @property {string} kind `storage`, or `execution` for a billed instance or program
102
+ * @property {string | null} resource the instance's item hash, for `execution`
103
+ * @property {number} credits
104
+ * @property {number} entries how many billing entries (about one an hour)
105
+ * @property {number} resources the most resources billed at once that day
106
+ * @property {number | null} sizeMib the largest size billed that day
107
+ * @property {string} usdPerCredit
108
+ * @property {'purchase' | 'list'} priceSource
109
+ * @property {string | null} eurPerUsd the ECB rate of the day
110
+ * @property {number | null} eurCents
111
+ */
112
+
113
+ /**
114
+ * The rows of one month → the statement's lines. Pure.
115
+ *
116
+ * @param {object} p
117
+ * @param {any[]} p.rows credit_history rows of the month
118
+ * @param {any[]} p.purchases every incoming row with a price, any time
119
+ */
120
+ export function summarise({ rows, purchases }) {
121
+ /** @type {TopUp[]} */
122
+ const topUps = [];
123
+ /** @type {{ time: string, credits: number, to: string }[]} */
124
+ const transfersOut = [];
125
+ /** @type {Map<string, UsageLine>} */
126
+ const days = new Map();
127
+ const priceOn = alephCreditPrice(
128
+ purchases.map((p) => ({ time: String(p?.message_timestamp), price: p?.price }))
129
+ );
130
+
131
+ for (const r of rows) {
132
+ const amount = num(r?.amount);
133
+ const time = new Date(String(r?.message_timestamp)).toISOString();
134
+ if (!Number.isFinite(amount) || amount === 0) continue;
135
+ if (amount > 0) {
136
+ const purchase = Boolean(r.price || r.tx_hash);
137
+ topUps.push({
138
+ time,
139
+ credits: amount,
140
+ bonus: num(r.bonus_amount) || 0,
141
+ how: purchase ? 'purchase' : 'transfer',
142
+ price: r.price ? String(r.price) : null,
143
+ token: r.token ? String(r.token) : null,
144
+ chain: r.chain ? String(r.chain) : null,
145
+ txHash: r.tx_hash ? String(r.tx_hash) : null,
146
+ from: purchase ? '' : String(r.origin ?? '')
147
+ });
148
+ continue;
149
+ }
150
+ if (r.payment_method !== 'credit_expense') {
151
+ transfersOut.push({ time, credits: -amount, to: String(r.origin ?? '') });
152
+ continue;
153
+ }
154
+ const date = time.slice(0, 10);
155
+ const resource = /^[0-9a-f]{64}$/.test(String(r.origin ?? '')) ? String(r.origin) : null;
156
+ const kind = resource ? 'execution' : String(r.origin_ref || 'other');
157
+ const key = `${date} ${kind} ${resource ?? ''}`;
158
+ const size = num(r.expense_size_mib);
159
+ const line = days.get(key) ?? {
160
+ date,
161
+ kind,
162
+ resource,
163
+ credits: 0,
164
+ entries: 0,
165
+ resources: 0,
166
+ sizeMib: null,
167
+ usdPerCredit: priceOn(date).usdPerCredit,
168
+ priceSource: priceOn(date).source,
169
+ eurPerUsd: null,
170
+ eurCents: null
171
+ };
172
+ line.credits += -amount;
173
+ line.entries += 1;
174
+ line.resources = Math.max(line.resources, num(r.expense_count) || 0);
175
+ if (Number.isFinite(size)) line.sizeMib = Math.max(line.sizeMib ?? 0, size);
176
+ days.set(key, line);
177
+ }
178
+ const usage = [...days.values()].sort(
179
+ (a, b) =>
180
+ a.date.localeCompare(b.date) ||
181
+ a.kind.localeCompare(b.kind) ||
182
+ String(a.resource).localeCompare(String(b.resource))
183
+ );
184
+ topUps.sort((a, b) => a.time.localeCompare(b.time));
185
+ transfersOut.sort((a, b) => a.time.localeCompare(b.time));
186
+ return { topUps, transfersOut, usage };
187
+ }
188
+
189
+ /**
190
+ * @param {object} [options]
191
+ * @param {typeof fetch} [options.fetch]
192
+ * @param {number} [options.timeoutMs]
193
+ * @param {(ms: number) => Promise<void>} [options.sleep]
194
+ * @param {number} [options.maxPages]
195
+ * @param {{ rate: (asset: string, date: string) => Promise<{ rate: string, source: string }> } | null} [options.rates]
196
+ * @param {() => Date} [options.now]
197
+ */
198
+ export function createAlephClient({
199
+ fetch: f = fetch,
200
+ timeoutMs = 30_000,
201
+ sleep,
202
+ maxPages = 200,
203
+ rates = null,
204
+ now = () => new Date()
205
+ } = {}) {
206
+ const getJson = createJsonFetcher({ fetch: f, timeoutMs, sleep });
207
+
208
+ return {
209
+ /**
210
+ * Which of these addresses are Aleph accounts: each one's credits now and
211
+ * how many credit entries it ever had. Read only; one balance and one
212
+ * summary request per address.
213
+ *
214
+ * @param {object} p
215
+ * @param {string[]} p.addresses 0x…, at most 50
216
+ * @param {string} [p.api] checked by the caller
217
+ */
218
+ async accounts({ addresses, api = ALEPH_API }) {
219
+ const unique = [...new Set(addresses.map((a) => String(a).toLowerCase()))];
220
+ if (unique.length > 50) throw new WalletError('at most 50 addresses', 'ALEPH_TOO_MANY', 400);
221
+ /** @type {{ address: string, credits: number, entries: number }[]} */
222
+ const out = [];
223
+ for (const lower of unique) {
224
+ if (!/^0x[0-9a-f]{40}$/.test(lower)) {
225
+ throw new WalletError('not an Aleph account address (0x + 40 hex)', 'ALEPH_ADDRESS', 400);
226
+ }
227
+ const address = toChecksumAddress(lower);
228
+ const base = `${api}/api/v0/addresses/${address}`;
229
+ const balance = await getJson(`${base}/balance`).catch((/** @type {any} */ e) => {
230
+ // An address Aleph has never seen: 404, nothing there.
231
+ if (e?.httpStatus === 404) return { credit_balance: 0 };
232
+ throw e;
233
+ });
234
+ const summary = await getJson(`${base}/credit_history/summary`);
235
+ out.push({
236
+ address,
237
+ credits: num(balance?.credit_balance) || 0,
238
+ entries: num(summary?.entry_count) || 0
239
+ });
240
+ }
241
+ return out;
242
+ },
243
+
244
+ /**
245
+ * @param {object} p
246
+ * @param {string} p.address 0x…
247
+ * @param {string} p.month YYYY-MM
248
+ * @param {string} [p.api] checked by the caller
249
+ */
250
+ async statement({ address: given, month, api = ALEPH_API }) {
251
+ if (!/^0x[0-9a-fA-F]{40}$/.test(given)) {
252
+ throw new WalletError('not an Aleph account address (0x + 40 hex)', 'ALEPH_ADDRESS', 400);
253
+ }
254
+ const address = toChecksumAddress(given);
255
+ const { start, end, next } = monthWindow(month);
256
+ const nowSeconds = Math.floor(now().getTime() / 1000);
257
+ if (start > nowSeconds) throw new WalletError('that month has not begun', 'ALEPH_MONTH', 400);
258
+ const base = `${api}/api/v0/addresses/${address}`;
259
+
260
+ const balance = await getJson(`${base}/balance`);
261
+ const current = num(balance?.credit_balance);
262
+ if (!Number.isFinite(current)) {
263
+ throw new WalletError('Aleph answered the balance without credits', 'ALEPH_DATA');
264
+ }
265
+ /** What came and went from a moment on. @param {number} from */
266
+ const netSince = async (from) => {
267
+ if (from > nowSeconds) return 0;
268
+ const s = await getJson(`${base}/credit_history/summary?startDate=${from}`);
269
+ const net = num(s?.total_amount);
270
+ if (!Number.isFinite(net)) {
271
+ throw new WalletError('Aleph answered the summary without a total', 'ALEPH_DATA');
272
+ }
273
+ return net;
274
+ };
275
+ const opening = current - (await netSince(start));
276
+ const closing = current - (await netSince(next));
277
+
278
+ /** @param {string} query */
279
+ const pages = async (query) => {
280
+ /** @type {any[]} */
281
+ const rows = [];
282
+ for (let page = 1; ; page++) {
283
+ if (page > maxPages) {
284
+ throw new WalletError(
285
+ `more than ${maxPages * PER_PAGE} credit entries; not read`,
286
+ 'ALEPH_TOO_MANY'
287
+ );
288
+ }
289
+ // A window without rows: Aleph answers 404 in plain text (the same
290
+ // address without the window answers 200) – an empty page, as the
291
+ // balance's 404 is nothing there.
292
+ const body = await getJson(
293
+ `${base}/credit_history?page=${page}&pagination=${PER_PAGE}${query}`
294
+ ).catch((/** @type {any} */ e) => {
295
+ if (e?.httpStatus === 404) return { credit_history: [], pagination_total: 0 };
296
+ throw e;
297
+ });
298
+ const batch = Array.isArray(body?.credit_history) ? body.credit_history : null;
299
+ if (!batch) throw new WalletError('Aleph answered without a history', 'ALEPH_DATA');
300
+ rows.push(...batch);
301
+ if (!batch.length || page * PER_PAGE >= num(body.pagination_total)) break;
302
+ }
303
+ return rows;
304
+ };
305
+ const rows = await pages(`&startDate=${start}&endDate=${end}`);
306
+ // Prices of every purchase up to the month's end, to value its consumption.
307
+ const purchases = (await pages(`&endDate=${end}&direction=incoming`)).filter((r) => r?.price);
308
+ const { topUps, transfersOut, usage } = summarise({ rows, purchases });
309
+
310
+ // What each billed resource is: its type and the name it was given.
311
+ /** @type {Record<string, { type: string, name: string }>} */
312
+ const resources = {};
313
+ for (const hash of new Set(usage.map((u) => u.resource).filter((h) => h !== null))) {
314
+ if (Object.keys(resources).length >= 50) break;
315
+ const body = await getJson(`${api}/api/v0/messages/${hash}`).catch(() => null);
316
+ const message = body?.message ?? body;
317
+ resources[/** @type {string} */ (hash)] = {
318
+ type: String(message?.type ?? ''),
319
+ name: String(message?.content?.metadata?.name ?? '').slice(0, 80)
320
+ };
321
+ }
322
+
323
+ /** @type {Map<string, string | null>} */
324
+ const eurPerUsd = new Map();
325
+ let rateSource = null;
326
+ if (rates) {
327
+ for (const line of usage) {
328
+ if (!eurPerUsd.has(line.date)) {
329
+ const r = await rates.rate('USD', line.date).catch(() => null);
330
+ eurPerUsd.set(line.date, r?.rate ?? null);
331
+ rateSource ??= r?.source ?? null;
332
+ }
333
+ const rate = eurPerUsd.get(line.date) ?? null;
334
+ line.eurPerUsd = rate;
335
+ line.eurCents =
336
+ rate === null
337
+ ? null
338
+ : Math.round(Number(alephCreditsInEur(line.credits, line.usdPerCredit, rate)) * 100);
339
+ }
340
+ }
341
+
342
+ const sum = (/** @type {number[]} */ xs) => xs.reduce((a, b) => a + b, 0);
343
+ const totals = {
344
+ topUps: sum(topUps.map((t) => t.credits)),
345
+ transfersOut: sum(transfersOut.map((t) => t.credits)),
346
+ usage: sum(usage.map((u) => u.credits)),
347
+ eurCents: usage.every((u) => u.eurCents !== null)
348
+ ? sum(usage.map((u) => /** @type {number} */ (u.eurCents)))
349
+ : null
350
+ };
351
+ return {
352
+ address,
353
+ month,
354
+ from: new Date(start * 1000).toISOString(),
355
+ until: new Date(end * 1000).toISOString(),
356
+ opening,
357
+ closing,
358
+ topUps,
359
+ transfersOut,
360
+ usage,
361
+ resources,
362
+ totals,
363
+ // opening + in − out = closing; a difference means entries the history did not list
364
+ difference: opening + totals.topUps - totals.usage - totals.transfersOut - closing,
365
+ rateSource,
366
+ entries: rows.length
367
+ };
368
+ }
369
+ };
370
+ }
371
+
372
+ /** A credit amount as a decimal string. @param {number} credits */
373
+ const credits = (credits) => plain(credits);
374
+
375
+ /**
376
+ * A statement's lines as ledger entries, seen from the account: purchases and
377
+ * transfers in (`received`), transfers out (`sent`), and each day's
378
+ * consumption per resource (`sent`, kind `usage`, with the USD price per
379
+ * credit it is valued at). Asset `ALEPH-CREDIT`, no market price.
380
+ *
381
+ * @param {Awaited<ReturnType<ReturnType<typeof createAlephClient>['statement']>>} statement
382
+ * @returns {import('@le-space/ledger').LedgerEntry[]}
383
+ */
384
+ export function alephEntries(statement) {
385
+ const { address, topUps, transfersOut, usage, resources } = statement;
386
+ const common = {
387
+ chain: 'aleph',
388
+ network: 'mainnet',
389
+ account: address,
390
+ height: 0,
391
+ asset: 'ALEPH-CREDIT',
392
+ contract: 'native',
393
+ decimals: 0,
394
+ method: '',
395
+ memo: '',
396
+ success: true,
397
+ priceAs: ''
398
+ };
399
+ const explorerUrl = `${ALEPH_EXPLORER}${address}`;
400
+ const out = [
401
+ ...topUps.map((t, i) =>
402
+ entry({
403
+ ...common,
404
+ id: `aleph:${address}:in:${t.time}:${i}`,
405
+ hash: t.txHash ?? '',
406
+ time: t.time,
407
+ type: 'received',
408
+ kind: 'transfer',
409
+ amount: credits(t.credits),
410
+ counterparty: t.how === 'purchase' ? 'aleph' : t.from,
411
+ counterpartyLabel:
412
+ t.how === 'purchase'
413
+ ? `Aleph Cloud (Kauf${t.token ? ` mit ${t.token}` : ''}${t.chain ? ` auf ${t.chain}` : ''})`
414
+ : '',
415
+ explorerUrl,
416
+ ...(t.price
417
+ ? { unitPrice: { currency: 'USD', amount: plain(t.price), source: 'purchase' } }
418
+ : {})
419
+ })
420
+ ),
421
+ ...transfersOut.map((t, i) =>
422
+ entry({
423
+ ...common,
424
+ id: `aleph:${address}:out:${t.time}:${i}`,
425
+ hash: '',
426
+ time: t.time,
427
+ type: 'sent',
428
+ kind: 'transfer',
429
+ amount: `-${credits(t.credits)}`,
430
+ counterparty: t.to,
431
+ counterpartyLabel: '',
432
+ explorerUrl
433
+ })
434
+ ),
435
+ ...usage.map((u) => {
436
+ const what = u.resource ? resources?.[u.resource] : null;
437
+ return entry({
438
+ ...common,
439
+ id: `aleph:${address}:usage:${u.date}:${u.kind}:${u.resource ?? ''}`,
440
+ hash: u.resource ?? '',
441
+ time: `${u.date}T00:00:00Z`,
442
+ type: 'sent',
443
+ kind: 'usage',
444
+ amount: `-${credits(u.credits)}`,
445
+ counterparty: 'aleph',
446
+ counterpartyLabel: `Aleph Cloud (${what?.name || u.kind})`,
447
+ memo: `${u.entries} Abrechnungen`,
448
+ explorerUrl,
449
+ unitPrice: { currency: 'USD', amount: u.usdPerCredit, source: u.priceSource }
450
+ });
451
+ })
452
+ ];
453
+ return sortEntries(out);
454
+ }
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,10 +43,9 @@
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';
@@ -68,34 +67,6 @@ const LOOKALIKE_GUARD = [
68
67
 
69
68
  const PAGE = 1000;
70
69
 
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
70
  /** @param {unknown} v */
100
71
  const bigintOf = (v) => (typeof v === 'string' && /^\d+$/.test(v) ? BigInt(v) : null);
101
72
 
@@ -695,3 +666,5 @@ export function createEvmClient({
695
666
  }
696
667
 
697
668
  export { markSwaps };
669
+ // The address helpers live in evm-address.js (no reader, no Alchemy); here as before.
670
+ export { isEvmAddress, toChecksumAddress };
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