dexbot 1.6.16 → 1.6.17

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.
Files changed (60) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/analysis/tradingview/README.md +2 -2
  3. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +1 -1
  4. package/claw/package.json +1 -1
  5. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  6. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  7. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +5 -3
  8. package/dist/analysis/tradingview/grid_reset_sim.js +1 -1
  9. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +4 -4
  10. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +1 -1
  11. package/dist/modules/account_bots.d.ts +3 -0
  12. package/dist/modules/chain_keys.d.ts +1 -1
  13. package/dist/modules/constants.d.ts +6 -0
  14. package/dist/modules/constants.js +34 -6
  15. package/dist/modules/credit_pricing.d.ts +20 -1
  16. package/dist/modules/credit_pricing.js +23 -1
  17. package/dist/modules/credit_runtime.js +33 -16
  18. package/dist/modules/dexbot_class.d.ts +3 -1
  19. package/dist/modules/dexbot_class.js +5 -2
  20. package/dist/modules/dexbot_cow_runtime.d.ts +28 -37
  21. package/dist/modules/dexbot_cow_runtime.js +47 -66
  22. package/dist/modules/dexbot_maintenance_runtime.js +68 -10
  23. package/dist/modules/launcher/credential_daemon.d.ts +14 -2
  24. package/dist/modules/launcher/credential_daemon.js +60 -26
  25. package/dist/modules/order/grid.d.ts +7 -0
  26. package/dist/modules/order/grid.js +157 -15
  27. package/dist/modules/order/index.d.ts +15 -0
  28. package/dist/modules/order/manager.d.ts +30 -7
  29. package/dist/modules/order/manager.js +108 -12
  30. package/dist/modules/order/strategy.d.ts +5 -0
  31. package/dist/modules/order/strategy.js +23 -2
  32. package/dist/modules/order/utils/math.d.ts +41 -1
  33. package/dist/modules/order/utils/math.js +47 -1
  34. package/dist/modules/order/utils/order.d.ts +13 -0
  35. package/dist/modules/order/utils/order.js +61 -7
  36. package/dist/modules/order/utils/system.d.ts +66 -0
  37. package/dist/modules/order/utils/system.js +135 -0
  38. package/dist/modules/order/utils/validate.d.ts +3 -1
  39. package/dist/modules/order/utils/validate.js +5 -1
  40. package/dist/modules/types.d.ts +35 -2
  41. package/dist/scripts/analyze-credit.js +64 -23
  42. package/dist/scripts/bts_distribution.d.ts +66 -0
  43. package/dist/scripts/bts_distribution.js +2102 -0
  44. package/dist/scripts/token_distribution.d.ts +45 -0
  45. package/dist/scripts/token_distribution.js +1870 -0
  46. package/dist/unlock.js +42 -24
  47. package/docs/COW_INVARIANTS.md +6 -0
  48. package/docs/DEXBOT_COMPARISON.md +5 -5
  49. package/docs/EVOLUTION.md +9 -8
  50. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +3 -1
  51. package/docs/GRID_PRICE_INVARIANT.md +6 -0
  52. package/docs/GRID_RECALCULATION.md +3 -3
  53. package/docs/LOGGING.md +9 -0
  54. package/docs/MPA_CREDIT_USAGE.md +3 -2
  55. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +117 -0
  56. package/docs/README.md +1 -1
  57. package/docs/architecture.md +98 -1
  58. package/market_adapter/README.md +2 -2
  59. package/package.json +3 -1
  60. package/scripts/README.md +85 -148
@@ -0,0 +1,1870 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * BitShares token distribution analyzer.
4
+ *
5
+ * The per-asset companion to scripts/bts_distribution.ts: answers "where is all
6
+ * of <token>?" on the live chain. Works for any issued asset (UIA/MPA) except
7
+ * the core asset (use bts_distribution for BTS).
8
+ *
9
+ * Buckets:
10
+ * - free account balances 2.5.x account_balance_object (asset_api rich list)
11
+ * - limit orders 1.7.x limit_order_object.for_sale (token sold)
12
+ * - liquidity pools 1.19.x liquidity_pool_object reserves
13
+ * - vesting balances 1.13.x vesting_balance_object (worker/witness/cashback/...)
14
+ * - P2P credit offers 1.21.x credit_offer_object.current_balance
15
+ * - P2P deal collateral 1.22.x credit_deal_object.collateral_amount
16
+ * - SameT funds 1.20.x samet_fund_object.balance
17
+ * - HTLC escrow 1.16.x htlc_object.transfer
18
+ * - accumulated market fees 2.3.x asset_dynamic_data_object.accumulated_fees
19
+ * - blinded balances 2.3.x asset_dynamic_data_object.confidential_supply
20
+ *
21
+ * The liquidity side is grouped by *counterpart asset*: every pool and every
22
+ * token sell order is bucketed by the asset on the other side of the trade
23
+ * (token/BTS, token/USD, token/other), so you can see which markets actually
24
+ * hold the token. The HTML report adds a separate liquidity donut and a 3%
25
+ * depth comparison: how much token can be sold (price -3%) or bought (price
26
+ * +3%), combining orderbook and constant-product pool per market, with the
27
+ * result also expressed as a percentage of total supply.
28
+ *
29
+ * Limit orders are not globally indexed by asset in bitshares-core, so the only
30
+ * exact enumeration is one get_limit_orders(token, other) call per listed asset
31
+ * (~6k calls on mainnet). Those calls run concurrently and are skipped with
32
+ * --no-orders.
33
+ *
34
+ * Read-only: opens its own ephemeral WebSocket, never touches a running bot,
35
+ * no keys, no transactions. Chain source of truth: bitshares-core 7.0.x.
36
+ *
37
+ * Usage:
38
+ * node dist/scripts/token_distribution.js <symbol|1.3.x>
39
+ * node dist/scripts/token_distribution.js <token> --json
40
+ * node dist/scripts/token_distribution.js <asset-id> --no-html
41
+ * node dist/scripts/token_distribution.js <token> --no-orders
42
+ * node dist/scripts/token_distribution.js <token> --node wss://cloud.xbts.io/ws
43
+ */
44
+ import fs from 'node:fs';
45
+ import path from 'node:path';
46
+ import { pathToFileURL } from 'node:url';
47
+ import { NODE_MANAGEMENT } from '../modules/constants.js';
48
+ import { PATHS } from '../modules/paths.js';
49
+ import { CLI_COLORS as colors } from '../modules/cli_colors.js';
50
+ // ---------------------------------------------------------------------------
51
+ // Constants
52
+ // ---------------------------------------------------------------------------
53
+ const DB_API = 0;
54
+ const LOGIN_API = 1;
55
+ const CORE_ID = '1.3.0';
56
+ const OBJECT_BATCH = 100;
57
+ const NAME_BATCH = 50;
58
+ const DEFAULT_DETAIL = 15;
59
+ const DEFAULT_VESTING_MAX = 200_000;
60
+ const DEFAULT_SCAN_GAP = 20_000;
61
+ const DEFAULT_CONCURRENCY = 12;
62
+ const DEFAULT_HTML = path.join(PATHS.ANALYSIS.CHARTS_DIR, 'token-distribution.html');
63
+ // asset_api (get_asset_holders) is allowlisted on only a few public nodes; this
64
+ // mirrors scripts/rich_list.ts and scripts/bts_distribution.ts.
65
+ const HOLDER_NODES = [
66
+ 'wss://dex.iobanker.com/ws',
67
+ 'wss://api.dex.trading/ws',
68
+ ];
69
+ const COLORS = [
70
+ '#5eb0ef', '#f0883e', '#3fb950', '#db61a2', '#a371f7', '#e3b341',
71
+ '#39c5cf', '#ff7b72', '#7ee787', '#d2a8ff', '#ffa657', '#8b949e',
72
+ ];
73
+ // ---------------------------------------------------------------------------
74
+ // CLI
75
+ // ---------------------------------------------------------------------------
76
+ class UsageError extends Error {
77
+ }
78
+ const HELP = `BitShares token distribution analyzer (read-only)
79
+
80
+ Usage:
81
+ node dist/scripts/token_distribution.js <symbol|1.3.x> [options]
82
+
83
+ Options:
84
+ --node URL BitShares node (repeatable; defaults to NODE_MANAGEMENT.DEFAULT_NODES)
85
+ --detail N Rows in top-holder / P2P / vesting tables (default ${DEFAULT_DETAIL})
86
+ --no-orders Skip the per-asset limit-order scan (saves ~20s on mainnet)
87
+ --concurrency N Concurrent get_limit_orders calls (default ${DEFAULT_CONCURRENCY})
88
+ --vesting-max N Highest 1.13.x object id to scan (default ${DEFAULT_VESTING_MAX})
89
+ --gap N Stop the 1.13.x scan after N consecutive missing ids (default ${DEFAULT_SCAN_GAP})
90
+ --html PATH HTML output path (default ${DEFAULT_HTML})
91
+ --no-html Skip the HTML report
92
+ --json Machine-readable JSON (HTML is still written unless --no-html)
93
+ -h, --help Show this help
94
+
95
+ The token argument accepts a symbol (<token>) or an asset id (<asset-id>).
96
+ BTS itself is rejected: use scripts/bts_distribution.ts for the core asset.
97
+ `;
98
+ function parseArgs(argv) {
99
+ const VALUE_FLAGS = new Set([
100
+ '--node', '--detail', '--concurrency', '--vesting-max', '--gap', '--html', '--asset',
101
+ ]);
102
+ const args = [];
103
+ for (const a of argv) {
104
+ const eq = a.indexOf('=');
105
+ if (a.startsWith('--') && eq > 0 && VALUE_FLAGS.has(a.slice(0, eq))) {
106
+ args.push(a.slice(0, eq), a.slice(eq + 1));
107
+ }
108
+ else {
109
+ args.push(a);
110
+ }
111
+ }
112
+ const opts = {
113
+ asset: null,
114
+ nodes: [],
115
+ json: false,
116
+ html: DEFAULT_HTML,
117
+ detail: DEFAULT_DETAIL,
118
+ vestingMax: DEFAULT_VESTING_MAX,
119
+ gap: DEFAULT_SCAN_GAP,
120
+ concurrency: DEFAULT_CONCURRENCY,
121
+ scanOrders: true,
122
+ help: false,
123
+ };
124
+ const positiveInt = (flag, raw) => {
125
+ const n = Number(raw);
126
+ if (!Number.isInteger(n) || n < 1)
127
+ throw new UsageError(`${flag} must be a positive integer`);
128
+ return n;
129
+ };
130
+ for (let i = 0; i < args.length; i++) {
131
+ const a = args[i];
132
+ const next = () => {
133
+ const value = args[++i];
134
+ if (value === undefined)
135
+ throw new UsageError(`Missing value for ${a}`);
136
+ return value;
137
+ };
138
+ if (a === '--node')
139
+ opts.nodes.push(next());
140
+ else if (a === '--asset')
141
+ opts.asset = next();
142
+ else if (a === '--detail')
143
+ opts.detail = positiveInt(a, next());
144
+ else if (a === '--concurrency')
145
+ opts.concurrency = Math.min(positiveInt(a, next()), 64);
146
+ else if (a === '--vesting-max')
147
+ opts.vestingMax = positiveInt(a, next());
148
+ else if (a === '--gap')
149
+ opts.gap = positiveInt(a, next());
150
+ else if (a === '--html')
151
+ opts.html = path.resolve(next());
152
+ else if (a === '--no-html')
153
+ opts.html = null;
154
+ else if (a === '--no-orders')
155
+ opts.scanOrders = false;
156
+ else if (a === '--json')
157
+ opts.json = true;
158
+ else if (a === '-h' || a === '--help')
159
+ opts.help = true;
160
+ else if (a.startsWith('-'))
161
+ throw new UsageError(`Unknown flag: ${a}`);
162
+ else if (opts.asset === null)
163
+ opts.asset = a;
164
+ else
165
+ throw new UsageError(`Unexpected argument: ${a}`);
166
+ }
167
+ if (!opts.help && !opts.asset)
168
+ throw new UsageError('a token symbol or asset id is required');
169
+ return opts;
170
+ }
171
+ class RpcClient {
172
+ url;
173
+ _id = 0;
174
+ _pending = new Map();
175
+ _closed = false;
176
+ _ws = null;
177
+ constructor(url) {
178
+ this.url = url;
179
+ }
180
+ connect(timeoutMs = 20000) {
181
+ return new Promise((resolve, reject) => {
182
+ let settled = false;
183
+ const ws = new WebSocket(this.url);
184
+ this._ws = ws;
185
+ const timer = setTimeout(() => {
186
+ if (settled)
187
+ return;
188
+ settled = true;
189
+ try {
190
+ ws.close();
191
+ }
192
+ catch { /* ignore */ }
193
+ reject(new Error(`connect timeout: ${this.url}`));
194
+ }, timeoutMs);
195
+ ws.onopen = () => {
196
+ if (settled)
197
+ return;
198
+ settled = true;
199
+ clearTimeout(timer);
200
+ resolve();
201
+ };
202
+ ws.onerror = () => {
203
+ if (settled)
204
+ return;
205
+ settled = true;
206
+ clearTimeout(timer);
207
+ reject(new Error(`connect error: ${this.url}`));
208
+ };
209
+ ws.onclose = () => {
210
+ this._closed = true;
211
+ for (const { reject: rj } of this._pending.values())
212
+ rj(new Error('connection closed'));
213
+ this._pending.clear();
214
+ };
215
+ ws.onmessage = (ev) => {
216
+ let msg;
217
+ try {
218
+ msg = JSON.parse(typeof ev.data === 'string' ? ev.data : String(ev.data));
219
+ }
220
+ catch {
221
+ return;
222
+ }
223
+ const pending = this._pending.get(msg.id);
224
+ if (!pending)
225
+ return;
226
+ this._pending.delete(msg.id);
227
+ if (msg.error) {
228
+ const text = msg.error.data?.message || msg.error.message || JSON.stringify(msg.error);
229
+ pending.reject(new Error(text));
230
+ }
231
+ else {
232
+ pending.resolve(msg.result);
233
+ }
234
+ };
235
+ });
236
+ }
237
+ call(api, method, args, timeoutMs = 60000) {
238
+ if (this._closed)
239
+ return Promise.reject(new Error('connection closed'));
240
+ return new Promise((resolve, reject) => {
241
+ const id = ++this._id;
242
+ const timer = setTimeout(() => {
243
+ if (!this._pending.has(id))
244
+ return;
245
+ this._pending.delete(id);
246
+ reject(new Error(`rpc timeout: ${method}`));
247
+ }, timeoutMs);
248
+ this._pending.set(id, {
249
+ resolve: (value) => { clearTimeout(timer); resolve(value); },
250
+ reject: (error) => { clearTimeout(timer); reject(error); },
251
+ });
252
+ this._ws?.send(JSON.stringify({ jsonrpc: '2.0', id, method: 'call', params: [api, method, args] }));
253
+ });
254
+ }
255
+ close() {
256
+ try {
257
+ this._ws?.close();
258
+ }
259
+ catch { /* ignore */ }
260
+ }
261
+ }
262
+ async function openSession(nodes) {
263
+ const errors = [];
264
+ for (const url of nodes) {
265
+ const client = new RpcClient(url);
266
+ try {
267
+ await client.connect();
268
+ await client.call(LOGIN_API, 'login', ['', '']);
269
+ const config = await client.call(LOGIN_API, 'get_config', []);
270
+ let assetApi = null;
271
+ try {
272
+ const api = await client.call(LOGIN_API, 'asset', []);
273
+ if (typeof api === 'number')
274
+ assetApi = api;
275
+ }
276
+ catch {
277
+ // Most public nodes deny asset_api; holders use a dedicated node.
278
+ }
279
+ return { client, node: url, config: config || {}, assetApi };
280
+ }
281
+ catch (e) {
282
+ errors.push(`${url}: ${e.message}`);
283
+ client.close();
284
+ }
285
+ }
286
+ throw new Error(`No reachable BitShares node.\n ${errors.join('\n ')}`);
287
+ }
288
+ async function openAssetApiSession(excludeNodes) {
289
+ const excluded = new Set(excludeNodes);
290
+ const candidates = [...HOLDER_NODES, ...NODE_MANAGEMENT.DEFAULT_NODES]
291
+ .filter((node, index, all) => all.indexOf(node) === index && !excluded.has(node));
292
+ for (const url of candidates) {
293
+ const client = new RpcClient(url);
294
+ try {
295
+ await client.connect(10000);
296
+ await client.call(LOGIN_API, 'login', ['', '']);
297
+ const config = await client.call(LOGIN_API, 'get_config', []);
298
+ const api = await client.call(LOGIN_API, 'asset', []);
299
+ if (typeof api === 'number')
300
+ return { client, node: url, config: config || {}, assetApi: api };
301
+ }
302
+ catch {
303
+ // try the next node
304
+ }
305
+ client.close();
306
+ }
307
+ return null;
308
+ }
309
+ // ---------------------------------------------------------------------------
310
+ // Chain queries
311
+ // ---------------------------------------------------------------------------
312
+ async function callDb(session, method, args) {
313
+ return session.client.call(DB_API, method, args);
314
+ }
315
+ async function fetchObjects(session, ids) {
316
+ const out = [];
317
+ for (let i = 0; i < ids.length; i += OBJECT_BATCH) {
318
+ const chunk = ids.slice(i, i + OBJECT_BATCH);
319
+ const page = await callDb(session, 'get_objects', [chunk]);
320
+ for (let j = 0; j < chunk.length; j++)
321
+ out.push(page?.[j] ?? null);
322
+ }
323
+ return out;
324
+ }
325
+ /** Paginate an endpoint whose cursor is the last returned object id. */
326
+ async function listPages(fetchPage, limit, maxPages = 10000) {
327
+ const seen = new Set();
328
+ const out = [];
329
+ let start = null;
330
+ for (let page = 0; page < maxPages; page++) {
331
+ const rows = await fetchPage(start);
332
+ if (!Array.isArray(rows) || rows.length === 0)
333
+ break;
334
+ let fresh = 0;
335
+ for (const row of rows) {
336
+ if (!row || typeof row.id !== 'string' || seen.has(row.id))
337
+ continue;
338
+ seen.add(row.id);
339
+ out.push(row);
340
+ fresh++;
341
+ }
342
+ if (rows.length < limit || fresh === 0)
343
+ break;
344
+ start = rows[rows.length - 1].id;
345
+ }
346
+ return out;
347
+ }
348
+ /** Enumerate every asset via list_assets (symbol-ordered, inclusive lower bound). */
349
+ async function listAllAssets(session) {
350
+ const limit = Math.max(1, Math.min(session.config.api_limit_get_assets ?? 100, 100));
351
+ const seen = new Set();
352
+ const out = [];
353
+ let lower = '';
354
+ for (let page = 0; page < 10000; page++) {
355
+ const rows = await callDb(session, 'list_assets', [lower, limit]);
356
+ if (!Array.isArray(rows) || rows.length === 0)
357
+ break;
358
+ let fresh = 0;
359
+ for (const row of rows) {
360
+ if (!row || seen.has(row.id))
361
+ continue;
362
+ seen.add(row.id);
363
+ out.push(row);
364
+ fresh++;
365
+ }
366
+ if (rows.length < limit || fresh === 0)
367
+ break;
368
+ const lastSymbol = rows[rows.length - 1]?.symbol;
369
+ if (typeof lastSymbol !== 'string')
370
+ break;
371
+ lower = lastSymbol;
372
+ }
373
+ return out;
374
+ }
375
+ /**
376
+ * Scan a dense-ish object id range with a gap tolerance. Used for 1.13.x
377
+ * vesting balances, which have no global by-asset index.
378
+ */
379
+ async function scanIdRange(session, prefix, maxId, gap, onProgress) {
380
+ const objects = [];
381
+ let index = 0;
382
+ let lastSeen = -1;
383
+ while (index <= maxId && index - lastSeen <= gap) {
384
+ const count = Math.min(OBJECT_BATCH, maxId - index + 1);
385
+ const ids = Array.from({ length: count }, (_, i) => `${prefix}.${index + i}`);
386
+ const page = await callDb(session, 'get_objects', [ids]);
387
+ for (let j = 0; j < count; j++) {
388
+ const obj = page?.[j];
389
+ if (obj) {
390
+ lastSeen = index + j;
391
+ objects.push(obj);
392
+ }
393
+ }
394
+ index += count;
395
+ onProgress?.(index);
396
+ }
397
+ return { objects, scannedTo: index, hitLimit: index > maxId && index - lastSeen <= gap };
398
+ }
399
+ async function resolveAccountNames(session, ids) {
400
+ const names = new Map();
401
+ const unique = [...new Set(ids.filter(Boolean))];
402
+ for (let i = 0; i < unique.length; i += NAME_BATCH) {
403
+ const chunk = unique.slice(i, i + NAME_BATCH);
404
+ try {
405
+ const rows = await callDb(session, 'get_accounts', [chunk]);
406
+ for (const row of rows)
407
+ if (row)
408
+ names.set(row.id, row.name);
409
+ }
410
+ catch {
411
+ // Cosmetic only.
412
+ }
413
+ }
414
+ return names;
415
+ }
416
+ async function resolveAsset(session, input) {
417
+ let stub = null;
418
+ if (/^1\.3\.\d+$/.test(input)) {
419
+ const rows = await callDb(session, 'get_assets', [[input]]);
420
+ stub = rows?.[0] ?? null;
421
+ }
422
+ else {
423
+ const rows = await callDb(session, 'lookup_asset_symbols', [[input]]);
424
+ stub = rows?.[0] ?? null;
425
+ if (!stub && input.toLowerCase().startsWith('bit')) {
426
+ const retry = await callDb(session, 'lookup_asset_symbols', [[input.slice(3)]]);
427
+ stub = retry?.[0] ?? null;
428
+ }
429
+ }
430
+ if (!stub)
431
+ throw new Error(`asset not found: ${input}`);
432
+ const full = await callDb(session, 'get_assets', [[stub.id]]);
433
+ return { ...stub, ...(full?.[0] ?? {}) };
434
+ }
435
+ async function fetchAssetHolders(session, assetId, onProgress) {
436
+ if (session.assetApi === null)
437
+ throw new Error('asset_api unavailable on this node');
438
+ const api = session.assetApi;
439
+ const pageSize = Math.max(1, Math.min(session.config.api_limit_get_asset_holders ?? 100, 100));
440
+ const rows = [];
441
+ let complete = false;
442
+ let nextProgress = 10000;
443
+ for (let start = 0; start < 2_000_000; start += pageSize) {
444
+ const page = await session.client.call(api, 'get_asset_holders', [assetId, start, pageSize]);
445
+ if (!Array.isArray(page) || page.length === 0) {
446
+ complete = true;
447
+ break;
448
+ }
449
+ rows.push(...page);
450
+ if (rows.length >= nextProgress) {
451
+ onProgress?.(rows.length);
452
+ nextProgress += 10000;
453
+ }
454
+ if (page.length < pageSize) {
455
+ complete = true;
456
+ break;
457
+ }
458
+ }
459
+ let totalCount = null;
460
+ try {
461
+ const count = await session.client.call(api, 'get_asset_holders_count', [assetId]);
462
+ if (typeof count === 'number')
463
+ totalCount = count;
464
+ }
465
+ catch {
466
+ // optional
467
+ }
468
+ return { rows, totalCount, complete };
469
+ }
470
+ // ---------------------------------------------------------------------------
471
+ // Numeric + formatting helpers
472
+ // ---------------------------------------------------------------------------
473
+ function mulDiv(a, b, divisor) {
474
+ if (divisor === 0n)
475
+ return 0n;
476
+ return (a * b) / divisor;
477
+ }
478
+ /**
479
+ * Constant-product depth for a 3% spot move. Reserves are the pool's token (X)
480
+ * and counterpart (Y) balances; fee is taken from the output side (as in the
481
+ * core liquidity_pool_exchange evaluator).
482
+ */
483
+ function poolDepthFor(tokenBalance, counterpartBalance, feePercent) {
484
+ const x = Number(tokenBalance);
485
+ const y = Number(counterpartBalance);
486
+ if (!(x > 0) || !(y > 0))
487
+ return { downQuote: 0n, downToken: 0n, upQuote: 0n, upToken: 0n };
488
+ const fee = Math.max(0, Math.min(feePercent, 10000)) / 10000;
489
+ const downFactor = 0.97;
490
+ const upFactor = 1.03;
491
+ const xDown = x / Math.sqrt(downFactor);
492
+ const yDown = y * Math.sqrt(downFactor);
493
+ const xUp = x / Math.sqrt(upFactor);
494
+ const yUp = y * Math.sqrt(upFactor);
495
+ return {
496
+ downToken: toBig(Math.ceil(xDown - x)),
497
+ downQuote: toBig(Math.max(0, Math.floor((y - yDown) * (1 - fee)))),
498
+ upQuote: toBig(Math.ceil(yUp - y)),
499
+ upToken: toBig(Math.max(0, Math.floor((x - xUp) * (1 - fee)))),
500
+ };
501
+ }
502
+ function toBig(value) {
503
+ if (value === null || value === undefined)
504
+ return 0n;
505
+ if (typeof value === 'number') {
506
+ if (!Number.isFinite(value))
507
+ return 0n;
508
+ return BigInt(Math.round(value));
509
+ }
510
+ try {
511
+ return BigInt(value);
512
+ }
513
+ catch {
514
+ return 0n;
515
+ }
516
+ }
517
+ function amountOf(amount) {
518
+ return amount ? toBig(amount.amount) : 0n;
519
+ }
520
+ function formatInteger(value) {
521
+ return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
522
+ }
523
+ function formatUnits(raw, precision) {
524
+ const negative = raw < 0n;
525
+ const abs = negative ? -raw : raw;
526
+ const divisor = 10n ** BigInt(precision);
527
+ const whole = abs / divisor;
528
+ const frac = precision > 0
529
+ ? (abs % divisor).toString().padStart(precision, '0').replace(/0+$/, '')
530
+ : '';
531
+ return `${negative ? '-' : ''}${formatInteger(whole)}${frac ? `.${frac}` : ''}`;
532
+ }
533
+ function compactUnits(raw, precision) {
534
+ const divisor = 10n ** BigInt(precision);
535
+ const whole = raw / divisor;
536
+ const negative = whole < 0n;
537
+ const abs = negative ? -whole : whole;
538
+ if (abs < 1000n)
539
+ return formatUnits(raw, precision);
540
+ const tiers = [
541
+ [10n ** 12n, 'T'], [10n ** 9n, 'B'], [10n ** 6n, 'M'], [10n ** 3n, 'K'],
542
+ ];
543
+ for (const [tier, suffix] of tiers) {
544
+ if (abs < tier)
545
+ continue;
546
+ const milli = (abs * 1000n) / tier;
547
+ const intPart = milli / 1000n;
548
+ const frac = (milli % 1000n).toString().padStart(3, '0').replace(/0+$/, '');
549
+ return `${negative ? '-' : ''}${intPart}${frac ? `.${frac}` : ''}${suffix}`;
550
+ }
551
+ return `${negative ? '-' : ''}${abs}`;
552
+ }
553
+ function sharePercent(part, whole, digits = 2) {
554
+ if (whole <= 0n)
555
+ return '—';
556
+ const scaled = Number((part * 1000000n) / whole);
557
+ return `${(scaled / 10_000).toFixed(digits)}%`;
558
+ }
559
+ function shareFraction(part, whole) {
560
+ if (whole <= 0n)
561
+ return 0;
562
+ return Number((part * 10000n) / whole) / 10_000;
563
+ }
564
+ function compareDesc(a, b) {
565
+ return a > b ? -1 : a < b ? 1 : 0;
566
+ }
567
+ function padStart(text, width) {
568
+ return text.padStart(width);
569
+ }
570
+ function padEnd(text, width) {
571
+ return text.padEnd(width);
572
+ }
573
+ function esc(text) {
574
+ return text.replace(/[&<>"']/g, (ch) => {
575
+ switch (ch) {
576
+ case '&': return '&amp;';
577
+ case '<': return '&lt;';
578
+ case '>': return '&gt;';
579
+ case '"': return '&quot;';
580
+ default: return '&#39;';
581
+ }
582
+ });
583
+ }
584
+ // ---------------------------------------------------------------------------
585
+ // Collection
586
+ // ---------------------------------------------------------------------------
587
+ function progress(enabled, message) {
588
+ if (!enabled || !process.stderr.isTTY)
589
+ return;
590
+ process.stderr.write(`\r\x1b[2K ${message}`);
591
+ }
592
+ function clearProgress(enabled) {
593
+ if (!enabled || !process.stderr.isTTY)
594
+ return;
595
+ process.stderr.write('\r\x1b[2K');
596
+ }
597
+ async function scanLimitOrders(session, tokenId, assets, limit, concurrency, onProgress) {
598
+ const byCounterpart = new Map();
599
+ const depthByCounterpart = new Map();
600
+ let total = 0n;
601
+ let orderCount = 0;
602
+ let pairsWith = 0;
603
+ let truncatedPairs = 0;
604
+ let failedPairs = 0;
605
+ let done = 0;
606
+ let cursor = 0;
607
+ const worker = async () => {
608
+ for (;;) {
609
+ const index = cursor++;
610
+ if (index >= assets.length)
611
+ return;
612
+ const other = assets[index];
613
+ if (other.id === tokenId)
614
+ continue;
615
+ let rows = null;
616
+ for (let attempt = 0; attempt < 2; attempt++) {
617
+ try {
618
+ rows = await callDb(session, 'get_limit_orders', [tokenId, other.id, limit]);
619
+ break;
620
+ }
621
+ catch {
622
+ if (attempt === 1)
623
+ failedPairs++;
624
+ }
625
+ }
626
+ if (rows) {
627
+ const asks = [];
628
+ const bids = [];
629
+ let side = 0;
630
+ for (const order of rows) {
631
+ const base = order.sell_price?.base;
632
+ const quote = order.sell_price?.quote;
633
+ if (!base || !quote)
634
+ continue;
635
+ const baseAmount = toBig(base.amount);
636
+ const quoteAmount = toBig(quote.amount);
637
+ if (baseAmount <= 0n || quoteAmount <= 0n)
638
+ continue;
639
+ if (base.asset_id === tokenId) {
640
+ // Token sell order (ask): token for sale, counterpart to receive.
641
+ const token = toBig(order.for_sale);
642
+ const receive = mulDiv(token, quoteAmount, baseAmount);
643
+ asks.push({
644
+ token, quote: receive,
645
+ price: Number(quoteAmount) / Number(baseAmount),
646
+ });
647
+ side++;
648
+ total += token;
649
+ }
650
+ else if (base.asset_id === other.id && quote.asset_id === tokenId) {
651
+ // Counterpart sell order (bid): counterpart for sale, token to receive.
652
+ const counterpart = toBig(order.for_sale);
653
+ const receive = mulDiv(counterpart, quoteAmount, baseAmount);
654
+ bids.push({
655
+ token: receive, quote: counterpart,
656
+ price: Number(baseAmount) / Number(quoteAmount),
657
+ });
658
+ }
659
+ }
660
+ if (side > 0) {
661
+ const agg = byCounterpart.get(other.id) ?? { amount: 0n, count: 0 };
662
+ agg.amount += asks.reduce((acc, level) => acc + level.token, 0n);
663
+ agg.count += side;
664
+ byCounterpart.set(other.id, agg);
665
+ orderCount += side;
666
+ pairsWith++;
667
+ if (side >= limit)
668
+ truncatedPairs++;
669
+ }
670
+ // 3% depth around the local orderbook mid.
671
+ let bestBid = 0;
672
+ let bestAsk = Number.POSITIVE_INFINITY;
673
+ for (const level of bids)
674
+ if (level.price > bestBid)
675
+ bestBid = level.price;
676
+ for (const level of asks)
677
+ if (level.price < bestAsk)
678
+ bestAsk = level.price;
679
+ let mid = null;
680
+ if (bestBid > 0 && Number.isFinite(bestAsk))
681
+ mid = (bestBid + bestAsk) / 2;
682
+ else if (bestAsk !== Number.POSITIVE_INFINITY)
683
+ mid = bestAsk;
684
+ else if (bestBid > 0)
685
+ mid = bestBid;
686
+ if (mid && mid > 0) {
687
+ const depth = {
688
+ downQuote: 0n, downToken: 0n, upQuote: 0n, upToken: 0n,
689
+ truncated: asks.length >= limit || bids.length >= limit,
690
+ };
691
+ for (const level of bids) {
692
+ if (level.price < mid * 0.97)
693
+ continue;
694
+ depth.downQuote += level.quote;
695
+ depth.downToken += level.token;
696
+ }
697
+ for (const level of asks) {
698
+ if (level.price > mid * 1.03)
699
+ continue;
700
+ depth.upQuote += level.quote;
701
+ depth.upToken += level.token;
702
+ }
703
+ depthByCounterpart.set(other.id, depth);
704
+ }
705
+ }
706
+ done++;
707
+ if (done % 500 === 0)
708
+ onProgress?.(done, assets.length);
709
+ }
710
+ };
711
+ await Promise.all(Array.from({ length: concurrency }, () => worker()));
712
+ return {
713
+ total, orderCount, pairsWith, truncatedPairs, failedPairs,
714
+ scannedAssets: assets.length, byCounterpart, depthByCounterpart,
715
+ };
716
+ }
717
+ async function collect(session, opts) {
718
+ if (!opts.asset)
719
+ throw new UsageError('a token symbol or asset id is required');
720
+ const showProgress = !opts.json;
721
+ const warnings = [];
722
+ const generatedAt = new Date().toISOString();
723
+ // ---- Asset + supply -----------------------------------------------------
724
+ progress(showProgress, 'resolving asset ...');
725
+ const asset = await resolveAsset(session, opts.asset);
726
+ if (asset.id === CORE_ID) {
727
+ throw new Error('BTS is the core asset; use scripts/bts_distribution.ts for the BTS distribution');
728
+ }
729
+ const dynRows = await fetchObjects(session, [asset.dynamic_asset_data_id]);
730
+ const dyn = dynRows[0];
731
+ if (!dyn)
732
+ throw new Error(`dynamic data missing for ${asset.symbol}`);
733
+ const supply = toBig(dyn.current_supply);
734
+ const confidential = toBig(dyn.confidential_supply);
735
+ const accumulatedFees = toBig(dyn.accumulated_fees);
736
+ const global = await callDb(session, 'get_dynamic_global_properties', []);
737
+ const precision = asset.precision;
738
+ const money = (value) => formatUnits(value, precision);
739
+ // ---- Assets (symbols + order scan universe) -----------------------------
740
+ progress(showProgress, 'listing assets ...');
741
+ const assets = await listAllAssets(session);
742
+ const assetById = new Map(assets.map((row) => [row.id, row]));
743
+ assetById.set(asset.id, asset);
744
+ const symbolOf = (id) => assetById.get(id)?.symbol ?? id;
745
+ const precisionOf = (id) => assetById.get(id)?.precision ?? 0;
746
+ // ---- Free account balances (rich list) ----------------------------------
747
+ progress(showProgress, 'fetching the rich list (asset_api) ...');
748
+ let holderSession = session;
749
+ let closeHolderSession = false;
750
+ if (session.assetApi === null) {
751
+ holderSession = await openAssetApiSession([session.node]);
752
+ closeHolderSession = holderSession !== null;
753
+ }
754
+ let holderSource = null;
755
+ let holderCount = 0;
756
+ let holderTotalCount = null;
757
+ let holderComplete = false;
758
+ let free = 0n;
759
+ const holderTop = [];
760
+ const holderAmounts = [];
761
+ const concentration = [];
762
+ if (holderSession?.assetApi !== null && holderSession?.assetApi !== undefined) {
763
+ holderSource = holderSession.node;
764
+ try {
765
+ const fetched = await fetchAssetHolders(holderSession, asset.id, (n) => progress(showProgress, `fetching the rich list ... ${formatInteger(BigInt(n))} accounts`));
766
+ holderCount = fetched.rows.length;
767
+ holderTotalCount = fetched.totalCount;
768
+ holderComplete = fetched.complete;
769
+ fetched.rows.forEach((holder, index) => {
770
+ const amount = toBig(holder.amount);
771
+ free += amount;
772
+ holderAmounts.push(amount);
773
+ if (index < opts.detail) {
774
+ holderTop.push({
775
+ rank: index + 1,
776
+ id: holder.account_id,
777
+ name: holder.name,
778
+ amount,
779
+ exchange: detectExchange(holder.name),
780
+ });
781
+ }
782
+ });
783
+ holderAmounts.sort((a, b) => compareDesc(a, b));
784
+ for (const top of [1, 10, 100, 1000]) {
785
+ if (holderAmounts.length < top)
786
+ continue;
787
+ concentration.push({
788
+ top, count: top,
789
+ amount: holderAmounts.slice(0, top).reduce((acc, value) => acc + value, 0n),
790
+ });
791
+ }
792
+ }
793
+ catch (e) {
794
+ warnings.push(`Rich list unavailable: ${e.message}`);
795
+ }
796
+ }
797
+ else {
798
+ warnings.push('No reachable node exposes asset_api::get_asset_holders; free balances are missing.');
799
+ }
800
+ if (closeHolderSession)
801
+ holderSession?.client.close();
802
+ // ---- Liquidity pools ----------------------------------------------------
803
+ progress(showProgress, 'listing liquidity pools ...');
804
+ const poolLimit = Math.max(1, Math.min(session.config.api_limit_get_liquidity_pools ?? 100, 1000));
805
+ let pools = [];
806
+ try {
807
+ pools = await listPages((start) => callDb(session, 'get_liquidity_pools_by_one_asset', [asset.id, poolLimit, start]), poolLimit);
808
+ }
809
+ catch (e) {
810
+ warnings.push(`Liquidity pools unavailable: ${e.message}`);
811
+ }
812
+ let poolTotal = 0n;
813
+ const poolByCounterpart = new Map();
814
+ const poolDepthByCounterpart = new Map();
815
+ for (const pool of pools) {
816
+ let amount = 0n;
817
+ let tokenBalance = 0n;
818
+ let counterpartBalance = 0n;
819
+ let counterpart = null;
820
+ if (pool.asset_a === asset.id) {
821
+ amount = toBig(pool.balance_a);
822
+ tokenBalance = amount;
823
+ counterpartBalance = toBig(pool.balance_b);
824
+ counterpart = pool.asset_b;
825
+ }
826
+ else if (pool.asset_b === asset.id) {
827
+ amount = toBig(pool.balance_b);
828
+ tokenBalance = amount;
829
+ counterpartBalance = toBig(pool.balance_a);
830
+ counterpart = pool.asset_a;
831
+ }
832
+ if (!counterpart)
833
+ continue;
834
+ poolTotal += amount;
835
+ const agg = poolByCounterpart.get(counterpart) ?? { amount: 0n, count: 0 };
836
+ agg.amount += amount;
837
+ agg.count++;
838
+ poolByCounterpart.set(counterpart, agg);
839
+ const depth = poolDepthFor(tokenBalance, counterpartBalance, pool.taker_fee_percent ?? 0);
840
+ const depthAgg = poolDepthByCounterpart.get(counterpart)
841
+ ?? { downQuote: 0n, downToken: 0n, upQuote: 0n, upToken: 0n };
842
+ depthAgg.downQuote += depth.downQuote;
843
+ depthAgg.downToken += depth.downToken;
844
+ depthAgg.upQuote += depth.upQuote;
845
+ depthAgg.upToken += depth.upToken;
846
+ poolDepthByCounterpart.set(counterpart, depthAgg);
847
+ }
848
+ // ---- Limit orders (token for sale) --------------------------------------
849
+ let ordersTotal = 0n;
850
+ let orderCount = 0;
851
+ let ordersPairsWith = 0;
852
+ let ordersTruncated = 0;
853
+ let ordersFailed = 0;
854
+ const orderByCounterpart = new Map();
855
+ let orderDepthByCounterpart = new Map();
856
+ if (opts.scanOrders) {
857
+ progress(showProgress, `scanning limit orders across ${formatInteger(BigInt(assets.length))} assets ...`);
858
+ const orderLimit = Math.max(1, Math.min(session.config.api_limit_get_limit_orders ?? 300, 1000));
859
+ const scan = await scanLimitOrders(session, asset.id, assets, orderLimit, opts.concurrency, (done, total) => progress(showProgress, `scanning limit orders ... ${done}/${total} assets`));
860
+ ordersTotal = scan.total;
861
+ orderCount = scan.orderCount;
862
+ ordersPairsWith = scan.pairsWith;
863
+ ordersTruncated = scan.truncatedPairs;
864
+ ordersFailed = scan.failedPairs;
865
+ for (const [id, agg] of scan.byCounterpart)
866
+ orderByCounterpart.set(id, agg);
867
+ orderDepthByCounterpart = scan.depthByCounterpart;
868
+ if (ordersTruncated > 0) {
869
+ warnings.push(`${ordersTruncated} market(s) hit the per-side order limit; order totals may be undercounted.`);
870
+ }
871
+ if (ordersFailed > 0) {
872
+ warnings.push(`${ordersFailed} market(s) failed the order query after retry; order totals may be undercounted.`);
873
+ }
874
+ }
875
+ else {
876
+ warnings.push('Limit-order scan skipped (--no-orders); the limit-order bucket is incomplete.');
877
+ }
878
+ // ---- Vesting balances (1.13.x) ------------------------------------------
879
+ progress(showProgress, 'scanning vesting balances (1.13.x) ...');
880
+ const vestingScan = await scanIdRange(session, '1.13', opts.vestingMax, opts.gap, (n) => progress(showProgress, `scanning vesting balances (1.13.x) ... ${n}`));
881
+ let vestingTotal = 0n;
882
+ let vestingCount = 0;
883
+ const vestingByType = new Map();
884
+ const vestingByOwner = new Map();
885
+ for (const vesting of vestingScan.objects) {
886
+ if (vesting.balance?.asset_id !== asset.id)
887
+ continue;
888
+ const amount = amountOf(vesting.balance);
889
+ vestingCount++;
890
+ vestingTotal += amount;
891
+ const type = vesting.balance_type || 'unspecified';
892
+ const agg = vestingByType.get(type) ?? { amount: 0n, count: 0 };
893
+ agg.amount += amount;
894
+ agg.count++;
895
+ vestingByType.set(type, agg);
896
+ vestingByOwner.set(vesting.owner, (vestingByOwner.get(vesting.owner) ?? 0n) + amount);
897
+ }
898
+ // ---- P2P credit offers / deals ------------------------------------------
899
+ progress(showProgress, 'listing P2P credit offers and deals ...');
900
+ const creditLimit = Math.max(1, Math.min(session.config.api_limit_get_credit_offers ?? 100, 1000));
901
+ let offers = [];
902
+ try {
903
+ offers = await listPages((start) => callDb(session, 'get_credit_offers_by_asset', [asset.id, creditLimit, start]), creditLimit);
904
+ }
905
+ catch {
906
+ try {
907
+ const all = await listPages((start) => callDb(session, 'list_credit_offers', [creditLimit, start]), creditLimit);
908
+ offers = all.filter((offer) => offer.asset_type === asset.id);
909
+ }
910
+ catch (e) {
911
+ warnings.push(`Credit offers unavailable: ${e.message}`);
912
+ }
913
+ }
914
+ let offersTotal = 0n;
915
+ for (const offer of offers)
916
+ offersTotal += toBig(offer.current_balance);
917
+ let collateralDeals = [];
918
+ try {
919
+ collateralDeals = await listPages((start) => callDb(session, 'get_credit_deals_by_collateral_asset', [asset.id, creditLimit, start]), creditLimit);
920
+ }
921
+ catch {
922
+ try {
923
+ const all = await listPages((start) => callDb(session, 'list_credit_deals', [creditLimit, start]), creditLimit);
924
+ collateralDeals = all.filter((deal) => deal.collateral_asset === asset.id);
925
+ }
926
+ catch (e) {
927
+ warnings.push(`Credit deals (collateral) unavailable: ${e.message}`);
928
+ }
929
+ }
930
+ let collateralTotal = 0n;
931
+ for (const deal of collateralDeals)
932
+ collateralTotal += toBig(deal.collateral_amount);
933
+ let debtDeals = [];
934
+ try {
935
+ debtDeals = await listPages((start) => callDb(session, 'get_credit_deals_by_debt_asset', [asset.id, creditLimit, start]), creditLimit);
936
+ }
937
+ catch {
938
+ try {
939
+ const all = await listPages((start) => callDb(session, 'list_credit_deals', [creditLimit, start]), creditLimit);
940
+ debtDeals = all.filter((deal) => deal.debt_asset === asset.id);
941
+ }
942
+ catch (e) {
943
+ warnings.push(`Credit deals (debt) unavailable: ${e.message}`);
944
+ }
945
+ }
946
+ let debtTotal = 0n;
947
+ for (const deal of debtDeals)
948
+ debtTotal += toBig(deal.debt_amount);
949
+ // A deal whose collateral and debt are both this asset is one lock, not two.
950
+ const collateralDealIds = new Set(collateralDeals.map((deal) => deal.id));
951
+ debtDeals = debtDeals.filter((deal) => !collateralDealIds.has(deal.id));
952
+ // ---- SameT funds --------------------------------------------------------
953
+ progress(showProgress, 'listing SameT funds ...');
954
+ const sametLimit = Math.max(1, Math.min(session.config.api_limit_get_samet_funds ?? 100, 1000));
955
+ let sametFunds = [];
956
+ try {
957
+ sametFunds = await listPages((start) => callDb(session, 'get_samet_funds_by_asset', [asset.id, sametLimit, start]), sametLimit);
958
+ }
959
+ catch (e) {
960
+ warnings.push(`SameT funds unavailable: ${e.message}`);
961
+ }
962
+ let sametTotal = 0n;
963
+ for (const fund of sametFunds)
964
+ sametTotal += toBig(fund.balance);
965
+ // ---- HTLC escrow --------------------------------------------------------
966
+ progress(showProgress, 'listing HTLCs ...');
967
+ const htlcLimit = Math.max(1, Math.min(session.config.api_limit_list_htlcs ?? 100, 1000));
968
+ let htlcs = [];
969
+ try {
970
+ htlcs = await listPages((start) => callDb(session, 'list_htlcs', [start ?? '1.16.0', htlcLimit]), htlcLimit);
971
+ }
972
+ catch (e) {
973
+ warnings.push(`HTLCs unavailable: ${e.message}`);
974
+ }
975
+ let htlcTotal = 0n;
976
+ for (const htlc of htlcs) {
977
+ if (htlc.transfer?.asset_id === asset.id)
978
+ htlcTotal += toBig(htlc.transfer.amount);
979
+ }
980
+ // ---- Buckets + supply reconciliation ------------------------------------
981
+ const locked = ordersTotal + poolTotal + vestingTotal + offersTotal
982
+ + collateralTotal + sametTotal + htlcTotal + accumulatedFees;
983
+ const identified = free + locked + confidential;
984
+ const residual = supply - identified;
985
+ const float = supply - locked;
986
+ const floatInclBlinded = float;
987
+ const buckets = [
988
+ {
989
+ key: 'free', label: 'Free account balances', amount: free, color: COLORS[0],
990
+ note: `${formatInteger(BigInt(holderCount))} holder accounts via asset_api`,
991
+ },
992
+ {
993
+ key: 'orders', label: 'Limit orders (for sale)', amount: ordersTotal, color: COLORS[1],
994
+ note: opts.scanOrders
995
+ ? `${formatInteger(BigInt(orderCount))} orders across ${ordersPairsWith} markets`
996
+ : 'scan skipped with --no-orders',
997
+ },
998
+ {
999
+ key: 'pools', label: 'Liquidity pools', amount: poolTotal, color: COLORS[2],
1000
+ note: `${formatInteger(BigInt(pools.length))} pool reserves`,
1001
+ },
1002
+ {
1003
+ key: 'vesting', label: 'Vesting balances', amount: vestingTotal, color: COLORS[3],
1004
+ note: `${formatInteger(BigInt(vestingCount))} vesting objects (1.13.x)`,
1005
+ },
1006
+ {
1007
+ key: 'creditOffers', label: 'P2P credit offers', amount: offersTotal, color: COLORS[4],
1008
+ note: `${offers.length} offer fund(s) currently lendable`,
1009
+ },
1010
+ {
1011
+ key: 'creditCollateral', label: 'P2P deal collateral', amount: collateralTotal, color: COLORS[5],
1012
+ note: `${collateralDeals.length} deal(s) using ${asset.symbol} as collateral`,
1013
+ },
1014
+ {
1015
+ key: 'samet', label: 'SameT funds', amount: sametTotal, color: COLORS[6],
1016
+ note: `${sametFunds.length} same-transaction fund(s)`,
1017
+ },
1018
+ {
1019
+ key: 'htlc', label: 'HTLC escrow', amount: htlcTotal, color: COLORS[7],
1020
+ note: `${htlcs.filter((h) => h.transfer?.asset_id === asset.id).length} HTLC(s)`,
1021
+ },
1022
+ {
1023
+ key: 'fees', label: 'Accumulated market fees', amount: accumulatedFees, color: COLORS[8],
1024
+ note: 'issuer-claimable fees held by the asset object',
1025
+ },
1026
+ {
1027
+ key: 'confidential', label: 'Blinded balances', amount: confidential, color: COLORS[9],
1028
+ note: 'confidential_supply, not visible in account balances',
1029
+ },
1030
+ ];
1031
+ if (residual !== 0n) {
1032
+ buckets.push({
1033
+ key: 'other', label: residual > 0n ? 'Other / unattributed' : 'Double-counted (negative)',
1034
+ amount: residual, color: COLORS[11],
1035
+ note: residual > 0n
1036
+ ? 'supply not matched to a known bucket (node drift or an unenumerated sink)'
1037
+ : 'buckets exceed supply; usually node/block drift between queries',
1038
+ });
1039
+ warnings.push(`Supply reconciliation is off by ${money(residual)} ${asset.symbol}.`);
1040
+ }
1041
+ // ---- Liquidity by counterpart -------------------------------------------
1042
+ const liquidityMap = new Map();
1043
+ const liquidityRow = (id) => {
1044
+ const row = liquidityMap.get(id) ?? {
1045
+ assetId: id, symbol: symbolOf(id), precision: precisionOf(id), amount: 0n, count: 0,
1046
+ poolAmount: 0n, orderAmount: 0n, poolCount: 0, orderCount: 0,
1047
+ obDownQuote: 0n, obDownToken: 0n, obUpQuote: 0n, obUpToken: 0n, obTruncated: false,
1048
+ poolDownQuote: 0n, poolDownToken: 0n, poolUpQuote: 0n, poolUpToken: 0n,
1049
+ };
1050
+ liquidityMap.set(id, row);
1051
+ return row;
1052
+ };
1053
+ for (const [id, agg] of poolByCounterpart) {
1054
+ const row = liquidityRow(id);
1055
+ row.poolAmount += agg.amount;
1056
+ row.poolCount += agg.count;
1057
+ row.amount += agg.amount;
1058
+ row.count += agg.count;
1059
+ }
1060
+ for (const [id, agg] of orderByCounterpart) {
1061
+ const row = liquidityRow(id);
1062
+ row.orderAmount += agg.amount;
1063
+ row.orderCount += agg.count;
1064
+ row.amount += agg.amount;
1065
+ row.count += agg.count;
1066
+ }
1067
+ for (const [id, depth] of poolDepthByCounterpart) {
1068
+ const row = liquidityRow(id);
1069
+ row.poolDownQuote += depth.downQuote;
1070
+ row.poolDownToken += depth.downToken;
1071
+ row.poolUpQuote += depth.upQuote;
1072
+ row.poolUpToken += depth.upToken;
1073
+ }
1074
+ for (const [id, depth] of orderDepthByCounterpart) {
1075
+ const row = liquidityRow(id);
1076
+ row.obDownQuote += depth.downQuote;
1077
+ row.obDownToken += depth.downToken;
1078
+ row.obUpQuote += depth.upQuote;
1079
+ row.obUpToken += depth.upToken;
1080
+ row.obTruncated = row.obTruncated || depth.truncated;
1081
+ }
1082
+ const liquidityByCounterpart = [...liquidityMap.values()]
1083
+ .filter((row) => row.amount > 0n)
1084
+ .sort((a, b) => compareDesc(a.amount, b.amount));
1085
+ const depth = {
1086
+ downOrderbookToken: liquidityByCounterpart.reduce((acc, row) => acc + row.obDownToken, 0n),
1087
+ downPoolToken: liquidityByCounterpart.reduce((acc, row) => acc + row.poolDownToken, 0n),
1088
+ upOrderbookToken: liquidityByCounterpart.reduce((acc, row) => acc + row.obUpToken, 0n),
1089
+ upPoolToken: liquidityByCounterpart.reduce((acc, row) => acc + row.poolUpToken, 0n),
1090
+ };
1091
+ const depthTotals = {
1092
+ ...depth,
1093
+ downToken: depth.downOrderbookToken + depth.downPoolToken,
1094
+ upToken: depth.upOrderbookToken + depth.upPoolToken,
1095
+ };
1096
+ // ---- Names for detail rows ----------------------------------------------
1097
+ const allOwnerIds = [
1098
+ ...vestingByOwner.keys(),
1099
+ ...offers.map((offer) => offer.owner_account),
1100
+ ...collateralDeals.map((deal) => deal.borrower),
1101
+ ...debtDeals.map((deal) => deal.borrower),
1102
+ ];
1103
+ const accountNames = await resolveAccountNames(session, allOwnerIds);
1104
+ let issuerName;
1105
+ if (asset.issuer) {
1106
+ const issuerNames = await resolveAccountNames(session, [asset.issuer]);
1107
+ issuerName = issuerNames.get(asset.issuer);
1108
+ }
1109
+ const offerRows = offers
1110
+ .slice()
1111
+ .sort((a, b) => compareDesc(toBig(a.current_balance), toBig(b.current_balance)))
1112
+ .slice(0, opts.detail)
1113
+ .map((offer) => ({
1114
+ id: offer.id,
1115
+ account: offer.owner_account,
1116
+ accountName: accountNames.get(offer.owner_account),
1117
+ debtAsset: offer.asset_type,
1118
+ debtSymbol: symbolOf(offer.asset_type),
1119
+ debtPrecision: precisionOf(offer.asset_type),
1120
+ debtAmount: 0n,
1121
+ collateralAsset: offer.asset_type,
1122
+ collateralSymbol: symbolOf(offer.asset_type),
1123
+ collateralPrecision: precisionOf(offer.asset_type),
1124
+ collateralAmount: toBig(offer.current_balance),
1125
+ }));
1126
+ const dealRow = (deal) => ({
1127
+ id: deal.id,
1128
+ account: deal.borrower,
1129
+ accountName: accountNames.get(deal.borrower),
1130
+ debtAsset: deal.debt_asset,
1131
+ debtSymbol: symbolOf(deal.debt_asset),
1132
+ debtPrecision: precisionOf(deal.debt_asset),
1133
+ debtAmount: toBig(deal.debt_amount),
1134
+ collateralAsset: deal.collateral_asset,
1135
+ collateralSymbol: symbolOf(deal.collateral_asset),
1136
+ collateralPrecision: precisionOf(deal.collateral_asset),
1137
+ collateralAmount: toBig(deal.collateral_amount),
1138
+ });
1139
+ const collateralRows = collateralDeals
1140
+ .slice()
1141
+ .sort((a, b) => compareDesc(toBig(a.collateral_amount), toBig(b.collateral_amount)))
1142
+ .slice(0, opts.detail)
1143
+ .map(dealRow);
1144
+ const debtRows = debtDeals
1145
+ .slice()
1146
+ .sort((a, b) => compareDesc(toBig(a.debt_amount), toBig(b.debt_amount)))
1147
+ .slice(0, opts.detail)
1148
+ .map(dealRow);
1149
+ // ---- Report -------------------------------------------------------------
1150
+ return {
1151
+ node: session.node,
1152
+ blockNum: global.head_block_number,
1153
+ blockTime: global.time,
1154
+ generatedAt,
1155
+ asset: {
1156
+ id: asset.id,
1157
+ symbol: asset.symbol,
1158
+ precision,
1159
+ issuer: asset.issuer,
1160
+ issuerName,
1161
+ maxSupply: asset.options?.max_supply ? toBig(asset.options.max_supply) : null,
1162
+ marketFeePercent: (asset.options?.market_fee_percent ?? 0) / 100,
1163
+ flags: asset.options?.flags ?? null,
1164
+ issuerPermissions: asset.options?.issuer_permissions ?? null,
1165
+ isBitasset: Boolean(asset.bitasset_data_id),
1166
+ poolShareAssetId: asset.for_liquidity_pool ?? null,
1167
+ },
1168
+ supply: { current: supply, confidential, accumulatedFees },
1169
+ buckets,
1170
+ free,
1171
+ locked,
1172
+ identified,
1173
+ residual,
1174
+ float,
1175
+ floatInclBlinded,
1176
+ holders: {
1177
+ sourceNode: holderSource,
1178
+ count: holderCount,
1179
+ totalCount: holderTotalCount,
1180
+ total: free,
1181
+ complete: holderComplete,
1182
+ top: holderTop,
1183
+ concentration,
1184
+ },
1185
+ orders: {
1186
+ scanned: opts.scanOrders,
1187
+ scannedAssets: assets.length,
1188
+ orderCount,
1189
+ pairsWith: ordersPairsWith,
1190
+ truncatedPairs: ordersTruncated,
1191
+ failedPairs: ordersFailed,
1192
+ total: ordersTotal,
1193
+ byCounterpart: [...orderByCounterpart.entries()]
1194
+ .map(([id, agg]) => ({
1195
+ assetId: id, symbol: symbolOf(id), precision: precisionOf(id),
1196
+ amount: agg.amount, count: agg.count,
1197
+ }))
1198
+ .sort((a, b) => compareDesc(a.amount, b.amount)),
1199
+ },
1200
+ pools: {
1201
+ count: pools.length,
1202
+ total: poolTotal,
1203
+ byCounterpart: [...poolByCounterpart.entries()]
1204
+ .map(([id, agg]) => ({
1205
+ assetId: id, symbol: symbolOf(id), precision: precisionOf(id),
1206
+ amount: agg.amount, count: agg.count,
1207
+ }))
1208
+ .sort((a, b) => compareDesc(a.amount, b.amount)),
1209
+ },
1210
+ vesting: {
1211
+ count: vestingCount,
1212
+ total: vestingTotal,
1213
+ byType: [...vestingByType.entries()]
1214
+ .map(([type, agg]) => ({ type, count: agg.count, amount: agg.amount }))
1215
+ .sort((a, b) => compareDesc(a.amount, b.amount)),
1216
+ scannedTo: vestingScan.scannedTo,
1217
+ hitLimit: vestingScan.hitLimit,
1218
+ },
1219
+ credit: {
1220
+ offersCount: offers.length,
1221
+ offersTotal,
1222
+ offers: offerRows,
1223
+ collateralCount: collateralDeals.length,
1224
+ collateralTotal,
1225
+ collateralDeals: collateralRows,
1226
+ debtCount: debtDeals.length,
1227
+ debtTotal,
1228
+ debtDeals: debtRows,
1229
+ },
1230
+ samet: { count: sametFunds.length, total: sametTotal },
1231
+ htlcs: {
1232
+ count: htlcs.filter((h) => h.transfer?.asset_id === asset.id).length,
1233
+ total: htlcTotal,
1234
+ },
1235
+ liquidityByCounterpart,
1236
+ depth: depthTotals,
1237
+ warnings,
1238
+ };
1239
+ }
1240
+ // ---------------------------------------------------------------------------
1241
+ // Exchange-name heuristic
1242
+ // ---------------------------------------------------------------------------
1243
+ const CEX_BRANDS = [
1244
+ [/mexc|mxccom|\bmxc\b/i, 'MEXC'],
1245
+ [/gate-?io|\bgate\b/i, 'Gate'],
1246
+ [/poloniex|\bpolo\b/i, 'Poloniex'],
1247
+ [/huobi/i, 'Huobi'],
1248
+ [/binance/i, 'Binance'],
1249
+ [/\bokx\b|\bokex\b/i, 'OKX'],
1250
+ [/kucoin/i, 'KuCoin'],
1251
+ [/bybit/i, 'Bybit'],
1252
+ [/bitget/i, 'Bitget'],
1253
+ [/bittrex/i, 'Bittrex'],
1254
+ [/upbit/i, 'Upbit'],
1255
+ [/coinbase/i, 'Coinbase'],
1256
+ [/kraken/i, 'Kraken'],
1257
+ [/bitfinex/i, 'Bitfinex'],
1258
+ [/bitstamp/i, 'Bitstamp'],
1259
+ [/coinex/i, 'CoinEx'],
1260
+ [/hitbtc/i, 'HitBTC'],
1261
+ [/crypto\.?com/i, 'Crypto.com'],
1262
+ [/luno/i, 'Luno'],
1263
+ [/btcturk/i, 'BTC Turk'],
1264
+ [/indodax/i, 'Indodax'],
1265
+ ];
1266
+ const CEX_HINT = /(^|[-_.\s])(exchange|cex|hot-?wallet|cold-?wallet|deposit|withdrawal|payout|transfers?)([-_.\s]|$)/i;
1267
+ function detectExchange(name) {
1268
+ if (!name)
1269
+ return undefined;
1270
+ for (const [pattern, label] of CEX_BRANDS) {
1271
+ if (pattern.test(name))
1272
+ return label;
1273
+ }
1274
+ if (CEX_HINT.test(name))
1275
+ return 'CEX?';
1276
+ return undefined;
1277
+ }
1278
+ // ---------------------------------------------------------------------------
1279
+ // Terminal rendering
1280
+ // ---------------------------------------------------------------------------
1281
+ function renderTerminal(report, opts) {
1282
+ const precision = report.asset.precision;
1283
+ const symbol = report.asset.symbol;
1284
+ const supply = report.supply.current;
1285
+ const money = (value) => formatUnits(value, precision);
1286
+ const pct = (value, whole = supply) => sharePercent(value, whole);
1287
+ const c = (code, text) => `${code}${text}${colors.reset}`;
1288
+ console.log();
1289
+ console.log(c(colors.bold + colors.cyan, ` ${symbol} distribution · block ${formatInteger(BigInt(report.blockNum))}`));
1290
+ console.log(c(colors.gray, ` ${report.node} · ${report.blockTime} · ${report.generatedAt}`));
1291
+ console.log(c(colors.gray, ` ${symbol} (${report.asset.id}) · precision ${precision} · issuer ${report.asset.issuerName ?? report.asset.issuer}`
1292
+ + `${report.asset.isBitasset ? ' · MPA' : ''}${report.asset.poolShareAssetId ? ' · pool share asset' : ''}`));
1293
+ console.log();
1294
+ console.log(` Total supply ${c(colors.white, money(supply))}`);
1295
+ console.log(` Free balances ${c(colors.buy, money(report.free))} ${pct(report.free)}`);
1296
+ console.log(` Locked ${c(colors.sell, money(report.locked))} ${pct(report.locked)}`);
1297
+ console.log(` Float (supply−lock)${c(colors.white, money(report.float))} ${pct(report.float)}`);
1298
+ console.log(` Blinded ${money(report.supply.confidential)} ${pct(report.supply.confidential)}`);
1299
+ if (report.locked > 0n && report.float > 0n) {
1300
+ console.log(c(colors.gray, ` locked / float ${(Number(report.locked * 10000n / report.float) / 10_000).toFixed(2)}×`));
1301
+ }
1302
+ const section = (title) => {
1303
+ console.log();
1304
+ console.log(c(colors.bold + colors.yellow, ` ── ${title} ${'─'.repeat(Math.max(0, 70 - title.length))}`));
1305
+ };
1306
+ section('Where the token sits');
1307
+ console.log(c(colors.gray, ` ${padEnd('Category', 26)} ${padStart(symbol, 18)} ${padStart('% supply', 10)} ${padStart('% float', 10)}`));
1308
+ for (const bucket of report.buckets) {
1309
+ console.log(` ${padEnd(bucket.label.slice(0, 26), 26)} ${padStart(money(bucket.amount), 18)} `
1310
+ + `${padStart(pct(bucket.amount), 10)} ${padStart(pct(bucket.amount, report.float), 10)}`);
1311
+ }
1312
+ section(`Liquidity by counterpart (${report.liquidityByCounterpart.length} assets)`);
1313
+ console.log(c(colors.gray, ` ${padEnd('Counterpart', 18)} ${padStart('POOLS', 16)} ${padStart('ORDERS', 16)} `
1314
+ + `${padStart('TOTAL', 16)} ${padStart('% LOCKED LIQ', 12)} ${padStart('% SUPPLY', 10)}`));
1315
+ for (const row of report.liquidityByCounterpart.slice(0, Math.max(opts.detail, 15))) {
1316
+ console.log(` ${padEnd(row.symbol.slice(0, 18), 18)} ${padStart(money(row.poolAmount), 16)} `
1317
+ + `${padStart(money(row.orderAmount), 16)} ${padStart(money(row.amount), 16)} `
1318
+ + `${padStart(pct(row.amount, report.pools.total + report.orders.total), 12)} `
1319
+ + `${padStart(pct(row.amount), 10)}`);
1320
+ }
1321
+ console.log(c(colors.gray, ` pools ${money(report.pools.total)} in ${report.pools.count} pool(s) · `
1322
+ + `orders ${money(report.orders.total)} in ${report.orders.orderCount} order(s)`));
1323
+ section('3% price-change liquidity');
1324
+ console.log(c(colors.gray, ' sellable = token sold until price −3% · buyable = token bought until +3%'));
1325
+ console.log(c(colors.gray, ' per market: orderbook + pool combined · each venue from its own mid/spot · OB% is token-based'));
1326
+ const downToken = report.depth.downToken;
1327
+ const upToken = report.depth.upToken;
1328
+ console.log(` Sellable within −3%: ${c(colors.sell, money(downToken))} ${symbol} = `
1329
+ + `${c(colors.bold, pct(downToken))} of supply`);
1330
+ console.log(c(colors.gray, ` orderbook ${money(report.depth.downOrderbookToken)} (${pct(report.depth.downOrderbookToken)}) + `
1331
+ + `pools ${money(report.depth.downPoolToken)} (${pct(report.depth.downPoolToken)})`));
1332
+ console.log(` Buyable within +3%: ${c(colors.buy, money(upToken))} ${symbol} = `
1333
+ + `${c(colors.bold, pct(upToken))} of supply`);
1334
+ console.log(c(colors.gray, ` orderbook ${money(report.depth.upOrderbookToken)} (${pct(report.depth.upOrderbookToken)}) + `
1335
+ + `pools ${money(report.depth.upPoolToken)} (${pct(report.depth.upPoolToken)})`));
1336
+ console.log(c(colors.gray, ' aggregate measure, not one simultaneous trade: venues are measured independently at their own prices'));
1337
+ const depthRows = report.liquidityByCounterpart
1338
+ .map((row) => ({
1339
+ row,
1340
+ down: row.obDownToken + row.poolDownToken,
1341
+ up: row.obUpToken + row.poolUpToken,
1342
+ }))
1343
+ .filter((item) => item.down > 0n || item.up > 0n)
1344
+ .sort((a, b) => compareDesc(a.down, b.down));
1345
+ const rowLimit = Math.max(opts.detail, 10);
1346
+ const shownRows = depthRows.slice(0, rowLimit);
1347
+ const restRows = depthRows.slice(rowLimit);
1348
+ const restDown = restRows.reduce((acc, item) => acc + item.down, 0n);
1349
+ const restUp = restRows.reduce((acc, item) => acc + item.up, 0n);
1350
+ const restObDown = restRows.reduce((acc, item) => acc + item.row.obDownToken, 0n);
1351
+ const restObUp = restRows.reduce((acc, item) => acc + item.row.obUpToken, 0n);
1352
+ console.log();
1353
+ console.log(c(colors.gray, ` ${padEnd('Counterpart', 18)} ${padStart('SELLABLE −3%', 20)} ${padStart('% SUPPLY', 9)} ${padStart('OB%', 7)} `
1354
+ + `${padStart('BUYABLE +3%', 20)} ${padStart('% SUPPLY', 9)} ${padStart('OB%', 7)}`));
1355
+ const printDepthLine = (label, down, downOb, up, upOb) => {
1356
+ console.log(` ${padEnd(label.slice(0, 18), 18)} ${padStart(money(down), 20)} ${padStart(pct(down), 9)} `
1357
+ + `${padStart(sharePercent(downOb, down), 7)} ${padStart(money(up), 20)} ${padStart(pct(up), 9)} `
1358
+ + `${padStart(sharePercent(upOb, up), 7)}`);
1359
+ };
1360
+ for (const item of shownRows) {
1361
+ printDepthLine(item.row.symbol, item.down, item.row.obDownToken, item.up, item.row.obUpToken);
1362
+ }
1363
+ if (restRows.length > 0) {
1364
+ printDepthLine(`Other ${restRows.length} markets`, restDown, restObDown, restUp, restObUp);
1365
+ }
1366
+ if (depthRows.length === 0) {
1367
+ console.log(c(colors.gray, ' no pool or orderbook depth inside ±3%'));
1368
+ }
1369
+ section(`Top holders (${report.holders.count} accounts, rich list)`);
1370
+ if (report.holders.top.length === 0) {
1371
+ console.log(c(colors.gray, ' no holder data (asset_api unavailable)'));
1372
+ }
1373
+ else {
1374
+ for (const row of report.holders.top) {
1375
+ console.log(` #${String(row.rank).padStart(3)} ${padEnd((row.name ?? row.id).slice(0, 28), 28)} `
1376
+ + `${padStart(money(row.amount), 20)} ${padStart(pct(row.amount), 8)}`
1377
+ + (row.exchange ? c(colors.gray, ` [${row.exchange}]`) : ''));
1378
+ }
1379
+ if (report.holders.concentration.length > 0) {
1380
+ console.log(c(colors.gray, ' concentration:'));
1381
+ for (const row of report.holders.concentration) {
1382
+ console.log(c(colors.gray, ` top ${String(row.top).padStart(5)} = ${money(row.amount)} (${pct(row.amount)})`));
1383
+ }
1384
+ }
1385
+ }
1386
+ if (report.vesting.count > 0) {
1387
+ section('Vesting balances');
1388
+ for (const row of report.vesting.byType) {
1389
+ console.log(` ${padEnd(row.type.slice(0, 24), 24)} ${String(row.count).padStart(6)} object(s) `
1390
+ + `${padStart(money(row.amount), 20)} ${padStart(pct(row.amount), 8)}`);
1391
+ }
1392
+ if (report.vesting.hitLimit) {
1393
+ console.log(c(colors.sell, ` warning: scan reached --vesting-max ${opts.vestingMax}; totals may be incomplete`));
1394
+ }
1395
+ }
1396
+ if (report.credit.offersCount > 0 || report.credit.collateralCount > 0 || report.credit.debtCount > 0) {
1397
+ section('P2P credit');
1398
+ console.log(c(colors.gray, ` offers ${money(report.credit.offersTotal)} in ${report.credit.offersCount} fund(s) · `
1399
+ + `deal collateral ${money(report.credit.collateralTotal)} in ${report.credit.collateralCount} deal(s) · `
1400
+ + `debt outstanding ${money(report.credit.debtTotal)} in ${report.credit.debtCount} deal(s) (not locked)`));
1401
+ }
1402
+ if (report.samet.count > 0 || report.htlcs.count > 0) {
1403
+ section('Other protocol locks');
1404
+ if (report.samet.count > 0) {
1405
+ console.log(` SameT funds ${money(report.samet.total)} in ${report.samet.count} fund(s)`);
1406
+ }
1407
+ if (report.htlcs.count > 0) {
1408
+ console.log(` HTLC escrow ${money(report.htlcs.total)} in ${report.htlcs.count} HTLC(s)`);
1409
+ }
1410
+ }
1411
+ if (report.warnings.length > 0) {
1412
+ section('Warnings');
1413
+ for (const warning of report.warnings)
1414
+ console.log(c(colors.sell, ` • ${warning}`));
1415
+ }
1416
+ console.log();
1417
+ console.log(c(colors.gray, ` reconcile: free ${money(report.free)} + locked ${money(report.locked)} `
1418
+ + `+ blinded ${money(report.supply.confidential)} + other ${money(report.residual)} = ${money(supply)}`));
1419
+ }
1420
+ function groupSlices(slices, total) {
1421
+ const kept = [];
1422
+ let other = 0n;
1423
+ for (const slice of slices) {
1424
+ if (slice.value <= 0n)
1425
+ continue;
1426
+ if (shareFraction(slice.value, total) < 0.01)
1427
+ other += slice.value;
1428
+ else
1429
+ kept.push(slice);
1430
+ }
1431
+ if (other > 0n)
1432
+ kept.push({ label: 'Other (smaller buckets)', value: other, color: '#6e7681' });
1433
+ return kept;
1434
+ }
1435
+ function donutSvg(slices, total, centerLabel, centerValue, unit, precision) {
1436
+ const radius = 42;
1437
+ const circumference = 2 * Math.PI * radius;
1438
+ let offset = 0;
1439
+ const parts = [];
1440
+ for (const slice of slices) {
1441
+ const length = circumference * shareFraction(slice.value, total);
1442
+ const pct = sharePercent(slice.value, total);
1443
+ parts.push(`<circle cx="50" cy="50" r="${radius}" fill="none" stroke="${slice.color}" stroke-width="15"`
1444
+ + ` stroke-dasharray="${length.toFixed(3)} ${(circumference - length).toFixed(3)}"`
1445
+ + ` stroke-dashoffset="${(-offset).toFixed(3)}" transform="rotate(-90 50 50)">`
1446
+ + `<title>${esc(slice.label)}: ${esc(formatUnits(slice.value, precision))} ${esc(unit)} (${pct})</title>`
1447
+ + '</circle>');
1448
+ offset += length;
1449
+ }
1450
+ return `<svg viewBox="0 0 100 100" role="img" aria-label="${esc(unit)} supply composition" class="donut">
1451
+ <circle cx="50" cy="50" r="${radius}" fill="none" stroke="#21262d" stroke-width="15"/>
1452
+ ${parts.join('')}
1453
+ <text x="50" y="44.5" text-anchor="middle" class="donut-kicker">${esc(centerLabel)}</text>
1454
+ <text x="50" y="55" text-anchor="middle" class="donut-value">${esc(centerValue)}</text>
1455
+ <text x="50" y="62" text-anchor="middle" class="donut-unit">${esc(unit)}</text>
1456
+ </svg>`;
1457
+ }
1458
+ function htmlTable(headers, rows, numericFrom = 1) {
1459
+ if (rows.length === 0)
1460
+ return '<p class="muted">No data.</p>';
1461
+ const head = headers.map((h, i) => `<th class="${i >= numericFrom ? 'num' : ''}">${esc(h)}</th>`).join('');
1462
+ const body = rows.map((row) => `<tr>${row.map((cell, i) => `<td class="${i >= numericFrom ? 'num' : ''}">${cell}</td>`).join('')}</tr>`).join('');
1463
+ return `<div class="table-wrap"><table><thead><tr>${head}</tr></thead><tbody>${body}</tbody></table></div>`;
1464
+ }
1465
+ function renderHtml(report) {
1466
+ const precision = report.asset.precision;
1467
+ const symbol = report.asset.symbol;
1468
+ const supply = report.supply.current;
1469
+ const money = (value) => formatUnits(value, precision);
1470
+ const pct = (value, whole = supply) => sharePercent(value, whole);
1471
+ const kpiValue = (value) => {
1472
+ const full = money(value);
1473
+ return full.length > 14 ? compactUnits(value, precision) : full;
1474
+ };
1475
+ const fmtAsset = (value, assetPrecision, assetSymbol) => `${formatUnits(value, assetPrecision)} ${assetSymbol}`;
1476
+ const allSlices = [
1477
+ ...report.buckets.map((bucket) => ({ label: bucket.label, value: bucket.amount, color: bucket.color })),
1478
+ ];
1479
+ const slices = groupSlices(allSlices, supply);
1480
+ const legend = slices.map((slice) => `<li>
1481
+ <span class="dot" style="background:${slice.color}"></span>
1482
+ <span class="legend-label">${esc(slice.label)}</span>
1483
+ <span class="legend-value">${money(slice.value)}</span>
1484
+ <span class="legend-share">${pct(slice.value)}</span>
1485
+ </li>`).join('');
1486
+ const maxBucket = report.buckets.reduce((max, bucket) => (bucket.amount > max ? bucket.amount : max), 0n);
1487
+ const bars = report.buckets.filter((bucket) => bucket.amount !== 0n).map((bucket) => `<div class="bar-row">
1488
+ <span class="bar-label"><span class="dot" style="background:${bucket.color}"></span>${esc(bucket.label)}</span>
1489
+ <span class="bar-track"><span class="bar-fill" style="width:${(shareFraction(bucket.amount, maxBucket) * 100).toFixed(2)}%;background:${bucket.color}"></span></span>
1490
+ <span class="bar-amount">${money(bucket.amount)}</span>
1491
+ <span class="bar-share">${pct(bucket.amount)}</span>
1492
+ </div>`).join('');
1493
+ const bucketRows = report.buckets.map((bucket) => [
1494
+ `<span class="dot" style="background:${bucket.color};margin-right:8px"></span>${esc(bucket.label)}`,
1495
+ money(bucket.amount),
1496
+ pct(bucket.amount),
1497
+ pct(bucket.amount, report.float),
1498
+ `<span class="muted">${esc(bucket.note)}</span>`,
1499
+ ]);
1500
+ const liquidityRows = report.liquidityByCounterpart.map((row) => [
1501
+ esc(row.symbol),
1502
+ money(row.poolAmount),
1503
+ money(row.orderAmount),
1504
+ money(row.amount),
1505
+ pct(row.amount, report.pools.total + report.orders.total),
1506
+ pct(row.amount),
1507
+ ]);
1508
+ const holderRows = report.holders.top.map((row) => [
1509
+ String(row.rank),
1510
+ `${esc(row.name ?? row.id)}${row.exchange ? ` <span class="tag cex">${esc(row.exchange)}</span>` : ''}`,
1511
+ esc(row.id),
1512
+ money(row.amount),
1513
+ pct(row.amount),
1514
+ ]);
1515
+ const concentrationRows = report.holders.concentration.map((row) => [
1516
+ `Top ${row.top}`,
1517
+ String(row.count),
1518
+ money(row.amount),
1519
+ pct(row.amount),
1520
+ ]);
1521
+ const vestingRows = report.vesting.byType.map((row) => [
1522
+ esc(row.type), String(row.count), money(row.amount), pct(row.amount),
1523
+ ]);
1524
+ const offerRows = report.credit.offers.map((row) => [
1525
+ esc(row.accountName ?? row.account),
1526
+ esc(row.id),
1527
+ fmtAsset(row.collateralAmount, row.collateralPrecision, row.collateralSymbol),
1528
+ pct(row.collateralAmount),
1529
+ ]);
1530
+ const collateralRows = report.credit.collateralDeals.map((row) => [
1531
+ esc(row.accountName ?? row.account),
1532
+ fmtAsset(row.collateralAmount, row.collateralPrecision, row.collateralSymbol),
1533
+ `${fmtAsset(row.debtAmount, row.debtPrecision, row.debtSymbol)} debt`,
1534
+ esc(row.id),
1535
+ ]);
1536
+ const debtRows = report.credit.debtDeals.map((row) => [
1537
+ esc(row.accountName ?? row.account),
1538
+ fmtAsset(row.debtAmount, row.debtPrecision, row.debtSymbol),
1539
+ fmtAsset(row.collateralAmount, row.collateralPrecision, row.collateralSymbol),
1540
+ esc(row.id),
1541
+ ]);
1542
+ const liquidityTotal = report.pools.total + report.orders.total;
1543
+ const liquiditySlices = groupSlices(report.liquidityByCounterpart.map((row, index) => ({
1544
+ label: row.symbol, value: row.amount, color: COLORS[index % COLORS.length],
1545
+ })), liquidityTotal);
1546
+ const liquidityLegend = liquiditySlices.map((slice) => `<li>
1547
+ <span class="dot" style="background:${slice.color}"></span>
1548
+ <span class="legend-label">${esc(slice.label)}</span>
1549
+ <span class="legend-value">${compactUnits(slice.value, precision)}</span>
1550
+ <span class="legend-share">${sharePercent(slice.value, liquidityTotal)}</span>
1551
+ </li>`).join('');
1552
+ const poolShare = shareFraction(report.pools.total, liquidityTotal);
1553
+ const orderShare = shareFraction(report.orders.total, liquidityTotal);
1554
+ const depthMarkets = report.liquidityByCounterpart
1555
+ .map((row) => ({
1556
+ row,
1557
+ down: row.obDownToken + row.poolDownToken,
1558
+ up: row.obUpToken + row.poolUpToken,
1559
+ }))
1560
+ .filter((item) => item.down > 0n || item.up > 0n)
1561
+ .sort((a, b) => compareDesc(a.down, b.down));
1562
+ const depthTop = depthMarkets.slice(0, 15);
1563
+ const depthRest = depthMarkets.slice(15);
1564
+ const restDepth = depthRest.reduce((acc, item) => ({
1565
+ down: acc.down + item.down,
1566
+ up: acc.up + item.up,
1567
+ obDown: acc.obDown + item.row.obDownToken,
1568
+ obUp: acc.obUp + item.row.obUpToken,
1569
+ }), { down: 0n, up: 0n, obDown: 0n, obUp: 0n });
1570
+ const sellableRows = depthTop.map((item) => [
1571
+ `${esc(item.row.symbol)}${item.row.obTruncated ? ' <span class="tag">capped</span>' : ''}`,
1572
+ money(item.down),
1573
+ pct(item.down),
1574
+ sharePercent(item.row.obDownToken, item.down),
1575
+ money(item.up),
1576
+ pct(item.up),
1577
+ sharePercent(item.row.obUpToken, item.up),
1578
+ ]);
1579
+ if (depthRest.length > 0) {
1580
+ sellableRows.push([
1581
+ `Other ${depthRest.length} markets`,
1582
+ money(restDepth.down),
1583
+ pct(restDepth.down),
1584
+ sharePercent(restDepth.obDown, restDepth.down),
1585
+ money(restDepth.up),
1586
+ pct(restDepth.up),
1587
+ sharePercent(restDepth.obUp, restDepth.up),
1588
+ ]);
1589
+ }
1590
+ const warnings = report.warnings.length > 0
1591
+ ? `<section class="card warn"><h2>Warnings</h2><ul>${report.warnings.map((w) => `<li>${esc(w)}</li>`).join('')}</ul></section>`
1592
+ : '';
1593
+ const vestingSection = report.vesting.count > 0 ? `<section class="card">
1594
+ <div class="head-row"><h2>Vesting balances</h2><span class="hint">1.13.x scan to ${formatInteger(BigInt(report.vesting.scannedTo))}</span></div>
1595
+ ${htmlTable(['Type', 'Count', symbol, 'Share of supply'], vestingRows, 1)}
1596
+ </section>` : '';
1597
+ const creditSection = (report.credit.offersCount + report.credit.collateralCount + report.credit.debtCount) > 0
1598
+ ? `<section class="card">
1599
+ <div class="head-row"><h2>P2P credit</h2><span class="hint">offers are locked; deal debt is owed, not locked</span></div>
1600
+ <h3 class="subhead">Credit offers (${money(report.credit.offersTotal)} in ${report.credit.offersCount} fund(s))</h3>
1601
+ ${htmlTable(['Owner', 'Offer', `${symbol} offered`, 'Share of supply'], offerRows, 2)}
1602
+ <h3 class="subhead">Deals using ${esc(symbol)} as collateral (${money(report.credit.collateralTotal)} locked)</h3>
1603
+ ${htmlTable(['Borrower', `Collateral (${symbol})`, 'Debt', 'Deal'], collateralRows, 1)}
1604
+ <h3 class="subhead">Deals with ${esc(symbol)} debt outstanding (${money(report.credit.debtTotal)} not locked)</h3>
1605
+ ${htmlTable(['Borrower', 'Debt', 'Collateral', 'Deal'], debtRows, 1)}
1606
+ </section>` : '';
1607
+ return `<!DOCTYPE html>
1608
+ <html lang="en">
1609
+ <head>
1610
+ <meta charset="utf-8"/>
1611
+ <meta name="viewport" content="width=device-width, initial-scale=1"/>
1612
+ <title>${esc(symbol)} distribution · block ${formatInteger(BigInt(report.blockNum))}</title>
1613
+ <style>
1614
+ :root{--bg:#0b0e14;--panel:#11161d;--panel-2:#161b22;--border:#242c38;--text:#d1d5db;--muted:#8b949e;--bright:#f0f6fc;--accent:#5eb0ef;--warn:#f0883e}
1615
+ *{box-sizing:border-box}
1616
+ html,body{margin:0;padding:0;background:var(--bg);color:var(--text);font-family:'Segoe UI',system-ui,-apple-system,sans-serif}
1617
+ body{padding:28px 22px 52px;max-width:1320px;margin:0 auto;line-height:1.45}
1618
+ h1,h2,h3{margin:0;font-weight:600;color:var(--bright)}
1619
+ h1{font-size:26px;letter-spacing:.2px}
1620
+ h2{font-size:15px;text-transform:uppercase;letter-spacing:1.3px;color:var(--muted);margin-bottom:14px}
1621
+ a{color:var(--accent)}
1622
+ .sub{color:var(--muted);font-size:13px;margin-top:6px;font-variant-numeric:tabular-nums}
1623
+ .hero{display:flex;justify-content:space-between;align-items:flex-end;gap:18px;flex-wrap:wrap;margin-bottom:22px}
1624
+ .badge{display:inline-block;padding:3px 9px;border:1px solid var(--border);border-radius:999px;font-size:11px;color:var(--muted);background:var(--panel)}
1625
+ .kpis{display:grid;grid-template-columns:repeat(auto-fit,minmax(190px,1fr));gap:14px;margin-bottom:22px}
1626
+ .kpi{background:linear-gradient(180deg,var(--panel-2),var(--panel));border:1px solid var(--border);border-radius:12px;padding:16px 18px}
1627
+ .kpi .k{font-size:11px;text-transform:uppercase;letter-spacing:1.1px;color:var(--muted)}
1628
+ .kpi .v{font-size:23px;font-weight:600;color:var(--bright);margin-top:5px;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
1629
+ .kpi .s{font-size:12px;color:var(--muted);margin-top:2px}
1630
+ .grid{display:grid;grid-template-columns:minmax(320px,420px) 1fr;gap:18px;margin-bottom:18px}
1631
+ @media(max-width:900px){.grid{grid-template-columns:1fr}}
1632
+ .card{background:var(--panel);border:1px solid var(--border);border-radius:14px;padding:20px 22px}
1633
+ .card.warn{border-color:#5c3a12;background:#1a1207;margin-bottom:18px}
1634
+ .card.warn h2{color:var(--warn)}
1635
+ .card.warn li{color:#f3c99a}
1636
+ .donut{width:100%;height:auto;max-height:380px;display:block}
1637
+ .donut-kicker{fill:var(--muted);font-size:4.4px;text-transform:uppercase;letter-spacing:.9px}
1638
+ .donut-value{fill:var(--bright);font-size:9px;font-weight:600;font-variant-numeric:tabular-nums}
1639
+ .donut-unit{fill:var(--muted);font-size:4.2px;letter-spacing:1px}
1640
+ .legend{list-style:none;margin:18px 0 0;padding:0;font-size:12.5px}
1641
+ .legend li{display:grid;grid-template-columns:12px 1fr auto 62px;gap:8px;align-items:center;padding:5px 0;border-top:1px solid #1c222b}
1642
+ .legend li:first-child{border-top:0}
1643
+ .dot{width:10px;height:10px;border-radius:3px;display:inline-block;flex:none}
1644
+ .legend-label{color:var(--text)}
1645
+ .legend-value{font-variant-numeric:tabular-nums;color:var(--bright)}
1646
+ .legend-share{text-align:right;color:var(--muted);font-variant-numeric:tabular-nums}
1647
+ .bars{display:flex;flex-direction:column;gap:9px}
1648
+ .bar-row{display:grid;grid-template-columns:minmax(190px,270px) 1fr 150px 62px;gap:12px;align-items:center;font-size:12.5px}
1649
+ .bar-label{display:flex;align-items:center;gap:8px;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1650
+ .bar-track{height:13px;background:#1b212b;border-radius:7px;overflow:hidden;border:1px solid #222b37}
1651
+ .bar-fill{display:block;height:100%;border-radius:7px;min-width:2px}
1652
+ .bar-amount{text-align:right;font-variant-numeric:tabular-nums;color:var(--bright)}
1653
+ .bar-share{text-align:right;font-variant-numeric:tabular-nums;color:var(--muted)}
1654
+ @media(max-width:760px){.bar-row{grid-template-columns:1fr 90px 54px}.bar-track{display:none}}
1655
+ .table-wrap{overflow-x:auto}
1656
+ table{width:100%;border-collapse:collapse;font-size:12.5px}
1657
+ th,td{text-align:left;padding:7px 10px;border-bottom:1px solid #1c222b;white-space:nowrap}
1658
+ th{font-size:10.5px;text-transform:uppercase;letter-spacing:.9px;color:var(--muted);font-weight:600}
1659
+ td.num,th.num{text-align:right;font-variant-numeric:tabular-nums}
1660
+ tbody tr:hover{background:#151b23}
1661
+ .tag{display:inline-block;padding:1px 6px;margin-left:6px;border-radius:999px;font-size:10px;background:#10263a;color:#7cc4ff;border:1px solid #245273}
1662
+ .muted{color:var(--muted);font-size:12.5px}
1663
+ .subhead{margin:18px 0 8px;font-size:12px;text-transform:uppercase;letter-spacing:.9px;color:var(--muted)}
1664
+ footer{margin-top:24px;color:var(--muted);font-size:11.5px;border-top:1px solid var(--border);padding-top:14px}
1665
+ footer p{margin:4px 0}
1666
+ .stack{display:grid;gap:18px}
1667
+ .head-row{display:flex;justify-content:space-between;gap:12px;align-items:baseline;margin-bottom:10px}
1668
+ .head-row .hint{font-size:11.5px;color:var(--muted)}
1669
+ </style>
1670
+ </head>
1671
+ <body>
1672
+ <div class="hero">
1673
+ <div>
1674
+ <h1>${esc(symbol)} token distribution</h1>
1675
+ <div class="sub">block ${esc(formatInteger(BigInt(report.blockNum)))} · ${esc(report.blockTime)} · ${esc(report.node)}</div>
1676
+ <div class="sub">${esc(symbol)} (${esc(report.asset.id)}) · precision ${precision} · issuer ${esc(report.asset.issuerName ?? report.asset.issuer)}${report.asset.isBitasset ? ' · MPA' : ''}</div>
1677
+ </div>
1678
+ <div><span class="badge">generated ${esc(report.generatedAt)}</span> <span class="badge">${report.orders.scannedAssets} assets scanned</span></div>
1679
+ </div>
1680
+
1681
+ ${warnings}
1682
+
1683
+ <div class="kpis">
1684
+ <div class="kpi"><div class="k">Total supply</div><div class="v">${kpiValue(supply)}</div><div class="s">${money(supply)} ${esc(symbol)} in existence</div></div>
1685
+ <div class="kpi"><div class="k">Free balances</div><div class="v">${kpiValue(report.free)}</div><div class="s">${pct(report.free)} · ${report.holders.count} accounts</div></div>
1686
+ <div class="kpi"><div class="k">Locked</div><div class="v">${kpiValue(report.locked)}</div><div class="s">${pct(report.locked)} of supply</div></div>
1687
+ <div class="kpi"><div class="k">Float</div><div class="v">${kpiValue(report.float)}</div><div class="s">${pct(report.float)} · supply − locked</div></div>
1688
+ <div class="kpi"><div class="k">Liquidity</div><div class="v">${kpiValue(report.pools.total + report.orders.total)}</div><div class="s">pools ${kpiValue(report.pools.total)} · orders ${kpiValue(report.orders.total)}</div></div>
1689
+ <div class="kpi"><div class="k">Sellable within −3%</div><div class="v">${kpiValue(report.depth.downToken)}</div><div class="s">${pct(report.depth.downToken)} of supply · OB ${pct(report.depth.downOrderbookToken)} + pool ${pct(report.depth.downPoolToken)}</div></div>
1690
+ </div>
1691
+
1692
+ <div class="grid">
1693
+ <section class="card">
1694
+ <h2>Where the ${esc(symbol)} is</h2>
1695
+ ${donutSvg(slices, supply, 'total supply', compactUnits(supply, precision), symbol, precision)}
1696
+ <ul class="legend">${legend}</ul>
1697
+ </section>
1698
+ <section class="card">
1699
+ <div class="head-row"><h2>Bucket sizes</h2><span class="hint">bars scaled to the largest bucket</span></div>
1700
+ <div class="bars">${bars}</div>
1701
+ <p class="muted" style="margin-top:16px">
1702
+ Float = supply − locked. Locked covers limit orders, pools, vesting, P2P offers/collateral,
1703
+ SameT funds, HTLC escrow and accumulated market fees. Blinded balances are invisible but
1704
+ part of the float; "Other" only appears when the buckets do not reconcile to supply.
1705
+ </p>
1706
+ </section>
1707
+ </div>
1708
+
1709
+ <div class="stack">
1710
+ <section class="card">
1711
+ <h2>Category breakdown</h2>
1712
+ ${htmlTable(['Category', symbol, 'Share of supply', 'Share of float', 'What it is'], bucketRows, 1)}
1713
+ </section>
1714
+
1715
+ <section class="card">
1716
+ <div class="head-row"><h2>Liquidity by counterpart</h2><span class="hint">pools + token sell orders, grouped by the asset on the other side</span></div>
1717
+ ${htmlTable(['Counterpart', 'Pools', 'Limit orders', 'Total', 'Share of liquidity', 'Share of supply'], liquidityRows, 1)}
1718
+ <p class="muted" style="margin-top:10px">
1719
+ ${report.pools.count} pool(s) holding ${money(report.pools.total)} ${esc(symbol)} ·
1720
+ ${report.orders.orderCount} sell order(s) holding ${money(report.orders.total)} ${esc(symbol)}
1721
+ ${report.orders.scanned ? `· scanned ${report.orders.scannedAssets} assets` : '· order scan skipped'}
1722
+ ${report.orders.truncatedPairs > 0 ? `· ${report.orders.truncatedPairs} market(s) truncated` : ''}
1723
+ ${report.orders.failedPairs > 0 ? `· ${report.orders.failedPairs} market(s) failed` : ''}.
1724
+ </p>
1725
+ </section>
1726
+
1727
+ <section class="card">
1728
+ <div class="head-row"><h2>Liquidity distribution by counterpart</h2><span class="hint">pools + token sell orders · token units</span></div>
1729
+ ${liquidityTotal > 0n ? `<div class="grid" style="margin-bottom:0;grid-template-columns:minmax(280px,360px) 1fr">
1730
+ <div>
1731
+ ${donutSvg(liquiditySlices, liquidityTotal, 'liquidity', compactUnits(liquidityTotal, precision), symbol, precision)}
1732
+ </div>
1733
+ <div>
1734
+ <div class="flow-bar" title="pool vs orderbook share of token liquidity">
1735
+ <span style="width:${(poolShare * 100).toFixed(2)}%;background:#3fb950;color:#0b0e14">pools ${compactUnits(report.pools.total, precision)} (${(poolShare * 100).toFixed(1)}%)</span>
1736
+ <span style="width:${(orderShare * 100).toFixed(2)}%;background:#f0883e;color:#1a1207">orders ${compactUnits(report.orders.total, precision)} (${(orderShare * 100).toFixed(1)}%)</span>
1737
+ </div>
1738
+ <ul class="legend">${liquidityLegend}</ul>
1739
+ </div>
1740
+ </div>` : '<p class="muted">No pool or orderbook liquidity found.</p>'}
1741
+ </section>
1742
+
1743
+ <section class="card">
1744
+ <div class="head-row"><h2>3% price-change liquidity</h2><span class="hint">orderbook + pool combined · token units</span></div>
1745
+ <div class="kpis" style="grid-template-columns:repeat(auto-fit,minmax(280px,1fr));margin:0 0 14px">
1746
+ <div class="kpi">
1747
+ <div class="k">Sellable within −3%</div>
1748
+ <div class="v">${kpiValue(report.depth.downToken)}</div>
1749
+ <div class="s">${pct(report.depth.downToken)} of supply · OB ${pct(report.depth.downOrderbookToken)} + pool ${pct(report.depth.downPoolToken)}</div>
1750
+ </div>
1751
+ <div class="kpi">
1752
+ <div class="k">Buyable within +3%</div>
1753
+ <div class="v">${kpiValue(report.depth.upToken)}</div>
1754
+ <div class="s">${pct(report.depth.upToken)} of supply · OB ${pct(report.depth.upOrderbookToken)} + pool ${pct(report.depth.upPoolToken)}</div>
1755
+ </div>
1756
+ </div>
1757
+ <p class="muted" style="margin:0 0 10px">
1758
+ <strong>Sellable</strong> = token sold until the price falls 3%; <strong>buyable</strong> = token bought until the
1759
+ price rises 3%. For every market the orderbook and constant-product pool contributions are added into one value.
1760
+ Each venue is measured from its own mid/spot, and pool depth is net of the pool taker fee. OB share is the
1761
+ token-based share of that combined value. Orderbook depth is capped by the node's per-side order limit.
1762
+ </p>
1763
+ ${sellableRows.length > 0
1764
+ ? htmlTable(['Counterpart', 'Sellable −3%', '% supply', 'OB share', 'Buyable +3%', '% supply', 'OB share'], sellableRows, 1)
1765
+ : '<p class="muted">No pool or orderbook depth inside ±3%.</p>'}
1766
+ <p class="muted" style="margin-top:10px">
1767
+ Aggregate measure, not one simultaneous trade: the same token cannot be sold in every market at once, so the
1768
+ totals are the sum of independent 3% moves per venue. Top 15 markets by sellable amount are shown; the remainder
1769
+ is aggregated into "Other markets".
1770
+ </p>
1771
+ </section>
1772
+
1773
+ <section class="card">
1774
+ <div class="head-row"><h2>Top holders</h2><span class="hint">asset_api rich list${report.holders.sourceNode ? ` · ${esc(report.holders.sourceNode)}` : ''}</span></div>
1775
+ <p class="muted" style="margin:0 0 10px">
1776
+ Top ${report.holders.count}${report.holders.totalCount !== null ? ` of ${report.holders.totalCount}` : ''} accounts hold
1777
+ ${money(report.holders.total)} ${esc(symbol)} (${pct(report.holders.total)} of supply).
1778
+ Exchange tags are name heuristics, not verified identities.
1779
+ </p>
1780
+ ${htmlTable(['#', 'Account', 'Id', symbol, 'Share of supply'], holderRows, 3)}
1781
+ ${concentrationRows.length > 0 ? `<h3 class="subhead">Concentration</h3>
1782
+ ${htmlTable(['Accounts', 'Count', symbol, 'Share of supply'], concentrationRows, 1)}` : ''}
1783
+ </section>
1784
+
1785
+ ${vestingSection}
1786
+ ${creditSection}
1787
+
1788
+ <section class="card">
1789
+ <h2>Asset info</h2>
1790
+ ${htmlTable(['Field', 'Value'], [
1791
+ ['Asset id', esc(report.asset.id)],
1792
+ ['Precision', String(precision)],
1793
+ ['Issuer', `${esc(report.asset.issuerName ?? report.asset.issuer)} (${esc(report.asset.issuer)})`],
1794
+ ['Max supply', report.asset.maxSupply !== null ? money(report.asset.maxSupply) : '—'],
1795
+ ['Market fee', `${report.asset.marketFeePercent.toFixed(2)}%`],
1796
+ ['Type', report.asset.isBitasset ? 'MPA (market-issued)' : 'UIA (user-issued)'],
1797
+ ['Pool share asset', report.asset.poolShareAssetId ? esc(report.asset.poolShareAssetId) : '—'],
1798
+ ['Accumulated fees', money(report.supply.accumulatedFees)],
1799
+ ['Blinded supply', money(report.supply.confidential)],
1800
+ ], 1)}
1801
+ </section>
1802
+ </div>
1803
+
1804
+ <footer>
1805
+ <p>Sources: bitshares-core 7.0.x database_api — <code>list_assets</code>, <code>get_liquidity_pools_by_one_asset</code>, <code>get_limit_orders</code>, <code>get_objects</code> (1.13.x), <code>get_credit_offers_by_asset</code>, <code>get_credit_deals_by_collateral_asset</code>, <code>get_credit_deals_by_debt_asset</code>, <code>get_samet_funds_by_asset</code>, <code>list_htlcs</code>${report.holders.sourceNode ? ', <code>asset_api::get_asset_holders</code>' : ''}.</p>
1806
+ <p>Read-only; no keys, no transactions. Limit-order totals are per market and capped by the node's per-side limit.</p>
1807
+ </footer>
1808
+ </body>
1809
+ </html>`;
1810
+ }
1811
+ // ---------------------------------------------------------------------------
1812
+ // Main
1813
+ // ---------------------------------------------------------------------------
1814
+ function htmlPathFor(report, opts) {
1815
+ if (!opts.html)
1816
+ return null;
1817
+ if (opts.html !== DEFAULT_HTML)
1818
+ return opts.html;
1819
+ const safe = report.asset.symbol.replace(/[^A-Za-z0-9._-]+/g, '_');
1820
+ return path.join(path.dirname(DEFAULT_HTML), `token-${safe}-distribution.html`);
1821
+ }
1822
+ async function main() {
1823
+ let opts;
1824
+ try {
1825
+ opts = parseArgs(process.argv.slice(2));
1826
+ }
1827
+ catch (e) {
1828
+ if (e instanceof UsageError) {
1829
+ console.error(`Error: ${e.message}\n`);
1830
+ console.error(HELP);
1831
+ process.exit(2);
1832
+ }
1833
+ throw e;
1834
+ }
1835
+ if (opts.help) {
1836
+ console.log(HELP);
1837
+ return;
1838
+ }
1839
+ const nodes = opts.nodes.length > 0 ? opts.nodes : [...NODE_MANAGEMENT.DEFAULT_NODES];
1840
+ const session = await openSession(nodes);
1841
+ try {
1842
+ const report = await collect(session, opts);
1843
+ clearProgress(!opts.json);
1844
+ const htmlPath = htmlPathFor(report, opts);
1845
+ if (htmlPath) {
1846
+ fs.mkdirSync(path.dirname(htmlPath), { recursive: true });
1847
+ fs.writeFileSync(htmlPath, renderHtml(report), 'utf8');
1848
+ }
1849
+ if (opts.json) {
1850
+ console.log(JSON.stringify({ ...report, html: htmlPath }, (_key, value) => {
1851
+ return typeof value === 'bigint' ? value.toString() : value;
1852
+ }, 2));
1853
+ }
1854
+ else {
1855
+ renderTerminal(report, opts);
1856
+ if (htmlPath)
1857
+ console.log(`\n HTML: ${htmlPath}`);
1858
+ }
1859
+ }
1860
+ finally {
1861
+ session.client.close();
1862
+ }
1863
+ }
1864
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
1865
+ main().catch((e) => {
1866
+ console.error(`\nError: ${e.message}`);
1867
+ process.exit(1);
1868
+ });
1869
+ }
1870
+ //# sourceMappingURL=token_distribution.js.map