@le-space/chains 0.0.0-stage → 0.1.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
+ }