@odatano/core 2.0.0-rc.2 → 2.0.0-rc.20

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 (132) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +251 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +139 -2
  4. package/@cds-models/CardanoIndexerService/index.js +18 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +224 -0
  6. package/@cds-models/CardanoODataService/index.js +27 -0
  7. package/@cds-models/CardanoSignService/index.d.ts +5 -2
  8. package/@cds-models/CardanoTransactionService/index.d.ts +9 -9
  9. package/@cds-models/odatano/cardano/index.d.ts +316 -0
  10. package/@cds-models/odatano/cardano/index.js +33 -0
  11. package/README.md +195 -136
  12. package/db/schema.cds +2121 -1633
  13. package/package.json +179 -173
  14. package/src/index.d.ts +10 -10
  15. package/src/index.js +24 -14
  16. package/src/plugin.js +39 -52
  17. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  18. package/srv/blockchain/backends/blockfrost-backend.js +45 -158
  19. package/srv/blockchain/backends/cardano-backend.d.ts +78 -158
  20. package/srv/blockchain/backends/cardano-backend.js +14 -5
  21. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  22. package/srv/blockchain/backends/koios-backend.js +292 -202
  23. package/srv/blockchain/backends/ogmios-backend.d.ts +59 -96
  24. package/srv/blockchain/backends/ogmios-backend.js +241 -153
  25. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  26. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  27. package/srv/blockchain/cardano-client.d.ts +50 -205
  28. package/srv/blockchain/cardano-client.js +80 -224
  29. package/srv/blockchain/cardano-indexer.d.ts +146 -244
  30. package/srv/blockchain/cardano-indexer.js +442 -285
  31. package/srv/blockchain/cardano-tx-builder.d.ts +19 -84
  32. package/srv/blockchain/cardano-tx-builder.js +21 -107
  33. package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
  34. package/srv/blockchain/crawler/certificate-backfill.js +150 -0
  35. package/srv/blockchain/crawler/crawler.d.ts +121 -53
  36. package/srv/blockchain/crawler/crawler.js +402 -82
  37. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  38. package/srv/blockchain/crawler/index.d.ts +5 -0
  39. package/srv/blockchain/crawler/index.js +35 -7
  40. package/srv/blockchain/crawler/sync-state.d.ts +44 -28
  41. package/srv/blockchain/crawler/sync-state.js +115 -43
  42. package/srv/blockchain/crawler/utxo-set-import.d.ts +69 -0
  43. package/srv/blockchain/crawler/utxo-set-import.js +269 -0
  44. package/srv/blockchain/ledger-state.d.ts +80 -0
  45. package/srv/blockchain/ledger-state.js +383 -0
  46. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  47. package/srv/blockchain/signing/cose-verifier.js +6 -12
  48. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  49. package/srv/blockchain/signing/external-signer.js +19 -122
  50. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  51. package/srv/blockchain/signing/hsm-signer.js +23 -63
  52. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  53. package/srv/blockchain/signing/signature-verifier.js +13 -54
  54. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  55. package/srv/blockchain/signing/submission-finalizer.js +16 -48
  56. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +71 -160
  57. package/srv/blockchain/transaction-building/buildooor-tx.js +185 -260
  58. package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
  59. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  60. package/srv/blockchain/wallet-worker/build-request.js +39 -23
  61. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  62. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  63. package/srv/blockchain/wallet-worker/index.js +2 -8
  64. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  65. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  66. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  67. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  68. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  69. package/srv/blockchain/wallet-worker/signers.js +3 -8
  70. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  71. package/srv/blockchain/wallet-worker/wallet-worker.js +34 -90
  72. package/srv/cardano-agent-service.cds +146 -0
  73. package/srv/cardano-agent-service.d.ts +2 -0
  74. package/srv/cardano-agent-service.js +12 -0
  75. package/srv/cardano-indexer-service.cds +164 -73
  76. package/srv/cardano-indexer-service.js +156 -11
  77. package/srv/cardano-service.cds +45 -0
  78. package/srv/cardano-service.js +38 -96
  79. package/srv/cardano-sign-service.cds +200 -180
  80. package/srv/cardano-sign-service.js +55 -173
  81. package/srv/cardano-tx-service.cds +32 -26
  82. package/srv/cardano-tx-service.js +133 -195
  83. package/srv/cardano-worker-service.js +7 -15
  84. package/srv/server.d.ts +28 -86
  85. package/srv/server.js +95 -128
  86. package/srv/utils/agent-grants-config.d.ts +37 -0
  87. package/srv/utils/agent-grants-config.js +138 -0
  88. package/srv/utils/agent-grants.d.ts +262 -0
  89. package/srv/utils/agent-grants.js +914 -0
  90. package/srv/utils/agent-token-auth.d.ts +16 -0
  91. package/srv/utils/agent-token-auth.js +78 -0
  92. package/srv/utils/backend-request-handler.d.ts +2 -16
  93. package/srv/utils/backend-request-handler.js +3 -18
  94. package/srv/utils/collections.d.ts +4 -8
  95. package/srv/utils/collections.js +4 -8
  96. package/srv/utils/const.d.ts +19 -68
  97. package/srv/utils/const.js +20 -69
  98. package/srv/utils/crypto.d.ts +3 -12
  99. package/srv/utils/crypto.js +5 -18
  100. package/srv/utils/db-indexes.d.ts +25 -0
  101. package/srv/utils/db-indexes.js +89 -0
  102. package/srv/utils/db-sanitize.d.ts +27 -0
  103. package/srv/utils/db-sanitize.js +85 -0
  104. package/srv/utils/error-codes.d.ts +18 -73
  105. package/srv/utils/error-codes.js +17 -70
  106. package/srv/utils/errors.d.ts +34 -178
  107. package/srv/utils/errors.js +55 -217
  108. package/srv/utils/liveness.d.ts +16 -0
  109. package/srv/utils/liveness.js +41 -0
  110. package/srv/utils/mappers.d.ts +82 -210
  111. package/srv/utils/mappers.js +272 -293
  112. package/srv/utils/network-context.js +2 -11
  113. package/srv/utils/pg-order-nulls.d.ts +14 -0
  114. package/srv/utils/pg-order-nulls.js +57 -0
  115. package/srv/utils/plutus-placeholders.d.ts +6 -18
  116. package/srv/utils/plutus-placeholders.js +6 -20
  117. package/srv/utils/rate-limiter.d.ts +46 -0
  118. package/srv/utils/rate-limiter.js +116 -0
  119. package/srv/utils/service-events.d.ts +2 -22
  120. package/srv/utils/service-events.js +3 -23
  121. package/srv/utils/signing-helper.d.ts +3 -18
  122. package/srv/utils/signing-helper.js +10 -32
  123. package/srv/utils/tx-build-helper.d.ts +18 -92
  124. package/srv/utils/tx-build-helper.js +32 -123
  125. package/srv/utils/tx-request-parsers.d.ts +14 -20
  126. package/srv/utils/tx-request-parsers.js +33 -20
  127. package/srv/utils/tx-utils.d.ts +4 -23
  128. package/srv/utils/tx-utils.js +12 -41
  129. package/srv/utils/types.d.ts +112 -169
  130. package/srv/utils/types.js +2 -6
  131. package/srv/utils/validators.d.ts +19 -89
  132. package/srv/utils/validators.js +31 -138
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.KoiosBackend = void 0;
7
+ exports.mapKoiosCertificates = mapKoiosCertificates;
7
8
  const cds_1 = __importDefault(require("@sap/cds"));
8
9
  const axios_1 = __importDefault(require("axios"));
9
10
  const backend_request_handler_1 = require("../../utils/backend-request-handler");
@@ -21,11 +22,8 @@ const KOIOS_URLS = {
21
22
  preprod: 'https://preprod.koios.rest/api/v1',
22
23
  };
23
24
  /**
24
- * Koios `reference_script` (with `_extended: true`) is an OBJECT
25
- * `{ hash, size, type, bytes, value }` — the previous `as string` cast handed
26
- * that object downstream and broke the v1.6.1 input-side refScript feature.
27
- * Returns the full script CBOR bytes when present (what the local Plutus eval
28
- * needs), falling back to the hash (resolved on-chain only).
25
+ * Koios `reference_script` (`_extended: true`) is an object `{ hash, size, type, bytes, value }`.
26
+ * Returns the full script CBOR when present (needed for local Plutus eval), else the hash.
29
27
  */
30
28
  function koiosRefScriptBytes(ref) {
31
29
  if (!ref)
@@ -44,28 +42,17 @@ function koiosRefScriptHash(ref) {
44
42
  const obj = ref;
45
43
  return obj.hash || null;
46
44
  }
47
- /**
48
- * Sort Koios /address_txs rows newest-first. Koios gives no ordering guarantee —
49
- * a bare `slice(0, limit)` returned ARBITRARY rather than recent transactions
50
- * (Blockfrost requests `order: 'desc'` for the same data).
51
- */
45
+ /** Sort Koios /address_txs rows newest-first — Koios gives no ordering guarantee. */
52
46
  function sortAddressTxsDesc(rows) {
53
47
  return [...rows].sort((a, b) => Number(b.block_height ?? b.block_time ?? 0) - Number(a.block_height ?? a.block_time ?? 0));
54
48
  }
55
- /**
56
- * KoiosBackend Implementation for CardanoBackend Interface
57
- * Implements the CardanoBackend interface using Koios API with Axios
58
- */
49
+ /** CardanoBackend implementation on the Koios REST API (Axios). */
59
50
  class KoiosBackend {
60
51
  name = 'koios';
61
52
  api;
62
53
  network;
63
- /**
64
- * Constructor
65
- */
66
54
  constructor(network, timeoutMs, apiKey) {
67
55
  const headers = {};
68
- // Add Authorization header if API key is configured
69
56
  if (apiKey) {
70
57
  headers['Authorization'] = `Bearer ${apiKey}`;
71
58
  }
@@ -75,12 +62,9 @@ class KoiosBackend {
75
62
  headers,
76
63
  });
77
64
  this.network = network;
78
- // Koios runs multiple instances behind a load balancer; during their schema
79
- // migrations single instances serve broken SQL functions (PostgREST 400,
80
- // e.g. code 42703 "column … does not exist") or hit statement timeouts
81
- // (57014) while the rest are healthy. Such failures are instance-specific,
82
- // so a short bounded retry usually lands on a healthy instance. Genuine
83
- // client-input errors (PG class 22 etc.) are not retried.
65
+ // Koios is load-balanced; single instances serve broken SQL functions (PostgREST 400,
66
+ // e.g. 42703) or statement timeouts (57014) while others are healthy, so a short
67
+ // bounded retry usually lands on a healthy instance. Client-input errors are not retried.
84
68
  this.api.interceptors.response.use(undefined, async (error) => {
85
69
  const config = error.config;
86
70
  const pgCode = error.response?.data?.code;
@@ -95,11 +79,8 @@ class KoiosBackend {
95
79
  return this.api.request(config);
96
80
  });
97
81
  }
98
- /**
99
- * Initialize the backend
100
- */
82
+ /** Probe /tip to verify connectivity. */
101
83
  async init() {
102
- // Test connection by fetching latest block
103
84
  try {
104
85
  await this.api.get('/tip');
105
86
  }
@@ -109,16 +90,9 @@ class KoiosBackend {
109
90
  return true;
110
91
  }
111
92
  /**
112
- * Retry a Koios API call up to 3 times with exponential backoff if the
113
- * result is an empty array. Koios sometimes returns [] transiently for
114
- * valid queries — a single retry is not always sufficient for historical
115
- * epoch lookups, so we retry with increasing delays (500 → 1000 → 2000 ms).
93
+ * Retry (500 → 1000 → 2000 ms) when Koios transiently returns [] for a valid query.
94
+ * Element type is `any` on purpose: only non-emptiness is checked; rows are narrowed at use sites.
116
95
  */
117
- // Type-agnostic retry helper: it only checks that `.data` is a non-empty
118
- // array, so the element type is intentionally `any` to avoid forcing every
119
- // Koios endpoint call site (block_info, epoch_info, account_info, …) to
120
- // declare a row shape just for the empty-array retry path. Row narrowing
121
- // happens at the use sites.
122
96
  async fetchWithRetryOnEmpty(fn, // eslint-disable-line @typescript-eslint/no-explicit-any
123
97
  label) {
124
98
  const maxRetries = 3;
@@ -139,13 +113,9 @@ class KoiosBackend {
139
113
  return [];
140
114
  }
141
115
  /**
142
- * Koios runs several load-balanced grest instances and they are occasionally
143
- * version-skewed: some return HTTP 400 with Postgres error 42804 ("structure
144
- * of query does not match function result type", e.g. `out_sum_lovelace`
145
- * word128 vs numeric on /epoch_info) while healthy instances serve the
146
- * IDENTICAL request fine. The same request therefore flips 200/400 between
147
- * calls. Retrying a few times lands on a healthy instance. Scoped strictly to
148
- * the 42804 type-skew error so genuine 400s (bad params) still fail fast.
116
+ * Retry on Postgres 42804 ("structure of query does not match function result type"):
117
+ * version-skewed Koios instances behind the load balancer return it for a request that
118
+ * healthy instances serve fine. Other 400s still fail fast.
149
119
  */
150
120
  async getWithRetryOn42804(url, config, label) {
151
121
  const maxRetries = 8;
@@ -245,8 +215,7 @@ class KoiosBackend {
245
215
  }
246
216
  const addressData = data[0];
247
217
  const addressUtxos = await this.getAddressUtxos(address);
248
- // Sum balances from the already-mapped UTxOs instead of re-iterating
249
- // address_info's utxo_set (whose asset_list can be null → crashed here).
218
+ // Sum balances from the mapped UTxOs; address_info's utxo_set may carry a null asset_list.
250
219
  const totals = new Map();
251
220
  for (const u of addressUtxos) {
252
221
  for (const a of u.amount) {
@@ -322,11 +291,8 @@ class KoiosBackend {
322
291
  }, this.name);
323
292
  }
324
293
  /**
325
- * Get UTxOs by payment credential. Returns UTxOs across all bech32 addresses
326
- * sharing the given 28-byte payment credential (key hash or script hash).
327
- * Native Koios endpoint — single round-trip with inline-datum hydration.
294
+ * UTxOs across all bech32 addresses sharing a payment credential (native Koios endpoint).
328
295
  * @param credHash 28-byte payment credential as 56-char lowercase hex
329
- * @returns {Promise<UTxO[]>} list of UTxOs across all bech32 forms
330
296
  */
331
297
  async getCredentialUtxos(credHash) {
332
298
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
@@ -365,7 +331,7 @@ class KoiosBackend {
365
331
  */
366
332
  async getNetworkInformation() {
367
333
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
368
- // Try /totals endpoint (works on mainnet, but returns empty array on preview/preprod testnet)
334
+ // /totals works on mainnet but returns [] on preview/preprod
369
335
  const { data: totalsData } = await this.api.get('/totals', {
370
336
  params: { order: 'epoch_no.desc', limit: 1 }
371
337
  });
@@ -386,8 +352,7 @@ class KoiosBackend {
386
352
  },
387
353
  };
388
354
  }
389
- // Fallback for preview/preprod network where /totals doesn't work
390
- // Use genesis endpoint to get max supply; remaining fields default to '0'
355
+ // Testnet fallback: max supply from /genesis, remaining fields '0'
391
356
  const { data: genesisData } = await this.api.get('/genesis');
392
357
  if (!genesisData || !Array.isArray(genesisData) || genesisData.length === 0) {
393
358
  throw new errors_1.NotFoundError('Genesis', this.name);
@@ -450,34 +415,35 @@ class KoiosBackend {
450
415
  if (!Array.isArray(data) || data.length === 0) {
451
416
  throw new errors_1.NotFoundError('Pool', this.name);
452
417
  }
453
- const poolData = data[0];
454
- return {
455
- poolId: poolData.pool_id_bech32 || poolData.pool_id_hex || poolId,
456
- vrfKeyHash: poolData.vrf_key_hash,
457
- blocksMinted: poolData.block_count,
458
- // Koios pool_info has no blocks-in-current-epoch figure — epoch_no
459
- // (the epoch NUMBER) was mapped here before, which is a different
460
- // semantic than Blockfrost's blocks_epoch. 0 = not available.
461
- blocksEpoch: 0,
462
- liveStake: poolData.live_stake || '0',
463
- liveSize: poolData.live_size || 0,
464
- liveDelegators: poolData.live_delegators || 0,
465
- liveSaturation: poolData.live_saturation || 0,
466
- activeStake: poolData.active_stake || '0',
467
- activeSize: poolData.active_size || 0,
468
- pledge: poolData.pledge || '0',
469
- margin: poolData.margin || 0,
470
- fixedCost: poolData.fixed_cost || '0',
471
- rewardAccount: poolData.reward_addr,
472
- };
418
+ return this._mapKoiosPool(data[0], poolId);
473
419
  }, this.name);
474
420
  }
421
+ /** Map one Koios /pool_info row to the canonical PoolData. */
422
+ _mapKoiosPool(poolData, fallbackId) {
423
+ return {
424
+ poolId: poolData.pool_id_bech32 || poolData.pool_id_hex || fallbackId,
425
+ vrfKeyHash: poolData.vrf_key_hash,
426
+ blocksMinted: poolData.block_count,
427
+ // Koios pool_info has no blocks-in-current-epoch figure. null = not available;
428
+ // a 0 would be indistinguishable from a real zero downstream.
429
+ blocksEpoch: null,
430
+ liveStake: poolData.live_stake || '0',
431
+ liveSize: poolData.live_size || 0,
432
+ liveDelegators: poolData.live_delegators || 0,
433
+ // Koios reports saturation in PERCENT (75.42); PoolData holds a fraction (0.7542)
434
+ // stored in Decimal(9, 4) — the percent value would overflow the column.
435
+ liveSaturation: (Number(poolData.live_saturation) || 0) / 100,
436
+ activeStake: poolData.active_stake || '0',
437
+ activeSize: poolData.active_size || 0,
438
+ pledge: poolData.pledge || '0',
439
+ margin: poolData.margin || 0,
440
+ fixedCost: poolData.fixed_cost || '0',
441
+ rewardAccount: poolData.reward_addr,
442
+ };
443
+ }
475
444
  /**
476
- * Get Asset Info (supply, mint history, CIP-25 + CIP-26 metadata).
477
- * Koios's `asset_info` returns total_supply, mint/burn counts split,
478
- * minting tx + creation_time, and both on-chain and registry metadata.
445
+ * Asset info from Koios `asset_info`: supply, mint/burn counts, minting tx, CIP-25 + CIP-26 metadata.
479
446
  * @param unit policyId + assetNameHex (concatenated hex)
480
- * @returns {Promise<AssetInfo>} canonical asset info
481
447
  */
482
448
  async getAssetInfo(unit) {
483
449
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
@@ -519,16 +485,7 @@ class KoiosBackend {
519
485
  const onchainMetadata = mintMeta && typeof mintMeta === 'object'
520
486
  ? (mintMeta['721'] ?? mintMeta)
521
487
  : null;
522
- const decodeUtf8 = (hex) => {
523
- if (!hex)
524
- return null;
525
- try {
526
- return Buffer.from(hex, 'hex').toString('utf8');
527
- }
528
- catch {
529
- return null;
530
- }
531
- };
488
+ const decodeUtf8 = (hex) => (hex ? (0, mappers_1.decodeAssetName)(hex) : null);
532
489
  const mintCnt = typeof a.mint_cnt === 'number' ? a.mint_cnt : 0;
533
490
  const burnCnt = typeof a.burn_cnt === 'number' ? a.burn_cnt : 0;
534
491
  return {
@@ -552,14 +509,9 @@ class KoiosBackend {
552
509
  }, this.name);
553
510
  }
554
511
  /**
555
- * Get latest mint/burn events for an asset.
556
- * Koios's `asset_history` returns minting_txs[{ tx_hash, block_time, quantity }]
557
- * with `quantity` SIGNED (negative = burn). Action is derived from sign;
558
- * the canonical `quantity` field stores absolute value.
559
- * @param unit policyId + assetNameHex (concatenated hex)
560
- * @param limit max number of events (default 100). Note: Koios returns ALL events;
561
- * limit is applied client-side after sort-by-block_time desc.
562
- * @returns {Promise<AssetHistoryEntry[]>} list of mint/burn events (most recent first)
512
+ * Latest mint/burn events. Koios `asset_history` returns ALL events with `quantity` SIGNED
513
+ * (negative = burn): action derives from the sign, `quantity` stores the absolute value,
514
+ * `limit` is applied client-side after sorting by block_time desc.
563
515
  */
564
516
  async getAssetHistory(unit, limit = 100) {
565
517
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
@@ -605,27 +557,26 @@ class KoiosBackend {
605
557
  if (!Array.isArray(data) || data.length === 0) {
606
558
  throw new errors_1.NotFoundError('Drep', this.name);
607
559
  }
608
- const drepData = data[0];
609
- // Koios changed the /drep_info schema (observed 2026-07): the old
610
- // `expired`/`retired`/`last_active_epoch` fields were replaced by
611
- // `drep_status` ('registered' | 'retired'), `active` (boolean) and
612
- // `expires_epoch_no`. Read the old fields first (mainnet/preprod may
613
- // lag the migration), then derive from the new ones.
614
- const retired = drepData.retired ?? drepData.drep_status === 'retired';
615
- const expired = drepData.expired ?? (drepData.active === false && !retired);
616
- return {
617
- drepId: drepData.drep_id,
618
- hex: drepData.hex,
619
- amount: drepData.amount,
620
- hasScript: drepData.has_script,
621
- // The new schema no longer reports the last-activity epoch (only
622
- // `expires_epoch_no`, which has different semantics) — keep 0 there.
623
- lastActiveEpoch: drepData.last_active_epoch ?? 0,
624
- expired,
625
- retired,
626
- };
560
+ return this._mapKoiosDrep(data[0]);
627
561
  }, this.name);
628
562
  }
563
+ /** Map one Koios /drep_info row to the canonical DrepData. */
564
+ _mapKoiosDrep(drepData) {
565
+ // Koios /drep_info exposes either `expired`/`retired`/`last_active_epoch` (older schema)
566
+ // or `drep_status` ('registered' | 'retired'), `active` and `expires_epoch_no`; read both.
567
+ const retired = drepData.retired ?? drepData.drep_status === 'retired';
568
+ const expired = drepData.expired ?? (drepData.active === false && !retired);
569
+ return {
570
+ drepId: drepData.drep_id,
571
+ hex: drepData.hex,
572
+ amount: drepData.amount,
573
+ hasScript: drepData.has_script,
574
+ // The newer schema has no last-activity epoch (`expires_epoch_no` differs in meaning) — 0 then.
575
+ lastActiveEpoch: drepData.last_active_epoch ?? 0,
576
+ expired,
577
+ retired,
578
+ };
579
+ }
629
580
  /**
630
581
  * Get Account Data for specified stake address
631
582
  * @param accountId account id
@@ -640,7 +591,6 @@ class KoiosBackend {
640
591
  if (!Array.isArray(data) || data.length === 0) {
641
592
  throw new errors_1.NotFoundError('Account', this.name);
642
593
  }
643
- // Fetch associated addresses
644
594
  const addressDataResponse = await this.api.post('/account_addresses', body);
645
595
  // Koios returns [{ stake_address, addresses: [...] }], flatten to get all addresses
646
596
  const addressesFlat = addressDataResponse.data.flatMap((item) => item.addresses);
@@ -823,12 +773,12 @@ class KoiosBackend {
823
773
  .map(tx => tx.tx_hash);
824
774
  }, this.name);
825
775
  }
826
- /**
827
- * Batch fetch multiple transactions by hash using Koios POST /tx_info.
828
- * Sends all hashes in one request (chunked at 100 per Koios limit).
829
- * @param txHashes array of transaction hashes
830
- * @returns {Promise<Map<string, Transaction>>} map of hash -> Transaction
831
- */
776
+ /** crawler.certificates: ask /tx_info for certificates + withdrawals on the crawl's batch call. */
777
+ crawlCertificates = false;
778
+ configureCrawl(options) {
779
+ this.crawlCertificates = Boolean(options.certificates);
780
+ }
781
+ /** Batch fetch transactions via POST /tx_info, chunked at 100 hashes (Koios limit). */
832
782
  async getTransactionsBatch(txHashes) {
833
783
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
834
784
  const BATCH_SIZE = 100;
@@ -840,8 +790,9 @@ class KoiosBackend {
840
790
  _inputs: true,
841
791
  _metadata: true,
842
792
  _assets: true,
843
- _withdrawals: false,
844
- _certs: false,
793
+ // certificates + withdrawals only when the crawl will write them (larger payload)
794
+ _withdrawals: this.crawlCertificates,
795
+ _certs: this.crawlCertificates,
845
796
  _scripts: false,
846
797
  _bytecode: false,
847
798
  });
@@ -860,12 +811,9 @@ class KoiosBackend {
860
811
  }, this.name);
861
812
  }
862
813
  // ---------------------------------------------------------------------------
863
- // PaginatingBackend — forward iteration for the chain crawler (v2.0)
814
+ // PaginatingBackend — forward iteration for the chain crawler
864
815
  // ---------------------------------------------------------------------------
865
- /**
866
- * Map a Koios /block_info response object to our BlockData (same shape getBlock
867
- * maps inline; kept private to avoid touching getBlock).
868
- */
816
+ /** Map a Koios /block_info row to BlockData. */
869
817
  mapKoiosBlockInfo(data) {
870
818
  return {
871
819
  time: data.block_time,
@@ -893,21 +841,17 @@ class KoiosBackend {
893
841
  }, this.name);
894
842
  }
895
843
  /**
896
- * Get up to `count` blocks following `afterHash`, in ascending chain order.
897
- * Koios has no "next after hash" endpoint, so we list blocks above the anchor height
898
- * (PostgREST gt + order + limit), then batch /block_info. When the caller already
899
- * knows the anchor height (the crawler's cursor), the hash→height resolution
900
- * round-trip is skipped entirely.
844
+ * Up to `count` blocks after `afterHash`, ascending. Koios has no "next after hash" endpoint:
845
+ * list blocks above the anchor height (PostgREST gt + order + limit), then batch /block_info.
846
+ * A known `afterHeight` skips the hash→height round-trip.
901
847
  */
902
848
  async getNextBlocks(afterHash, count, afterHeight) {
903
849
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
904
850
  let anchorHeight = afterHeight;
905
851
  if (anchorHeight != null && anchorHeight > 0) {
906
- // A height hint saves the hash -> height lookup, but it must never be
907
- // trusted as proof that the cursor is still on the canonical chain.
908
- // After a rollback Koios can continue listing canonical blocks above H
909
- // even though `afterHash` is the now-orphaned block at H. Validate the
910
- // canonical hash first so the crawler enters its reorg-recovery path.
852
+ // A height hint is not proof the cursor is still canonical: after a rollback Koios
853
+ // keeps listing blocks above H while `afterHash` is orphaned. Validate the hash first
854
+ // so the crawler enters reorg recovery.
911
855
  const canonical = await this.fetchWithRetryOnEmpty(() => this.api.get(`/blocks?block_height=eq.${anchorHeight}&limit=1`), `getNextBlocks/anchor(${anchorHeight})`);
912
856
  const canonicalHash = canonical[0]?.hash;
913
857
  if (!canonicalHash) {
@@ -928,12 +872,9 @@ class KoiosBackend {
928
872
  return [];
929
873
  const requestedHashes = rows.map((r) => r.hash);
930
874
  const infos = await this.fetchWithRetryOnEmpty(() => this.api.post('/block_info', { _block_hashes: requestedHashes }), `getNextBlocks/info(${afterHash})`);
931
- // Completeness guard: Koios' load-balanced instances can return a PARTIAL
932
- // /block_info batch (fetchWithRetryOnEmpty only retries fully empty
933
- // responses). Returning the subset would let the crawler advance its cursor
934
- // past the missing block, leaving a permanent hole in the pre-synced range
935
- // (crawled entities are non-temporal — nothing re-fetches them). Fail the
936
- // round as transient instead; the next round retries the same anchor.
875
+ // Load-balanced instances can return a PARTIAL /block_info batch. Returning the subset
876
+ // would advance the cursor past the missing block and leave a permanent hole (crawled
877
+ // entities are never re-fetched), so fail the round as transient instead.
937
878
  if (infos.length < requestedHashes.length) {
938
879
  const returned = new Set(infos.map((d) => d.hash));
939
880
  const missing = requestedHashes.filter((h) => !returned.has(h));
@@ -944,10 +885,84 @@ class KoiosBackend {
944
885
  .sort((a, b) => (a.height ?? 0) - (b.height ?? 0));
945
886
  }, this.name);
946
887
  }
888
+ // ---------------------------------------------------------------------------
889
+ // EnumeratingBackend — full pool/DRep set for the crawler's epoch snapshots
890
+ // ---------------------------------------------------------------------------
891
+ /** Rows per page when listing ids (PostgREST caps a response at 1000 rows). */
892
+ static LIST_PAGE_SIZE = 1000;
893
+ /** Ids resolved per /pool_info / /drep_info request. */
894
+ static INFO_BATCH_SIZE = 50;
895
+ /** Page cap — 500 pages is 500 000 ids, far beyond any real pool or DRep set. */
896
+ static LIST_MAX_PAGES = 500;
897
+ /**
898
+ * Page through a PostgREST list endpoint and collect one id column. Stops on the first
899
+ * short page, so a complete set costs exactly ceil(n / 1000) + 1 requests.
900
+ */
901
+ async listAllIds(path, column, label) {
902
+ const ids = [];
903
+ for (let page = 0; page < KoiosBackend.LIST_MAX_PAGES; page++) {
904
+ const offset = page * KoiosBackend.LIST_PAGE_SIZE;
905
+ const { data } = await this.getWithRetryOn42804(`${path}?select=${column}&limit=${KoiosBackend.LIST_PAGE_SIZE}&offset=${offset}`, {}, label);
906
+ if (!Array.isArray(data) || data.length === 0)
907
+ return ids;
908
+ for (const row of data) {
909
+ const id = row[column];
910
+ if (typeof id === 'string' && id)
911
+ ids.push(id);
912
+ }
913
+ if (data.length < KoiosBackend.LIST_PAGE_SIZE)
914
+ return ids;
915
+ }
916
+ logger.warn(`${label}: stopped after ${KoiosBackend.LIST_MAX_PAGES} pages — the list may be truncated`);
917
+ return ids;
918
+ }
919
+ /**
920
+ * All stake-pool ids known to Koios (bech32), including retired ones — a snapshot that
921
+ * silently dropped retiring pools would misreport the epoch's pool set.
922
+ */
923
+ async getPoolIds() {
924
+ return (0, backend_request_handler_1.handleBackendRequest)(() => this.listAllIds('/pool_list', 'pool_id_bech32', 'getPoolIds'), this.name);
925
+ }
926
+ /**
927
+ * Resolve pool ids in batches. Ids Koios does not return are omitted rather than
928
+ * substituted with empty rows — a missing pool is better than an invented one.
929
+ */
930
+ async getPools(poolIds) {
931
+ return (0, backend_request_handler_1.handleBackendRequest)(async () => {
932
+ const out = [];
933
+ for (let i = 0; i < poolIds.length; i += KoiosBackend.INFO_BATCH_SIZE) {
934
+ const batch = poolIds.slice(i, i + KoiosBackend.INFO_BATCH_SIZE);
935
+ const { data } = await this.api.post('/pool_info', { _pool_bech32_ids: batch });
936
+ if (!Array.isArray(data))
937
+ continue;
938
+ for (const row of data)
939
+ out.push(this._mapKoiosPool(row, ''));
940
+ }
941
+ return out;
942
+ }, this.name);
943
+ }
944
+ /** All DRep ids known to Koios (bech32). */
945
+ async getDrepIds() {
946
+ return (0, backend_request_handler_1.handleBackendRequest)(() => this.listAllIds('/drep_list', 'drep_id', 'getDrepIds'), this.name);
947
+ }
948
+ /** Resolve DRep ids in batches; unknown ids are omitted (see getPools). */
949
+ async getDreps(drepIds) {
950
+ return (0, backend_request_handler_1.handleBackendRequest)(async () => {
951
+ const out = [];
952
+ for (let i = 0; i < drepIds.length; i += KoiosBackend.INFO_BATCH_SIZE) {
953
+ const batch = drepIds.slice(i, i + KoiosBackend.INFO_BATCH_SIZE);
954
+ const { data } = await this.api.post('/drep_info', { _drep_ids: batch });
955
+ if (!Array.isArray(data))
956
+ continue;
957
+ for (const row of data)
958
+ out.push(this._mapKoiosDrep(row));
959
+ }
960
+ return out;
961
+ }, this.name);
962
+ }
947
963
  /**
948
- * Get the full transaction list of a block in block order via /block_txs → /tx_info
949
- * batch. Handles both the current flattened shape ({tx_hash} per row) and the older
950
- * {tx_hashes:[...]} shape defensively.
964
+ * Full transaction list of a block in block order via /block_txs → /tx_info batch.
965
+ * Accepts both the flattened ({tx_hash} per row) and the {tx_hashes:[...]} shape.
951
966
  */
952
967
  async getBlockTransactions(blockHash) {
953
968
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
@@ -964,9 +979,8 @@ class KoiosBackend {
964
979
  const byHash = await this.getTransactionsBatch(hashes);
965
980
  const missing = hashes.filter(h => !byHash.has(h));
966
981
  if (missing.length > 0) {
967
- // Advancing the block cursor with only a subset of /tx_info would make
968
- // the omitted transactions permanent. Surface a 503 so the crawler
969
- // retries the whole block without persisting it.
982
+ // A partial /tx_info would make the omitted transactions permanent — 503 so the
983
+ // crawler retries the whole block without persisting it.
970
984
  throw new errors_1.ProviderUnavailableError(`Incomplete transaction data for block ${blockHash}: ${missing.length}/${hashes.length} transaction(s) missing`, this.name);
971
985
  }
972
986
  return hashes.map(h => byHash.get(h));
@@ -975,9 +989,7 @@ class KoiosBackend {
975
989
  //-----------------------------------------------------------------------------
976
990
  // Private Helpers
977
991
  //-----------------------------------------------------------------------------
978
- /**
979
- * Map a Koios /tx_info response object to the normalized Transaction type.
980
- */
992
+ /** Map a Koios /tx_info row to the normalized Transaction. */
981
993
  _mapKoiosTx(tx) {
982
994
  let labels = [];
983
995
  if (tx.metadata) {
@@ -993,61 +1005,139 @@ class KoiosBackend {
993
1005
  blockHeight: Number(tx.block_height),
994
1006
  blockTime: tx.tx_timestamp ?? tx.block_time ?? 0,
995
1007
  slot: tx.absolute_slot ?? tx.slot_no ?? 0,
996
- // Koios /tx_info fields are `tx_block_index` and `fee` (verified against
997
- // the live OpenAPI spec) — `tx_index`/`tx_fee` never existed, so the fee
998
- // was always reported as '0'
1008
+ // Koios spells these `tx_block_index` and `fee` (not `tx_index` / `tx_fee`)
999
1009
  index: tx.tx_block_index ?? 0,
1000
1010
  fee: tx.fee || '0',
1001
1011
  deposit: tx.deposit || '0',
1012
+ // undefined (not []) when Koios does not report the field at all — the indexer then
1013
+ // falls back to the input/output delta instead of reading "no mint" into a gap.
1014
+ mint: Array.isArray(tx.assets_minted)
1015
+ ? tx.assets_minted
1016
+ .filter((a) => a?.policy_id && a.quantity != null)
1017
+ .map((a) => ({
1018
+ unit: `${a.policy_id}${a.asset_name ?? ''}`,
1019
+ quantity: String(a.quantity),
1020
+ }))
1021
+ : undefined,
1002
1022
  size: tx.tx_size,
1003
- inputs: tx.inputs.map((input) => {
1004
- const amount = [
1005
- { unit: 'lovelace', quantity: input.value }
1006
- ];
1007
- if (input.asset_list && Array.isArray(input.asset_list)) {
1008
- for (const asset of input.asset_list) {
1009
- amount.push({
1010
- unit: `${asset.policy_id}${asset.asset_name}`,
1011
- quantity: asset.quantity
1012
- });
1013
- }
1014
- }
1015
- return {
1016
- address: input.payment_addr?.bech32 || input.address || '',
1017
- txHash: input.tx_hash,
1018
- outputIndex: input.tx_index,
1019
- amount: amount,
1020
- dataHash: input.datum_hash || null,
1021
- inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(input.inline_datum),
1022
- referenceScriptHash: koiosRefScriptHash(input.reference_script),
1023
- };
1024
- }),
1025
- outputs: tx.outputs.map((output) => {
1026
- const amount = [
1027
- { unit: 'lovelace', quantity: output.value }
1028
- ];
1029
- if (output.asset_list && Array.isArray(output.asset_list)) {
1030
- for (const asset of output.asset_list) {
1031
- amount.push({
1032
- unit: `${asset.policy_id}${asset.asset_name}`,
1033
- quantity: asset.quantity
1034
- });
1035
- }
1036
- }
1037
- return {
1038
- address: output.payment_addr?.bech32 || output.address || '',
1039
- amount: amount,
1040
- txHash: tx.tx_hash,
1041
- outputIndex: output.tx_index,
1042
- dataHash: output.datum_hash || null,
1043
- inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(output.inline_datum),
1044
- isCollateral: false,
1045
- referenceScriptHash: koiosRefScriptHash(output.reference_script),
1046
- };
1047
- }),
1048
- metadata: labels
1023
+ // Phase-2 validity as db-sync records it; undefined on a Koios without the field, so the
1024
+ // indexer keeps treating such a source as "no phase-2 information".
1025
+ spendsCollaterals: typeof tx.valid_contract === 'boolean' ? tx.valid_contract === false : undefined,
1026
+ inputs: [
1027
+ ...asKoiosList(tx.inputs).map((input) => mapKoiosInput(input)),
1028
+ ...asKoiosList(tx.collateral_inputs).map((input) => mapKoiosInput(input, { isCollateral: true })),
1029
+ ...asKoiosList(tx.reference_inputs).map((input) => mapKoiosInput(input, { isReference: true })),
1030
+ ],
1031
+ outputs: [
1032
+ ...asKoiosList(tx.outputs).map((output) => mapKoiosOutput(tx.tx_hash, output, false)),
1033
+ // CIP-40 collateral return: produced only when the script phase failed
1034
+ ...asKoiosList(tx.collateral_output).map((output) => mapKoiosOutput(tx.tx_hash, output, true)),
1035
+ ],
1036
+ metadata: labels,
1037
+ // undefined (not []) when the call did not ask for them (`_certs: false` on the lazy
1038
+ // path) — the indexer tells "none" from "not reported" by exactly this.
1039
+ certificates: Array.isArray(tx.certificates) ? mapKoiosCertificates(tx.certificates) : undefined,
1040
+ withdrawals: Array.isArray(tx.withdrawals)
1041
+ ? tx.withdrawals
1042
+ .filter((w) => !!w.stake_addr)
1043
+ .map((w) => ({ stakeAddress: String(w.stake_addr), amount: String(w.amount ?? '0') }))
1044
+ : undefined,
1049
1045
  };
1050
1046
  }
1051
1047
  }
1052
1048
  exports.KoiosBackend = KoiosBackend;
1049
+ /**
1050
+ * Koios is loose about shapes: `collateral_output` arrives as one object (the spec says
1051
+ * array) and `asset_list` on it as the JSON STRING "[]". Normalize both before mapping.
1052
+ */
1053
+ function asKoiosList(v) {
1054
+ if (Array.isArray(v))
1055
+ return v;
1056
+ if (typeof v === 'string') {
1057
+ try {
1058
+ const parsed = JSON.parse(v);
1059
+ return Array.isArray(parsed) ? parsed : [];
1060
+ }
1061
+ catch {
1062
+ return [];
1063
+ }
1064
+ }
1065
+ return v && typeof v === 'object' ? [v] : [];
1066
+ }
1067
+ function koiosAmount(io) {
1068
+ const amount = [{ unit: 'lovelace', quantity: io.value }];
1069
+ for (const asset of asKoiosList(io.asset_list)) {
1070
+ amount.push({ unit: `${asset.policy_id}${asset.asset_name}`, quantity: asset.quantity });
1071
+ }
1072
+ return amount;
1073
+ }
1074
+ function mapKoiosInput(input, flags = {}) {
1075
+ return {
1076
+ address: input.payment_addr?.bech32 || input.address || '',
1077
+ txHash: input.tx_hash,
1078
+ outputIndex: input.tx_index,
1079
+ amount: koiosAmount(input),
1080
+ dataHash: input.datum_hash || null,
1081
+ inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(input.inline_datum),
1082
+ referenceScriptHash: koiosRefScriptHash(input.reference_script),
1083
+ ...flags,
1084
+ };
1085
+ }
1086
+ function mapKoiosOutput(txHash, output, isCollateral) {
1087
+ return {
1088
+ address: output.payment_addr?.bech32 || output.address || '',
1089
+ amount: koiosAmount(output),
1090
+ txHash,
1091
+ outputIndex: output.tx_index,
1092
+ dataHash: output.datum_hash || null,
1093
+ inlineDatum: (0, tx_build_helper_1.inlineDatumToHex)(output.inline_datum),
1094
+ isCollateral,
1095
+ referenceScriptHash: koiosRefScriptHash(output.reference_script),
1096
+ };
1097
+ }
1098
+ /** Koios certificate `type` → shared `CertificateKind`; anything else passes through raw. */
1099
+ const KOIOS_CERT_KINDS = {
1100
+ stake_registration: 'stake_registration',
1101
+ stake_deregistration: 'stake_deregistration',
1102
+ pool_delegation: 'pool_delegation',
1103
+ // older Koios releases named the pool delegation plainly
1104
+ delegation: 'pool_delegation',
1105
+ vote_delegation: 'vote_delegation',
1106
+ pool_update: 'pool_registration',
1107
+ pool_retire: 'pool_retirement',
1108
+ drep_registration: 'drep_registration',
1109
+ drep_update: 'drep_update',
1110
+ drep_retire: 'drep_retirement',
1111
+ drep_deregistration: 'drep_retirement',
1112
+ committee_hot_auth: 'committee_hot_auth',
1113
+ committee_resign: 'committee_resign',
1114
+ treasury_MIR: 'treasury_mir',
1115
+ reserve_MIR: 'reserve_mir',
1116
+ pot_transfer: 'pot_transfer',
1117
+ param_proposal: 'param_proposal',
1118
+ };
1119
+ /**
1120
+ * Normalize Koios `/tx_info` certificates (`_certs: true`). Field names inside `info` differ
1121
+ * per type (`retiring_epoch` is spelled `retiring epoch` in current Koios), so every alias is read.
1122
+ */
1123
+ function mapKoiosCertificates(certs) {
1124
+ const str = (v) => (typeof v === 'string' && v.length ? v : null);
1125
+ const num = (v) => {
1126
+ const n = typeof v === 'string' ? Number(v) : v;
1127
+ return typeof n === 'number' && Number.isFinite(n) ? n : null;
1128
+ };
1129
+ return certs.map((c, position) => {
1130
+ const info = c.info ?? {};
1131
+ const deposit = info.deposit;
1132
+ return {
1133
+ certIndex: num(c.index) ?? position,
1134
+ kind: (c.type && KOIOS_CERT_KINDS[c.type]) || c.type || 'other',
1135
+ stakeAddress: str(info.stake_address) ?? str(info.stake_addr),
1136
+ poolId: str(info.pool_id_bech32) ?? str(info.pool),
1137
+ drepId: str(info.drep_id),
1138
+ deposit: deposit != null && deposit !== '' ? String(deposit) : null,
1139
+ epoch: num(info.retiring_epoch) ?? num(info['retiring epoch']),
1140
+ };
1141
+ });
1142
+ }
1053
1143
  //# sourceMappingURL=koios-backend.js.map