@le-space/chains 0.0.0-stage → 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.
@@ -0,0 +1,87 @@
1
+ // Filfox's API on 127.0.0.1 for tests: an address's balance and its
2
+ // transfers, newest first, 100 a page (Filfox refuses more), its token
3
+ // transfers and a message's receiver, and 404 for an
4
+ // address it does not know. Addresses and message CIDs are made up, with
5
+ // valid Filecoin checksums.
6
+
7
+ import http from 'node:http';
8
+ import { createHash } from 'node:crypto';
9
+ import { base32nopad } from '@scure/base';
10
+ import { blake2b } from '@noble/hashes/blake2.js';
11
+
12
+ // A wallet or contract in its f410f form, as Filfox names FEVM addresses.
13
+ export { toFilecoinAddress } from '../../src/filecoin.js';
14
+
15
+ /** A made-up f1 address with a valid checksum. @param {string} seed */
16
+ export function fakeFilecoinAddress(seed) {
17
+ const payload = createHash('sha256').update(`f1:${seed}`).digest().subarray(0, 20);
18
+ const sum = blake2b(new Uint8Array([1, ...payload]), { dkLen: 4 });
19
+ return `f1${base32nopad.encode(new Uint8Array([...payload, ...sum])).toLowerCase()}`;
20
+ }
21
+
22
+ /** A made-up message CID in Filecoin's form. @param {string} seed */
23
+ export function fakeMessageCid(seed) {
24
+ const bytes = createHash('sha256').update(`cid:${seed}`).digest();
25
+ return `bafy2bzace${base32nopad
26
+ .encode(new Uint8Array([...bytes, ...bytes.subarray(0, 1)]))
27
+ .toLowerCase()
28
+ .slice(0, 52)}`;
29
+ }
30
+
31
+ /**
32
+ * @param {object} options
33
+ * @param {Record<string, { balance: string, transfers: any[], tokenTransfers?: any[] }>} options.addresses
34
+ * @param {Record<string, { to: string }>} [options.messages] a message's receiver, by CID
35
+ */
36
+ export async function startFakeFilfox({ addresses, messages = {} }) {
37
+ const state = { requests: 0, pages: 0, tokenPages: 0, messages: 0 };
38
+ const server = http.createServer((req, res) => {
39
+ state.requests++;
40
+ const url = new URL(req.url ?? '/', 'http://x');
41
+ /** @param {number} status @param {unknown} body */
42
+ const send = (status, body) => {
43
+ res.writeHead(status, { 'content-type': 'application/json' });
44
+ res.end(JSON.stringify(body));
45
+ };
46
+ const msg = /^\/api\/v1\/message\/([a-z0-9]+)$/.exec(url.pathname);
47
+ if (msg) {
48
+ state.messages++;
49
+ return messages[msg[1]] ? send(200, { cid: msg[1], ...messages[msg[1]] }) : send(404, {});
50
+ }
51
+ const m = /^\/api\/v1\/address\/([a-z0-9]+)(\/transfers|\/token-transfers)?$/.exec(
52
+ url.pathname
53
+ );
54
+ const known = m ? addresses[m[1]] : undefined;
55
+ if (!m || !known) return send(404, { error: 'Not Found' });
56
+ if (!m[2]) {
57
+ return send(200, {
58
+ address: m[1],
59
+ balance: known.balance,
60
+ actor: 'account',
61
+ tokenTransferCount: known.tokenTransfers?.length ?? 0
62
+ });
63
+ }
64
+ if (m[2] === '/token-transfers') {
65
+ state.tokenPages++;
66
+ const list = [...(known.tokenTransfers ?? [])].sort((a, b) => b.height - a.height);
67
+ return send(200, { totalCount: list.length, transfers: list.slice(0, 100) });
68
+ }
69
+ const size = Number(url.searchParams.get('pageSize') ?? 20);
70
+ if (size > 100) return send(400, { error: 'pageSize' });
71
+ const page = Number(url.searchParams.get('page') ?? 0);
72
+ state.pages++;
73
+ const sorted = [...known.transfers].sort((a, b) => b.height - a.height);
74
+ send(200, {
75
+ totalCount: sorted.length,
76
+ transfers: sorted.slice(page * size, page * size + size),
77
+ types: ['burn-fee', 'miner-fee', 'transfer']
78
+ });
79
+ });
80
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(undefined)));
81
+ const port = /** @type {import('node:net').AddressInfo} */ (server.address()).port;
82
+ return {
83
+ url: `http://127.0.0.1:${port}/api/v1`,
84
+ state,
85
+ close: () => new Promise((resolve) => server.close(() => resolve(undefined)))
86
+ };
87
+ }