@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/near.js ADDED
@@ -0,0 +1,655 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Reads what an own NEAR account paid and received in a period, from the
3
+ // NearBlocks API (v3), and maps it to ledger entries (@eigenbeleg/ledger-core).
4
+ //
5
+ // /v3/accounts/<id>/txns transactions the account signed or received:
6
+ // native NEAR sent or received, and the gas fee of
7
+ // every transaction the account signed
8
+ // /v3/accounts/<id>/ft-txns NEP-141 token movements (USDC, USDT, …), exact
9
+ // per event
10
+ //
11
+ // Every amount NearBlocks gives here is an integer string in base units, so
12
+ // nothing passes through a float. What is not read yet (and said so in the
13
+ // README): NEAR that reaches the account inside another transaction's inner
14
+ // receipts – a staking pool paying out a withdrawal, say.
15
+ //
16
+ // Powered by NearBlocks.io APIs.
17
+ //
18
+ // Moved from Le-Space/eigenbeleg-agent packages/chain-near at e56769a
19
+ // (Le-Space/eigenbeleg-agent#6). Changed here: the endpoints can be handed in
20
+ // (`endpoints: { api, rpc, explorer }`, e.g. behind a proxy), and the
21
+ // pipeline's `block` descriptor stays in Eigenbeleg.
22
+
23
+ import { entry, fromUnits, fromUtf8, sortEntries, toBase64, toUnits, utf8 } from '@le-space/ledger';
24
+
25
+ export const NETWORKS = {
26
+ mainnet: {
27
+ api: 'https://api.nearblocks.io',
28
+ explorer: 'https://nearblocks.io/txns/',
29
+ rpc: 'https://archival-rpc.mainnet.fastnear.com'
30
+ },
31
+ testnet: {
32
+ api: 'https://api-testnet.nearblocks.io',
33
+ explorer: 'https://testnet.nearblocks.io/txns/',
34
+ rpc: 'https://archival-rpc.testnet.fastnear.com'
35
+ }
36
+ };
37
+
38
+ export const NEAR_DECIMALS = 24;
39
+ /** Who receives a NEAR fee: the protocol burns it; no one issues an invoice. */
40
+ export const NETWORK_COUNTERPARTY = { address: 'near', label: 'NEAR-Netzwerk' };
41
+
42
+ /**
43
+ * The network's endpoints, with the caller's own in place of any.
44
+ *
45
+ * @param {string} network
46
+ * @param {Partial<{ api: string, rpc: string, explorer: string }>} [own]
47
+ */
48
+ export function endpointsOf(network, own = {}) {
49
+ const net = NETWORKS[/** @type {keyof typeof NETWORKS} */ (network)];
50
+ if (!net) throw new Error(`unknown network ${network}`);
51
+ return { ...net, ...own };
52
+ }
53
+
54
+ const ACCOUNT_ID = /^(?=.{2,64}$)(([a-z\d]+[-_])*[a-z\d]+\.)*([a-z\d]+[-_])*[a-z\d]+$/;
55
+
56
+ /** A NEAR account id (named or 64-hex implicit). @param {string} id */
57
+ export function isAccountId(id) {
58
+ return typeof id === 'string' && ACCOUNT_ID.test(id);
59
+ }
60
+
61
+ /**
62
+ * Tokens with a trusted market price, by contract. Anything else an account
63
+ * holds is listed in the CSV but never valued: airdropped spam tokens are
64
+ * common on NEAR.
65
+ */
66
+ export const TOKENS = {
67
+ mainnet: {
68
+ '17208628f84f5d6ad33f0da3bbbeb27ffcb398eac501a31bd6ad2011e36133a1': {
69
+ symbol: 'USDC',
70
+ priceAs: 'USDC',
71
+ decimals: 6
72
+ },
73
+ 'a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48.factory.bridge.near': {
74
+ symbol: 'USDC.e',
75
+ priceAs: 'USDC',
76
+ decimals: 6
77
+ },
78
+ 'usdt.tether-token.near': { symbol: 'USDT', priceAs: 'USDT', decimals: 6 },
79
+ 'wrap.near': { symbol: 'wNEAR', priceAs: 'NEAR', decimals: 24 }
80
+ },
81
+ testnet: {
82
+ '3e2210e1184b45b64c8a434c0a7e7b23cc04ea7eb7a6c3c32520d03d4afcb8af': {
83
+ symbol: 'USDC',
84
+ priceAs: 'USDC',
85
+ decimals: 6
86
+ },
87
+ 'usdc.fakes.testnet': { symbol: 'USDC.e', priceAs: 'USDC', decimals: 6 },
88
+ 'wrap.testnet': { symbol: 'wNEAR', priceAs: 'NEAR', decimals: 24 }
89
+ }
90
+ };
91
+
92
+ /** Methods whose attached NEAR is not a payment for something but a token or storage mechanic. */
93
+ const FT_METHODS = new Set([
94
+ 'ft_transfer',
95
+ 'ft_transfer_call',
96
+ 'mt_transfer',
97
+ 'mt_transfer_call',
98
+ 'nft_transfer',
99
+ 'nft_transfer_call'
100
+ ]);
101
+ const STORAGE_METHODS = new Set(['storage_deposit']);
102
+ const STAKE_METHODS = new Set(['deposit_and_stake', 'deposit', 'stake']);
103
+
104
+ /** ISO date → nanosecond timestamp string. @param {string} iso */
105
+ const ns = (iso) => (BigInt(new Date(iso).getTime()) * 1_000_000n).toString();
106
+ /** nanosecond string → ISO. @param {string} t */
107
+ const iso = (t) => new Date(Number(BigInt(t) / 1_000_000n)).toISOString();
108
+
109
+ /**
110
+ * Walks a NearBlocks v3 list newest first, from just before `to` back to `from`.
111
+ *
112
+ * @param {object} p
113
+ * @param {string} p.url without query
114
+ * @param {string} p.fromTs ns, inclusive
115
+ * @param {string} p.toTs ns, exclusive
116
+ * @param {typeof fetch} p.fetch
117
+ * @param {Record<string,string>} p.headers
118
+ * @param {number} p.maxPages
119
+ * @param {boolean} [p.partial] stop at maxPages instead of failing (fixtures only)
120
+ */
121
+ async function walk({ url, fromTs, toTs, fetch, headers, maxPages, partial = false }) {
122
+ /** @type {any[]} */
123
+ const rows = [];
124
+ let next = '';
125
+ for (let page = 0; page < maxPages; page++) {
126
+ const q = new URLSearchParams({ limit: '25', before_ts: toTs });
127
+ if (next) q.set('next', next);
128
+ const body = await getJson(fetch, `${url}?${q}`, headers);
129
+ const data = Array.isArray(body?.data) ? body.data : [];
130
+ let older = false;
131
+ for (const row of data) {
132
+ const t = String(row.block_timestamp ?? row.block?.block_timestamp ?? '0');
133
+ if (BigInt(t) < BigInt(fromTs)) {
134
+ older = true;
135
+ break;
136
+ }
137
+ rows.push(row);
138
+ }
139
+ next = body?.meta?.next_page ?? '';
140
+ if (older || !next || data.length === 0) return rows;
141
+ }
142
+ if (partial) return rows;
143
+ throw new Error(`more than ${maxPages} pages of history in the period; narrow it`);
144
+ }
145
+
146
+ /** @param {typeof fetch} fetch @param {string} url @param {Record<string,string>} headers */
147
+ async function getJson(fetch, url, headers) {
148
+ for (let attempt = 0; ; attempt++) {
149
+ /** @type {Response} */
150
+ let res;
151
+ try {
152
+ res = await fetch(url, { headers });
153
+ } catch (e) {
154
+ // In a browser a 429 without CORS headers, or a dropped connection, is a TypeError.
155
+ if (!(e instanceof TypeError) || attempt >= 4) throw e;
156
+ await new Promise((r) => setTimeout(r, 2000 * 2 ** attempt));
157
+ continue;
158
+ }
159
+ if ((res.status === 429 || res.status >= 500) && attempt < 4) {
160
+ await new Promise((r) => setTimeout(r, 2000 * 2 ** attempt));
161
+ continue;
162
+ }
163
+ if (!res.ok) throw new Error(`NearBlocks answered ${res.status} for ${new URL(url).pathname}`);
164
+ return res.json();
165
+ }
166
+ }
167
+
168
+ /**
169
+ * The raw NearBlocks rows for an account and period, as a fixture keeps them.
170
+ *
171
+ * @param {object} p
172
+ * @param {string} p.account
173
+ * @param {'mainnet' | 'testnet'} [p.network]
174
+ * @param {string} p.from YYYY-MM-DD, inclusive
175
+ * @param {string} p.to YYYY-MM-DD, inclusive
176
+ * @param {typeof fetch} [p.fetch]
177
+ * @param {string} [p.apiKey] a NearBlocks key, for its higher rate limit
178
+ * @param {number} [p.maxPages]
179
+ * @param {boolean} [p.partial]
180
+ * @param {Partial<{ api: string, rpc: string, explorer: string }>} [p.endpoints] instead of the network's own
181
+ */
182
+ export async function fetchRaw({
183
+ account,
184
+ network = 'mainnet',
185
+ from,
186
+ to,
187
+ fetch = globalThis.fetch,
188
+ apiKey,
189
+ maxPages = 40,
190
+ partial = false,
191
+ endpoints
192
+ }) {
193
+ if (!isAccountId(account)) throw new Error('not a NEAR account id');
194
+ const net = endpointsOf(network, endpoints);
195
+ const fromTs = ns(`${from}T00:00:00Z`);
196
+ const end = new Date(`${to}T00:00:00Z`);
197
+ end.setUTCDate(end.getUTCDate() + 1);
198
+ const toTs = ns(end.toISOString());
199
+ /** @type {Record<string,string>} */
200
+ const headers = { accept: 'application/json' };
201
+ if (apiKey) headers.authorization = `Bearer ${apiKey}`;
202
+ const base = `${net.api}/v3/accounts/${encodeURIComponent(account)}`;
203
+ const txns = await walk({ url: `${base}/txns`, fromTs, toTs, fetch, headers, maxPages, partial });
204
+ const ftTxns = await walk({
205
+ url: `${base}/ft-txns`,
206
+ fromTs,
207
+ toTs,
208
+ fetch,
209
+ headers,
210
+ maxPages,
211
+ partial
212
+ });
213
+ return { account, network, from, to, txns, ftTxns, explorer: net.explorer };
214
+ }
215
+
216
+ /**
217
+ * Ledger entries from the raw rows.
218
+ *
219
+ * @param {{ account: string, network: 'mainnet' | 'testnet', txns: any[], ftTxns: any[], explorer?: string }} raw
220
+ * @returns {import('@le-space/ledger').LedgerEntry[]}
221
+ */
222
+ export function mapRaw({
223
+ account,
224
+ network,
225
+ txns,
226
+ ftTxns,
227
+ explorer = endpointsOf(network).explorer
228
+ }) {
229
+ /** @type {import('@le-space/ledger').LedgerEntry[]} */
230
+ const out = [];
231
+ const seen = new Set();
232
+ for (const t of txns) {
233
+ const hash = String(t.transaction_hash);
234
+ if (seen.has(hash)) continue;
235
+ seen.add(hash);
236
+ const time = iso(String(t.block_timestamp ?? t.block?.block_timestamp));
237
+ const height = Number(t.block?.block_height ?? 0);
238
+ const success = t.outcomes?.status !== false;
239
+ const signer = String(t.signer_account_id ?? '');
240
+ const receiver = String(t.receiver_account_id ?? '');
241
+ const deposit = BigInt(String(t.actions_agg?.deposit ?? '0'));
242
+ const actions = Array.isArray(t.actions) ? t.actions : [];
243
+ const methods = actions.map((/** @type {any} */ a) => a.method).filter(Boolean);
244
+ const method = methods[0] ?? '';
245
+ const common = {
246
+ chain: 'near',
247
+ network,
248
+ account,
249
+ hash,
250
+ height,
251
+ time,
252
+ contract: 'native',
253
+ asset: 'NEAR',
254
+ priceAs: 'NEAR',
255
+ decimals: NEAR_DECIMALS,
256
+ explorerUrl: explorer + hash
257
+ };
258
+
259
+ if (signer === account) {
260
+ const fee = BigInt(String(t.outcomes_agg?.transaction_fee ?? '0'));
261
+ if (fee > 0n)
262
+ out.push(
263
+ entry({
264
+ ...common,
265
+ id: `near:${account}:${hash}:fee`,
266
+ type: 'fee',
267
+ kind: 'fee',
268
+ amount: fromUnits(-fee, NEAR_DECIMALS),
269
+ counterparty: NETWORK_COUNTERPARTY.address,
270
+ counterpartyLabel: NETWORK_COUNTERPARTY.label,
271
+ method,
272
+ memo: '',
273
+ // A failed transaction still burns its gas.
274
+ success: true
275
+ })
276
+ );
277
+ // A failed transaction gives its deposit back; the 1 yoctoNEAR a token
278
+ // transfer must attach is no payment.
279
+ const tokenMechanic =
280
+ deposit === 1n && methods.some((/** @type {string} */ m) => FT_METHODS.has(m));
281
+ if (deposit > 0n && success && receiver !== account && !tokenMechanic) {
282
+ out.push(
283
+ entry({
284
+ ...common,
285
+ id: `near:${account}:${hash}:deposit`,
286
+ type: 'sent',
287
+ kind: kindOf(actions, methods),
288
+ amount: fromUnits(-deposit, NEAR_DECIMALS),
289
+ counterparty: receiver,
290
+ counterpartyLabel: '',
291
+ method,
292
+ memo: '',
293
+ success
294
+ })
295
+ );
296
+ }
297
+ } else if (receiver === account && deposit > 1n && success) {
298
+ // 1 yoctoNEAR is a token transfer's security deposit passing through
299
+ // (a relayed meta transaction hands it on to the token contract), no payment.
300
+ out.push(
301
+ entry({
302
+ ...common,
303
+ id: `near:${account}:${hash}:deposit`,
304
+ type: 'received',
305
+ kind: 'transfer',
306
+ amount: fromUnits(deposit, NEAR_DECIMALS),
307
+ counterparty: signer,
308
+ counterpartyLabel: '',
309
+ method,
310
+ memo: '',
311
+ success
312
+ })
313
+ );
314
+ }
315
+ }
316
+ for (const f of ftTxns) {
317
+ if (String(f.affected_account_id) !== account) continue;
318
+ const delta = BigInt(String(f.delta_amount ?? '0'));
319
+ if (delta === 0n) continue;
320
+ const hash = String(f.transaction_hash);
321
+ const meta = f.meta ?? f.ft ?? {};
322
+ const contract = String(f.contract_account_id ?? meta.contract ?? '');
323
+ const listed =
324
+ /** @type {Record<string, {symbol: string, priceAs: string, decimals: number}>} */ (
325
+ TOKENS[network]
326
+ )[contract];
327
+ // A listed token's decimals are ours; an unlisted one's come from the
328
+ // indexer and, where it has none, the token is skipped: a wrong scale
329
+ // would turn 1.5 into 1,500,000.
330
+ const decimals = listed?.decimals ?? (Number.isInteger(meta.decimals) ? meta.decimals : NaN);
331
+ if (!Number.isInteger(decimals)) continue;
332
+ out.push(
333
+ entry({
334
+ id: `near:${account}:${hash}:ft:${f.receipt_id ?? ''}:${f.event_index ?? ''}`,
335
+ chain: 'near',
336
+ network,
337
+ account,
338
+ hash,
339
+ height: Number(f.block?.block_height ?? 0),
340
+ time: iso(String(f.block_timestamp ?? f.block?.block_timestamp)),
341
+ type: delta < 0n ? 'sent' : 'received',
342
+ kind: 'transfer',
343
+ asset: listed?.symbol ?? String(meta.symbol ?? contract),
344
+ priceAs: listed?.priceAs ?? '',
345
+ contract,
346
+ decimals,
347
+ amount: fromUnits(delta, decimals),
348
+ counterparty: String(f.involved_account_id ?? ''),
349
+ counterpartyLabel: '',
350
+ method: String(f.cause ?? '').toLowerCase(),
351
+ memo: '',
352
+ success: f.outcomes?.status !== false,
353
+ explorerUrl: explorer + hash
354
+ })
355
+ );
356
+ }
357
+ return sortEntries(out);
358
+ }
359
+
360
+ /** @param {any[]} actions @param {string[]} methods */
361
+ function kindOf(actions, methods) {
362
+ if (methods.some((m) => STORAGE_METHODS.has(m))) return 'storage';
363
+ if (methods.some((m) => STAKE_METHODS.has(m))) return 'stake';
364
+ if (actions.some((a) => a.action === 'FUNCTION_CALL')) return 'call';
365
+ return 'transfer';
366
+ }
367
+
368
+ /**
369
+ * Ledger entries for an account and period.
370
+ *
371
+ * @param {Parameters<typeof fetchRaw>[0]} p
372
+ */
373
+ export async function readNear(p) {
374
+ return storageKept(mapRaw(await fetchRaw(p)), p);
375
+ }
376
+
377
+ /**
378
+ * A storage deposit attaches more than the contract keeps, or the account
379
+ * was registered already: the contract sends the rest back in an inner
380
+ * receipt. The entry becomes what was kept; one fully refunded goes.
381
+ * Read from an archival RPC (EXPERIMENTAL_tx_status); if that cannot be
382
+ * read, the whole read fails rather than overstate a payment.
383
+ *
384
+ * @param {import('@le-space/ledger').LedgerEntry[]} entries
385
+ * @param {{ network?: 'mainnet' | 'testnet', fetch?: typeof fetch, endpoints?: Partial<{ rpc: string }> }} p
386
+ */
387
+ export async function storageKept(
388
+ entries,
389
+ { network = 'mainnet', fetch = globalThis.fetch, endpoints }
390
+ ) {
391
+ const out = [];
392
+ for (const e of entries) {
393
+ if (e.kind !== 'storage' || e.type !== 'sent') {
394
+ out.push(e);
395
+ continue;
396
+ }
397
+ const res = await fetch(endpointsOf(network, endpoints).rpc, {
398
+ method: 'POST',
399
+ headers: { 'content-type': 'application/json' },
400
+ body: JSON.stringify({
401
+ jsonrpc: '2.0',
402
+ id: 1,
403
+ method: 'EXPERIMENTAL_tx_status',
404
+ params: { tx_hash: e.hash, sender_account_id: e.account, wait_until: 'NONE' }
405
+ })
406
+ });
407
+ const body = res.ok ? await res.json() : null;
408
+ const receipts = body?.result?.receipts;
409
+ if (!Array.isArray(receipts))
410
+ throw new Error(`NEAR RPC could not tell what the storage deposit in ${e.hash} kept`);
411
+ let refund = 0n;
412
+ for (const r of receipts) {
413
+ if (r.predecessor_id !== e.counterparty || r.receiver_id !== e.account) continue;
414
+ for (const a of r.receipt?.Action?.actions ?? [])
415
+ if (a?.Transfer?.deposit) refund += BigInt(a.Transfer.deposit);
416
+ }
417
+ const kept = -toUnits(e.amount, NEAR_DECIMALS) - refund;
418
+ if (kept <= 0n) continue;
419
+ out.push(refund ? entry({ ...e, amount: fromUnits(-kept, NEAR_DECIMALS) }) : e);
420
+ }
421
+ return out;
422
+ }
423
+
424
+ /** @param {typeof fetch} fetch @param {string} url @param {string} method @param {any} params */
425
+ async function rpc(fetch, url, method, params, { tries = 4, wait = 1000 } = {}) {
426
+ /** @type {Response | null} */
427
+ let res = null;
428
+ // A rate limit (429) or a hiccup (5xx) is asked again, a little later each time. In a
429
+ // browser such an answer often comes without CORS headers and so shows up as a failed
430
+ // fetch (TypeError); that is retried the same way.
431
+ for (let attempt = 0; ; attempt++) {
432
+ try {
433
+ res = await fetch(url, {
434
+ method: 'POST',
435
+ headers: { 'content-type': 'application/json' },
436
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params })
437
+ });
438
+ if ((res.status === 429 || res.status >= 500) && attempt < tries) {
439
+ await new Promise((r) => setTimeout(r, wait * 2 ** attempt));
440
+ continue;
441
+ }
442
+ break;
443
+ } catch (e) {
444
+ if (!(e instanceof TypeError) || attempt >= tries) throw e;
445
+ await new Promise((r) => setTimeout(r, wait * 2 ** attempt));
446
+ }
447
+ }
448
+ const body = res.ok ? await res.json() : null;
449
+ if (!body || body.error) {
450
+ const e = new Error(
451
+ `NEAR RPC ${method}: ${String(body?.error?.cause?.name ?? body?.error?.message ?? res.status)}`
452
+ );
453
+ /** @type {any} */ (e).cause = body?.error?.cause?.name;
454
+ throw e;
455
+ }
456
+ return body.result;
457
+ }
458
+
459
+ /**
460
+ * The last block before a moment (archival RPC): interpolated from block
461
+ * times, then stepped to the exact one. Heights without a block are skipped.
462
+ *
463
+ * @param {{ network?: 'mainnet' | 'testnet', before: string, fetch?: typeof fetch, endpoints?: Partial<{ rpc: string }> }} p before: ISO
464
+ * @returns {Promise<{ height: number, time: string }>}
465
+ */
466
+ export async function blockBefore({
467
+ network = 'mainnet',
468
+ before,
469
+ fetch = globalThis.fetch,
470
+ endpoints
471
+ }) {
472
+ const url = endpointsOf(network, endpoints).rpc;
473
+ const target = BigInt(Date.parse(before)) * 1_000_000n;
474
+ /** @type {Map<number, bigint | null>} */
475
+ const seen = new Map();
476
+ const ts = async (/** @type {number} */ h) => {
477
+ if (!seen.has(h)) {
478
+ try {
479
+ seen.set(h, BigInt((await rpc(fetch, url, 'block', { block_id: h })).header.timestamp));
480
+ } catch (e) {
481
+ if (/** @type {any} */ (e).cause !== 'UNKNOWN_BLOCK') throw e;
482
+ seen.set(h, null);
483
+ }
484
+ }
485
+ return seen.get(h) ?? null;
486
+ };
487
+ /** The nearest existing block at or below h. */
488
+ const at = async (/** @type {number} */ h) => {
489
+ for (let i = 0; i < 50; i++) {
490
+ const t = await ts(h - i);
491
+ if (t !== null) return { h: h - i, t };
492
+ }
493
+ throw new Error(`no block near height ${h}`);
494
+ };
495
+ const head = (await rpc(fetch, url, 'block', { finality: 'final' })).header;
496
+ let hi = { h: Number(head.height), t: BigInt(head.timestamp) };
497
+ if (target >= hi.t) throw new Error('the moment has not passed on chain yet');
498
+ let lo = await at(Math.max(1, hi.h - 200_000));
499
+ // widen until lo is before the target
500
+ while (lo.t >= target) {
501
+ const span = hi.h - lo.h;
502
+ hi = lo;
503
+ lo = await at(Math.max(1, lo.h - span * 4));
504
+ if (lo.h <= 1 && lo.t >= target) throw new Error('the moment is before the chain began');
505
+ }
506
+ // interpolation search, then bisection
507
+ for (let i = 0; i < 60 && hi.h - lo.h > 1; i++) {
508
+ const guess =
509
+ i < 8
510
+ ? lo.h + Number(((target - lo.t) * BigInt(hi.h - lo.h)) / (hi.t - lo.t))
511
+ : Math.floor((lo.h + hi.h) / 2);
512
+ const mid = await at(Math.min(hi.h - 1, Math.max(lo.h + 1, guess)));
513
+ if (mid.h <= lo.h) break;
514
+ if (mid.t < target) lo = mid;
515
+ else hi = mid;
516
+ }
517
+ return { height: lo.h, time: new Date(Number(lo.t / 1_000_000n)).toISOString() };
518
+ }
519
+
520
+ /**
521
+ * What an account held just before a moment: NEAR (liquid plus staked by a
522
+ * validator) and the listed tokens asked for. From the archival RPC.
523
+ *
524
+ * @param {{ account: string, network?: 'mainnet' | 'testnet', before: string, contracts?: string[], fetch?: typeof fetch, endpoints?: Partial<{ rpc: string }> }} p
525
+ * @returns {Promise<{ height: number, time: string, balances: Record<string, { asset: string, amount: string }> }>}
526
+ */
527
+ export async function balancesBefore({
528
+ account,
529
+ network = 'mainnet',
530
+ before,
531
+ contracts = [],
532
+ fetch = globalThis.fetch,
533
+ endpoints
534
+ }) {
535
+ if (!isAccountId(account)) throw new Error('not a NEAR account id');
536
+ const url = endpointsOf(network, endpoints).rpc;
537
+ const block = await blockBefore({ network, before, fetch, endpoints });
538
+ /** @type {Record<string, { asset: string, amount: string }>} */
539
+ const balances = {};
540
+ try {
541
+ const a = await rpc(fetch, url, 'query', {
542
+ request_type: 'view_account',
543
+ block_id: block.height,
544
+ account_id: account
545
+ });
546
+ balances.native = {
547
+ asset: 'NEAR',
548
+ amount: fromUnits(BigInt(a.amount) + BigInt(a.locked ?? '0'), NEAR_DECIMALS)
549
+ };
550
+ } catch (e) {
551
+ // The account did not exist yet.
552
+ if (!/UNKNOWN_ACCOUNT/.test(String(/** @type {any} */ (e).cause))) throw e;
553
+ balances.native = { asset: 'NEAR', amount: '0' };
554
+ }
555
+ const listed = /** @type {Record<string, { symbol: string, decimals: number }>} */ (
556
+ TOKENS[network]
557
+ );
558
+ for (const c of contracts) {
559
+ const t = listed[c];
560
+ if (!t) continue;
561
+ let units = 0n;
562
+ try {
563
+ const r = await rpc(fetch, url, 'query', {
564
+ request_type: 'call_function',
565
+ block_id: block.height,
566
+ account_id: c,
567
+ method_name: 'ft_balance_of',
568
+ args_base64: toBase64(utf8(JSON.stringify({ account_id: account })))
569
+ });
570
+ units = BigInt(JSON.parse(fromUtf8(Uint8Array.from(r.result))));
571
+ } catch {
572
+ units = 0n; // not registered with the token yet
573
+ }
574
+ balances[c] = { asset: t.symbol, amount: fromUnits(units, t.decimals) };
575
+ }
576
+ return { ...block, balances };
577
+ }
578
+
579
+ /** `{ native: { asset: 'NEAR', amount } … }` → `{ NEAR: amount … }`. @param {Record<string, { asset: string, amount: string }>} b */
580
+ const bySymbol = (b) => Object.fromEntries(Object.values(b).map((x) => [x.asset, x.amount]));
581
+
582
+ /**
583
+ * What a Kontoauszug needs for one account and period: its bookings, and its
584
+ * balances before the first and after the last day, read from the archival
585
+ * RPC – so the statement can check that opening balance plus bookings is the
586
+ * closing balance.
587
+ *
588
+ * @param {Parameters<typeof fetchRaw>[0]} p
589
+ */
590
+ export async function statementNear(p) {
591
+ const network = p.network ?? 'mainnet';
592
+ const fetch = p.fetch ?? globalThis.fetch;
593
+ const entries = await readNear(p);
594
+ const contracts = [
595
+ ...new Set(entries.filter((e) => e.contract !== 'native' && e.priceAs).map((e) => e.contract))
596
+ ];
597
+ const end = new Date(`${p.to}T00:00:00Z`);
598
+ end.setUTCDate(end.getUTCDate() + 1);
599
+ const opening = await balancesBefore({
600
+ account: p.account,
601
+ network,
602
+ before: `${p.from}T00:00:00Z`,
603
+ contracts,
604
+ fetch,
605
+ endpoints: p.endpoints
606
+ });
607
+ const closing = await balancesBefore({
608
+ account: p.account,
609
+ network,
610
+ before: end.toISOString(),
611
+ contracts,
612
+ fetch,
613
+ endpoints: p.endpoints
614
+ });
615
+ return {
616
+ entries,
617
+ opening: bySymbol(opening.balances),
618
+ closing: bySymbol(closing.balances),
619
+ method: /** @type {'archive'} */ ('archive'),
620
+ at: {
621
+ opening: { height: opening.height, time: opening.time },
622
+ closing: { height: closing.height, time: closing.time }
623
+ }
624
+ };
625
+ }
626
+
627
+ /** A public account that signs transactions every day (Aurora's relayer, fees only): the live check reads it. */
628
+ export const PROBE_ACCOUNT = 'relay.aurora';
629
+
630
+ /**
631
+ * Checks the block against live data: one page of yesterday's history of a
632
+ * busy public account must map to valid entries.
633
+ *
634
+ * @param {{ fetch?: typeof fetch, apiKey?: string, day?: string }} [o] day: YYYY-MM-DD, yesterday when not given
635
+ */
636
+ export async function probe({
637
+ fetch = globalThis.fetch,
638
+ apiKey,
639
+ day = new Date(Date.now() - 86400000).toISOString().slice(0, 10)
640
+ } = {}) {
641
+ const raw = await fetchRaw({
642
+ account: PROBE_ACCOUNT,
643
+ network: 'mainnet',
644
+ from: day,
645
+ to: day,
646
+ fetch,
647
+ apiKey,
648
+ maxPages: 1,
649
+ partial: true
650
+ });
651
+ const entries = mapRaw(raw);
652
+ if (entries.length === 0)
653
+ throw new Error(`no entries for ${PROBE_ACCOUNT} on ${day}: the data source may have changed`);
654
+ return { sample: `${PROBE_ACCOUNT} on ${day}`, entries: entries.length };
655
+ }