@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,278 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // A fake of everything the Filecoin Pay reader asks, from one list of events
3
+ // given as plain objects: the makers' index (GraphQL: userTokens, rails,
4
+ // settlements, oneTimePayments), Filfox's token transfers of an address, and
5
+ // Blockscout's log API with its eth_call (by topic and block range, at most
6
+ // `perPage` an answer – as the real one). Any of the three can be switched
7
+ // off, to see the reader take the other way. Every address, hash and amount
8
+ // handed to it is made up.
9
+ import { keccak_256 } from '@noble/hashes/sha3.js';
10
+
11
+ const hex = (/** @type {Uint8Array} */ b) =>
12
+ Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');
13
+ const topic = (/** @type {string} */ sig) => `0x${hex(keccak_256(new TextEncoder().encode(sig)))}`;
14
+ const word = (/** @type {string | bigint | number} */ v) =>
15
+ typeof v === 'string' && v.startsWith('0x')
16
+ ? v.slice(2).toLowerCase().padStart(64, '0')
17
+ : BigInt(v).toString(16).padStart(64, '0');
18
+
19
+ const SIG = {
20
+ railCreated: 'RailCreated(uint256,address,address,address,address,address,address,uint256)',
21
+ deposit: 'DepositRecorded(address,address,address,uint256)',
22
+ withdraw: 'WithdrawRecorded(address,address,address,uint256)',
23
+ settled: 'RailSettled(uint256,uint256,uint256,uint256,uint256,uint256)',
24
+ oneTime: 'RailOneTimePaymentProcessed(uint256,uint256,uint256,uint256)'
25
+ };
26
+ const GENESIS = 1598306400;
27
+ /** The block of a moment. @param {string} iso */
28
+ export const blockAt = (iso) => Math.floor((Date.parse(iso) / 1000 - GENESIS) / 30);
29
+ /** Smallest units of an 18-decimal token. @param {string} amount */
30
+ export const units = (amount) => {
31
+ const [whole, frac = ''] = amount.split('.');
32
+ return BigInt(whole + frac.padEnd(18, '0').slice(0, 18));
33
+ };
34
+ const ZERO = `0x${'0'.repeat(40)}`;
35
+
36
+ /**
37
+ * @typedef {{ at: string, tx?: string } & (
38
+ * | { rail: number, payer: string, payee: string, token: string, operator: string, commissionBps?: number }
39
+ * | { deposit: string, token: string, from: string, to: string }
40
+ * | { withdraw: string, token: string, from: string, to: string }
41
+ * | { settled: string, railId: number, toPayee: string, commission: string, fee: string, upTo: string }
42
+ * | { oneTime: string, railId: number, commission?: string, fee?: string }
43
+ * )} PayEvent
44
+ */
45
+
46
+ /**
47
+ * @param {object} p
48
+ * @param {string} p.contract
49
+ * @param {PayEvent[]} p.events
50
+ * @param {Record<string, string>} p.funds payer (lower case) → the balance now, as a decimal
51
+ * @param {number} [p.perPage]
52
+ * @param {string} [p.token] the token the index and Filfox know (0x…)
53
+ * @param {(address: string) => string} [p.toFilecoin] 0x… → f410f…, for Filfox's answers
54
+ * @param {{ index?: boolean, blockscout?: boolean, filfox?: boolean }} [p.down] which of the three answers 503
55
+ * @param {string} [p.key] the one key Blockscout's keyed host (api.blockscout.com) takes, in the
56
+ * `authorization` header as the real one reads it; without it that host answers 402, with
57
+ * another 401, and a key in the URL is refused (400) – the reader must not put it there
58
+ * @returns {typeof fetch & { calls: string[] }}
59
+ */
60
+ export function filecoinPayFetch({
61
+ contract,
62
+ events,
63
+ funds,
64
+ perPage = 1000,
65
+ token = '',
66
+ toFilecoin = (a) => a,
67
+ down = {},
68
+ key = ''
69
+ }) {
70
+ const logs = events.map((/** @type {any} */ e, i) => {
71
+ const block = blockAt(e.at);
72
+ const base = {
73
+ address: contract,
74
+ blockNumber: `0x${block.toString(16)}`,
75
+ timeStamp: `0x${Math.floor(Date.parse(e.at) / 1000).toString(16)}`,
76
+ transactionHash: e.tx ?? `0x${(i + 1).toString(16).padStart(64, '0')}`,
77
+ logIndex: `0x${i.toString(16)}`
78
+ };
79
+ if ('rail' in e)
80
+ return {
81
+ ...base,
82
+ topics: [
83
+ topic(SIG.railCreated),
84
+ `0x${word(e.rail)}`,
85
+ `0x${word(e.payer)}`,
86
+ `0x${word(e.payee)}`
87
+ ],
88
+ data: `0x${word(e.token)}${word(e.operator)}${word(ZERO)}${word(ZERO)}${word(e.commissionBps ?? 0)}`
89
+ };
90
+ if ('deposit' in e)
91
+ return {
92
+ ...base,
93
+ topics: [topic(SIG.deposit), `0x${word(e.token)}`, `0x${word(e.from)}`, `0x${word(e.to)}`],
94
+ data: `0x${word(units(e.deposit))}`
95
+ };
96
+ if ('withdraw' in e)
97
+ return {
98
+ ...base,
99
+ topics: [topic(SIG.withdraw), `0x${word(e.token)}`, `0x${word(e.from)}`, `0x${word(e.to)}`],
100
+ data: `0x${word(units(e.withdraw))}`
101
+ };
102
+ if ('settled' in e)
103
+ return {
104
+ ...base,
105
+ topics: [topic(SIG.settled), `0x${word(e.railId)}`],
106
+ data: `0x${word(units(e.settled))}${word(units(e.toPayee))}${word(units(e.commission))}${word(units(e.fee))}${word(blockAt(e.upTo))}`
107
+ };
108
+ const fee = units(e.fee ?? '0');
109
+ const commission = units(e.commission ?? '0');
110
+ return {
111
+ ...base,
112
+ topics: [topic(SIG.oneTime), `0x${word(e.railId)}`],
113
+ data: `0x${word(units(e.oneTime) - fee - commission)}${word(commission)}${word(fee)}`
114
+ };
115
+ });
116
+ const json = (/** @type {unknown} */ body, status = 200) =>
117
+ new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
118
+ /** @type {string[]} */
119
+ const calls = [];
120
+ const f = /** @type {any} */ (
121
+ async (/** @type {any} */ input, /** @type {any} */ init) => {
122
+ const url = new URL(String(input));
123
+ const unavailable = () => json({ error: 'unavailable' }, 503);
124
+ // ---- the makers' index
125
+ if (url.hostname === 'api.goldsky.com') {
126
+ const query = String(JSON.parse(String(init?.body ?? '{}')).query ?? '');
127
+ const name = /\{\s*(\w+)\(/.exec(query)?.[1] ?? '';
128
+ calls.push(`index ${name}`);
129
+ if (down.index) return unavailable();
130
+ const payer = /(?:payer|account): "(0x[0-9a-f]{40})"/.exec(query)?.[1] ?? '';
131
+ const since = Number(/createdAt_gte: "(\d+)"/.exec(query)?.[1] ?? 0);
132
+ const after = /id_gt: "([^"]+)"/.exec(query)?.[1] ?? '';
133
+ const all = /** @type {any[]} */ (events);
134
+ const rails = all.filter((e) => 'rail' in e && e.payer === payer && e.token === token);
135
+ const railOf = (/** @type {number} */ id) => rails.find((r) => r.rail === id);
136
+ const at = (/** @type {any} */ e) => Math.floor(Date.parse(e.at) / 1000);
137
+ /** @type {any[]} */
138
+ let rows = [];
139
+ if (name === 'userTokens') {
140
+ rows =
141
+ payer in funds
142
+ ? [{ id: `${payer}-token`, funds: String(units(funds[payer])), lockupCurrent: '0' }]
143
+ : [];
144
+ } else if (name === 'rails') {
145
+ rows = rails.map((r) => ({
146
+ id: `rail-${String(r.rail).padStart(9, '0')}`,
147
+ railId: String(r.rail),
148
+ commissionRateBps: String(r.commissionBps ?? 0),
149
+ createdAt: String(at(r)),
150
+ payee: { id: r.payee },
151
+ operator: { id: r.operator }
152
+ }));
153
+ } else if (name === 'settlements') {
154
+ rows = all
155
+ .map((e, i) => ({ e, i }))
156
+ .filter(({ e }) => 'settled' in e && railOf(e.railId) && at(e) >= since)
157
+ .map(({ e, i }) => ({
158
+ id: `0x${(i + 1).toString(16).padStart(64, '0')}`,
159
+ totalSettledAmount: String(units(e.settled)),
160
+ totalNetPayeeAmount: String(units(e.toPayee)),
161
+ networkFee: String(units(e.fee)),
162
+ operatorCommission: String(units(e.commission)),
163
+ settledUpto: String(blockAt(e.upTo)),
164
+ txHash: e.tx ?? `0x${(i + 1).toString(16).padStart(64, '0')}`,
165
+ createdAt: String(at(e)),
166
+ rail: { railId: String(e.railId) }
167
+ }));
168
+ } else if (name === 'oneTimePayments') {
169
+ rows = all
170
+ .map((e, i) => ({ e, i }))
171
+ .filter(({ e }) => 'oneTime' in e && railOf(e.railId) && at(e) >= since)
172
+ .map(({ e, i }) => {
173
+ const fee = units(e.fee ?? '0');
174
+ const commission = units(e.commission ?? '0');
175
+ return {
176
+ id: `0x${(i + 1).toString(16).padStart(64, '0')}`,
177
+ totalAmount: String(units(e.oneTime)),
178
+ netPayeeAmount: String(units(e.oneTime) - fee - commission),
179
+ networkFee: String(fee),
180
+ operatorCommission: String(commission),
181
+ txHash: e.tx ?? `0x${(i + 1).toString(16).padStart(64, '0')}`,
182
+ createdAt: String(at(e)),
183
+ rail: { railId: String(e.railId) }
184
+ };
185
+ });
186
+ }
187
+ rows = rows.filter((r) => !after || r.id > after).sort((a, b) => (a.id < b.id ? -1 : 1));
188
+ return json({ data: { [name]: rows.slice(0, 1000) } });
189
+ }
190
+ // ---- Filfox: the token's transfers of an address, newest first
191
+ if (url.hostname === 'filfox.info') {
192
+ const address = decodeURIComponent(
193
+ /\/address\/([^/]+)\/token-transfers/.exec(url.pathname)?.[1] ?? ''
194
+ );
195
+ calls.push('filfox token-transfers');
196
+ if (down.filfox) return unavailable();
197
+ const page = Number(url.searchParams.get('page') ?? 0);
198
+ const transfers = /** @type {any[]} */ (events)
199
+ .map((e, i) => ({ e, i }))
200
+ .filter(({ e }) => 'deposit' in e || 'withdraw' in e)
201
+ .map(({ e, i }) =>
202
+ 'deposit' in e
203
+ ? { e, i, from: e.from, to: contract, value: units(e.deposit) }
204
+ : { e, i, from: contract, to: e.to, value: units(e.withdraw) }
205
+ )
206
+ .map((t) => ({
207
+ height: blockAt(t.e.at),
208
+ timestamp: Math.floor(Date.parse(t.e.at) / 1000),
209
+ message: `bafy2bzacefake${String(t.i).padStart(4, '0')}`,
210
+ from: toFilecoin(t.from),
211
+ to: toFilecoin(t.to),
212
+ token: toFilecoin(t.e.token),
213
+ value: String(t.value)
214
+ }))
215
+ .filter((t) => t.from === address || t.to === address)
216
+ .sort((a, b) => b.timestamp - a.timestamp);
217
+ return json({
218
+ totalCount: transfers.length,
219
+ transfers: transfers.slice(page * 100, page * 100 + 100)
220
+ });
221
+ }
222
+ // ---- Blockscout
223
+ if (down.blockscout) {
224
+ calls.push('blockscout (down)');
225
+ return unavailable();
226
+ }
227
+ if (url.hostname === 'api.blockscout.com') {
228
+ const given = new Headers(init?.headers ?? {}).get('authorization') ?? '';
229
+ if (url.searchParams.has('apikey')) {
230
+ calls.push('blockscout (key in the URL)');
231
+ return json({ error: 'the key belongs in the header' }, 400);
232
+ }
233
+ if (!given) {
234
+ calls.push('blockscout (no key)');
235
+ return json({ error: 'Proceed with API key or make a X402 payment to continue' }, 402);
236
+ }
237
+ if (!key || given !== `Bearer ${key}`) {
238
+ calls.push('blockscout (wrong key)');
239
+ return json({ error: 'Unauthorized' }, 401);
240
+ }
241
+ const rpc = url.pathname.endsWith('/json-rpc');
242
+ if (rpc ? url.pathname !== '/314/json-rpc' : url.searchParams.get('chain_id') !== '314') {
243
+ return json({ error: 'unknown chain' }, 404);
244
+ }
245
+ calls.push('keyed');
246
+ }
247
+ if (url.pathname.endsWith('/eth-rpc') || url.pathname.endsWith('/json-rpc')) {
248
+ calls.push('eth_call');
249
+ const call = JSON.parse(String(init?.body ?? '{}'));
250
+ const data = String(call?.params?.[0]?.data ?? '');
251
+ const owner = `0x${data.slice(-40)}`;
252
+ const have = units(funds[owner] ?? '0');
253
+ return json({
254
+ jsonrpc: '2.0',
255
+ id: 1,
256
+ result: `0x${word(have)}${word(0)}${word(0)}${word(0)}`
257
+ });
258
+ }
259
+ const q = url.searchParams;
260
+ calls.push(`getLogs ${q.get('topic0')?.slice(0, 10)} from ${q.get('fromBlock')}`);
261
+ if (q.get('address')?.toLowerCase() !== contract.toLowerCase())
262
+ return json({ message: 'No logs found', result: [], status: '0' });
263
+ const from = Number(q.get('fromBlock') ?? 0);
264
+ const found = logs
265
+ .filter((l) => l.topics[0] === q.get('topic0'))
266
+ .filter((l) => Number.parseInt(l.blockNumber, 16) >= from)
267
+ .filter((l) =>
268
+ [1, 2, 3].every((n) => !q.get(`topic${n}`) || l.topics[n] === q.get(`topic${n}`))
269
+ )
270
+ .sort((a, b) => Number.parseInt(a.blockNumber, 16) - Number.parseInt(b.blockNumber, 16));
271
+ return found.length
272
+ ? json({ message: 'OK', result: found.slice(0, perPage), status: '1' })
273
+ : json({ message: 'No logs found', result: [], status: '0' });
274
+ }
275
+ );
276
+ f.calls = calls;
277
+ return f;
278
+ }