@le-space/chains 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/package.json +5 -3
- package/src/aleph.js +448 -0
- package/src/index.js +3 -0
- package/src/registry.js +13 -2
- package/test/support/aleph-fetch.js +80 -0
- package/test/support/aleph-sample.js +74 -0
package/README.md
CHANGED
|
@@ -7,10 +7,11 @@ 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
17
|
- `CHAINS`, `chainOf`, `publicChains` – the chains, their assets, default endpoints and explorers (`registry`).
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@le-space/chains",
|
|
3
|
-
"version": "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.2.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": {
|
|
@@ -28,6 +28,7 @@
|
|
|
28
28
|
"./bitcoin": "./src/bitcoin.js",
|
|
29
29
|
"./filecoin": "./src/filecoin.js",
|
|
30
30
|
"./near": "./src/near.js",
|
|
31
|
+
"./aleph": "./src/aleph.js",
|
|
31
32
|
"./testing/cosmos": "./test/support/fake-cosmos.js",
|
|
32
33
|
"./testing/filfox": "./test/support/fake-filfox.js"
|
|
33
34
|
},
|
|
@@ -46,7 +47,8 @@
|
|
|
46
47
|
"@noble/hashes": "2.4.0",
|
|
47
48
|
"@scure/base": "2.4.0",
|
|
48
49
|
"@scure/bip32": "2.4.0",
|
|
49
|
-
"@le-space/ledger": "^0.
|
|
50
|
+
"@le-space/ledger": "^0.2.0",
|
|
51
|
+
"@le-space/rates": "^0.2.0"
|
|
50
52
|
},
|
|
51
53
|
"devDependencies": {
|
|
52
54
|
"prettier": "3.6.2",
|
package/src/aleph.js
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
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.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
|
+
const body = await getJson(
|
|
290
|
+
`${base}/credit_history?page=${page}&pagination=${PER_PAGE}${query}`
|
|
291
|
+
);
|
|
292
|
+
const batch = Array.isArray(body?.credit_history) ? body.credit_history : null;
|
|
293
|
+
if (!batch) throw new WalletError('Aleph answered without a history', 'ALEPH_DATA');
|
|
294
|
+
rows.push(...batch);
|
|
295
|
+
if (!batch.length || page * PER_PAGE >= num(body.pagination_total)) break;
|
|
296
|
+
}
|
|
297
|
+
return rows;
|
|
298
|
+
};
|
|
299
|
+
const rows = await pages(`&startDate=${start}&endDate=${end}`);
|
|
300
|
+
// Prices of every purchase up to the month's end, to value its consumption.
|
|
301
|
+
const purchases = (await pages(`&endDate=${end}&direction=incoming`)).filter((r) => r?.price);
|
|
302
|
+
const { topUps, transfersOut, usage } = summarise({ rows, purchases });
|
|
303
|
+
|
|
304
|
+
// What each billed resource is: its type and the name it was given.
|
|
305
|
+
/** @type {Record<string, { type: string, name: string }>} */
|
|
306
|
+
const resources = {};
|
|
307
|
+
for (const hash of new Set(usage.map((u) => u.resource).filter((h) => h !== null))) {
|
|
308
|
+
if (Object.keys(resources).length >= 50) break;
|
|
309
|
+
const body = await getJson(`${api}/api/v0/messages/${hash}`).catch(() => null);
|
|
310
|
+
const message = body?.message ?? body;
|
|
311
|
+
resources[/** @type {string} */ (hash)] = {
|
|
312
|
+
type: String(message?.type ?? ''),
|
|
313
|
+
name: String(message?.content?.metadata?.name ?? '').slice(0, 80)
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** @type {Map<string, string | null>} */
|
|
318
|
+
const eurPerUsd = new Map();
|
|
319
|
+
let rateSource = null;
|
|
320
|
+
if (rates) {
|
|
321
|
+
for (const line of usage) {
|
|
322
|
+
if (!eurPerUsd.has(line.date)) {
|
|
323
|
+
const r = await rates.rate('USD', line.date).catch(() => null);
|
|
324
|
+
eurPerUsd.set(line.date, r?.rate ?? null);
|
|
325
|
+
rateSource ??= r?.source ?? null;
|
|
326
|
+
}
|
|
327
|
+
const rate = eurPerUsd.get(line.date) ?? null;
|
|
328
|
+
line.eurPerUsd = rate;
|
|
329
|
+
line.eurCents =
|
|
330
|
+
rate === null
|
|
331
|
+
? null
|
|
332
|
+
: Math.round(Number(alephCreditsInEur(line.credits, line.usdPerCredit, rate)) * 100);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
const sum = (/** @type {number[]} */ xs) => xs.reduce((a, b) => a + b, 0);
|
|
337
|
+
const totals = {
|
|
338
|
+
topUps: sum(topUps.map((t) => t.credits)),
|
|
339
|
+
transfersOut: sum(transfersOut.map((t) => t.credits)),
|
|
340
|
+
usage: sum(usage.map((u) => u.credits)),
|
|
341
|
+
eurCents: usage.every((u) => u.eurCents !== null)
|
|
342
|
+
? sum(usage.map((u) => /** @type {number} */ (u.eurCents)))
|
|
343
|
+
: null
|
|
344
|
+
};
|
|
345
|
+
return {
|
|
346
|
+
address,
|
|
347
|
+
month,
|
|
348
|
+
from: new Date(start * 1000).toISOString(),
|
|
349
|
+
until: new Date(end * 1000).toISOString(),
|
|
350
|
+
opening,
|
|
351
|
+
closing,
|
|
352
|
+
topUps,
|
|
353
|
+
transfersOut,
|
|
354
|
+
usage,
|
|
355
|
+
resources,
|
|
356
|
+
totals,
|
|
357
|
+
// opening + in − out = closing; a difference means entries the history did not list
|
|
358
|
+
difference: opening + totals.topUps - totals.usage - totals.transfersOut - closing,
|
|
359
|
+
rateSource,
|
|
360
|
+
entries: rows.length
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** A credit amount as a decimal string. @param {number} credits */
|
|
367
|
+
const credits = (credits) => plain(credits);
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* A statement's lines as ledger entries, seen from the account: purchases and
|
|
371
|
+
* transfers in (`received`), transfers out (`sent`), and each day's
|
|
372
|
+
* consumption per resource (`sent`, kind `usage`, with the USD price per
|
|
373
|
+
* credit it is valued at). Asset `ALEPH-CREDIT`, no market price.
|
|
374
|
+
*
|
|
375
|
+
* @param {Awaited<ReturnType<ReturnType<typeof createAlephClient>['statement']>>} statement
|
|
376
|
+
* @returns {import('@le-space/ledger').LedgerEntry[]}
|
|
377
|
+
*/
|
|
378
|
+
export function alephEntries(statement) {
|
|
379
|
+
const { address, topUps, transfersOut, usage, resources } = statement;
|
|
380
|
+
const common = {
|
|
381
|
+
chain: 'aleph',
|
|
382
|
+
network: 'mainnet',
|
|
383
|
+
account: address,
|
|
384
|
+
height: 0,
|
|
385
|
+
asset: 'ALEPH-CREDIT',
|
|
386
|
+
contract: 'native',
|
|
387
|
+
decimals: 0,
|
|
388
|
+
method: '',
|
|
389
|
+
memo: '',
|
|
390
|
+
success: true,
|
|
391
|
+
priceAs: ''
|
|
392
|
+
};
|
|
393
|
+
const explorerUrl = `${ALEPH_EXPLORER}${address}`;
|
|
394
|
+
const out = [
|
|
395
|
+
...topUps.map((t, i) =>
|
|
396
|
+
entry({
|
|
397
|
+
...common,
|
|
398
|
+
id: `aleph:${address}:in:${t.time}:${i}`,
|
|
399
|
+
hash: t.txHash ?? '',
|
|
400
|
+
time: t.time,
|
|
401
|
+
type: 'received',
|
|
402
|
+
kind: 'transfer',
|
|
403
|
+
amount: credits(t.credits),
|
|
404
|
+
counterparty: t.how === 'purchase' ? 'aleph' : t.from,
|
|
405
|
+
counterpartyLabel:
|
|
406
|
+
t.how === 'purchase'
|
|
407
|
+
? `Aleph Cloud (Kauf${t.token ? ` mit ${t.token}` : ''}${t.chain ? ` auf ${t.chain}` : ''})`
|
|
408
|
+
: '',
|
|
409
|
+
explorerUrl,
|
|
410
|
+
...(t.price
|
|
411
|
+
? { unitPrice: { currency: 'USD', amount: plain(t.price), source: 'purchase' } }
|
|
412
|
+
: {})
|
|
413
|
+
})
|
|
414
|
+
),
|
|
415
|
+
...transfersOut.map((t, i) =>
|
|
416
|
+
entry({
|
|
417
|
+
...common,
|
|
418
|
+
id: `aleph:${address}:out:${t.time}:${i}`,
|
|
419
|
+
hash: '',
|
|
420
|
+
time: t.time,
|
|
421
|
+
type: 'sent',
|
|
422
|
+
kind: 'transfer',
|
|
423
|
+
amount: `-${credits(t.credits)}`,
|
|
424
|
+
counterparty: t.to,
|
|
425
|
+
counterpartyLabel: '',
|
|
426
|
+
explorerUrl
|
|
427
|
+
})
|
|
428
|
+
),
|
|
429
|
+
...usage.map((u) => {
|
|
430
|
+
const what = u.resource ? resources?.[u.resource] : null;
|
|
431
|
+
return entry({
|
|
432
|
+
...common,
|
|
433
|
+
id: `aleph:${address}:usage:${u.date}:${u.kind}:${u.resource ?? ''}`,
|
|
434
|
+
hash: u.resource ?? '',
|
|
435
|
+
time: `${u.date}T00:00:00Z`,
|
|
436
|
+
type: 'sent',
|
|
437
|
+
kind: 'usage',
|
|
438
|
+
amount: `-${credits(u.credits)}`,
|
|
439
|
+
counterparty: 'aleph',
|
|
440
|
+
counterpartyLabel: `Aleph Cloud (${what?.name || u.kind})`,
|
|
441
|
+
memo: `${u.entries} Abrechnungen`,
|
|
442
|
+
explorerUrl,
|
|
443
|
+
unitPrice: { currency: 'USD', amount: u.usdPerCredit, source: u.priceSource }
|
|
444
|
+
});
|
|
445
|
+
})
|
|
446
|
+
];
|
|
447
|
+
return sortEntries(out);
|
|
448
|
+
}
|
package/src/index.js
CHANGED
|
@@ -13,6 +13,8 @@
|
|
|
13
13
|
// filecoin Filfox
|
|
14
14
|
// near NearBlocks + an archival RPC (from Eigenbeleg);
|
|
15
15
|
// `near` here, or `@le-space/chains/near`
|
|
16
|
+
// aleph Aleph Cloud credits (no chain: Aleph's API, by the
|
|
17
|
+
// Ethereum address); `aleph` here, or `/aleph`
|
|
16
18
|
|
|
17
19
|
export * from './core.js';
|
|
18
20
|
export { CHAINS, KNOWN_EVM_CONTRACTS, chainOf, publicChains } from './registry.js';
|
|
@@ -61,3 +63,4 @@ export {
|
|
|
61
63
|
/** @typedef {import('./registry.js').Chain} Chain */
|
|
62
64
|
/** @typedef {import('@le-space/ledger/wallet-entry').WalletEntry} WalletEntry */
|
|
63
65
|
export * as near from './near.js';
|
|
66
|
+
export * as aleph from './aleph.js';
|
package/src/registry.js
CHANGED
|
@@ -95,6 +95,11 @@ import { FILECOIN } from './filecoin-chain.js';
|
|
|
95
95
|
|
|
96
96
|
const USDC = { symbol: 'USDC', decimals: 6 };
|
|
97
97
|
const ETH = { symbol: 'ETH', decimals: 18 };
|
|
98
|
+
// Aleph Cloud's token (ALEPH), what Aleph's credits and storage are paid
|
|
99
|
+
// with: on Ethereum and Base. Checked 2026-11-06: CoinGecko's platform list
|
|
100
|
+
// for `aleph`, Blockscout's token page (Ethereum) and the contract's own
|
|
101
|
+
// symbol() and decimals() (Base).
|
|
102
|
+
const ALEPH = { symbol: 'ALEPH', decimals: 18 };
|
|
98
103
|
|
|
99
104
|
/** @param {string} base e.g. https://etherscan.io */
|
|
100
105
|
const etherscanLike = (/** @type {string} */ name, /** @type {string} */ base) => ({
|
|
@@ -139,7 +144,10 @@ export const CHAINS = Object.freeze({
|
|
|
139
144
|
chainId: 1,
|
|
140
145
|
caip2: 'eip155:1',
|
|
141
146
|
native: ETH,
|
|
142
|
-
tokens: {
|
|
147
|
+
tokens: {
|
|
148
|
+
'0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48': USDC,
|
|
149
|
+
'0x27702a26126e0b3702af63ee09ac4d1a084ef628': ALEPH
|
|
150
|
+
},
|
|
143
151
|
endpoints: { api: 'https://eth.blockscout.com/api' },
|
|
144
152
|
alternatives: { api: [] },
|
|
145
153
|
explorer: etherscanLike('Etherscan', 'https://etherscan.io'),
|
|
@@ -153,7 +161,10 @@ export const CHAINS = Object.freeze({
|
|
|
153
161
|
chainId: 8453,
|
|
154
162
|
caip2: 'eip155:8453',
|
|
155
163
|
native: ETH,
|
|
156
|
-
tokens: {
|
|
164
|
+
tokens: {
|
|
165
|
+
'0x833589fcd6edb6e08f4c7c32d4f71b54bda02913': USDC,
|
|
166
|
+
'0xc0fbc4967259786c743361a5885ef49380473dcf': ALEPH
|
|
167
|
+
},
|
|
157
168
|
endpoints: { api: 'https://base.blockscout.com/api' },
|
|
158
169
|
alternatives: { api: [] },
|
|
159
170
|
explorer: etherscanLike('Basescan', 'https://basescan.org'),
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// A fake Aleph API as a `fetch` function, for Node and browser tests alike:
|
|
3
|
+
// balance, credit history (filters, pages, newest first), its summary, and
|
|
4
|
+
// messages. Every address, hash and amount handed to it is made up.
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @typedef {object} Row
|
|
8
|
+
* @property {string} at ISO
|
|
9
|
+
* @property {number} amount credits; negative leaves
|
|
10
|
+
* @property {string} [price] USD per credit, a purchase's
|
|
11
|
+
* @property {string} [txHash]
|
|
12
|
+
* @property {string} [token]
|
|
13
|
+
* @property {string} [chain]
|
|
14
|
+
* @property {string} [paymentMethod]
|
|
15
|
+
* @property {string} [origin]
|
|
16
|
+
* @property {string} [originRef]
|
|
17
|
+
* @property {number} [count]
|
|
18
|
+
* @property {number} [sizeMib]
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* @param {{ accounts: Record<string, { balance: number, rows: Row[] }>, messages?: Record<string, { type: string, name: string }> }} data
|
|
23
|
+
* @returns {typeof fetch}
|
|
24
|
+
*/
|
|
25
|
+
export function alephFetch({ accounts, messages = {} }) {
|
|
26
|
+
const json = (/** @type {unknown} */ body, status = 200) =>
|
|
27
|
+
new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
|
|
28
|
+
return async (input) => {
|
|
29
|
+
const url = new URL(String(input));
|
|
30
|
+
const q = url.searchParams;
|
|
31
|
+
const message = /^\/api\/v0\/messages\/([0-9a-f]{64})$/.exec(url.pathname);
|
|
32
|
+
if (message) {
|
|
33
|
+
const m = messages[message[1]];
|
|
34
|
+
return m
|
|
35
|
+
? json({ message: { type: m.type, content: { metadata: { name: m.name } } } })
|
|
36
|
+
: json({}, 404);
|
|
37
|
+
}
|
|
38
|
+
const m =
|
|
39
|
+
/^\/api\/v0\/addresses\/(0x[0-9a-fA-F]{40})\/(balance|credit_history)(\/summary)?$/.exec(
|
|
40
|
+
url.pathname
|
|
41
|
+
);
|
|
42
|
+
// Keyed in any case here; the client asks with the EIP-55 checksum, as Aleph needs.
|
|
43
|
+
const key = m
|
|
44
|
+
? Object.keys(accounts).find((a) => a.toLowerCase() === m[1].toLowerCase())
|
|
45
|
+
: undefined;
|
|
46
|
+
const account = key ? accounts[key] : undefined;
|
|
47
|
+
if (!m || !account) return json({}, 404);
|
|
48
|
+
if (m[2] === 'balance') return json({ credit_balance: account.balance });
|
|
49
|
+
const from = q.has('startDate') ? Number(q.get('startDate')) * 1000 : -Infinity;
|
|
50
|
+
const to = q.has('endDate') ? Number(q.get('endDate')) * 1000 : Infinity;
|
|
51
|
+
const direction = q.get('direction');
|
|
52
|
+
const rows = account.rows
|
|
53
|
+
.filter((r) => Date.parse(r.at) >= from && Date.parse(r.at) <= to)
|
|
54
|
+
.filter((r) => !direction || (direction === 'incoming' ? r.amount > 0 : r.amount < 0))
|
|
55
|
+
.sort((a, b) => b.at.localeCompare(a.at));
|
|
56
|
+
if (m[3])
|
|
57
|
+
return json({
|
|
58
|
+
total_amount: rows.reduce((n, r) => n + r.amount, 0),
|
|
59
|
+
entry_count: rows.length
|
|
60
|
+
});
|
|
61
|
+
const per = Number(q.get('pagination') ?? 100);
|
|
62
|
+
const page = Number(q.get('page') ?? 1);
|
|
63
|
+
return json({
|
|
64
|
+
pagination_total: rows.length,
|
|
65
|
+
credit_history: rows.slice((page - 1) * per, page * per).map((r) => ({
|
|
66
|
+
message_timestamp: r.at,
|
|
67
|
+
amount: r.amount,
|
|
68
|
+
price: r.price ?? null,
|
|
69
|
+
tx_hash: r.txHash ?? null,
|
|
70
|
+
token: r.token ?? null,
|
|
71
|
+
chain: r.chain ?? null,
|
|
72
|
+
payment_method: r.paymentMethod ?? null,
|
|
73
|
+
origin: r.origin ?? null,
|
|
74
|
+
origin_ref: r.originRef ?? null,
|
|
75
|
+
expense_count: r.count ?? null,
|
|
76
|
+
expense_size_mib: r.sizeMib ?? null
|
|
77
|
+
}))
|
|
78
|
+
});
|
|
79
|
+
};
|
|
80
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// A made-up Aleph account and month for the tests (Node and browser): a
|
|
3
|
+
// purchase before August at 0.000002 USD per credit, then storage, an
|
|
4
|
+
// instance, a transfer in and one out, and a line in September.
|
|
5
|
+
|
|
6
|
+
export const ACCOUNT = `0x${'a1'.repeat(20)}`;
|
|
7
|
+
export const OTHER = `0x${'b2'.repeat(20)}`;
|
|
8
|
+
export const VM = 'c3'.repeat(32);
|
|
9
|
+
export const BILLING = 'd4'.repeat(32);
|
|
10
|
+
|
|
11
|
+
/** @returns {import('./aleph-fetch.js').Row[]} */
|
|
12
|
+
export function sampleRows() {
|
|
13
|
+
return [
|
|
14
|
+
{
|
|
15
|
+
at: '2026-07-20T08:00:00.000Z',
|
|
16
|
+
amount: 1_000_000,
|
|
17
|
+
price: '0.000002',
|
|
18
|
+
txHash: `0x${'ab'.repeat(32)}`,
|
|
19
|
+
token: 'ALEPH',
|
|
20
|
+
chain: 'ETH'
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
at: '2026-08-01T00:30:00.000Z',
|
|
24
|
+
amount: -100,
|
|
25
|
+
paymentMethod: 'credit_expense',
|
|
26
|
+
originRef: 'storage',
|
|
27
|
+
count: 3,
|
|
28
|
+
sizeMib: 12.5
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
at: '2026-08-01T01:30:00.000Z',
|
|
32
|
+
amount: -100,
|
|
33
|
+
paymentMethod: 'credit_expense',
|
|
34
|
+
originRef: 'storage',
|
|
35
|
+
count: 4,
|
|
36
|
+
sizeMib: 13
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
at: '2026-08-01T02:00:00.000Z',
|
|
40
|
+
amount: -2000,
|
|
41
|
+
paymentMethod: 'credit_expense',
|
|
42
|
+
originRef: BILLING,
|
|
43
|
+
origin: VM
|
|
44
|
+
},
|
|
45
|
+
{ at: '2026-08-15T12:00:00.000Z', amount: 50_000, origin: OTHER },
|
|
46
|
+
{
|
|
47
|
+
at: '2026-08-20T12:00:00.000Z',
|
|
48
|
+
amount: -5_000,
|
|
49
|
+
paymentMethod: 'credit_transfer',
|
|
50
|
+
origin: OTHER
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
at: '2026-09-01T00:30:00.000Z',
|
|
54
|
+
amount: -120,
|
|
55
|
+
paymentMethod: 'credit_expense',
|
|
56
|
+
originRef: 'storage',
|
|
57
|
+
count: 4,
|
|
58
|
+
sizeMib: 13
|
|
59
|
+
}
|
|
60
|
+
];
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Balance now: 2,000,000 before July, then every row. */
|
|
64
|
+
export const sampleBalance = () => 2_000_000 + sampleRows().reduce((n, r) => n + r.amount, 0);
|
|
65
|
+
|
|
66
|
+
/** EUR per USD, the same every day. */
|
|
67
|
+
export const flatUsd = {
|
|
68
|
+
rate: async (/** @type {string} */ asset, /** @type {string} */ date) => ({
|
|
69
|
+
asset,
|
|
70
|
+
date,
|
|
71
|
+
rate: '0.9',
|
|
72
|
+
source: 'ecb'
|
|
73
|
+
})
|
|
74
|
+
};
|