@odatano/core 1.11.0 → 2.0.0-rc.10

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 (133) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +255 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +177 -0
  4. package/@cds-models/CardanoIndexerService/index.js +27 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +693 -2172
  6. package/@cds-models/CardanoODataService/index.js +88 -390
  7. package/@cds-models/CardanoSignService/index.d.ts +448 -1576
  8. package/@cds-models/CardanoSignService/index.js +62 -293
  9. package/@cds-models/CardanoTransactionService/index.d.ts +437 -1494
  10. package/@cds-models/CardanoTransactionService/index.js +60 -271
  11. package/@cds-models/CardanoWorkerService/index.d.ts +224 -0
  12. package/@cds-models/CardanoWorkerService/index.js +32 -0
  13. package/@cds-models/_/index.d.ts +70 -40
  14. package/@cds-models/_/index.js +17 -32
  15. package/@cds-models/cds/outbox/index.d.ts +28 -0
  16. package/@cds-models/index.d.ts +225 -522
  17. package/@cds-models/index.js +35 -218
  18. package/@cds-models/odatano/cardano/index.d.ts +919 -2884
  19. package/@cds-models/odatano/cardano/index.js +115 -536
  20. package/@cds-models/sap/common/index.d.ts +196 -600
  21. package/@cds-models/sap/common/index.js +28 -269
  22. package/README.md +194 -102
  23. package/db/schema.cds +388 -1
  24. package/db/types.cds +48 -0
  25. package/package.json +48 -33
  26. package/src/index.d.ts +7 -1
  27. package/src/index.js +30 -2
  28. package/src/plugin.js +33 -20
  29. package/srv/blockchain/backends/blockfrost-backend.d.ts +21 -2
  30. package/srv/blockchain/backends/blockfrost-backend.js +69 -25
  31. package/srv/blockchain/backends/cardano-backend.d.ts +69 -0
  32. package/srv/blockchain/backends/cardano-backend.js +13 -0
  33. package/srv/blockchain/backends/koios-backend.d.ts +26 -2
  34. package/srv/blockchain/backends/koios-backend.js +148 -25
  35. package/srv/blockchain/backends/ogmios-backend.d.ts +60 -9
  36. package/srv/blockchain/backends/ogmios-backend.js +326 -10
  37. package/srv/blockchain/cardano-client.d.ts +19 -0
  38. package/srv/blockchain/cardano-client.js +36 -0
  39. package/srv/blockchain/cardano-indexer.d.ts +50 -1
  40. package/srv/blockchain/cardano-indexer.js +193 -0
  41. package/srv/blockchain/crawler/crawler.d.ts +176 -0
  42. package/srv/blockchain/crawler/crawler.js +744 -0
  43. package/srv/blockchain/crawler/hooks.d.ts +43 -0
  44. package/srv/blockchain/crawler/hooks.js +62 -0
  45. package/srv/blockchain/crawler/index.d.ts +35 -0
  46. package/srv/blockchain/crawler/index.js +168 -0
  47. package/srv/blockchain/crawler/sync-state.d.ts +106 -0
  48. package/srv/blockchain/crawler/sync-state.js +287 -0
  49. package/srv/blockchain/signing/hsm-signer.d.ts +45 -0
  50. package/srv/blockchain/signing/hsm-signer.js +8 -1
  51. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +20 -0
  52. package/srv/blockchain/transaction-building/buildooor-tx.js +104 -20
  53. package/srv/blockchain/wallet-worker/build-request.d.ts +26 -0
  54. package/srv/blockchain/wallet-worker/build-request.js +370 -0
  55. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +117 -0
  56. package/srv/blockchain/wallet-worker/confirmation-tracker.js +290 -0
  57. package/srv/blockchain/wallet-worker/index.d.ts +14 -0
  58. package/srv/blockchain/wallet-worker/index.js +80 -0
  59. package/srv/blockchain/wallet-worker/job-store.d.ts +272 -0
  60. package/srv/blockchain/wallet-worker/job-store.js +597 -0
  61. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +43 -0
  62. package/srv/blockchain/wallet-worker/lease-heartbeat.js +99 -0
  63. package/srv/blockchain/wallet-worker/signers.d.ts +57 -0
  64. package/srv/blockchain/wallet-worker/signers.js +131 -0
  65. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +145 -0
  66. package/srv/blockchain/wallet-worker/wallet-worker.js +542 -0
  67. package/srv/cardano-agent-service.cds +150 -0
  68. package/srv/cardano-agent-service.d.ts +2 -0
  69. package/srv/cardano-agent-service.js +16 -0
  70. package/srv/cardano-indexer-service.cds +106 -0
  71. package/srv/cardano-indexer-service.d.ts +2 -0
  72. package/srv/cardano-indexer-service.js +79 -0
  73. package/srv/cardano-service.js +79 -4
  74. package/srv/cardano-sign-service.cds +200 -180
  75. package/srv/cardano-tx-service.cds +32 -26
  76. package/srv/cardano-tx-service.d.ts +1 -11
  77. package/srv/cardano-tx-service.js +107 -200
  78. package/srv/cardano-worker-service.cds +125 -0
  79. package/srv/cardano-worker-service.d.ts +2 -0
  80. package/srv/cardano-worker-service.js +199 -0
  81. package/srv/server.d.ts +34 -2
  82. package/srv/server.js +246 -36
  83. package/srv/utils/agent-grants-config.d.ts +65 -0
  84. package/srv/utils/agent-grants-config.js +148 -0
  85. package/srv/utils/agent-grants.d.ts +314 -0
  86. package/srv/utils/agent-grants.js +821 -0
  87. package/srv/utils/agent-token-auth.d.ts +19 -0
  88. package/srv/utils/agent-token-auth.js +81 -0
  89. package/srv/utils/collections.d.ts +13 -0
  90. package/srv/utils/collections.js +24 -0
  91. package/srv/utils/crypto.d.ts +16 -0
  92. package/srv/utils/crypto.js +75 -0
  93. package/srv/utils/db-sanitize.d.ts +40 -0
  94. package/srv/utils/db-sanitize.js +98 -0
  95. package/srv/utils/error-codes.d.ts +6 -0
  96. package/srv/utils/error-codes.js +6 -0
  97. package/srv/utils/errors.d.ts +12 -0
  98. package/srv/utils/errors.js +45 -0
  99. package/srv/utils/liveness.d.ts +23 -0
  100. package/srv/utils/liveness.js +49 -0
  101. package/srv/utils/mappers.d.ts +27 -0
  102. package/srv/utils/mappers.js +80 -10
  103. package/srv/utils/rate-limiter.d.ts +57 -0
  104. package/srv/utils/rate-limiter.js +126 -0
  105. package/srv/utils/service-events.d.ts +26 -0
  106. package/srv/utils/service-events.js +46 -0
  107. package/srv/utils/tx-request-parsers.d.ts +71 -0
  108. package/srv/utils/tx-request-parsers.js +202 -0
  109. package/srv/utils/tx-utils.d.ts +2 -1
  110. package/srv/utils/tx-utils.js +3 -2
  111. package/srv/utils/types.d.ts +17 -1
  112. package/@cds-models/CardanoODataService/index.d.ts.map +0 -1
  113. package/@cds-models/CardanoODataService/index.js.map +0 -1
  114. package/@cds-models/CardanoODataService/index.ts +0 -776
  115. package/@cds-models/CardanoSignService/index.d.ts.map +0 -1
  116. package/@cds-models/CardanoSignService/index.js.map +0 -1
  117. package/@cds-models/CardanoSignService/index.ts +0 -569
  118. package/@cds-models/CardanoTransactionService/index.d.ts.map +0 -1
  119. package/@cds-models/CardanoTransactionService/index.js.map +0 -1
  120. package/@cds-models/CardanoTransactionService/index.ts +0 -526
  121. package/@cds-models/_/index.d.ts.map +0 -1
  122. package/@cds-models/_/index.js.map +0 -1
  123. package/@cds-models/_/index.ts +0 -96
  124. package/@cds-models/cds/outbox/index.ts +0 -27
  125. package/@cds-models/index.d.ts.map +0 -1
  126. package/@cds-models/index.js.map +0 -1
  127. package/@cds-models/index.ts +0 -245
  128. package/@cds-models/odatano/cardano/index.d.ts.map +0 -1
  129. package/@cds-models/odatano/cardano/index.js.map +0 -1
  130. package/@cds-models/odatano/cardano/index.ts +0 -789
  131. package/@cds-models/sap/common/index.d.ts.map +0 -1
  132. package/@cds-models/sap/common/index.js.map +0 -1
  133. package/@cds-models/sap/common/index.ts +0 -249
package/src/index.js CHANGED
@@ -36,7 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.parseTransaction = exports.getHsmSigner = exports.shutdownAppContext = exports.loadHsmConfigFromEnv = exports.loadConfigFromEnv = exports.getCardanoTxBuilder = exports.getCardanoClient = exports.getCardanoIndexer = exports.getAppContext = exports.CardanoTransactionBuilder = exports.CardanoIndexer = exports.CardanoClient = void 0;
39
+ exports.parseTransaction = exports.loadAgentGrantsConfig = exports.registerTransportLane = exports.AGENT_ALWAYS_ALLOWED_EVENTS = exports.AGENT_ALLOWLISTABLE_ACTIONS = exports.AGENT_ROLE = exports.AGENT_TOKEN_PREFIX = exports.AGENT_TOKEN_HEADER = exports.hashAgentToken = exports.resolveUsageWindow = exports.getGrantUsage = exports.revokeAgentGrantById = exports.rotateAgentGrantToken = exports.updateAgentGrant = exports.issueAgentGrant = exports.getHsmSigner = exports.shutdownAppContext = exports.startWalletWorkerIfConfigured = exports.loadWalletWorkerConfigFromEnv = exports.startCrawlerIfConfigured = exports.loadCrawlerConfigFromEnv = exports.loadHsmConfigFromEnv = exports.loadConfigFromEnv = exports.getCardanoTxBuilder = exports.getCardanoClient = exports.getCardanoIndexer = exports.getAppContext = exports.CardanoTransactionBuilder = exports.CardanoIndexer = exports.CardanoClient = void 0;
40
40
  exports.initialize = initialize;
41
41
  exports.shutdown = shutdown;
42
42
  exports.getStatus = getStatus;
@@ -57,10 +57,34 @@ Object.defineProperty(exports, "getCardanoClient", { enumerable: true, get: func
57
57
  Object.defineProperty(exports, "getCardanoTxBuilder", { enumerable: true, get: function () { return server_1.getCardanoTxBuilder; } });
58
58
  Object.defineProperty(exports, "loadConfigFromEnv", { enumerable: true, get: function () { return server_1.loadConfigFromEnv; } });
59
59
  Object.defineProperty(exports, "loadHsmConfigFromEnv", { enumerable: true, get: function () { return server_1.loadHsmConfigFromEnv; } });
60
+ Object.defineProperty(exports, "loadCrawlerConfigFromEnv", { enumerable: true, get: function () { return server_1.loadCrawlerConfigFromEnv; } });
61
+ Object.defineProperty(exports, "startCrawlerIfConfigured", { enumerable: true, get: function () { return server_1.startCrawlerIfConfigured; } });
62
+ Object.defineProperty(exports, "loadWalletWorkerConfigFromEnv", { enumerable: true, get: function () { return server_1.loadWalletWorkerConfigFromEnv; } });
63
+ Object.defineProperty(exports, "startWalletWorkerIfConfigured", { enumerable: true, get: function () { return server_1.startWalletWorkerIfConfigured; } });
60
64
  Object.defineProperty(exports, "shutdownAppContext", { enumerable: true, get: function () { return server_1.shutdownAppContext; } });
61
65
  // Re-export HSM signer for programmatic access
62
66
  var hsm_signer_1 = require("../srv/blockchain/signing/hsm-signer");
63
67
  Object.defineProperty(exports, "getHsmSigner", { enumerable: true, get: function () { return hsm_signer_1.getHsmSigner; } });
68
+ // Agent grants (v2.0, AGENT_GRANTS_DESIGN.md): the programmatic seams other
69
+ // packages build on — @odatano/x402 sells grants through issueAgentGrant and
70
+ // adds its payment lane through registerTransportLane.
71
+ var agent_grants_1 = require("../srv/utils/agent-grants");
72
+ Object.defineProperty(exports, "issueAgentGrant", { enumerable: true, get: function () { return agent_grants_1.issueAgentGrant; } });
73
+ Object.defineProperty(exports, "updateAgentGrant", { enumerable: true, get: function () { return agent_grants_1.updateAgentGrant; } });
74
+ Object.defineProperty(exports, "rotateAgentGrantToken", { enumerable: true, get: function () { return agent_grants_1.rotateAgentGrantToken; } });
75
+ Object.defineProperty(exports, "revokeAgentGrantById", { enumerable: true, get: function () { return agent_grants_1.revokeAgentGrantById; } });
76
+ Object.defineProperty(exports, "getGrantUsage", { enumerable: true, get: function () { return agent_grants_1.getGrantUsage; } });
77
+ Object.defineProperty(exports, "resolveUsageWindow", { enumerable: true, get: function () { return agent_grants_1.resolveUsageWindow; } });
78
+ Object.defineProperty(exports, "hashAgentToken", { enumerable: true, get: function () { return agent_grants_1.hashAgentToken; } });
79
+ Object.defineProperty(exports, "AGENT_TOKEN_HEADER", { enumerable: true, get: function () { return agent_grants_1.AGENT_TOKEN_HEADER; } });
80
+ Object.defineProperty(exports, "AGENT_TOKEN_PREFIX", { enumerable: true, get: function () { return agent_grants_1.AGENT_TOKEN_PREFIX; } });
81
+ Object.defineProperty(exports, "AGENT_ROLE", { enumerable: true, get: function () { return agent_grants_1.AGENT_ROLE; } });
82
+ Object.defineProperty(exports, "AGENT_ALLOWLISTABLE_ACTIONS", { enumerable: true, get: function () { return agent_grants_1.AGENT_ALLOWLISTABLE_ACTIONS; } });
83
+ Object.defineProperty(exports, "AGENT_ALWAYS_ALLOWED_EVENTS", { enumerable: true, get: function () { return agent_grants_1.AGENT_ALWAYS_ALLOWED_EVENTS; } });
84
+ var cap_auth_1 = require("@odatano/cap-auth");
85
+ Object.defineProperty(exports, "registerTransportLane", { enumerable: true, get: function () { return cap_auth_1.registerTransportLane; } });
86
+ var agent_grants_config_1 = require("../srv/utils/agent-grants-config");
87
+ Object.defineProperty(exports, "loadAgentGrantsConfig", { enumerable: true, get: function () { return agent_grants_config_1.loadAgentGrantsConfig; } });
64
88
  // Re-export pure CBOR utilities (no CAP round-trip needed)
65
89
  var cbor_1 = require("../srv/cbor");
66
90
  Object.defineProperty(exports, "parseTransaction", { enumerable: true, get: function () { return cbor_1.parseTransaction; } });
@@ -85,8 +109,12 @@ async function initialize() {
85
109
  if (!alreadyInitialized) {
86
110
  logger.info('ODATANO core initialized');
87
111
  }
112
+ // Start the pre-sync crawler if configured (plugin mode). Non-fatal.
113
+ const { startCrawlerIfConfigured, startWalletWorkerIfConfigured, redriveInterruptedSubmissionsIfConfigured } = await Promise.resolve().then(() => __importStar(require('../srv/server')));
114
+ await startCrawlerIfConfigured();
115
+ // Start the wallet worker if configured (plugin mode). Non-fatal.
116
+ await startWalletWorkerIfConfigured();
88
117
  // Re-drive deferred submissions interrupted by a restart (plugin mode). Non-fatal.
89
- const { redriveInterruptedSubmissionsIfConfigured } = await Promise.resolve().then(() => __importStar(require('../srv/server')));
90
118
  await redriveInterruptedSubmissionsIfConfigured();
91
119
  }
92
120
  /**
package/src/plugin.js CHANGED
@@ -52,28 +52,46 @@ if (!cds_1.default.env.requires) {
52
52
  if (!cds_1.default.env.requires.kinds) {
53
53
  cds_1.default.env.requires.kinds = {};
54
54
  }
55
+ /** The schema and the six CDS services this package ships, package-qualified. */
56
+ const PLUGIN_MODEL = [
57
+ '@odatano/core/db/schema',
58
+ '@odatano/core/srv/cardano-service',
59
+ '@odatano/core/srv/cardano-tx-service',
60
+ '@odatano/core/srv/cardano-sign-service',
61
+ '@odatano/core/srv/cardano-indexer-service',
62
+ '@odatano/core/srv/cardano-worker-service',
63
+ '@odatano/core/srv/cardano-agent-service'
64
+ ];
65
+ /** Relative `@impl` values used in the CDS files (rewritten in plugin mode, see below). */
66
+ const IMPL_PATHS = [
67
+ 'srv/cardano-service',
68
+ 'srv/cardano-tx-service',
69
+ 'srv/cardano-sign-service',
70
+ 'srv/cardano-indexer-service',
71
+ 'srv/cardano-worker-service',
72
+ 'srv/cardano-agent-service'
73
+ ];
55
74
  cds_1.default.env.requires.kinds['odatano-core'] = {
56
75
  impl: '@odatano/core',
57
- model: [
58
- '@odatano/core/db/schema',
59
- '@odatano/core/srv/cardano-service',
60
- '@odatano/core/srv/cardano-tx-service',
61
- '@odatano/core/srv/cardano-sign-service'
62
- ]
76
+ model: [...PLUGIN_MODEL]
63
77
  };
64
78
  // CRITICAL: Also set model directly on the requires entry.
65
79
  // CAP's _link_required_services() merges kind→requires BEFORE cds-plugin.js runs,
66
80
  // so the model array on the kind is never merged. Set it directly.
67
81
  const req = cds_1.default.env.requires['odatano-core'];
68
82
  if (req) {
69
- req.model = [
70
- '@odatano/core/db/schema',
71
- '@odatano/core/srv/cardano-service',
72
- '@odatano/core/srv/cardano-tx-service',
73
- '@odatano/core/srv/cardano-sign-service'
74
- ];
83
+ req.model = [...PLUGIN_MODEL];
75
84
  }
76
85
  logger.debug('Plugin registered');
86
+ /**
87
+ * Agent grants (AGENT_GRANTS_DESIGN.md). Off by default; switched on by
88
+ * cds.requires.odatano-core.agentGrants.enabled / AGENT_GRANTS_ENABLED=true.
89
+ * Has to run at plugin load, before CAP builds its middlewares (the auth impl
90
+ * is swapped here). srv/server.ts makes the same call for standalone mode, where
91
+ * this file is never loaded; the call is idempotent and never throws.
92
+ */
93
+ require('../srv/utils/agent-grants-config')
94
+ .activateAgentGrants();
77
95
  /**
78
96
  * Rewrite @impl paths for plugin mode.
79
97
  * CDS files use relative @impl (e.g. 'srv/cardano-service') which resolves from cds.root.
@@ -86,14 +104,9 @@ cds_1.default.on('loaded', (model) => {
86
104
  return;
87
105
  const defs = model.definitions ?? {};
88
106
  for (const def of Object.values(defs)) {
89
- if (def['@impl'] === 'srv/cardano-service') {
90
- def['@impl'] = '@odatano/core/srv/cardano-service';
91
- }
92
- else if (def['@impl'] === 'srv/cardano-tx-service') {
93
- def['@impl'] = '@odatano/core/srv/cardano-tx-service';
94
- }
95
- else if (def['@impl'] === 'srv/cardano-sign-service') {
96
- def['@impl'] = '@odatano/core/srv/cardano-sign-service';
107
+ const impl = def['@impl'];
108
+ if (impl && IMPL_PATHS.includes(impl)) {
109
+ def['@impl'] = `@odatano/core/${impl}`;
97
110
  }
98
111
  }
99
112
  });
@@ -1,11 +1,11 @@
1
- import { CardanoBackend } from './cardano-backend';
1
+ import { CardanoBackend, PaginatingBackend } from './cardano-backend';
2
2
  import { Transaction, BlockData, Address, UTxO, NetworkInformation, EpochData, MetadataLabelTx, PoolData, AccountData, DrepData, AssetInfo, AssetHistoryEntry, LedgerProtocolParameters } from '../../utils/types';
3
3
  import { Network } from '../cardano-client';
4
4
  /**
5
5
  * BlockfrostBackend Implementation for CardanoBackend Interface
6
6
  * Implements the CardanoBackend interface using Blockfrost API SDK
7
7
  */
8
- export declare class BlockfrostBackend implements CardanoBackend {
8
+ export declare class BlockfrostBackend implements CardanoBackend, PaginatingBackend {
9
9
  readonly name = "blockfrost";
10
10
  private api;
11
11
  private network;
@@ -151,5 +151,24 @@ export declare class BlockfrostBackend implements CardanoBackend {
151
151
  * @returns {Promise<Map<string, Transaction>>} map of hash -> Transaction
152
152
  */
153
153
  getTransactionsBatch(txHashes: string[]): Promise<Map<string, Transaction>>;
154
+ /**
155
+ * Map a Blockfrost block summary (from blocks()/blocksNext()) to our BlockData.
156
+ * Same shape getBlock() maps inline — kept private to avoid touching getBlock().
157
+ */
158
+ private toBlockData;
159
+ /**
160
+ * Get a block by its height. Blockfrost's `blocks` endpoint accepts a height as
161
+ * well as a hash.
162
+ */
163
+ getBlockByHeight(height: number): Promise<BlockData>;
164
+ /**
165
+ * Get up to `count` blocks immediately following `afterHash`, in ascending chain order.
166
+ */
167
+ getNextBlocks(afterHash: string, count: number): Promise<BlockData[]>;
168
+ /**
169
+ * Get the full transaction list of a block in block order. Blockfrost returns tx
170
+ * hashes; details are batched via getTransactionsBatch. Order is preserved.
171
+ */
172
+ getBlockTransactions(blockHash: string): Promise<Transaction[]>;
154
173
  }
155
174
  //# sourceMappingURL=blockfrost-backend.d.ts.map
@@ -68,21 +68,7 @@ class BlockfrostBackend {
68
68
  * @returns {Promise<BlockData>} block data
69
69
  */
70
70
  async getBlock(blockHash) {
71
- return (0, backend_request_handler_1.handleBackendRequest)(async () => {
72
- const blockdata = await this.api.blocks(blockHash);
73
- return {
74
- time: blockdata.time,
75
- height: blockdata.height,
76
- hash: blockdata.hash,
77
- slot: blockdata.slot,
78
- slotLeader: blockdata.slot_leader,
79
- epoch: blockdata.epoch,
80
- epochSlot: blockdata.epoch_slot,
81
- size: blockdata.size,
82
- txCount: blockdata.tx_count,
83
- fees: blockdata.fees,
84
- };
85
- }, this.name);
71
+ return (0, backend_request_handler_1.handleBackendRequest)(async () => this.toBlockData(await this.api.blocks(blockHash)), this.name);
86
72
  }
87
73
  /**
88
74
  * Get Epoch Data
@@ -288,16 +274,7 @@ class BlockfrostBackend {
288
274
  return (0, backend_request_handler_1.handleBackendRequest)(async () => {
289
275
  const a = await this.api.assetsById(unit);
290
276
  const reg = a.metadata ?? null;
291
- const decodeUtf8 = (hex) => {
292
- if (!hex)
293
- return null;
294
- try {
295
- return Buffer.from(hex, 'hex').toString('utf8');
296
- }
297
- catch {
298
- return null;
299
- }
300
- };
277
+ const decodeUtf8 = (hex) => (hex ? (0, mappers_1.decodeAssetName)(hex) : null);
301
278
  return {
302
279
  unit: a.asset,
303
280
  policyId: a.policy_id,
@@ -596,6 +573,73 @@ class BlockfrostBackend {
596
573
  return result;
597
574
  }, this.name);
598
575
  }
576
+ // ---------------------------------------------------------------------------
577
+ // PaginatingBackend — forward iteration for the chain crawler (v2.0)
578
+ // ---------------------------------------------------------------------------
579
+ /**
580
+ * Map a Blockfrost block summary (from blocks()/blocksNext()) to our BlockData.
581
+ * Same shape getBlock() maps inline — kept private to avoid touching getBlock().
582
+ */
583
+ toBlockData(b) {
584
+ return {
585
+ time: b.time,
586
+ height: b.height,
587
+ hash: b.hash,
588
+ slot: b.slot,
589
+ slotLeader: b.slot_leader,
590
+ epoch: b.epoch,
591
+ epochSlot: b.epoch_slot,
592
+ size: b.size,
593
+ txCount: b.tx_count,
594
+ fees: b.fees,
595
+ };
596
+ }
597
+ /**
598
+ * Get a block by its height. Blockfrost's `blocks` endpoint accepts a height as
599
+ * well as a hash.
600
+ */
601
+ async getBlockByHeight(height) {
602
+ return (0, backend_request_handler_1.handleBackendRequest)(async () => this.toBlockData(await this.api.blocks(height)), this.name);
603
+ }
604
+ /**
605
+ * Get up to `count` blocks immediately following `afterHash`, in ascending chain order.
606
+ */
607
+ async getNextBlocks(afterHash, count) {
608
+ return (0, backend_request_handler_1.handleBackendRequest)(async () => {
609
+ let blocks;
610
+ try {
611
+ blocks = await this.api.blocksNext(afterHash, { count });
612
+ }
613
+ catch (err) {
614
+ // Blockfrost only knows canonical blocks — a 404 on the anchor means the
615
+ // cursor block was orphaned by a reorg. Emit the crawler's explicit
616
+ // mismatch signal (same contract as KoiosBackend.getNextBlocks); a plain
617
+ // NotFoundError would be treated as transient and the crawler would halt
618
+ // with an error streak instead of entering reorg recovery.
619
+ const normalized = (0, errors_1.normalizeBackendError)(err, this.name);
620
+ if (normalized.statusCode === 404) {
621
+ throw new errors_1.ProviderUnavailableError(`CHAIN_POINT_MISMATCH: cursor block ${afterHash} is unknown to ${this.name} — likely orphaned by a reorg`, this.name);
622
+ }
623
+ throw err;
624
+ }
625
+ return blocks.map(b => this.toBlockData(b));
626
+ }, this.name);
627
+ }
628
+ /**
629
+ * Get the full transaction list of a block in block order. Blockfrost returns tx
630
+ * hashes; details are batched via getTransactionsBatch. Order is preserved.
631
+ */
632
+ async getBlockTransactions(blockHash) {
633
+ return (0, backend_request_handler_1.handleBackendRequest)(async () => {
634
+ const hashes = await this.api.blocksTxsAll(blockHash);
635
+ if (!hashes.length)
636
+ return [];
637
+ const byHash = await this.getTransactionsBatch(hashes);
638
+ return hashes
639
+ .map(h => byHash.get(h))
640
+ .filter((t) => t !== undefined);
641
+ }, this.name);
642
+ }
599
643
  }
600
644
  exports.BlockfrostBackend = BlockfrostBackend;
601
645
  //# sourceMappingURL=blockfrost-backend.js.map
@@ -179,4 +179,73 @@ export interface EvaluatingBackend extends CardanoBackend {
179
179
  * @returns true if the backend supports evaluateTransaction
180
180
  */
181
181
  export declare function isEvaluatingBackend(backend: CardanoBackend): backend is EvaluatingBackend;
182
+ /** A chain position the crawler can start from, stream to, or roll back to. */
183
+ export interface ChainPoint {
184
+ slot: number;
185
+ hash: string;
186
+ height?: number;
187
+ }
188
+ /** Callbacks driven by a streamed chain-sync (Ogmios). */
189
+ export interface ChainSyncCallbacks {
190
+ /**
191
+ * A new block (with its full transaction list) extends the chain.
192
+ * @param tip the node's current chain tip, when the protocol supplies it — lets the
193
+ * consumer track sync progress / detect being caught up
194
+ */
195
+ rollForward(block: BlockData, txs: Transaction[], tip?: ChainPoint): Promise<void>;
196
+ /** The chain rolled back to `point` (or to genesis). All blocks after it are abandoned. */
197
+ rollBackward(point: ChainPoint | 'origin'): Promise<void>;
198
+ /**
199
+ * A message-handler error stalled the stream (mapping failure, callback throw). The
200
+ * stream stops requesting further blocks; the consumer should record the error and
201
+ * close/restart. Optional — without it such errors are only logged.
202
+ */
203
+ onError?(err: unknown): Promise<void>;
204
+ }
205
+ /** Handle to an open chain-sync stream. */
206
+ export interface ChainSyncHandle {
207
+ /** Stop streaming and release the underlying connection. */
208
+ close(): Promise<void>;
209
+ }
210
+ /**
211
+ * Backend that can stream the chain forward from a point, emitting ordered
212
+ * rollForward + native rollBackward (reorg) events. Implemented by Ogmios via the
213
+ * chain-synchronization protocol — the crawler's primary, reorg-aware source.
214
+ */
215
+ export interface ChainSyncBackend extends CardanoBackend {
216
+ /**
217
+ * Open a chain-sync stream starting just after the first of `from` that is still
218
+ * on the node's chain (or from genesis).
219
+ * @param from candidate intersection points, NEWEST FIRST, or 'origin' for a
220
+ * fresh sync. Passing ancestors as well as the last-indexed point is what makes
221
+ * a reorg that happened while we were disconnected resolvable: the node
222
+ * intersects at the last common block and reports it via rollBackward, instead
223
+ * of failing the whole stream with "No intersection found".
224
+ * @param callbacks rollForward / rollBackward handlers
225
+ * @returns a handle to close the stream
226
+ */
227
+ openChainSync(from: ChainPoint[] | 'origin', callbacks: ChainSyncCallbacks): Promise<ChainSyncHandle>;
228
+ }
229
+ /** Type guard: does this backend support streamed chain-sync? */
230
+ export declare function isChainSyncBackend(backend: CardanoBackend): backend is ChainSyncBackend;
231
+ /**
232
+ * Backend that can walk the chain forward by pagination (no live node). The
233
+ * crawler's fallback source when no Ogmios chain-sync is available. Reorgs are
234
+ * detected by the crawler via parent-hash mismatch (not delivered natively).
235
+ */
236
+ export interface PaginatingBackend extends CardanoBackend {
237
+ /** Fetch a block by its height. */
238
+ getBlockByHeight(height: number): Promise<BlockData>;
239
+ /**
240
+ * Fetch up to `count` blocks immediately following `afterHash`, in chain order.
241
+ * @param afterHeight optional height of `afterHash` when the caller already knows it
242
+ * (the crawler's cursor does) — lets height-listing backends
243
+ * (Koios) skip a hash→height resolution round-trip
244
+ */
245
+ getNextBlocks(afterHash: string, count: number, afterHeight?: number): Promise<BlockData[]>;
246
+ /** Fetch the full transaction list of a block, in block order. */
247
+ getBlockTransactions(blockHash: string): Promise<Transaction[]>;
248
+ }
249
+ /** Type guard: can this backend be walked forward by pagination? */
250
+ export declare function isPaginatingBackend(backend: CardanoBackend): backend is PaginatingBackend;
182
251
  //# sourceMappingURL=cardano-backend.d.ts.map
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.isEvaluatingBackend = isEvaluatingBackend;
4
+ exports.isChainSyncBackend = isChainSyncBackend;
5
+ exports.isPaginatingBackend = isPaginatingBackend;
4
6
  /**
5
7
  * Type guard to check if a backend supports transaction evaluation
6
8
  * @param backend - The backend to check
@@ -9,4 +11,15 @@ exports.isEvaluatingBackend = isEvaluatingBackend;
9
11
  function isEvaluatingBackend(backend) {
10
12
  return typeof backend.evaluateTransaction === 'function';
11
13
  }
14
+ /** Type guard: does this backend support streamed chain-sync? */
15
+ function isChainSyncBackend(backend) {
16
+ return typeof backend.openChainSync === 'function';
17
+ }
18
+ /** Type guard: can this backend be walked forward by pagination? */
19
+ function isPaginatingBackend(backend) {
20
+ const b = backend;
21
+ return typeof b.getBlockByHeight === 'function'
22
+ && typeof b.getNextBlocks === 'function'
23
+ && typeof b.getBlockTransactions === 'function';
24
+ }
12
25
  //# sourceMappingURL=cardano-backend.js.map
@@ -1,11 +1,11 @@
1
- import { CardanoBackend } from './cardano-backend';
1
+ import { CardanoBackend, PaginatingBackend } from './cardano-backend';
2
2
  import { Transaction, BlockData, Address, UTxO, NetworkInformation, EpochData, MetadataLabelTx, PoolData, DrepData, AccountData, AssetInfo, AssetHistoryEntry, LedgerProtocolParameters } from '../../utils/types';
3
3
  import { Network } from '../cardano-client';
4
4
  /**
5
5
  * KoiosBackend Implementation for CardanoBackend Interface
6
6
  * Implements the CardanoBackend interface using Koios API with Axios
7
7
  */
8
- export declare class KoiosBackend implements CardanoBackend {
8
+ export declare class KoiosBackend implements CardanoBackend, PaginatingBackend {
9
9
  readonly name = "koios";
10
10
  private api;
11
11
  private network;
@@ -173,6 +173,30 @@ export declare class KoiosBackend implements CardanoBackend {
173
173
  * @returns {Promise<Map<string, Transaction>>} map of hash -> Transaction
174
174
  */
175
175
  getTransactionsBatch(txHashes: string[]): Promise<Map<string, Transaction>>;
176
+ /**
177
+ * Map a Koios /block_info response object to our BlockData (same shape getBlock
178
+ * maps inline; kept private to avoid touching getBlock).
179
+ */
180
+ private mapKoiosBlockInfo;
181
+ /**
182
+ * Get a block by its height via the PostgREST-filtered /blocks list, then resolve
183
+ * full data through /block_info.
184
+ */
185
+ getBlockByHeight(height: number): Promise<BlockData>;
186
+ /**
187
+ * Get up to `count` blocks following `afterHash`, in ascending chain order.
188
+ * Koios has no "next after hash" endpoint, so we list blocks above the anchor height
189
+ * (PostgREST gt + order + limit), then batch /block_info. When the caller already
190
+ * knows the anchor height (the crawler's cursor), the hash→height resolution
191
+ * round-trip is skipped entirely.
192
+ */
193
+ getNextBlocks(afterHash: string, count: number, afterHeight?: number): Promise<BlockData[]>;
194
+ /**
195
+ * Get the full transaction list of a block in block order via /block_txs → /tx_info
196
+ * batch. Handles both the current flattened shape ({tx_hash} per row) and the older
197
+ * {tx_hashes:[...]} shape defensively.
198
+ */
199
+ getBlockTransactions(blockHash: string): Promise<Transaction[]>;
176
200
  /**
177
201
  * Map a Koios /tx_info response object to the normalized Transaction type.
178
202
  */
@@ -12,6 +12,9 @@ const mappers_1 = require("../../utils/mappers");
12
12
  const const_1 = require("../../utils/const");
13
13
  const tx_build_helper_1 = require("../../utils/tx-build-helper");
14
14
  const logger = cds_1.default.log('KoiosBackend');
15
+ /** Bounded retries for instance-specific PostgREST server errors (42703, 57014, …). */
16
+ const PG_SERVER_ERROR_MAX_RETRIES = 2;
17
+ const PG_SERVER_ERROR_RETRY_DELAY_MS = 300;
15
18
  const KOIOS_URLS = {
16
19
  mainnet: 'https://api.koios.rest/api/v1',
17
20
  preview: 'https://preview.koios.rest/api/v1',
@@ -72,6 +75,25 @@ class KoiosBackend {
72
75
  headers,
73
76
  });
74
77
  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.
84
+ this.api.interceptors.response.use(undefined, async (error) => {
85
+ const config = error.config;
86
+ const pgCode = error.response?.data?.code;
87
+ if (!config || !(0, errors_1.isPostgrestServerErrorCode)(pgCode))
88
+ throw error;
89
+ const attempt = (config.pgRetryCount ?? 0) + 1;
90
+ if (attempt > PG_SERVER_ERROR_MAX_RETRIES)
91
+ throw error;
92
+ config.pgRetryCount = attempt;
93
+ logger.warn(`Koios instance returned server-side SQL error ${pgCode} for ${config.url} — retry ${attempt}/${PG_SERVER_ERROR_MAX_RETRIES}`);
94
+ await new Promise(resolve => setTimeout(resolve, PG_SERVER_ERROR_RETRY_DELAY_MS * attempt));
95
+ return this.api.request(config);
96
+ });
75
97
  }
76
98
  /**
77
99
  * Initialize the backend
@@ -181,19 +203,7 @@ class KoiosBackend {
181
203
  if (!results || results.length === 0) {
182
204
  throw new errors_1.NotFoundError('Block', this.name);
183
205
  }
184
- const data = results[0];
185
- return {
186
- time: data.block_time,
187
- height: data.block_height,
188
- hash: data.hash,
189
- slot: data.abs_slot,
190
- epoch: data.epoch_no,
191
- epochSlot: data.epoch_slot,
192
- slotLeader: data.vrf_key,
193
- size: data.block_size,
194
- txCount: data.tx_count,
195
- fees: data.total_fees,
196
- };
206
+ return this.mapKoiosBlockInfo(results[0]);
197
207
  }, this.name);
198
208
  }
199
209
  /**
@@ -509,16 +519,7 @@ class KoiosBackend {
509
519
  const onchainMetadata = mintMeta && typeof mintMeta === 'object'
510
520
  ? (mintMeta['721'] ?? mintMeta)
511
521
  : null;
512
- const decodeUtf8 = (hex) => {
513
- if (!hex)
514
- return null;
515
- try {
516
- return Buffer.from(hex, 'hex').toString('utf8');
517
- }
518
- catch {
519
- return null;
520
- }
521
- };
522
+ const decodeUtf8 = (hex) => (hex ? (0, mappers_1.decodeAssetName)(hex) : null);
522
523
  const mintCnt = typeof a.mint_cnt === 'number' ? a.mint_cnt : 0;
523
524
  const burnCnt = typeof a.burn_cnt === 'number' ? a.burn_cnt : 0;
524
525
  return {
@@ -596,14 +597,23 @@ class KoiosBackend {
596
597
  throw new errors_1.NotFoundError('Drep', this.name);
597
598
  }
598
599
  const drepData = data[0];
600
+ // Koios changed the /drep_info schema (observed 2026-07): the old
601
+ // `expired`/`retired`/`last_active_epoch` fields were replaced by
602
+ // `drep_status` ('registered' | 'retired'), `active` (boolean) and
603
+ // `expires_epoch_no`. Read the old fields first (mainnet/preprod may
604
+ // lag the migration), then derive from the new ones.
605
+ const retired = drepData.retired ?? drepData.drep_status === 'retired';
606
+ const expired = drepData.expired ?? (drepData.active === false && !retired);
599
607
  return {
600
608
  drepId: drepData.drep_id,
601
609
  hex: drepData.hex,
602
610
  amount: drepData.amount,
603
611
  hasScript: drepData.has_script,
612
+ // The new schema no longer reports the last-activity epoch (only
613
+ // `expires_epoch_no`, which has different semantics) — keep 0 there.
604
614
  lastActiveEpoch: drepData.last_active_epoch ?? 0,
605
- expired: drepData.expired,
606
- retired: drepData.retired,
615
+ expired,
616
+ retired,
607
617
  };
608
618
  }, this.name);
609
619
  }
@@ -840,6 +850,119 @@ class KoiosBackend {
840
850
  return result;
841
851
  }, this.name);
842
852
  }
853
+ // ---------------------------------------------------------------------------
854
+ // PaginatingBackend — forward iteration for the chain crawler (v2.0)
855
+ // ---------------------------------------------------------------------------
856
+ /**
857
+ * Map a Koios /block_info response object to our BlockData (same shape getBlock
858
+ * maps inline; kept private to avoid touching getBlock).
859
+ */
860
+ mapKoiosBlockInfo(data) {
861
+ return {
862
+ time: data.block_time,
863
+ height: data.block_height,
864
+ hash: data.hash,
865
+ slot: data.abs_slot,
866
+ epoch: data.epoch_no,
867
+ epochSlot: data.epoch_slot,
868
+ slotLeader: data.vrf_key,
869
+ size: data.block_size,
870
+ txCount: data.tx_count,
871
+ fees: data.total_fees,
872
+ };
873
+ }
874
+ /**
875
+ * Get a block by its height via the PostgREST-filtered /blocks list, then resolve
876
+ * full data through /block_info.
877
+ */
878
+ async getBlockByHeight(height) {
879
+ return (0, backend_request_handler_1.handleBackendRequest)(async () => {
880
+ const rows = await this.fetchWithRetryOnEmpty(() => this.api.get(`/blocks?block_height=eq.${height}&limit=1`), `getBlockByHeight(${height})`);
881
+ if (!rows.length)
882
+ throw new errors_1.NotFoundError('Block', this.name);
883
+ return await this.getBlock(rows[0].hash);
884
+ }, this.name);
885
+ }
886
+ /**
887
+ * Get up to `count` blocks following `afterHash`, in ascending chain order.
888
+ * Koios has no "next after hash" endpoint, so we list blocks above the anchor height
889
+ * (PostgREST gt + order + limit), then batch /block_info. When the caller already
890
+ * knows the anchor height (the crawler's cursor), the hash→height resolution
891
+ * round-trip is skipped entirely.
892
+ */
893
+ async getNextBlocks(afterHash, count, afterHeight) {
894
+ return (0, backend_request_handler_1.handleBackendRequest)(async () => {
895
+ let anchorHeight = afterHeight;
896
+ if (anchorHeight != null && anchorHeight > 0) {
897
+ // A height hint saves the hash -> height lookup, but it must never be
898
+ // trusted as proof that the cursor is still on the canonical chain.
899
+ // After a rollback Koios can continue listing canonical blocks above H
900
+ // even though `afterHash` is the now-orphaned block at H. Validate the
901
+ // canonical hash first so the crawler enters its reorg-recovery path.
902
+ const canonical = await this.fetchWithRetryOnEmpty(() => this.api.get(`/blocks?block_height=eq.${anchorHeight}&limit=1`), `getNextBlocks/anchor(${anchorHeight})`);
903
+ const canonicalHash = canonical[0]?.hash;
904
+ if (!canonicalHash) {
905
+ throw new errors_1.ProviderUnavailableError(`Unable to validate canonical block at height ${anchorHeight}`, this.name);
906
+ }
907
+ if (canonicalHash !== afterHash) {
908
+ throw new errors_1.ProviderUnavailableError(`CHAIN_POINT_MISMATCH: cursor block ${afterHash} at height ${anchorHeight} is no longer canonical (canonical block: ${canonicalHash})`, this.name);
909
+ }
910
+ }
911
+ else {
912
+ const info = await this.fetchWithRetryOnEmpty(() => this.api.post('/block_info', { _block_hashes: [afterHash] }), `getNextBlocks/height(${afterHash})`);
913
+ if (!info.length)
914
+ throw new errors_1.NotFoundError('Block', this.name);
915
+ anchorHeight = info[0].block_height;
916
+ }
917
+ const rows = await this.fetchWithRetryOnEmpty(() => this.api.get(`/blocks?block_height=gt.${anchorHeight}&order=block_height.asc&limit=${count}`), `getNextBlocks(${afterHash})`);
918
+ if (!rows.length)
919
+ return [];
920
+ const requestedHashes = rows.map((r) => r.hash);
921
+ const infos = await this.fetchWithRetryOnEmpty(() => this.api.post('/block_info', { _block_hashes: requestedHashes }), `getNextBlocks/info(${afterHash})`);
922
+ // Completeness guard: Koios' load-balanced instances can return a PARTIAL
923
+ // /block_info batch (fetchWithRetryOnEmpty only retries fully empty
924
+ // responses). Returning the subset would let the crawler advance its cursor
925
+ // past the missing block, leaving a permanent hole in the pre-synced range
926
+ // (crawled entities are non-temporal — nothing re-fetches them). Fail the
927
+ // round as transient instead; the next round retries the same anchor.
928
+ if (infos.length < requestedHashes.length) {
929
+ const returned = new Set(infos.map((d) => d.hash));
930
+ const missing = requestedHashes.filter((h) => !returned.has(h));
931
+ throw new errors_1.ProviderUnavailableError(`Incomplete /block_info batch: ${infos.length}/${requestedHashes.length} blocks returned (missing: ${missing.slice(0, 3).join(', ')}${missing.length > 3 ? ', …' : ''})`, this.name);
932
+ }
933
+ return infos
934
+ .map((d) => this.mapKoiosBlockInfo(d))
935
+ .sort((a, b) => (a.height ?? 0) - (b.height ?? 0));
936
+ }, this.name);
937
+ }
938
+ /**
939
+ * Get the full transaction list of a block in block order via /block_txs → /tx_info
940
+ * batch. Handles both the current flattened shape ({tx_hash} per row) and the older
941
+ * {tx_hashes:[...]} shape defensively.
942
+ */
943
+ async getBlockTransactions(blockHash) {
944
+ return (0, backend_request_handler_1.handleBackendRequest)(async () => {
945
+ const rows = await this.fetchWithRetryOnEmpty(() => this.api.post('/block_txs', { _block_hashes: [blockHash] }), `getBlockTransactions(${blockHash})`);
946
+ const hashes = [];
947
+ for (const row of rows) {
948
+ if (Array.isArray(row.tx_hashes))
949
+ hashes.push(...row.tx_hashes);
950
+ else if (row.tx_hash)
951
+ hashes.push(row.tx_hash);
952
+ }
953
+ if (!hashes.length)
954
+ return [];
955
+ const byHash = await this.getTransactionsBatch(hashes);
956
+ const missing = hashes.filter(h => !byHash.has(h));
957
+ if (missing.length > 0) {
958
+ // Advancing the block cursor with only a subset of /tx_info would make
959
+ // the omitted transactions permanent. Surface a 503 so the crawler
960
+ // retries the whole block without persisting it.
961
+ throw new errors_1.ProviderUnavailableError(`Incomplete transaction data for block ${blockHash}: ${missing.length}/${hashes.length} transaction(s) missing`, this.name);
962
+ }
963
+ return hashes.map(h => byHash.get(h));
964
+ }, this.name);
965
+ }
843
966
  //-----------------------------------------------------------------------------
844
967
  // Private Helpers
845
968
  //-----------------------------------------------------------------------------