@le-space/chains 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,938 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Filecoin Pay, read only: what a payer's balance in the payment contract of
3
+ // Filecoin Onchain Cloud was used for in one month. Storage there is not
4
+ // paid by transfers of a wallet. A wallet pays USDFC *into* the contract, and
5
+ // the contract pays the storage providers out of that balance over "rails",
6
+ // settled from time to time. Only the paying in shows in the wallet; this
7
+ // reads the rest, so that the storage has a document: a statement per payer
8
+ // and month, as Aleph's and Akash's credits have.
9
+ //
10
+ // Two ways to read it, the first one first:
11
+ //
12
+ // 1. The index its makers keep (a subgraph at Goldsky, the one their own
13
+ // explorer pay.filecoin.cloud asks): settlements and one-time payments
14
+ // by payer, and the balance now. It has no paying in and taking out.
15
+ // Those are two of the contract's events, asked of Blockscout (two
16
+ // requests, by payer – they also show what somebody else paid into
17
+ // the payer's balance). Where Blockscout does not answer, the USDFC
18
+ // transfers between the payer and the contract are read from Filfox
19
+ // instead, as the Filecoin wallet reader does; the statement then says
20
+ // that money paid in by another address is not in it.
21
+ // 2. Where the index does not answer: the contract's own events from
22
+ // Blockscout's log API (RailCreated, DepositRecorded, WithdrawRecorded,
23
+ // RailSettled, RailOneTimePaymentProcessed) and the balance by
24
+ // `eth_call` (`accounts(token, owner)`). Without a key Blockscout
25
+ // allows about ten requests and then none for minutes; with one
26
+ // (dev.blockscout.com, free) it is asked through api.blockscout.com,
27
+ // the key in the `authorization` header, never in a URL.
28
+ // The public RPC is no way: it gives events for 360 blocks.
29
+ //
30
+ // Whoever is asked sees the payer's address and this machine's IP.
31
+ //
32
+ // A settlement is the unit of consumption: what left the payer's balance for
33
+ // one rail, up to the epoch it names, split into what the provider got, the
34
+ // operator's commission and the network fee. Rails are settled when someone
35
+ // asks for it, so a month's settlements need not cover exactly that month –
36
+ // each line says up to when it paid. What has run up since the last
37
+ // settlement is not in the statement; the balance says what is left.
38
+ //
39
+ // Balances: the balance now, less what came and plus what went since the
40
+ // month began (or ended). Only USDFC is read, the token storage is paid in.
41
+ // A payer that is also a payee of rails gets money this does not read: its
42
+ // balances would be off by it.
43
+ //
44
+ // Addresses: `0x…` or the same account's `f410f…`. Times are UTC, the month
45
+ // is the UTC month. Error messages name a host at most, never an address.
46
+
47
+ import { entry, multiply, normalize, sortEntries } from '@le-space/ledger';
48
+ import { unitsToDecimal } from '@le-space/ledger/decimal';
49
+ import { base32nopad } from '@scure/base';
50
+ import { keccak_256 } from '@noble/hashes/sha3.js';
51
+ import { createJsonFetcher, WalletError } from './http.js';
52
+ import { isFilecoinAddress, toFilecoinAddress } from './filecoin.js';
53
+
54
+ /**
55
+ * Mainnet, from the makers' own published addresses (`@filoz/synapse-core`
56
+ * 0.10.0, `filecoinPayV1Address[314]` and
57
+ * `filecoinWarmStorageServiceAddress[314]`); USDFC as in filecoin-chain.js.
58
+ */
59
+ export const FILECOIN_PAY = Object.freeze({
60
+ contract: '0x23b1e018f08bb982348b15a86ee926eebf7f4daa',
61
+ token: Object.freeze({
62
+ symbol: 'USDFC',
63
+ decimals: 18,
64
+ contract: '0x80b98d3aa09ffff255c3ba4a241111ff1262f045'
65
+ }),
66
+ /** Operators of rails that are known for the service they run. */
67
+ services: Object.freeze({
68
+ '0x8408502033c418e1bbc97ce9ac48e5528f371a9f': 'Filecoin Warm Storage'
69
+ }),
70
+ /** The makers' index, as their explorer pay.filecoin.cloud is built to ask it (read 2026-11-19). */
71
+ index:
72
+ 'https://api.goldsky.com/api/public/project_cmb9tuo8r1xdw01ykb8uidk7h/subgraphs/filecoin-pay-mainnet/prod/gn',
73
+ filfox: 'https://filfox.info/api/v1',
74
+ api: 'https://filecoin.blockscout.com/api',
75
+ /** Blockscout's API for a key: every chain behind one host, by `chain_id`. */
76
+ keyedApi: 'https://api.blockscout.com/v2/api',
77
+ /** Its JSON-RPC for a key (`eth_call`): the chain in the path. */
78
+ keyedRpc: 'https://api.blockscout.com/{chain}/json-rpc',
79
+ chainId: 314,
80
+ message: 'https://filfox.info/en/message/{tx}',
81
+ explorer: Object.freeze({
82
+ name: 'Blockscout',
83
+ tx: 'https://filecoin.blockscout.com/tx/{tx}',
84
+ address: 'https://filecoin.blockscout.com/address/{address}'
85
+ })
86
+ });
87
+
88
+ /** Filecoin's mainnet began at this second; an epoch (an FEVM block) is 30 seconds. */
89
+ const GENESIS = 1598306400;
90
+ const EPOCH_SECONDS = 30;
91
+ /** Blockscout gives at most this many logs an answer. */
92
+ const PER_PAGE = 1000;
93
+
94
+ const hex = (/** @type {Uint8Array} */ bytes) =>
95
+ Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
96
+ const topicOf = (/** @type {string} */ signature) =>
97
+ `0x${hex(keccak_256(new TextEncoder().encode(signature)))}`;
98
+
99
+ const TOPIC = Object.freeze({
100
+ railCreated: topicOf(
101
+ 'RailCreated(uint256,address,address,address,address,address,address,uint256)'
102
+ ),
103
+ deposit: topicOf('DepositRecorded(address,address,address,uint256)'),
104
+ withdraw: topicOf('WithdrawRecorded(address,address,address,uint256)'),
105
+ settled: topicOf('RailSettled(uint256,uint256,uint256,uint256,uint256,uint256)'),
106
+ oneTime: topicOf('RailOneTimePaymentProcessed(uint256,uint256,uint256,uint256)')
107
+ });
108
+ const ACCOUNTS = `0x${hex(keccak_256(new TextEncoder().encode('accounts(address,address)'))).slice(0, 8)}`;
109
+
110
+ /** An address as a 32-byte topic or call argument. @param {string} address 0x…, lower case */
111
+ const word = (address) => address.slice(2).padStart(64, '0');
112
+ /** The address in a 32-byte topic or data word. @param {string} w 64 hex characters */
113
+ const addressOf = (w) => `0x${w.slice(-40).toLowerCase()}`;
114
+ /** The 32-byte words of a log's data. @param {unknown} data */
115
+ function words(data) {
116
+ const body = String(data ?? '').replace(/^0x/, '');
117
+ if (body.length % 64 !== 0 || !/^[0-9a-fA-F]*$/.test(body)) return [];
118
+ return body.match(/.{64}/g) ?? [];
119
+ }
120
+ const uint = (/** @type {string | undefined} */ w) => (w ? BigInt(`0x${w}`) : 0n);
121
+
122
+ /** The epoch a second lies in. @param {number} seconds Unix */
123
+ export const epochAt = (seconds) => Math.max(0, Math.floor((seconds - GENESIS) / EPOCH_SECONDS));
124
+ /** When an epoch began, ISO. @param {number} epoch */
125
+ export const epochTime = (epoch) =>
126
+ new Date((GENESIS + epoch * EPOCH_SECONDS) * 1000).toISOString();
127
+
128
+ /**
129
+ * The Ethereum form of a payer's address: `0x…` as it is (lower case), or
130
+ * the account behind a valid `f410f…`. Null for anything else – an f1 or f3
131
+ * address has no account in a contract.
132
+ *
133
+ * @param {unknown} address
134
+ * @returns {string | null}
135
+ */
136
+ export function payerAddress(address) {
137
+ const a = String(address ?? '').trim();
138
+ if (/^0x[0-9a-fA-F]{40}$/.test(a)) return a.toLowerCase();
139
+ if (!/^f410f[a-z2-7]+$/.test(a) || !isFilecoinAddress(a)) return null;
140
+ const raw = base32nopad.decode(a.slice(5).toUpperCase());
141
+ return `0x${hex(raw.slice(0, 20))}`;
142
+ }
143
+
144
+ /**
145
+ * `YYYY-MM` → its first second, the first second after it, Unix, UTC.
146
+ *
147
+ * @param {string} month
148
+ */
149
+ export function payMonth(month) {
150
+ const m = /^(\d{4})-(0[1-9]|1[0-2])$/.exec(month);
151
+ if (!m) throw new WalletError('month must be YYYY-MM', 'FILPAY_MONTH', 400);
152
+ return {
153
+ start: Date.UTC(Number(m[1]), Number(m[2]) - 1, 1) / 1000,
154
+ next: Date.UTC(Number(m[1]), Number(m[2]), 1) / 1000
155
+ };
156
+ }
157
+
158
+ /**
159
+ * @typedef {object} PayLog one event of the contract, as Blockscout gives it
160
+ * @property {string[]} topics
161
+ * @property {string} data
162
+ * @property {number} time Unix
163
+ * @property {number} block
164
+ * @property {string} txHash
165
+ * @property {string} key transaction and log index: one event once
166
+ */
167
+
168
+ /**
169
+ * @typedef {object} Rail
170
+ * @property {string} id
171
+ * @property {string} payee 0x…
172
+ * @property {string} operator 0x…
173
+ * @property {string} service the operator's service, '' when not known
174
+ * @property {number} commissionBps
175
+ * @property {string} createdAt ISO
176
+ */
177
+
178
+ /**
179
+ * @typedef {object} Movement money paid into or taken out of the balance
180
+ * @property {string} time ISO
181
+ * @property {string} amount decimal, positive
182
+ * @property {string} other who paid in, or where it was taken out to (0x…)
183
+ * @property {string} txHash
184
+ */
185
+
186
+ /**
187
+ * @typedef {object} UsageLine one settlement of one rail
188
+ * @property {string} time ISO, when it was settled
189
+ * @property {string} date YYYY-MM-DD (UTC)
190
+ * @property {string} railId
191
+ * @property {string} payee 0x…
192
+ * @property {string} service
193
+ * @property {boolean} oneTime a one-time payment, not a rate over time
194
+ * @property {string} amount what left the balance, decimal
195
+ * @property {string} toPayee of it, what the provider got
196
+ * @property {string} commission of it, the operator's commission
197
+ * @property {string} networkFee of it, the network's fee
198
+ * @property {string | null} paidUntil ISO: up to when the rail is paid by this; null for a one-time payment
199
+ * @property {string} txHash
200
+ * @property {string | null} eurPerUnit the day's rate, EUR per USDFC
201
+ * @property {number | null} eurCents
202
+ */
203
+
204
+ /**
205
+ * @typedef {object} PayRecords what either source gives, in one shape
206
+ * @property {Map<string, Rail>} rails the payer's rails in the token, by id
207
+ * @property {{ at: number, units: bigint, other: string, txHash: string }[]} paidIn since the month began
208
+ * @property {{ at: number, units: bigint, other: string, txHash: string }[]} takenOut since the month began
209
+ * @property {{ at: number, railId: string, total: bigint, toPayee: bigint, commission: bigint, fee: bigint, upTo: number | null, txHash: string }[]} spent
210
+ * settlements and one-time payments since the month began; `upTo` the epoch a settlement paid up to
211
+ * @property {bigint} fundsNow the balance now, in the token's smallest units
212
+ * @property {bigint} lockedNow of it, what is held for running rails
213
+ * @property {'events' | 'transfers'} [movementsFrom] where paid in and taken out come from:
214
+ * the contract's events, or – without them – the payer's own token transfers
215
+ */
216
+
217
+ /**
218
+ * The contract's events (Blockscout) → the records. Pure.
219
+ *
220
+ * @param {object} p
221
+ * @param {PayLog[]} p.rails RailCreated of the payer
222
+ * @param {PayLog[]} p.deposits DepositRecorded to the payer
223
+ * @param {PayLog[]} p.withdrawals WithdrawRecorded from the payer
224
+ * @param {PayLog[]} p.settled RailSettled of any rail
225
+ * @param {PayLog[]} p.oneTime RailOneTimePaymentProcessed of any rail
226
+ * @param {bigint} p.fundsNow
227
+ * @param {bigint} [p.lockedNow]
228
+ * @returns {PayRecords}
229
+ */
230
+ export function recordsFromLogs({
231
+ rails,
232
+ deposits,
233
+ withdrawals,
234
+ settled,
235
+ oneTime,
236
+ fundsNow,
237
+ lockedNow = 0n
238
+ }) {
239
+ const { token, services } = FILECOIN_PAY;
240
+ const iso = (/** @type {number} */ s) => new Date(s * 1000).toISOString();
241
+ const tokenTopic = `0x${word(token.contract)}`;
242
+
243
+ /** @type {Map<string, Rail>} */
244
+ const byId = new Map();
245
+ for (const log of rails) {
246
+ const w = words(log.data);
247
+ // data: token, operator, validator, serviceFeeRecipient, commissionRateBps
248
+ if (w.length < 5 || addressOf(w[0]) !== token.contract) continue;
249
+ const id = uint(log.topics[1]?.slice(2)).toString();
250
+ const operator = addressOf(w[1]);
251
+ byId.set(id, {
252
+ id,
253
+ payee: addressOf(String(log.topics[3] ?? '')),
254
+ operator,
255
+ service: /** @type {Record<string, string>} */ (services)[operator] ?? '',
256
+ commissionBps: Number(uint(w[4])),
257
+ createdAt: iso(log.time)
258
+ });
259
+ }
260
+
261
+ /** @param {PayLog[]} logs @param {number} otherTopic which topic names the other side */
262
+ const movements = (logs, otherTopic) =>
263
+ logs
264
+ .filter((l) => l.topics[1]?.toLowerCase() === tokenTopic)
265
+ .map((l) => ({
266
+ at: l.time,
267
+ units: uint(words(l.data)[0]),
268
+ other: addressOf(String(l.topics[otherTopic] ?? '')),
269
+ txHash: l.txHash
270
+ }));
271
+
272
+ /** @type {PayRecords['spent']} */
273
+ const spent = [];
274
+ for (const l of settled) {
275
+ const railId = uint(l.topics[1]?.slice(2)).toString();
276
+ const w = words(l.data);
277
+ if (!byId.has(railId) || w.length < 5) continue;
278
+ spent.push({
279
+ at: l.time,
280
+ railId,
281
+ total: uint(w[0]),
282
+ toPayee: uint(w[1]),
283
+ commission: uint(w[2]),
284
+ fee: uint(w[3]),
285
+ upTo: Number(uint(w[4])),
286
+ txHash: l.txHash
287
+ });
288
+ }
289
+ for (const l of oneTime) {
290
+ const railId = uint(l.topics[1]?.slice(2)).toString();
291
+ const w = words(l.data);
292
+ if (!byId.has(railId) || w.length < 3) continue;
293
+ const [toPayee, commission, fee] = [uint(w[0]), uint(w[1]), uint(w[2])];
294
+ spent.push({
295
+ at: l.time,
296
+ railId,
297
+ total: toPayee + commission + fee,
298
+ toPayee,
299
+ commission,
300
+ fee,
301
+ upTo: null,
302
+ txHash: l.txHash
303
+ });
304
+ }
305
+ return {
306
+ rails: byId,
307
+ paidIn: movements(deposits, 2),
308
+ takenOut: movements(withdrawals, 3),
309
+ spent,
310
+ fundsNow,
311
+ lockedNow
312
+ };
313
+ }
314
+
315
+ /**
316
+ * The records of a month → the statement's lines. Pure.
317
+ *
318
+ * @param {PayRecords} records
319
+ * @param {{ start: number, next: number }} window the month's first second, and the first after it
320
+ */
321
+ export function summarisePay(
322
+ { rails: byId, paidIn, takenOut, spent: all, fundsNow },
323
+ { start, next }
324
+ ) {
325
+ const { token } = FILECOIN_PAY;
326
+ const dec = (/** @type {bigint} */ units) => unitsToDecimal(units, token.decimals);
327
+ const iso = (/** @type {number} */ s) => new Date(s * 1000).toISOString();
328
+ // A settlement that moved nothing (the rail was paid up already) is no line.
329
+ const spent = all.filter((s) => s.total > 0n && byId.has(s.railId));
330
+
331
+ const sum = (/** @type {bigint[]} */ xs) => xs.reduce((a, b) => a + b, 0n);
332
+ /** What came less what went, from a moment on. @param {number} from */
333
+ const netSince = (from) =>
334
+ sum(paidIn.filter((m) => m.at >= from).map((m) => m.units)) -
335
+ sum(takenOut.filter((m) => m.at >= from).map((m) => m.units)) -
336
+ sum(spent.filter((s) => s.at >= from).map((s) => s.total));
337
+ const within = (/** @type {{ at: number }} */ x) => x.at >= start && x.at < next;
338
+
339
+ /** @param {typeof paidIn} list @returns {Movement[]} */
340
+ const lines = (list) =>
341
+ list
342
+ .filter(within)
343
+ .sort((a, b) => a.at - b.at)
344
+ .map((m) => ({ time: iso(m.at), amount: dec(m.units), other: m.other, txHash: m.txHash }));
345
+ /** @type {UsageLine[]} */
346
+ const usage = spent
347
+ .filter(within)
348
+ .sort((a, b) => a.at - b.at || a.railId.localeCompare(b.railId, 'en', { numeric: true }))
349
+ .map((s) => {
350
+ const rail = /** @type {Rail} */ (byId.get(s.railId));
351
+ return {
352
+ time: iso(s.at),
353
+ date: iso(s.at).slice(0, 10),
354
+ railId: s.railId,
355
+ payee: rail.payee,
356
+ service: rail.service,
357
+ oneTime: s.upTo === null,
358
+ amount: dec(s.total),
359
+ toPayee: dec(s.toPayee),
360
+ commission: dec(s.commission),
361
+ networkFee: dec(s.fee),
362
+ paidUntil: s.upTo === null ? null : epochTime(s.upTo),
363
+ txHash: s.txHash,
364
+ eurPerUnit: null,
365
+ eurCents: null
366
+ };
367
+ });
368
+ const used = new Set(usage.map((u) => u.railId));
369
+ return {
370
+ opening: dec(fundsNow - netSince(start)),
371
+ closing: dec(fundsNow - netSince(next)),
372
+ deposits: lines(paidIn),
373
+ withdrawals: lines(takenOut),
374
+ usage,
375
+ rails: Object.fromEntries([...byId].filter(([id]) => used.has(id))),
376
+ railCount: byId.size,
377
+ totals: {
378
+ deposits: dec(sum(paidIn.filter(within).map((m) => m.units))),
379
+ withdrawals: dec(sum(takenOut.filter(within).map((m) => m.units))),
380
+ usage: dec(sum(spent.filter(within).map((s) => s.total)))
381
+ }
382
+ };
383
+ }
384
+
385
+ /**
386
+ * @param {object} [options]
387
+ * @param {typeof fetch} [options.fetch]
388
+ * @param {number} [options.timeoutMs]
389
+ * @param {(ms: number) => Promise<void>} [options.sleep]
390
+ * @param {number} [options.maxPages] answers read per list before giving up
391
+ * @param {number} [options.perPage] how many logs Blockscout gives an answer (a full answer is read on)
392
+ * @param {number} [options.pauseMs] the wait between two requests to Blockscout
393
+ * @param {{ rate: (asset: string, date: string) => Promise<{ rate: string, source: string }> } | null} [options.rates]
394
+ * @param {() => Date} [options.now]
395
+ * @param {{ api: string, rpc: string }} [options.keyed] where a Blockscout key is sent: Blockscout's
396
+ * keyed host. Set where the client is made, not per request, so that whoever asks for a
397
+ * statement cannot have the key sent elsewhere (tests: a fake on this machine).
398
+ */
399
+ export function createFilecoinPayClient({
400
+ fetch: f = fetch,
401
+ timeoutMs = 30_000,
402
+ sleep,
403
+ maxPages = 40,
404
+ perPage = PER_PAGE,
405
+ pauseMs = 350,
406
+ rates = null,
407
+ now = () => new Date(),
408
+ keyed = {
409
+ api: FILECOIN_PAY.keyedApi,
410
+ rpc: FILECOIN_PAY.keyedRpc.replace('{chain}', String(FILECOIN_PAY.chainId))
411
+ }
412
+ } = {}) {
413
+ const wait = sleep ?? ((/** @type {number} */ ms) => new Promise((r) => setTimeout(r, ms)));
414
+ const getJson = createJsonFetcher({ fetch: f, timeoutMs, sleep: wait });
415
+ // Blockscout's public API refuses a quick run of requests (HTTP 429): one
416
+ // after the other, with a breath between them.
417
+ let asked = false;
418
+ /** @type {typeof getJson} */
419
+ const slowly = async (url, init, options) => {
420
+ if (asked && pauseMs > 0) await wait(pauseMs);
421
+ asked = true;
422
+ return getJson(url, init, options);
423
+ };
424
+ const tooMany = () =>
425
+ new WalletError('more events since that month than are read here', 'FILPAY_TOO_MANY', 413);
426
+
427
+ // ---- 1. the makers' index, and Filfox for what was paid in and taken out
428
+
429
+ /**
430
+ * One GraphQL list, whole: asked on by id until an answer is not full.
431
+ *
432
+ * @param {string} index @param {string} name the list's field
433
+ * @param {string} where the filter's inside, without the id
434
+ * @param {string} fields
435
+ * @returns {Promise<any[]>}
436
+ */
437
+ async function listed(index, name, where, fields) {
438
+ /** @type {any[]} */
439
+ const out = [];
440
+ let after = '';
441
+ for (let page = 0; ; page++) {
442
+ if (page >= maxPages) throw tooMany();
443
+ const query = `{ ${name}(first: 1000, orderBy: id, where: { ${where}${after ? `, id_gt: "${after}"` : ''} }) { id ${fields} } }`;
444
+ const body = await getJson(index, {
445
+ method: 'POST',
446
+ headers: { 'content-type': 'application/json' },
447
+ body: JSON.stringify({ query })
448
+ });
449
+ const batch = body?.data?.[name];
450
+ if (!Array.isArray(batch))
451
+ throw new WalletError('the index answered without a list', 'FILPAY_INDEX');
452
+ out.push(...batch);
453
+ if (batch.length < 1000) break;
454
+ after = String(batch.at(-1)?.id ?? '');
455
+ if (!after) break;
456
+ }
457
+ return out;
458
+ }
459
+
460
+ /**
461
+ * @param {string} payer 0x…, lower case
462
+ * @param {number} start the month's first second
463
+ * @param {{ index: string, filfox: string, blockscout: string, blockscoutKey?: string }} endpoints
464
+ * @returns {Promise<PayRecords>}
465
+ */
466
+ async function fromIndex(payer, start, endpoints) {
467
+ const { token, services, contract } = FILECOIN_PAY;
468
+ const own = `payer: "${payer}", token: "${token.contract}"`;
469
+ const tokens = await listed(
470
+ endpoints.index,
471
+ 'userTokens',
472
+ `account: "${payer}", token: "${token.contract}"`,
473
+ 'funds lockupCurrent'
474
+ );
475
+ const railRows = await listed(
476
+ endpoints.index,
477
+ 'rails',
478
+ own,
479
+ 'railId commissionRateBps createdAt payee { id } operator { id }'
480
+ );
481
+ /** @type {Map<string, Rail>} */
482
+ const rails = new Map();
483
+ for (const r of railRows) {
484
+ const operator = String(r?.operator?.id ?? '').toLowerCase();
485
+ rails.set(String(r.railId), {
486
+ id: String(r.railId),
487
+ payee: String(r?.payee?.id ?? '').toLowerCase(),
488
+ operator,
489
+ service: /** @type {Record<string, string>} */ (services)[operator] ?? '',
490
+ commissionBps: Number(r.commissionRateBps ?? 0),
491
+ createdAt: new Date(Number(r.createdAt ?? 0) * 1000).toISOString()
492
+ });
493
+ }
494
+ const big = (/** @type {unknown} */ v) => (/^\d+$/.test(String(v)) ? BigInt(String(v)) : 0n);
495
+ /** @type {PayRecords['spent']} */
496
+ const spent = [];
497
+ if (rails.size) {
498
+ const settled = await listed(
499
+ endpoints.index,
500
+ 'settlements',
501
+ `rail_: { ${own} }, createdAt_gte: "${start}"`,
502
+ 'totalSettledAmount totalNetPayeeAmount networkFee operatorCommission settledUpto txHash createdAt rail { railId }'
503
+ );
504
+ for (const x of settled) {
505
+ spent.push({
506
+ at: Number(x.createdAt),
507
+ railId: String(x?.rail?.railId),
508
+ total: big(x.totalSettledAmount),
509
+ toPayee: big(x.totalNetPayeeAmount),
510
+ commission: big(x.operatorCommission),
511
+ fee: big(x.networkFee),
512
+ upTo: Number(x.settledUpto),
513
+ txHash: String(x.txHash ?? '')
514
+ });
515
+ }
516
+ const once = await listed(
517
+ endpoints.index,
518
+ 'oneTimePayments',
519
+ `${own}, createdAt_gte: "${start}"`,
520
+ 'totalAmount netPayeeAmount networkFee operatorCommission txHash createdAt rail { railId }'
521
+ );
522
+ for (const x of once) {
523
+ spent.push({
524
+ at: Number(x.createdAt),
525
+ railId: String(x?.rail?.railId),
526
+ total: big(x.totalAmount),
527
+ toPayee: big(x.netPayeeAmount),
528
+ commission: big(x.operatorCommission),
529
+ fee: big(x.networkFee),
530
+ upTo: null,
531
+ txHash: String(x.txHash ?? '')
532
+ });
533
+ }
534
+ }
535
+
536
+ // Paid in and taken out: the contract's own events where Blockscout gives
537
+ // them – they name the balance that got the money, whoever sent it.
538
+ /** @type {PayRecords['paidIn']} */
539
+ let paidIn = [];
540
+ /** @type {PayRecords['takenOut']} */
541
+ let takenOut = [];
542
+ /** @type {'events' | 'transfers'} */
543
+ let movementsFrom = 'events';
544
+ try {
545
+ const fromBlock = epochAt(start);
546
+ const moved = recordsFromLogs({
547
+ rails: [],
548
+ deposits: await logs(endpoints, TOPIC.deposit, fromBlock, { index: 3, value: payer }),
549
+ withdrawals: await logs(endpoints, TOPIC.withdraw, fromBlock, { index: 2, value: payer }),
550
+ settled: [],
551
+ oneTime: [],
552
+ fundsNow: 0n
553
+ });
554
+ paidIn = moved.paidIn;
555
+ takenOut = moved.takenOut;
556
+ } catch (/** @type {any} */ error) {
557
+ if (error?.code === 'FILPAY_TOO_MANY') throw error;
558
+ // Else the token's transfers between the payer and the contract, newest
559
+ // first, read back to the month's beginning. What another address paid
560
+ // into this balance is not among them.
561
+ movementsFrom = 'transfers';
562
+ const self = toFilecoinAddress(payer);
563
+ const pay = toFilecoinAddress(contract);
564
+ const usdfc = toFilecoinAddress(token.contract);
565
+ for (let page = 0; ; page++) {
566
+ if (page >= maxPages) throw tooMany();
567
+ const body = await getJson(
568
+ `${endpoints.filfox}/address/${encodeURIComponent(self)}/token-transfers?pageSize=100&page=${page}`
569
+ );
570
+ const list = Array.isArray(body?.transfers) ? body.transfers : [];
571
+ let older = false;
572
+ for (const t of list) {
573
+ const at = Number(t?.timestamp);
574
+ if (!Number.isFinite(at)) continue;
575
+ if (at < start) {
576
+ older = true;
577
+ continue;
578
+ }
579
+ if (String(t?.token) !== usdfc || !/^\d+$/.test(String(t?.value))) continue;
580
+ const move = {
581
+ at,
582
+ units: BigInt(String(t.value)),
583
+ other: payer,
584
+ txHash: String(t.message ?? '')
585
+ };
586
+ if (t.from === self && t.to === pay) paidIn.push(move);
587
+ else if (t.from === pay && t.to === self) takenOut.push(move);
588
+ }
589
+ if (older || list.length < 100) break;
590
+ }
591
+ }
592
+ return {
593
+ rails,
594
+ paidIn,
595
+ takenOut,
596
+ spent,
597
+ fundsNow: big(tokens[0]?.funds),
598
+ lockedNow: big(tokens[0]?.lockupCurrent),
599
+ movementsFrom
600
+ };
601
+ }
602
+
603
+ // ---- 2. the contract's events, from Blockscout
604
+
605
+ /**
606
+ * Blockscout's Etherscan-like API with a query: the chain's own instance, or
607
+ * – with a key – the one host for every chain. The key is not in the URL:
608
+ * it goes in a header (`keyHeaders`), so no log of URLs can hold it.
609
+ *
610
+ * @param {{ blockscout: string, blockscoutKey?: string }} endpoints
611
+ * @param {Record<string, string>} query
612
+ */
613
+ const blockscoutUrl = (endpoints, query) => {
614
+ const params = new URLSearchParams(query);
615
+ if (!endpoints.blockscoutKey) return `${endpoints.blockscout}?${params}`;
616
+ params.set('chain_id', String(FILECOIN_PAY.chainId));
617
+ return `${keyed.api}?${params}`;
618
+ };
619
+ /** @param {{ blockscoutKey?: string }} endpoints @returns {Record<string, string>} */
620
+ const keyHeaders = (endpoints) =>
621
+ endpoints.blockscoutKey ? { authorization: `Bearer ${endpoints.blockscoutKey}` } : {};
622
+
623
+ /**
624
+ * Every log of one event, oldest first, from a block on; narrowed to one
625
+ * indexed argument where given.
626
+ *
627
+ * @param {{ blockscout: string, blockscoutKey?: string }} endpoints
628
+ * @param {string} topic0 @param {number} fromBlock
629
+ * @param {{ index: 1 | 2 | 3, value: string } | null} [where]
630
+ * @returns {Promise<PayLog[]>}
631
+ */
632
+ async function logs(endpoints, topic0, fromBlock, where = null) {
633
+ /** @type {Map<string, PayLog>} */
634
+ const seen = new Map();
635
+ let from = fromBlock;
636
+ for (let page = 0; ; page++) {
637
+ if (page >= maxPages) throw tooMany();
638
+ /** @type {Record<string, string>} */
639
+ const query = {
640
+ module: 'logs',
641
+ action: 'getLogs',
642
+ address: FILECOIN_PAY.contract,
643
+ topic0,
644
+ fromBlock: String(from),
645
+ toBlock: 'latest'
646
+ };
647
+ if (where) {
648
+ query[`topic${where.index}`] = `0x${word(where.value)}`;
649
+ query[`topic0_${where.index}_opr`] = 'and';
650
+ }
651
+ const body = await slowly(blockscoutUrl(endpoints, query), {
652
+ headers: keyHeaders(endpoints)
653
+ });
654
+ // "No logs found" comes with status 0 and an empty result.
655
+ const batch = Array.isArray(body?.result) ? body.result : null;
656
+ if (!batch) throw new WalletError('Blockscout answered without logs', 'FILPAY_DATA');
657
+ let last = from;
658
+ for (const r of batch) {
659
+ const block = Number.parseInt(String(r?.blockNumber), 16);
660
+ const time = Number.parseInt(String(r?.timeStamp), 16);
661
+ const txHash = String(r?.transactionHash ?? '');
662
+ if (!Number.isFinite(block) || !Number.isFinite(time) || !Array.isArray(r?.topics))
663
+ continue;
664
+ const key = `${txHash}:${String(r.logIndex)}`;
665
+ seen.set(key, {
666
+ topics: r.topics.filter((/** @type {unknown} */ t) => typeof t === 'string'),
667
+ data: String(r.data ?? ''),
668
+ time,
669
+ block,
670
+ txHash,
671
+ key
672
+ });
673
+ last = Math.max(last, block);
674
+ }
675
+ if (batch.length < perPage) break;
676
+ // A full answer: on from its last block (read again, kept once).
677
+ if (last === from) throw tooMany();
678
+ from = last;
679
+ }
680
+ return [...seen.values()].sort((a, b) => a.block - b.block || a.key.localeCompare(b.key));
681
+ }
682
+
683
+ /**
684
+ * The payer's balance in the contract now, by `eth_call`.
685
+ *
686
+ * @param {{ blockscout: string, blockscoutKey?: string }} endpoints @param {string} payer
687
+ */
688
+ async function fundsOf(endpoints, payer) {
689
+ const data = `${ACCOUNTS}${word(FILECOIN_PAY.token.contract)}${word(payer)}`;
690
+ // The module API has no `eth_call` (no `proxy` module, checked 2026-11-19):
691
+ // the JSON-RPC of the instance, or of the keyed host.
692
+ const body = await slowly(
693
+ endpoints.blockscoutKey ? keyed.rpc : `${endpoints.blockscout}/eth-rpc`,
694
+ {
695
+ method: 'POST',
696
+ headers: { 'content-type': 'application/json', ...keyHeaders(endpoints) },
697
+ body: JSON.stringify({
698
+ jsonrpc: '2.0',
699
+ id: 1,
700
+ method: 'eth_call',
701
+ params: [{ to: FILECOIN_PAY.contract, data }, 'latest']
702
+ })
703
+ }
704
+ );
705
+ const w = words(body?.result);
706
+ if (w.length < 4)
707
+ throw new WalletError('Blockscout answered the balance without one', 'FILPAY_DATA');
708
+ return { funds: uint(w[0]), lockup: uint(w[1]) };
709
+ }
710
+
711
+ /**
712
+ * @param {string} payer @param {number} start
713
+ * @param {{ blockscout: string, blockscoutKey?: string }} endpoints
714
+ * @returns {Promise<PayRecords>}
715
+ */
716
+ async function fromLogs(payer, start, endpoints) {
717
+ const fromBlock = epochAt(start);
718
+ const account = await fundsOf(endpoints, payer);
719
+ const rails = await logs(endpoints, TOPIC.railCreated, 0, { index: 2, value: payer });
720
+ const deposits = await logs(endpoints, TOPIC.deposit, fromBlock, { index: 3, value: payer });
721
+ const withdrawals = await logs(endpoints, TOPIC.withdraw, fromBlock, {
722
+ index: 2,
723
+ value: payer
724
+ });
725
+ // A payer without rails spent nothing: the two long lists are not asked for.
726
+ const settled = rails.length ? await logs(endpoints, TOPIC.settled, fromBlock) : [];
727
+ const oneTime = rails.length ? await logs(endpoints, TOPIC.oneTime, fromBlock) : [];
728
+ return recordsFromLogs({
729
+ rails,
730
+ deposits,
731
+ withdrawals,
732
+ settled,
733
+ oneTime,
734
+ fundsNow: account.funds,
735
+ lockedNow: account.lockup
736
+ });
737
+ }
738
+
739
+ return {
740
+ /**
741
+ * One payer's balance in Filecoin Pay in one month: what it was at the
742
+ * beginning and the end, what was paid in and taken out, and each
743
+ * settlement of each rail, valued in euros. From the makers' index first;
744
+ * from Blockscout when the index does not answer (or `source` says so).
745
+ *
746
+ * @param {object} p
747
+ * @param {string} p.address the payer, `0x…` or `f410f…`
748
+ * @param {string} p.month YYYY-MM
749
+ * @param {'index' | 'logs'} [p.source] one way only; both in turn when left out
750
+ * @param {{ index?: string, filfox?: string, blockscout?: string, blockscoutKey?: string }} [p.endpoints] checked by the caller
751
+ */
752
+ async statement({ address, month, source, endpoints = {} }) {
753
+ const payer = payerAddress(address);
754
+ if (!payer) {
755
+ throw new WalletError(
756
+ 'not an address with an account in a contract (0x…, or f410f…)',
757
+ 'FILPAY_ADDRESS',
758
+ 400
759
+ );
760
+ }
761
+ const { start, next } = payMonth(month);
762
+ const nowSeconds = Math.floor(now().getTime() / 1000);
763
+ if (start > nowSeconds)
764
+ throw new WalletError('that month has not begun', 'FILPAY_MONTH', 400);
765
+ const at = {
766
+ index: (endpoints.index ?? FILECOIN_PAY.index).replace(/\/+$/, ''),
767
+ filfox: (endpoints.filfox ?? FILECOIN_PAY.filfox).replace(/\/+$/, ''),
768
+ blockscout: (endpoints.blockscout ?? FILECOIN_PAY.api).replace(/\/+$/, ''),
769
+ ...(endpoints.blockscoutKey ? { blockscoutKey: endpoints.blockscoutKey } : {})
770
+ };
771
+
772
+ /** @type {PayRecords} */
773
+ let records;
774
+ /** @type {'index' | 'logs'} */
775
+ let from = source ?? 'index';
776
+ /** @type {string | null} why the index was not used */
777
+ let indexFailed = null;
778
+ if (from === 'index') {
779
+ try {
780
+ records = await fromIndex(payer, start, at);
781
+ } catch (/** @type {any} */ error) {
782
+ // One way was asked for, or the history is too long either way: said as it is.
783
+ if (source === 'index' || error?.code === 'FILPAY_TOO_MANY') throw error;
784
+ indexFailed = String(error?.code ?? 'error');
785
+ from = 'logs';
786
+ records = await fromLogs(payer, start, at);
787
+ }
788
+ } else {
789
+ records = await fromLogs(payer, start, at);
790
+ }
791
+
792
+ const summary = summarisePay(records, { start, next });
793
+
794
+ /** @type {Map<string, string | null>} */
795
+ const eurPerUnit = new Map();
796
+ let rateSource = null;
797
+ if (rates) {
798
+ for (const line of summary.usage) {
799
+ if (!eurPerUnit.has(line.date)) {
800
+ const r = await rates.rate(FILECOIN_PAY.token.symbol, line.date).catch(() => null);
801
+ eurPerUnit.set(line.date, r?.rate ?? null);
802
+ rateSource ??= r?.source ?? null;
803
+ }
804
+ const rate = eurPerUnit.get(line.date) ?? null;
805
+ line.eurPerUnit = rate;
806
+ line.eurCents =
807
+ rate === null
808
+ ? null
809
+ : Math.round(Number(normalize(multiply(line.amount, rate, 8))) * 100);
810
+ }
811
+ }
812
+ const cents = summary.usage.map((u) => u.eurCents);
813
+ const dec = (/** @type {bigint} */ units) =>
814
+ unitsToDecimal(units, FILECOIN_PAY.token.decimals);
815
+ return {
816
+ address: payer,
817
+ filecoinAddress: toFilecoinAddress(payer),
818
+ month,
819
+ from: new Date(start * 1000).toISOString(),
820
+ until: new Date((next - 1) * 1000).toISOString(),
821
+ asset: FILECOIN_PAY.token.symbol,
822
+ decimals: FILECOIN_PAY.token.decimals,
823
+ ...summary,
824
+ totals: {
825
+ ...summary.totals,
826
+ eurCents:
827
+ summary.usage.length && cents.every((c) => c !== null)
828
+ ? cents.reduce((a, b) => /** @type {number} */ (a) + /** @type {number} */ (b), 0)
829
+ : summary.usage.length
830
+ ? null
831
+ : 0
832
+ },
833
+ /** As it is now, not at the month's end: the balance, and what of it is held for running rails. */
834
+ now: {
835
+ funds: dec(records.fundsNow),
836
+ lockedUp: dec(records.lockedNow),
837
+ at: now().toISOString()
838
+ },
839
+ rateSource,
840
+ /** Where the lines come from, and – when the index was passed over – why. */
841
+ source: from,
842
+ indexFailed,
843
+ /**
844
+ * `transfers`: paid in and taken out are the payer's own transfers to
845
+ * and from the contract; what another address paid in is missing, and
846
+ * the balances are off by it.
847
+ */
848
+ movementsFrom: records.movementsFrom ?? 'events',
849
+ entries: records.paidIn.length + records.takenOut.length + records.spent.length
850
+ };
851
+ }
852
+ };
853
+ }
854
+
855
+ /**
856
+ * A statement's lines as ledger entries, seen from the payer's balance in the
857
+ * contract: paid in (`received`), taken out (`sent`), and each settlement
858
+ * (`sent`, kind `usage`) with the provider as the other side. Asset USDFC,
859
+ * priced as a dollar stablecoin where a rate is needed.
860
+ *
861
+ * @param {Awaited<ReturnType<ReturnType<typeof createFilecoinPayClient>['statement']>>} statement
862
+ * @returns {import('@le-space/ledger').LedgerEntry[]}
863
+ */
864
+ export function filecoinPayEntries(statement) {
865
+ const { address, deposits, withdrawals, usage } = statement;
866
+ const { token, explorer } = FILECOIN_PAY;
867
+ // A message's CID (from Filfox) or a transaction's hash (from the index and Blockscout).
868
+ const link = (/** @type {string} */ tx) =>
869
+ (tx.startsWith('0x') ? explorer.tx : FILECOIN_PAY.message).replace('{tx}', tx);
870
+ const common = {
871
+ chain: 'filecoin-pay',
872
+ network: 'mainnet',
873
+ account: address,
874
+ height: 0,
875
+ asset: token.symbol,
876
+ contract: token.contract,
877
+ decimals: token.decimals,
878
+ method: '',
879
+ success: true,
880
+ priceAs: 'USDC'
881
+ };
882
+ return sortEntries([
883
+ ...deposits.map((d, i) =>
884
+ entry({
885
+ ...common,
886
+ id: `filecoin-pay:${address}:in:${d.txHash}:${i}`,
887
+ hash: d.txHash,
888
+ time: d.time,
889
+ type: 'received',
890
+ kind: 'transfer',
891
+ amount: d.amount,
892
+ counterparty: d.other,
893
+ counterpartyLabel: d.other === address ? 'Einzahlung in Filecoin Pay' : '',
894
+ memo: '',
895
+ explorerUrl: link(d.txHash)
896
+ })
897
+ ),
898
+ ...withdrawals.map((w, i) =>
899
+ entry({
900
+ ...common,
901
+ id: `filecoin-pay:${address}:out:${w.txHash}:${i}`,
902
+ hash: w.txHash,
903
+ time: w.time,
904
+ type: 'sent',
905
+ kind: 'transfer',
906
+ amount: `-${w.amount}`,
907
+ counterparty: w.other,
908
+ counterpartyLabel: w.other === address ? 'Auszahlung aus Filecoin Pay' : '',
909
+ memo: '',
910
+ explorerUrl: link(w.txHash)
911
+ })
912
+ ),
913
+ ...usage.map((u, i) =>
914
+ entry({
915
+ ...common,
916
+ id: `filecoin-pay:${address}:usage:${u.txHash}:${u.railId}:${i}`,
917
+ hash: u.txHash,
918
+ time: u.time,
919
+ type: 'sent',
920
+ kind: 'usage',
921
+ amount: `-${u.amount}`,
922
+ counterparty: u.payee,
923
+ counterpartyLabel: `${u.service || 'Filecoin Pay'} (Rail ${u.railId})`,
924
+ memo: u.paidUntil ? `bezahlt bis ${u.paidUntil.slice(0, 10)}` : 'Einmalzahlung',
925
+ explorerUrl: link(u.txHash),
926
+ ...(u.eurPerUnit
927
+ ? {
928
+ unitPrice: {
929
+ currency: 'EUR',
930
+ amount: u.eurPerUnit,
931
+ source: statement.rateSource ?? ''
932
+ }
933
+ }
934
+ : {})
935
+ })
936
+ )
937
+ ]);
938
+ }