@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/LICENSE +662 -0
- package/README.md +25 -2
- package/package.json +56 -3
- package/src/akash-console.js +456 -0
- package/src/akash-deployments.js +145 -0
- package/src/alchemy.js +648 -0
- package/src/bech32.js +126 -0
- package/src/bitcoin.js +366 -0
- package/src/core.js +8 -0
- package/src/cosmos-chains.js +80 -0
- package/src/cosmos.js +591 -0
- package/src/evm.js +697 -0
- package/src/explorer.js +14 -0
- package/src/filecoin-chain.js +45 -0
- package/src/filecoin.js +398 -0
- package/src/http.js +121 -0
- package/src/index.js +63 -0
- package/src/near.js +655 -0
- package/src/protobuf.js +130 -0
- package/src/registry.js +279 -0
- package/src/swaps.js +61 -0
- package/src/wallets.js +236 -0
- package/test/support/fake-cosmos.js +650 -0
- package/test/support/fake-filfox.js +87 -0
package/src/explorer.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// Links into a block explorer, from its URL templates.
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @typedef {object} Explorer
|
|
5
|
+
* @property {string} name
|
|
6
|
+
* @property {string} tx URL with `{tx}`
|
|
7
|
+
* @property {string} address URL with `{address}`
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** @param {Explorer} explorer @param {string} tx */
|
|
11
|
+
export const txUrl = (explorer, tx) => explorer.tx.replace('{tx}', encodeURIComponent(tx));
|
|
12
|
+
/** @param {Explorer} explorer @param {string} address */
|
|
13
|
+
export const addressUrl = (explorer, address) =>
|
|
14
|
+
explorer.address.replace('{address}', encodeURIComponent(address));
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// Filecoin as a chain the bridge reads (#242): its assets, the FEVM tokens
|
|
2
|
+
// and contracts listed for it, Filfox as the default API and explorer.
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @typedef {object} FilecoinChain
|
|
6
|
+
* @property {string} id
|
|
7
|
+
* @property {'filecoin'} kind
|
|
8
|
+
* @property {string} name
|
|
9
|
+
* @property {string} shortName
|
|
10
|
+
* @property {string} caip2
|
|
11
|
+
* @property {import('@le-space/ledger/wallet-entry').ChainAsset} native
|
|
12
|
+
* @property {Record<string, import('@le-space/ledger/wallet-entry').ChainAsset>} tokens FEVM ERC-20s booked here: lower-case `0x` contract → asset
|
|
13
|
+
* @property {Record<string, string>} contracts FEVM contracts a swap is named after: lower-case `0x` → name
|
|
14
|
+
* @property {{ api: string }} endpoints Filfox's API, …/api/v1
|
|
15
|
+
* @property {{ api: string[] }} alternatives
|
|
16
|
+
* @property {import('./explorer.js').Explorer} explorer
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** @type {FilecoinChain} */
|
|
20
|
+
export const FILECOIN = {
|
|
21
|
+
id: 'filecoin',
|
|
22
|
+
kind: 'filecoin',
|
|
23
|
+
name: 'Filecoin',
|
|
24
|
+
shortName: 'Filecoin',
|
|
25
|
+
caip2: 'fil:f',
|
|
26
|
+
native: { symbol: 'FIL', decimals: 18 },
|
|
27
|
+
// USDFC, Secured Finance's FIL-backed stablecoin (issue #301): checked
|
|
28
|
+
// 2026-10-05 against Secured Finance's contract list, CoinGecko's
|
|
29
|
+
// platform entry and the contract's own symbol() and decimals().
|
|
30
|
+
tokens: { '0x80b98d3aa09ffff255c3ba4a241111ff1262f045': { symbol: 'USDFC', decimals: 18 } },
|
|
31
|
+
// From Sushi's own config (sushi-labs/sushi, src/evm/config): the
|
|
32
|
+
// router its app sends swaps through, its V2 router, and the wrapped FIL.
|
|
33
|
+
contracts: {
|
|
34
|
+
'0xac4c6e212a361c968f1725b4d055b47e63f80b75': 'SushiSwap',
|
|
35
|
+
'0x46b3fdf7b5cde91ac049936bf0bdb12c5d22202e': 'SushiSwap V2 (Router)',
|
|
36
|
+
'0x60e1773636cf5e4a227d9ac24f20feca034ee25a': 'WFIL'
|
|
37
|
+
},
|
|
38
|
+
endpoints: { api: 'https://filfox.info/api/v1' },
|
|
39
|
+
alternatives: { api: [] },
|
|
40
|
+
explorer: {
|
|
41
|
+
name: 'Filfox',
|
|
42
|
+
tx: 'https://filfox.info/en/message/{tx}',
|
|
43
|
+
address: 'https://filfox.info/en/address/{address}'
|
|
44
|
+
}
|
|
45
|
+
};
|
package/src/filecoin.js
ADDED
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
// A Filecoin wallet, read only, by its address (issue: Filecoin as an own
|
|
2
|
+
// wallet, after #215). The history comes from Filfox's public API, no key:
|
|
3
|
+
//
|
|
4
|
+
// GET /address/<a> the balance (attoFIL)
|
|
5
|
+
// GET /address/<a>/transfers?pageSize=100&page=<n>
|
|
6
|
+
// every value movement, newest first:
|
|
7
|
+
// `send` / `receive` (type transfer),
|
|
8
|
+
// `miner-fee`, `burn-fee`
|
|
9
|
+
//
|
|
10
|
+
// Filfox sees the address and this Mac's IP – the consent screen says so.
|
|
11
|
+
//
|
|
12
|
+
// A message is the unit, and its CID is the hash: the same CID an exchange
|
|
13
|
+
// reports for a deposit (Kraken's txid `bafy2bzace…`), so a withdrawal from
|
|
14
|
+
// here pairs with that deposit as an own transfer. Per message:
|
|
15
|
+
// - each `send` an entry `sent`, each `receive` an entry `received`,
|
|
16
|
+
// with the other side's address;
|
|
17
|
+
// - its `miner-fee` and `burn-fee` together one entry `fee` – what sending
|
|
18
|
+
// the message cost; only messages this address sent pay one.
|
|
19
|
+
//
|
|
20
|
+
// Addresses: f1 (secp256k1), f3 (BLS) and f410f (delegated, FEVM; also
|
|
21
|
+
// given as its `0x…` Ethereum form, converted here) are checked
|
|
22
|
+
// by their blake2b checksum before anything is asked; f0 (an ID) has none and
|
|
23
|
+
// is taken as it is. The log gets counts, never an address or a CID.
|
|
24
|
+
//
|
|
25
|
+
// FEVM tokens (issue #301): where the address has token transfers,
|
|
26
|
+
//
|
|
27
|
+
// GET /address/<a>/token-transfers?pageSize=100&page=<n>
|
|
28
|
+
//
|
|
29
|
+
// gives them, by message too. Only the tokens listed for the chain are
|
|
30
|
+
// booked (chain.js `tokens`, by contract – a token's symbol is its own
|
|
31
|
+
// claim); their balance is the sum of the whole history. A message in which
|
|
32
|
+
// the wallet gives one asset and gets another is a swap, as on the EVM
|
|
33
|
+
// chains (swaps.js markSwaps): a FIL → USDFC swap on SushiSwap, say. Its router
|
|
34
|
+
// is named from the message's receiver (`GET /message/<cid>`, asked for swaps
|
|
35
|
+
// only) where it is a known contract (chain.js `contracts`).
|
|
36
|
+
|
|
37
|
+
import { base32nopad } from '@scure/base';
|
|
38
|
+
import { blake2b } from '@noble/hashes/blake2.js';
|
|
39
|
+
import { fromHex } from '@le-space/ledger/bytes';
|
|
40
|
+
|
|
41
|
+
import {
|
|
42
|
+
addressUrl,
|
|
43
|
+
createJsonFetcher,
|
|
44
|
+
markSwaps,
|
|
45
|
+
txUrl,
|
|
46
|
+
unitsToDecimal,
|
|
47
|
+
WalletError
|
|
48
|
+
} from './core.js';
|
|
49
|
+
|
|
50
|
+
const PAGE = 100;
|
|
51
|
+
|
|
52
|
+
/** `-1.5` → its smallest units, signed. @param {string} amount @param {number} decimals */
|
|
53
|
+
function decimalToUnits(amount, decimals) {
|
|
54
|
+
const m = /^(-?)(\d+)(?:\.(\d+))?$/.exec(amount);
|
|
55
|
+
if (!m) return 0n;
|
|
56
|
+
const units = BigInt(m[2] + (m[3] ?? '').padEnd(decimals, '0').slice(0, decimals));
|
|
57
|
+
return m[1] ? -units : units;
|
|
58
|
+
}
|
|
59
|
+
/** A wallet with more movements than this is too large to read here. */
|
|
60
|
+
const MAX_PAGES = 200;
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* An Ethereum-style address in its Filecoin form: `0x…` (20 bytes) →
|
|
64
|
+
* `f410f…`, the delegated address of the same account (namespace 10, the
|
|
65
|
+
* Ethereum address manager), with its blake2b checksum. Anything else comes
|
|
66
|
+
* back as it was, trimmed.
|
|
67
|
+
*
|
|
68
|
+
* @param {unknown} address
|
|
69
|
+
*/
|
|
70
|
+
export function toFilecoinAddress(address) {
|
|
71
|
+
const a = String(address ?? '').trim();
|
|
72
|
+
if (!/^0x[0-9a-fA-F]{40}$/.test(a)) return a;
|
|
73
|
+
const payload = fromHex(a.slice(2));
|
|
74
|
+
const sum = blake2b(new Uint8Array([4, 10, ...payload]), { dkLen: 4 });
|
|
75
|
+
return `f410f${base32nopad.encode(new Uint8Array([...payload, ...sum])).toLowerCase()}`;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Whether a string is a Filecoin mainnet address with a valid checksum.
|
|
80
|
+
*
|
|
81
|
+
* @param {unknown} address
|
|
82
|
+
*/
|
|
83
|
+
export function isFilecoinAddress(address) {
|
|
84
|
+
const a = String(address ?? '').trim();
|
|
85
|
+
if (/^f0\d{1,20}$/.test(a)) return true;
|
|
86
|
+
const m = /^f(1|3|410f)([a-z2-7]+)$/.exec(a);
|
|
87
|
+
if (!m) return false;
|
|
88
|
+
let raw;
|
|
89
|
+
try {
|
|
90
|
+
raw = base32nopad.decode(m[2].toUpperCase());
|
|
91
|
+
} catch {
|
|
92
|
+
return false;
|
|
93
|
+
}
|
|
94
|
+
const payload = raw.slice(0, -4);
|
|
95
|
+
const sum = raw.slice(-4);
|
|
96
|
+
/** @type {number[]} */ let head;
|
|
97
|
+
if (m[1] === '1') {
|
|
98
|
+
if (payload.length !== 20) return false;
|
|
99
|
+
head = [1];
|
|
100
|
+
} else if (m[1] === '3') {
|
|
101
|
+
if (payload.length !== 48) return false;
|
|
102
|
+
head = [3];
|
|
103
|
+
} else {
|
|
104
|
+
if (payload.length !== 20) return false;
|
|
105
|
+
head = [4, 10]; // delegated, namespace 10 (the Ethereum address manager), as leb128
|
|
106
|
+
}
|
|
107
|
+
const calc = blake2b(new Uint8Array([...head, ...payload]), { dkLen: 4 });
|
|
108
|
+
return calc.every((b, i) => b === sum[i]);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* @typedef {object} FilfoxTransfer
|
|
113
|
+
* @property {number} height
|
|
114
|
+
* @property {number} timestamp unix seconds
|
|
115
|
+
* @property {string} message the message CID
|
|
116
|
+
* @property {string} from
|
|
117
|
+
* @property {string} to
|
|
118
|
+
* @property {string} value signed attoFIL
|
|
119
|
+
* @property {'send' | 'receive' | 'miner-fee' | 'burn-fee'} type
|
|
120
|
+
*/
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Filfox's transfers of one address → wallet entries.
|
|
124
|
+
*
|
|
125
|
+
* @param {FilfoxTransfer[]} transfers
|
|
126
|
+
* @param {import('./filecoin-chain.js').FilecoinChain} chain
|
|
127
|
+
* @returns {import('@le-space/ledger/wallet-entry').WalletEntry[]}
|
|
128
|
+
*/
|
|
129
|
+
export function normalizeFilecoin(transfers, chain) {
|
|
130
|
+
const { symbol, decimals } = chain.native;
|
|
131
|
+
/** @type {Map<string, FilfoxTransfer[]>} */
|
|
132
|
+
const byMessage = new Map();
|
|
133
|
+
for (const t of transfers) {
|
|
134
|
+
if (typeof t?.message !== 'string' || !/^bafy2bzace[a-z2-7]+$/.test(t.message)) continue;
|
|
135
|
+
const list = byMessage.get(t.message) ?? [];
|
|
136
|
+
list.push(t);
|
|
137
|
+
byMessage.set(t.message, list);
|
|
138
|
+
}
|
|
139
|
+
/** @type {import('@le-space/ledger/wallet-entry').WalletEntry[]} */
|
|
140
|
+
const entries = [];
|
|
141
|
+
for (const [cid, list] of byMessage) {
|
|
142
|
+
const first = list[0];
|
|
143
|
+
const time = new Date(Number(first.timestamp) * 1000).toISOString();
|
|
144
|
+
const base = {
|
|
145
|
+
hash: cid,
|
|
146
|
+
height: Number(first.height),
|
|
147
|
+
time,
|
|
148
|
+
date: time.slice(0, 10),
|
|
149
|
+
asset: symbol,
|
|
150
|
+
decimals,
|
|
151
|
+
counterpartyLabel: '',
|
|
152
|
+
memo: '',
|
|
153
|
+
success: true,
|
|
154
|
+
explorerUrl: txUrl(chain.explorer, cid)
|
|
155
|
+
};
|
|
156
|
+
let fee = 0n;
|
|
157
|
+
let n = 0;
|
|
158
|
+
for (const t of list) {
|
|
159
|
+
let value;
|
|
160
|
+
try {
|
|
161
|
+
value = BigInt(t.value);
|
|
162
|
+
} catch {
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
if (t.type === 'miner-fee' || t.type === 'burn-fee') {
|
|
166
|
+
fee += value < 0n ? -value : value;
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
if (t.type !== 'send' && t.type !== 'receive') continue;
|
|
170
|
+
const out = t.type === 'send';
|
|
171
|
+
const amount = out ? (value < 0n ? value : -value) : value < 0n ? -value : value;
|
|
172
|
+
entries.push({
|
|
173
|
+
...base,
|
|
174
|
+
id: `${cid}:${t.type}:${n++}`,
|
|
175
|
+
type: out ? 'sent' : 'received',
|
|
176
|
+
kind: 'transfer',
|
|
177
|
+
amount: unitsToDecimal(amount, decimals),
|
|
178
|
+
counterparty: String(out ? t.to : t.from)
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
if (fee > 0n) {
|
|
182
|
+
entries.push({
|
|
183
|
+
...base,
|
|
184
|
+
id: `${cid}:fee`,
|
|
185
|
+
type: 'fee',
|
|
186
|
+
kind: 'fee',
|
|
187
|
+
amount: unitsToDecimal(-fee, decimals),
|
|
188
|
+
counterparty: ''
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return entries.sort((a, b) =>
|
|
193
|
+
a.height === b.height ? (a.id < b.id ? -1 : 1) : a.height - b.height
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* @typedef {object} FilfoxTokenTransfer
|
|
199
|
+
* @property {number} height
|
|
200
|
+
* @property {number} timestamp unix seconds
|
|
201
|
+
* @property {string} message the message CID
|
|
202
|
+
* @property {string} from
|
|
203
|
+
* @property {string} to
|
|
204
|
+
* @property {string} token the contract, as f410f…
|
|
205
|
+
* @property {string} value unsigned, in the token's smallest unit
|
|
206
|
+
* @property {string} [symbol] the token's own claim
|
|
207
|
+
* @property {number} [decimals] the token's own claim
|
|
208
|
+
*/
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Filfox's token transfers of one address → wallet entries for the listed
|
|
212
|
+
* tokens, and the moves of other tokens (they only name a swap's side).
|
|
213
|
+
*
|
|
214
|
+
* @param {FilfoxTokenTransfer[]} transfers
|
|
215
|
+
* @param {import('./filecoin-chain.js').FilecoinChain} chain
|
|
216
|
+
* @param {string} address the wallet, as f410f… (or f1/f3/f0)
|
|
217
|
+
* @returns {{ entries: import('@le-space/ledger/wallet-entry').WalletEntry[], unlisted: { hash: string, asset: string, amount: string, listed: false }[], unknownTokens: string[] }}
|
|
218
|
+
*/
|
|
219
|
+
export function normalizeFilecoinTokens(transfers, chain, address) {
|
|
220
|
+
/** @type {Map<string, import('@le-space/ledger/wallet-entry').ChainAsset>} f410f contract → asset */
|
|
221
|
+
const listed = new Map(
|
|
222
|
+
Object.entries(chain.tokens ?? {}).map(([contract, a]) => [toFilecoinAddress(contract), a])
|
|
223
|
+
);
|
|
224
|
+
/** @type {import('@le-space/ledger/wallet-entry').WalletEntry[]} */
|
|
225
|
+
const entries = [];
|
|
226
|
+
/** @type {{ hash: string, asset: string, amount: string, listed: false }[]} */
|
|
227
|
+
const unlisted = [];
|
|
228
|
+
/** @type {Set<string>} */
|
|
229
|
+
const unknown = new Set();
|
|
230
|
+
/** @type {Map<string, number>} */
|
|
231
|
+
const seen = new Map();
|
|
232
|
+
for (const t of transfers) {
|
|
233
|
+
const cid = t?.message;
|
|
234
|
+
if (typeof cid !== 'string' || !/^bafy2bzace[a-z2-7]+$/.test(cid)) continue;
|
|
235
|
+
const out = t.from === address;
|
|
236
|
+
const into = t.to === address;
|
|
237
|
+
if (out === into) continue;
|
|
238
|
+
let value;
|
|
239
|
+
try {
|
|
240
|
+
value = BigInt(t.value);
|
|
241
|
+
} catch {
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
if (value <= 0n) continue;
|
|
245
|
+
const asset = listed.get(String(t.token));
|
|
246
|
+
if (!asset) {
|
|
247
|
+
unknown.add(String(t.token));
|
|
248
|
+
unlisted.push({
|
|
249
|
+
hash: cid,
|
|
250
|
+
// Only a swap's side, never booked: the token's own claim, marked as such.
|
|
251
|
+
asset: String(t.symbol ?? '?').slice(0, 20),
|
|
252
|
+
amount: unitsToDecimal(out ? -value : value, Number(t.decimals ?? 18)),
|
|
253
|
+
listed: false
|
|
254
|
+
});
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
const n = seen.get(cid) ?? 0;
|
|
258
|
+
seen.set(cid, n + 1);
|
|
259
|
+
const time = new Date(Number(t.timestamp) * 1000).toISOString();
|
|
260
|
+
entries.push({
|
|
261
|
+
id: `${cid}:token:${n}`,
|
|
262
|
+
hash: cid,
|
|
263
|
+
height: Number(t.height),
|
|
264
|
+
time,
|
|
265
|
+
date: time.slice(0, 10),
|
|
266
|
+
type: out ? 'sent' : 'received',
|
|
267
|
+
kind: 'transfer',
|
|
268
|
+
asset: asset.symbol,
|
|
269
|
+
decimals: asset.decimals,
|
|
270
|
+
amount: unitsToDecimal(out ? -value : value, asset.decimals),
|
|
271
|
+
counterparty: String(out ? t.to : t.from),
|
|
272
|
+
counterpartyLabel: '',
|
|
273
|
+
memo: '',
|
|
274
|
+
success: true,
|
|
275
|
+
explorerUrl: txUrl(chain.explorer, cid)
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
return { entries, unlisted, unknownTokens: [...unknown] };
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* @param {object} options
|
|
283
|
+
* @param {typeof fetch} options.fetch
|
|
284
|
+
* @param {number} [options.timeoutMs]
|
|
285
|
+
* @param {(ms: number) => Promise<void>} [options.sleep]
|
|
286
|
+
*/
|
|
287
|
+
export function createFilecoinClient({ fetch: f, timeoutMs, sleep }) {
|
|
288
|
+
const get = createJsonFetcher({ fetch: f, timeoutMs, sleep });
|
|
289
|
+
|
|
290
|
+
return {
|
|
291
|
+
/**
|
|
292
|
+
* @param {{ chain: import('./filecoin-chain.js').FilecoinChain, address: string, endpoints: { api: string } }} params
|
|
293
|
+
*/
|
|
294
|
+
async history({ chain, address, endpoints }) {
|
|
295
|
+
// A `0x…` address is read as its f410f form (toFilecoinAddress).
|
|
296
|
+
const a = toFilecoinAddress(address);
|
|
297
|
+
if (!isFilecoinAddress(a)) {
|
|
298
|
+
throw new WalletError(
|
|
299
|
+
'not a Filecoin address (f1…, f3…, f410f… or f0…)',
|
|
300
|
+
'WALLET_ADDRESS',
|
|
301
|
+
400
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
const info = await get(`${endpoints.api}/address/${encodeURIComponent(a)}`);
|
|
305
|
+
/** @type {FilfoxTransfer[]} */
|
|
306
|
+
const transfers = [];
|
|
307
|
+
let total = Infinity;
|
|
308
|
+
for (let page = 0; page * PAGE < total; page++) {
|
|
309
|
+
if (page >= MAX_PAGES) {
|
|
310
|
+
throw new WalletError(
|
|
311
|
+
`more than ${MAX_PAGES * PAGE} movements on this address`,
|
|
312
|
+
'WALLET_TOO_LARGE',
|
|
313
|
+
413
|
|
314
|
+
);
|
|
315
|
+
}
|
|
316
|
+
const body = await get(
|
|
317
|
+
`${endpoints.api}/address/${encodeURIComponent(a)}/transfers?pageSize=${PAGE}&page=${page}`
|
|
318
|
+
);
|
|
319
|
+
const list = Array.isArray(body?.transfers) ? body.transfers : [];
|
|
320
|
+
total = Number(body?.totalCount ?? 0);
|
|
321
|
+
transfers.push(...list);
|
|
322
|
+
if (list.length < PAGE) break;
|
|
323
|
+
}
|
|
324
|
+
/** @type {FilfoxTokenTransfer[]} */
|
|
325
|
+
const tokenTransfers = [];
|
|
326
|
+
let tokenTotal = Number(info?.tokenTransferCount ?? 0) > 0 ? Infinity : 0;
|
|
327
|
+
for (let page = 0; page * PAGE < tokenTotal; page++) {
|
|
328
|
+
if (page >= MAX_PAGES) {
|
|
329
|
+
throw new WalletError(
|
|
330
|
+
`more than ${MAX_PAGES * PAGE} token movements on this address`,
|
|
331
|
+
'WALLET_TOO_LARGE',
|
|
332
|
+
413
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
const body = await get(
|
|
336
|
+
`${endpoints.api}/address/${encodeURIComponent(a)}/token-transfers?pageSize=${PAGE}&page=${page}`
|
|
337
|
+
);
|
|
338
|
+
const list = Array.isArray(body?.transfers) ? body.transfers : [];
|
|
339
|
+
tokenTotal = Number(body?.totalCount ?? 0);
|
|
340
|
+
tokenTransfers.push(...list);
|
|
341
|
+
if (list.length < PAGE) break;
|
|
342
|
+
}
|
|
343
|
+
const tokens = normalizeFilecoinTokens(tokenTransfers, chain, a);
|
|
344
|
+
const entries = [...normalizeFilecoin(transfers, chain), ...tokens.entries];
|
|
345
|
+
markSwaps(/** @type {any[]} */ (entries), tokens.unlisted, () => '');
|
|
346
|
+
// A swap's router: the receiver of its message, where it is a known contract.
|
|
347
|
+
/** @type {Map<string, string>} f410f → name */
|
|
348
|
+
const names = new Map(
|
|
349
|
+
Object.entries(chain.contracts ?? {}).map(([c, name]) => [toFilecoinAddress(c), name])
|
|
350
|
+
);
|
|
351
|
+
/** @type {Map<string, any>} */
|
|
352
|
+
const swaps = new Map();
|
|
353
|
+
for (const e of /** @type {any[]} */ (entries)) if (e.swap) swaps.set(e.hash, e.swap);
|
|
354
|
+
for (const [cid, swap] of swaps) {
|
|
355
|
+
const message = await get(`${endpoints.api}/message/${encodeURIComponent(cid)}`).catch(
|
|
356
|
+
() => null
|
|
357
|
+
);
|
|
358
|
+
swap.via = names.get(String(message?.to ?? '')) ?? '';
|
|
359
|
+
}
|
|
360
|
+
entries.sort((x, y) =>
|
|
361
|
+
x.height === y.height ? (x.id < y.id ? -1 : 1) : x.height - y.height
|
|
362
|
+
);
|
|
363
|
+
let balance = 0n;
|
|
364
|
+
try {
|
|
365
|
+
balance = BigInt(info?.balance ?? 0);
|
|
366
|
+
} catch {
|
|
367
|
+
balance = 0n;
|
|
368
|
+
}
|
|
369
|
+
return {
|
|
370
|
+
entries,
|
|
371
|
+
balances: [
|
|
372
|
+
{
|
|
373
|
+
asset: chain.native.symbol,
|
|
374
|
+
amount: unitsToDecimal(balance, chain.native.decimals),
|
|
375
|
+
decimals: chain.native.decimals
|
|
376
|
+
},
|
|
377
|
+
// A listed token's balance: the sum of its whole history, read above.
|
|
378
|
+
...Object.values(chain.tokens ?? {})
|
|
379
|
+
.filter((t) => tokens.entries.some((e) => e.asset === t.symbol))
|
|
380
|
+
.map((t) => ({
|
|
381
|
+
asset: t.symbol,
|
|
382
|
+
amount: unitsToDecimal(
|
|
383
|
+
tokens.entries
|
|
384
|
+
.filter((e) => e.asset === t.symbol)
|
|
385
|
+
.reduce((sum, e) => sum + decimalToUnits(e.amount, t.decimals), 0n),
|
|
386
|
+
t.decimals
|
|
387
|
+
),
|
|
388
|
+
decimals: t.decimals
|
|
389
|
+
}))
|
|
390
|
+
],
|
|
391
|
+
transactions: new Set(entries.map((e) => e.hash)).size,
|
|
392
|
+
unknownAssets: tokens.unknownTokens.length,
|
|
393
|
+
history: { earliestHeight: 0, earliestTime: null, pruned: false },
|
|
394
|
+
addressUrl: addressUrl(chain.explorer, a)
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
};
|
|
398
|
+
}
|
package/src/http.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// JSON over HTTPS for the chain clients: a timeout per request, a few
|
|
2
|
+
// retries on what is worth retrying (no answer, 5xx, 429, a body that is no
|
|
3
|
+
// JSON – public RPCs do that now and then), and errors with a code.
|
|
4
|
+
//
|
|
5
|
+
// Error messages name the host at most, never a path or a query: those
|
|
6
|
+
// carry the wallet's address, and the bridge logs error messages.
|
|
7
|
+
|
|
8
|
+
export class WalletError extends Error {
|
|
9
|
+
/** @param {string} message @param {string} code @param {number} [status] */
|
|
10
|
+
constructor(message, code, status = 502) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.name = 'WalletError';
|
|
13
|
+
this.code = code;
|
|
14
|
+
this.status = status;
|
|
15
|
+
/** @type {number | undefined} the HTTP status of a refusal, when there was one */
|
|
16
|
+
this.httpStatus = undefined;
|
|
17
|
+
/** @type {unknown} its JSON body, never sent on or logged */
|
|
18
|
+
this.body = undefined;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** @param {string} url */
|
|
23
|
+
export function hostOf(url) {
|
|
24
|
+
try {
|
|
25
|
+
return new URL(url).host;
|
|
26
|
+
} catch {
|
|
27
|
+
return '?';
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* An endpoint the bridge may call: https, or http on this machine when
|
|
33
|
+
* `allowLoopback` (tests). No user:password@, no fragment. Returns it
|
|
34
|
+
* without a trailing slash, or null.
|
|
35
|
+
*
|
|
36
|
+
* @param {unknown} value
|
|
37
|
+
* @param {{ allowLoopback?: boolean }} [options]
|
|
38
|
+
*/
|
|
39
|
+
export function checkEndpoint(value, { allowLoopback = false } = {}) {
|
|
40
|
+
if (typeof value !== 'string' || value.length > 300) return null;
|
|
41
|
+
let url;
|
|
42
|
+
try {
|
|
43
|
+
url = new URL(value.trim());
|
|
44
|
+
} catch {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
if (url.username || url.password || url.hash || url.search) return null;
|
|
48
|
+
const loopback = url.hostname === '127.0.0.1' || url.hostname === 'localhost';
|
|
49
|
+
if (url.protocol !== 'https:' && !(allowLoopback && loopback && url.protocol === 'http:')) {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
return url.toString().replace(/\/+$/, '');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* @param {object} options
|
|
57
|
+
* @param {typeof fetch} options.fetch
|
|
58
|
+
* @param {number} [options.timeoutMs]
|
|
59
|
+
* @param {number} [options.retries]
|
|
60
|
+
* @param {(ms: number) => Promise<void>} [options.sleep]
|
|
61
|
+
*/
|
|
62
|
+
export function createJsonFetcher({
|
|
63
|
+
fetch: f,
|
|
64
|
+
timeoutMs = 20_000,
|
|
65
|
+
retries = 2,
|
|
66
|
+
sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
67
|
+
}) {
|
|
68
|
+
/**
|
|
69
|
+
* @param {string} url
|
|
70
|
+
* @param {RequestInit} [init]
|
|
71
|
+
* @param {{ retryIf?: (body: any) => boolean }} [options] a JSON answer that is a transient error
|
|
72
|
+
* @returns {Promise<any>}
|
|
73
|
+
*/
|
|
74
|
+
return async function getJson(url, init = {}, { retryIf } = {}) {
|
|
75
|
+
const host = hostOf(url);
|
|
76
|
+
/** @type {WalletError | null} */
|
|
77
|
+
let last = null;
|
|
78
|
+
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
79
|
+
if (attempt > 0) await sleep(1000 * 2 ** (attempt - 1));
|
|
80
|
+
let res;
|
|
81
|
+
try {
|
|
82
|
+
res = await f(url, {
|
|
83
|
+
...init,
|
|
84
|
+
headers: { accept: 'application/json', ...(init.headers ?? {}) },
|
|
85
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
86
|
+
redirect: 'error'
|
|
87
|
+
});
|
|
88
|
+
} catch (/** @type {any} */ error) {
|
|
89
|
+
last =
|
|
90
|
+
error?.name === 'TimeoutError' || error?.name === 'AbortError'
|
|
91
|
+
? new WalletError(`${host} did not answer in time`, 'WALLET_TIMEOUT', 504)
|
|
92
|
+
: new WalletError(`${host} is not reachable`, 'WALLET_UNREACHABLE');
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
const body = await res.json().catch(() => undefined);
|
|
96
|
+
if (res.status === 429 || res.status >= 500 || body === undefined) {
|
|
97
|
+
last = new WalletError(
|
|
98
|
+
res.status === 429
|
|
99
|
+
? `${host} limits requests (HTTP 429)`
|
|
100
|
+
: `${host} answered ${res.status}${body === undefined ? ' without JSON' : ''}`,
|
|
101
|
+
res.status === 429 ? 'WALLET_RATE_LIMIT' : 'WALLET_NODE',
|
|
102
|
+
res.status === 429 ? 429 : 502
|
|
103
|
+
);
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
if (retryIf?.(body)) {
|
|
107
|
+
last = new WalletError(`${host} is busy`, 'WALLET_RATE_LIMIT', 429);
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (!res.ok) {
|
|
111
|
+
const error = new WalletError(`${host} answered ${res.status}`, 'WALLET_NODE');
|
|
112
|
+
// For a caller that tells its API's refusals apart (Alchemy: 401, 403).
|
|
113
|
+
error.httpStatus = res.status;
|
|
114
|
+
error.body = body;
|
|
115
|
+
throw error;
|
|
116
|
+
}
|
|
117
|
+
return body;
|
|
118
|
+
}
|
|
119
|
+
throw /** @type {WalletError} */ (last);
|
|
120
|
+
};
|
|
121
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// @le-space/chains: own wallets on public chains, read only, by their
|
|
3
|
+
// address – as @le-space/ledger WalletEntry records (NEAR: LedgerEntry).
|
|
4
|
+
// Runs in a browser and in Node: `fetch`, endpoints and keys (an Alchemy key,
|
|
5
|
+
// a NearBlocks key, a Bitcoin zpub) are handed in by the caller; nothing is
|
|
6
|
+
// read from disk, a keychain or the environment.
|
|
7
|
+
//
|
|
8
|
+
// createWalletService every chain behind one call (Belege's bridge)
|
|
9
|
+
// cosmos Nym's Nyx, Akash (CometBFT RPC + REST, the Akash
|
|
10
|
+
// Console indexer, deployments)
|
|
11
|
+
// evm Ethereum, Base, Polygon, … (Blockscout, Alchemy)
|
|
12
|
+
// bitcoin Esplora, addresses from a zpub/xpub
|
|
13
|
+
// filecoin Filfox
|
|
14
|
+
// near NearBlocks + an archival RPC (from Eigenbeleg);
|
|
15
|
+
// `near` here, or `@le-space/chains/near`
|
|
16
|
+
|
|
17
|
+
export * from './core.js';
|
|
18
|
+
export { CHAINS, KNOWN_EVM_CONTRACTS, chainOf, publicChains } from './registry.js';
|
|
19
|
+
export { createWalletService } from './wallets.js';
|
|
20
|
+
|
|
21
|
+
export { AKASH_CHAIN, NYX_CHAIN } from './cosmos-chains.js';
|
|
22
|
+
export {
|
|
23
|
+
createCosmosClient,
|
|
24
|
+
denomLabel,
|
|
25
|
+
normalizeCosmosTx,
|
|
26
|
+
parseCoins,
|
|
27
|
+
readEvents,
|
|
28
|
+
transfersOf,
|
|
29
|
+
untransferredOf,
|
|
30
|
+
markBmeSwap
|
|
31
|
+
} from './cosmos.js';
|
|
32
|
+
export { bech32Decode, bech32Encode, isCosmosAddress, moduleAddress } from './bech32.js';
|
|
33
|
+
export { decodeTx, encodeTx } from './protobuf.js';
|
|
34
|
+
export { createAkashConsoleClient, normalizeConsoleTx } from './akash-console.js';
|
|
35
|
+
export { createAkashDeploymentsClient, decUnits } from './akash-deployments.js';
|
|
36
|
+
|
|
37
|
+
export { createEvmClient, isEvmAddress, normalizeEvm, toChecksumAddress } from './evm.js';
|
|
38
|
+
export { alchemyBaseUrl, computeUnitsOf, createAlchemyReader, isAlchemyKey } from './alchemy.js';
|
|
39
|
+
|
|
40
|
+
export {
|
|
41
|
+
ADDRESS_TYPES,
|
|
42
|
+
createBitcoinClient,
|
|
43
|
+
deriveAddress,
|
|
44
|
+
keyFingerprint,
|
|
45
|
+
normalizeBitcoin,
|
|
46
|
+
parseExtendedKey,
|
|
47
|
+
parseStoredKey
|
|
48
|
+
} from './bitcoin.js';
|
|
49
|
+
|
|
50
|
+
export { FILECOIN } from './filecoin-chain.js';
|
|
51
|
+
export {
|
|
52
|
+
createFilecoinClient,
|
|
53
|
+
isFilecoinAddress,
|
|
54
|
+
normalizeFilecoin,
|
|
55
|
+
normalizeFilecoinTokens,
|
|
56
|
+
toFilecoinAddress
|
|
57
|
+
} from './filecoin.js';
|
|
58
|
+
|
|
59
|
+
/** @typedef {import('./cosmos-chains.js').CosmosChain} CosmosChain */
|
|
60
|
+
/** @typedef {import('./filecoin-chain.js').FilecoinChain} FilecoinChain */
|
|
61
|
+
/** @typedef {import('./registry.js').Chain} Chain */
|
|
62
|
+
/** @typedef {import('@le-space/ledger/wallet-entry').WalletEntry} WalletEntry */
|
|
63
|
+
export * as near from './near.js';
|