@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.
package/src/wallets.js ADDED
@@ -0,0 +1,236 @@
1
+ // Own wallets, read only: which chains there are (GET /chains) and the
2
+ // history and balance of one address (POST /<chain>/wallet). The app keeps
3
+ // the list of wallets in its sealed store and names chain, address and,
4
+ // optionally, its own endpoints on every request; the bridge keeps nothing.
5
+ //
6
+ // No wallet key, no mnemonic, no signature: an address is public, and all
7
+ // the bridge does is ask a node about it. That node (Nym's RPC, Blockscout,
8
+ // Alchemy when an Alchemy API key is set up, or the one the person named)
9
+ // sees the address and this Mac's IP address – the consent screen says so.
10
+ // The Alchemy key stays in the bridge: GET /chains says only whether there
11
+ // is one.
12
+
13
+ import { chainOf, publicChains } from './registry.js';
14
+ import { createCosmosClient } from './cosmos.js';
15
+ import { createAkashConsoleClient } from './akash-console.js';
16
+ import { createAkashDeploymentsClient } from './akash-deployments.js';
17
+ import { isCosmosAddress } from './bech32.js';
18
+ import { createEvmClient } from './evm.js';
19
+ import { createBitcoinClient } from './bitcoin.js';
20
+ import { createFilecoinClient } from './filecoin.js';
21
+ import { checkEndpoint, WalletError } from './http.js';
22
+
23
+ /**
24
+ * @param {object} [options]
25
+ * @param {typeof fetch} [options.fetch]
26
+ * @param {boolean} [options.allowLoopback] endpoints on http://127.0.0.1 (tests only)
27
+ * @param {number} [options.timeoutMs]
28
+ * @param {(ms: number) => Promise<void>} [options.sleep]
29
+ * @param {() => Promise<string | null>} [options.getZpub] the Bitcoin key (the bridge: from its keychain)
30
+ * @param {number} [options.bitcoinPauseMs] between Esplora requests (tests: 0)
31
+ * @param {() => Promise<string | null>} [options.alchemyKey] the Alchemy API key, or null
32
+ * @param {(network: string) => string} [options.alchemyBaseUrl] tests: a fake Alchemy
33
+ */
34
+ export function createWalletService({
35
+ fetch: f = fetch,
36
+ allowLoopback = false,
37
+ timeoutMs,
38
+ sleep,
39
+ getZpub = async () => null,
40
+ bitcoinPauseMs,
41
+ alchemyKey = async () => null,
42
+ alchemyBaseUrl
43
+ } = {}) {
44
+ const cosmos = createCosmosClient({ fetch: f, timeoutMs, sleep });
45
+ const indexer = createAkashConsoleClient({ fetch: f, sleep });
46
+ const evm = createEvmClient({
47
+ fetch: f,
48
+ timeoutMs,
49
+ sleep,
50
+ alchemy: { key: alchemyKey, baseUrl: alchemyBaseUrl }
51
+ });
52
+ const filecoin = createFilecoinClient({ fetch: f, timeoutMs, sleep });
53
+ const deployments = createAkashDeploymentsClient({ fetch: f, timeoutMs, sleep });
54
+ const bitcoin = createBitcoinClient({
55
+ fetch: f,
56
+ getZpub,
57
+ timeoutMs,
58
+ sleep,
59
+ pauseMs: bitcoinPauseMs
60
+ });
61
+
62
+ /**
63
+ * The endpoints a request asks for, each checked, or the chain's defaults.
64
+ *
65
+ * @param {import('./registry.js').Chain} chain
66
+ * @param {any} request
67
+ */
68
+ function endpointsOf(chain, request) {
69
+ const given = /** @type {Record<string, unknown>} */ (
70
+ request?.endpoints && typeof request.endpoints === 'object' ? request.endpoints : {}
71
+ );
72
+ /** @type {Record<string, string>} */
73
+ const endpoints = {};
74
+ let ownEndpoint = false;
75
+ for (const [name, fallback] of Object.entries(chain.endpoints)) {
76
+ const value = given[name];
77
+ if (value === undefined || value === null || value === '') {
78
+ endpoints[name] = fallback;
79
+ continue;
80
+ }
81
+ const checked = checkEndpoint(value, { allowLoopback });
82
+ if (!checked) {
83
+ throw new WalletError(
84
+ `the ${name.toUpperCase()} endpoint must be an https:// URL without user, query or fragment`,
85
+ 'WALLET_ENDPOINT',
86
+ 400
87
+ );
88
+ }
89
+ endpoints[name] = checked;
90
+ ownEndpoint = true;
91
+ }
92
+ return { endpoints, ownEndpoint };
93
+ }
94
+
95
+ return {
96
+ chains: publicChains,
97
+ /** The fingerprint of the Bitcoin key in the keychain, or null. */
98
+ bitcoinKey: () => bitcoin.fingerprint(),
99
+ /** Whether an Alchemy key is set up; never the key. */
100
+ alchemy: async () => Boolean(await alchemyKey().catch(() => null)),
101
+ /** @param {string} id */
102
+ has: (id) => Boolean(chainOf(id)),
103
+
104
+ /**
105
+ * @param {{ chain?: unknown, address?: unknown, endpoints?: unknown, hashes?: unknown }} request
106
+ * `hashes`: transactions another source names for this wallet (an exchange's
107
+ * withdrawal), read from the indexer where the address's own reading lacks them
108
+ */
109
+ async sync(request) {
110
+ const chain = chainOf(String(request?.chain ?? ''));
111
+ if (!chain) throw new WalletError('unknown chain', 'WALLET_CHAIN', 400);
112
+ if (chain.kind === 'monero') {
113
+ throw new WalletError(
114
+ "Monero cannot be read by an address: import the wallet's export in the app",
115
+ 'WALLET_IMPORT_ONLY',
116
+ 400
117
+ );
118
+ }
119
+ const address = typeof request?.address === 'string' ? request.address.trim() : '';
120
+ const { endpoints, ownEndpoint } = endpointsOf(chain, request);
121
+ let result =
122
+ chain.kind === 'filecoin'
123
+ ? await filecoin.history({
124
+ chain,
125
+ address,
126
+ endpoints: /** @type {{ api: string }} */ (endpoints)
127
+ })
128
+ : chain.kind === 'bitcoin'
129
+ ? await bitcoin.history({
130
+ chain,
131
+ address,
132
+ endpoints: /** @type {{ api: string }} */ (endpoints)
133
+ })
134
+ : chain.kind === 'cosmos'
135
+ ? await cosmos.history({
136
+ chain,
137
+ address,
138
+ endpoints: /** @type {{ rpc: string, rest: string }} */ (endpoints)
139
+ })
140
+ : await evm.history({
141
+ chain,
142
+ address,
143
+ endpoints: /** @type {{ api: string }} */ (endpoints),
144
+ ownEndpoint
145
+ });
146
+ // A pruned node: what it no longer knows, from the chain's indexer. If
147
+ // that fails, the sync keeps what the node gave and says the history
148
+ // is short, as without an indexer.
149
+ if (chain.kind === 'cosmos' && endpoints.indexer && 'history' in result) {
150
+ const history = /** @type {any} */ (result.history);
151
+ if (history.pruned) {
152
+ try {
153
+ const older = await indexer.history({
154
+ chain,
155
+ address,
156
+ indexer: endpoints.indexer,
157
+ beforeHeight: history.earliestHeight
158
+ });
159
+ result = {
160
+ ...result,
161
+ entries: [...older.entries, ...result.entries],
162
+ transactions: result.transactions + older.transactions,
163
+ unknownAssets: result.unknownAssets + older.unknownAssets,
164
+ history: {
165
+ ...history,
166
+ completedBy: 'indexer',
167
+ unknownAmounts: older.unknownAmounts,
168
+ indexerFrom: older.earliestTime
169
+ }
170
+ };
171
+ } catch (/** @type {any} */ error) {
172
+ result = {
173
+ ...result,
174
+ history: { ...history, indexerError: String(error?.code ?? 'WALLET_INDEXER') }
175
+ };
176
+ }
177
+ }
178
+ }
179
+ // Transactions another source names for this wallet (an exchange's
180
+ // withdrawal hash, #303): asked of the indexer where the address's
181
+ // own reading has none of them – its listing can leave one out.
182
+ const hashes = Array.isArray(request?.hashes)
183
+ ? [
184
+ ...new Set(
185
+ request.hashes
186
+ .map((/** @type {unknown} */ h) => String(h ?? '').toUpperCase())
187
+ .filter((/** @type {string} */ h) => /^[0-9A-F]{64}$/.test(h))
188
+ )
189
+ ].slice(0, 100)
190
+ : [];
191
+ if (chain.kind === 'cosmos' && endpoints.indexer && hashes.length) {
192
+ const known = new Set(result.entries.map((e) => String(e.hash).toUpperCase()));
193
+ const missing = hashes.filter((h) => !known.has(h));
194
+ if (missing.length) {
195
+ const named = await indexer.byHashes({
196
+ chain,
197
+ address,
198
+ indexer: endpoints.indexer,
199
+ hashes: missing
200
+ });
201
+ result = {
202
+ ...result,
203
+ entries: [...named.entries, ...result.entries].sort((a, b) => a.height - b.height),
204
+ transactions: result.transactions + named.found,
205
+ history: { .../** @type {any} */ (result.history ?? {}), byHash: named.found }
206
+ };
207
+ }
208
+ }
209
+ return { chain: chain.id, endpoints, ...result };
210
+ },
211
+
212
+ /**
213
+ * An Akash wallet's deployments with what each cost (#305), for the
214
+ * monthly usage statement.
215
+ *
216
+ * @param {{ address?: unknown, endpoints?: unknown }} request
217
+ */
218
+ async akashDeployments(request) {
219
+ const chain = chainOf('akash');
220
+ if (!chain || chain.kind !== 'cosmos') throw new WalletError('no Akash', 'WALLET_CHAIN', 400);
221
+ const address = typeof request?.address === 'string' ? request.address.trim() : '';
222
+ if (!isCosmosAddress(address, chain.bech32Prefix)) {
223
+ throw new WalletError('not an Akash address', 'WALLET_ADDRESS', 400);
224
+ }
225
+ const { endpoints } = endpointsOf(chain, request);
226
+ return {
227
+ deployments: await deployments.deployments({
228
+ address,
229
+ rest: endpoints.rest,
230
+ indexer: endpoints.indexer
231
+ }),
232
+ actBalance: await deployments.actBalance({ address, rest: endpoints.rest })
233
+ };
234
+ }
235
+ };
236
+ }
@@ -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
+ };