@odatano/core 2.0.0-rc.4 → 2.0.0-rc.40

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 (166) 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/CardanoBackendService/index.d.ts +357 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +194 -2
  6. package/@cds-models/CardanoIndexerService/index.js +25 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +305 -7
  8. package/@cds-models/CardanoODataService/index.js +34 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +28 -3
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +46 -13
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/index.d.ts +72 -0
  14. package/@cds-models/index.js +12 -0
  15. package/@cds-models/odatano/cardano/index.d.ts +408 -7
  16. package/@cds-models/odatano/cardano/index.js +42 -0
  17. package/README.md +64 -5
  18. package/db/schema.cds +2297 -1633
  19. package/db/types.cds +114 -0
  20. package/package.json +27 -6
  21. package/scripts/migrate-slot-leader.mjs +104 -0
  22. package/scripts/migrate-txseq.mjs +147 -0
  23. package/src/index.d.ts +18 -11
  24. package/src/index.js +44 -14
  25. package/src/plugin.js +42 -52
  26. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  27. package/srv/blockchain/backends/blockfrost-backend.js +53 -162
  28. package/srv/blockchain/backends/cardano-backend.d.ts +104 -158
  29. package/srv/blockchain/backends/cardano-backend.js +19 -5
  30. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  31. package/srv/blockchain/backends/koios-backend.js +376 -235
  32. package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
  33. package/srv/blockchain/backends/odatano-backend.js +170 -0
  34. package/srv/blockchain/backends/ogmios-backend.d.ts +162 -94
  35. package/srv/blockchain/backends/ogmios-backend.js +556 -201
  36. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  37. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  38. package/srv/blockchain/cardano-client.d.ts +87 -202
  39. package/srv/blockchain/cardano-client.js +210 -240
  40. package/srv/blockchain/cardano-indexer.d.ts +311 -242
  41. package/srv/blockchain/cardano-indexer.js +1238 -362
  42. package/srv/blockchain/cardano-tx-builder.d.ts +44 -81
  43. package/srv/blockchain/cardano-tx-builder.js +173 -132
  44. package/srv/blockchain/crawler/certificate-backfill.d.ts +67 -0
  45. package/srv/blockchain/crawler/certificate-backfill.js +169 -0
  46. package/srv/blockchain/crawler/crawler.d.ts +139 -54
  47. package/srv/blockchain/crawler/crawler.js +478 -96
  48. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  49. package/srv/blockchain/crawler/index.d.ts +5 -0
  50. package/srv/blockchain/crawler/index.js +35 -7
  51. package/srv/blockchain/crawler/sync-state.d.ts +46 -28
  52. package/srv/blockchain/crawler/sync-state.js +128 -43
  53. package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
  54. package/srv/blockchain/crawler/transaction-backfill.js +283 -0
  55. package/srv/blockchain/crawler/utxo-set-import.d.ts +78 -0
  56. package/srv/blockchain/crawler/utxo-set-import.js +363 -0
  57. package/srv/blockchain/ledger-state.d.ts +101 -0
  58. package/srv/blockchain/ledger-state.js +432 -0
  59. package/srv/blockchain/pending-spends.d.ts +28 -0
  60. package/srv/blockchain/pending-spends.js +89 -0
  61. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  62. package/srv/blockchain/signing/cose-verifier.js +6 -12
  63. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  64. package/srv/blockchain/signing/external-signer.js +19 -122
  65. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  66. package/srv/blockchain/signing/hsm-signer.js +23 -63
  67. package/srv/blockchain/signing/signature-verifier.d.ts +14 -45
  68. package/srv/blockchain/signing/signature-verifier.js +73 -76
  69. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  70. package/srv/blockchain/signing/submission-finalizer.js +16 -49
  71. package/srv/blockchain/stored-chain.d.ts +33 -0
  72. package/srv/blockchain/stored-chain.js +234 -0
  73. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +111 -173
  74. package/srv/blockchain/transaction-building/buildooor-tx.js +649 -326
  75. package/srv/blockchain/transaction-building/caller-datums.d.ts +29 -0
  76. package/srv/blockchain/transaction-building/caller-datums.js +139 -0
  77. package/srv/blockchain/transaction-building/cardano-tx.d.ts +10 -35
  78. package/srv/blockchain/transaction-rows.d.ts +12 -0
  79. package/srv/blockchain/transaction-rows.js +43 -0
  80. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  81. package/srv/blockchain/wallet-worker/build-request.js +18 -23
  82. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  84. package/srv/blockchain/wallet-worker/index.js +2 -8
  85. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  86. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  87. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  88. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  89. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  90. package/srv/blockchain/wallet-worker/signers.js +3 -8
  91. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  92. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  93. package/srv/cardano-agent-service.cds +146 -0
  94. package/srv/cardano-agent-service.d.ts +2 -0
  95. package/srv/cardano-agent-service.js +12 -0
  96. package/srv/cardano-backend-service.cds +52 -0
  97. package/srv/cardano-backend-service.d.ts +2 -0
  98. package/srv/cardano-backend-service.js +244 -0
  99. package/srv/cardano-indexer-service.cds +201 -73
  100. package/srv/cardano-indexer-service.js +280 -11
  101. package/srv/cardano-service.cds +65 -2
  102. package/srv/cardano-service.js +170 -129
  103. package/srv/cardano-sign-service.cds +200 -180
  104. package/srv/cardano-sign-service.js +57 -184
  105. package/srv/cardano-tx-service.cds +439 -370
  106. package/srv/cardano-tx-service.js +231 -190
  107. package/srv/cardano-ui.cds +16 -16
  108. package/srv/cardano-worker-service.js +7 -15
  109. package/srv/cbor/index.d.ts +1 -1
  110. package/srv/cbor/parse.d.ts +27 -0
  111. package/srv/cbor/parse.js +63 -2
  112. package/srv/server.d.ts +28 -86
  113. package/srv/server.js +132 -135
  114. package/srv/utils/agent-grants-config.d.ts +37 -0
  115. package/srv/utils/agent-grants-config.js +138 -0
  116. package/srv/utils/agent-grants.d.ts +262 -0
  117. package/srv/utils/agent-grants.js +922 -0
  118. package/srv/utils/agent-token-auth.d.ts +16 -0
  119. package/srv/utils/agent-token-auth.js +78 -0
  120. package/srv/utils/backend-request-handler.d.ts +2 -16
  121. package/srv/utils/backend-request-handler.js +3 -18
  122. package/srv/utils/collections.d.ts +4 -8
  123. package/srv/utils/collections.js +4 -8
  124. package/srv/utils/const.d.ts +30 -67
  125. package/srv/utils/const.js +32 -72
  126. package/srv/utils/crypto.d.ts +3 -12
  127. package/srv/utils/crypto.js +5 -18
  128. package/srv/utils/db-indexes.d.ts +25 -0
  129. package/srv/utils/db-indexes.js +94 -0
  130. package/srv/utils/db-sanitize.d.ts +27 -0
  131. package/srv/utils/db-sanitize.js +85 -0
  132. package/srv/utils/epoch-slots.d.ts +20 -0
  133. package/srv/utils/epoch-slots.js +43 -0
  134. package/srv/utils/error-codes.d.ts +20 -73
  135. package/srv/utils/error-codes.js +19 -70
  136. package/srv/utils/errors.d.ts +50 -177
  137. package/srv/utils/errors.js +94 -218
  138. package/srv/utils/legacy-service-paths.d.ts +11 -0
  139. package/srv/utils/legacy-service-paths.js +58 -0
  140. package/srv/utils/liveness.d.ts +16 -0
  141. package/srv/utils/liveness.js +40 -0
  142. package/srv/utils/mappers.d.ts +128 -214
  143. package/srv/utils/mappers.js +354 -299
  144. package/srv/utils/network-context.js +2 -11
  145. package/srv/utils/pg-inline-json.d.ts +8 -0
  146. package/srv/utils/pg-inline-json.js +62 -0
  147. package/srv/utils/pg-order-nulls.d.ts +14 -0
  148. package/srv/utils/pg-order-nulls.js +56 -0
  149. package/srv/utils/plutus-placeholders.d.ts +23 -16
  150. package/srv/utils/plutus-placeholders.js +63 -27
  151. package/srv/utils/rate-limiter.d.ts +46 -0
  152. package/srv/utils/rate-limiter.js +116 -0
  153. package/srv/utils/service-events.d.ts +2 -22
  154. package/srv/utils/service-events.js +3 -23
  155. package/srv/utils/signing-helper.d.ts +6 -16
  156. package/srv/utils/signing-helper.js +36 -60
  157. package/srv/utils/tx-build-helper.d.ts +28 -93
  158. package/srv/utils/tx-build-helper.js +75 -124
  159. package/srv/utils/tx-request-parsers.d.ts +101 -28
  160. package/srv/utils/tx-request-parsers.js +410 -43
  161. package/srv/utils/tx-utils.d.ts +4 -23
  162. package/srv/utils/tx-utils.js +12 -41
  163. package/srv/utils/types.d.ts +252 -179
  164. package/srv/utils/types.js +2 -6
  165. package/srv/utils/validators.d.ts +24 -90
  166. package/srv/utils/validators.js +50 -147
package/srv/server.js CHANGED
@@ -3,6 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.activateAgentGrants = exports.loadAgentGrantsConfig = void 0;
6
7
  exports.getAppContext = getAppContext;
7
8
  exports.getCardanoIndexer = getCardanoIndexer;
8
9
  exports.getCardanoClient = getCardanoClient;
@@ -26,17 +27,39 @@ const cardano_tx_builder_1 = require("./blockchain/cardano-tx-builder");
26
27
  const hsm_signer_1 = require("./blockchain/signing/hsm-signer");
27
28
  const errors_1 = require("./utils/errors");
28
29
  const network_context_1 = require("./utils/network-context");
30
+ const db_sanitize_1 = require("./utils/db-sanitize");
31
+ const db_indexes_1 = require("./utils/db-indexes");
32
+ const pg_order_nulls_1 = require("./utils/pg-order-nulls");
33
+ const pg_inline_json_1 = require("./utils/pg-inline-json");
29
34
  const crawler_1 = require("./blockchain/crawler");
30
35
  const wallet_worker_1 = require("./blockchain/wallet-worker");
36
+ const agent_grants_config_1 = require("./utils/agent-grants-config");
37
+ const legacy_service_paths_1 = require("./utils/legacy-service-paths");
31
38
  const process_1 = require("process");
32
39
  const logger = cds_1.default.log('ODATANO');
33
40
  const VALID_NETWORKS = ['mainnet', 'preview', 'preprod'];
34
- const VALID_BACKENDS = ['blockfrost', 'koios', 'ogmios'];
41
+ function coreCdsConfig() {
42
+ const requires = cds_1.default.env?.requires;
43
+ return requires?.['odatano-core'] ?? {};
44
+ }
45
+ const VALID_BACKENDS = ['blockfrost', 'koios', 'ogmios', 'odatano'];
35
46
  const CRAWLER_LIMITS = {
36
47
  batchSize: { min: 1, max: 100 },
37
48
  confirmationDepth: { min: 0, max: 2160 },
38
49
  pollIntervalMs: { min: 1000, max: 3_600_000 },
50
+ assetEnrichRate: { min: 1, max: 20 },
39
51
  };
52
+ const VALID_ASSET_CATALOGUE_MODES = ['off', 'bare', 'enrich'];
53
+ /** Parse a boolean crawler flag that defaults to `fallback` when unset. */
54
+ function crawlerBoolean(raw, name, fallback) {
55
+ if (raw === undefined || raw === null)
56
+ return fallback;
57
+ if (raw === true || raw === 'true')
58
+ return true;
59
+ if (raw === false || raw === 'false')
60
+ return false;
61
+ throw new errors_1.ConfigError(`Invalid ${name} "${String(raw)}". Must be true or false.`);
62
+ }
40
63
  /** Parse an integer without allowing JavaScript's lossy/implicit coercions. */
41
64
  function crawlerInteger(raw, name, min, max, defaultValue) {
42
65
  if (raw == null)
@@ -54,24 +77,32 @@ function crawlerInteger(raw, name, min, max, defaultValue) {
54
77
  let appContext = null;
55
78
  let bootstrapError = null;
56
79
  /**
57
- * Initialize the application context with blockchain components
58
- * Called once during CAP server startup via cds.on('served')
59
- * @param config - CardanoClientConfig
60
- * @param protocolParams - Optional protocol parameters (for tests to skip backend call)
80
+ * Initialize the application context; every start path (standalone hook, plugin) comes through here.
81
+ * @param protocolParams - optional, lets tests skip the backend call
61
82
  */
62
83
  async function initializeAppContext(config, protocolParams, hsmConfig) {
63
84
  logger.debug('Initializing blockchain components...');
64
- // Create CardanoClient from configuration
85
+ // Database first. Postgres ORDER BY without a NULLS clause on key / NOT NULL columns so
86
+ // the indexes serve `$top` / `$orderby`, bulk rows inline instead of through a COPY buffer;
87
+ // then the secondary indexes the model cannot declare.
88
+ (0, pg_order_nulls_1.installPostgresOrderNulls)();
89
+ (0, pg_inline_json_1.installPostgresInlineJson)();
90
+ try {
91
+ await (0, db_indexes_1.ensureDbIndexes)();
92
+ }
93
+ catch (err) {
94
+ logger.warn('secondary indexes not ensured (non-fatal):', err);
95
+ }
65
96
  const cardanoClient = new cardano_client_1.CardanoClient(config);
66
- // Publish the active network for leaf utilities (e.g. network-aware validators)
67
- // without forcing them to import this module / the full server graph.
97
+ // Lets leaf utilities (network-aware validators) read the network without importing this module.
68
98
  (0, network_context_1.setActiveNetwork)(config.network);
69
- // Create CardanoTransactionBuilder with the client
70
99
  const cardanoTxBuilder = new cardano_tx_builder_1.CardanoTransactionBuilder(cardanoClient);
71
100
  await cardanoTxBuilder.init(protocolParams);
72
- // Create CardanoIndexer with client and transaction builder
101
+ // PostgreSQL rejects U+0000 in text/JSON; one db-level `before` hook covers every write.
102
+ if ((0, db_sanitize_1.installDbSanitizer)())
103
+ logger.debug('DB NUL sanitizer installed');
73
104
  const cardanoIndexer = new cardano_indexer_1.CardanoIndexer(cardanoClient, cardanoTxBuilder);
74
- // Initialize HSM signer if configured (failure is non-fatal — won't crash the app)
105
+ // HSM signer failure is non-fatal
75
106
  if (hsmConfig?.enabled) {
76
107
  try {
77
108
  const hsmSigner = new hsm_signer_1.HsmSigner(hsmConfig);
@@ -91,11 +122,17 @@ async function initializeAppContext(config, protocolParams, hsmConfig) {
91
122
  cardanoTxBuilder,
92
123
  };
93
124
  }
125
+ /** Agent-grant feature switch; its own module so src/plugin.ts can read it at load. */
126
+ var agent_grants_config_2 = require("./utils/agent-grants-config");
127
+ Object.defineProperty(exports, "loadAgentGrantsConfig", { enumerable: true, get: function () { return agent_grants_config_2.loadAgentGrantsConfig; } });
128
+ Object.defineProperty(exports, "activateAgentGrants", { enumerable: true, get: function () { return agent_grants_config_2.activateAgentGrants; } });
129
+ // Standalone mode never loads src/plugin.ts, so swap the auth impl here as well
130
+ // (bin/serve.js imports this file before the middlewares exist). Idempotent.
131
+ (0, agent_grants_config_1.activateAgentGrants)();
132
+ (0, legacy_service_paths_1.registerLegacyServicePaths)();
94
133
  /**
95
- * Get the application context (must be called after bootstrap)
96
- * @throws {ProviderUnavailableError} 503 when uninitialized — request handlers using
97
- * handleRequest/mapError translate this into a clean 503 response instead of a raw 500.
98
- * If bootstrap actively failed, the cause is appended to the message.
134
+ * The application context.
135
+ * @throws {ProviderUnavailableError} 503 when uninitialized; a bootstrap failure is appended as cause.
99
136
  */
100
137
  function getAppContext() {
101
138
  if (!appContext) {
@@ -107,45 +144,25 @@ function getAppContext() {
107
144
  }
108
145
  return appContext;
109
146
  }
110
- /**
111
- * Get the CardanoIndexer instance
112
- * Convenience function for services
113
- */
114
147
  function getCardanoIndexer() {
115
148
  return getAppContext().cardanoIndexer;
116
149
  }
117
- /**
118
- * Get the CardanoClient instance
119
- * Convenience function for services
120
- */
121
150
  function getCardanoClient() {
122
151
  return getAppContext().cardanoClient;
123
152
  }
124
- /**
125
- * Get the CardanoTransactionBuilder instance
126
- * Convenience function for services and plugin consumers
127
- */
128
153
  function getCardanoTxBuilder() {
129
154
  return getAppContext().cardanoTxBuilder;
130
155
  }
131
156
  let hsmConfigInstance;
132
- /**
133
- * Get the HSM configuration (if HSM is enabled).
134
- * Used by sign service to check requiresRole.
135
- */
157
+ /** HSM configuration when enabled; the sign service reads requiresRole from it. */
136
158
  function getHsmConfig() {
137
159
  return hsmConfigInstance;
138
160
  }
139
161
  /**
140
- * Initialize from a pre-built config (used by plugin's src/index.ts)
141
- * @param config - validated CardanoClientConfig
142
- * @param protocolParams - Optional protocol parameters (for tests)
162
+ * Initialize from a pre-built config (plugin path). Idempotent: a second call must not
163
+ * create a duplicate CardanoClient; tests reinitialize via resetAppContext() / createTestContext().
143
164
  */
144
165
  async function initializeFromConfig(config, protocolParams, hsmConfig) {
145
- // Idempotent: a previous call (plugin's cds.on('served'), server.ts's served hook,
146
- // or an earlier programmatic initialize()) already built the context. Direct callers
147
- // such as @odatano/x402's bridge must not produce a duplicate CardanoClient.
148
- // Tests that need to reinitialize should use resetAppContext() / createTestContext().
149
166
  if (appContext) {
150
167
  logger.debug('initializeFromConfig: appContext already initialized, skipping');
151
168
  return;
@@ -156,37 +173,27 @@ async function initializeFromConfig(config, protocolParams, hsmConfig) {
156
173
  bootstrapError = null;
157
174
  }
158
175
  catch (err) {
159
- // Capture the cause so getAppContext() surfaces a structured 503 with diagnostics
160
- // even in PLUGIN mode (src/plugin.ts only logs the error) — previously bootstrapError
161
- // stayed null there and the failure showed up as a causeless "not initialized".
176
+ // Keep the cause so getAppContext() can surface a structured 503 in plugin mode too.
162
177
  bootstrapError = err instanceof Error ? err : new Error(String(err));
163
- throw err; // still propagate so the plugin/programmatic caller sees it
178
+ throw err;
164
179
  }
165
180
  }
166
- /**
167
- * Reset the application context (for testing only)
168
- * Allows tests to inject their own instances
169
- */
181
+ /** Reset the application context (tests only); lets tests inject their own instances. */
170
182
  function resetAppContext(context) {
171
183
  if (process.env.NODE_ENV === 'production') {
172
184
  throw new Error('resetAppContext() is not available in production');
173
185
  }
174
186
  appContext = context;
175
187
  bootstrapError = null;
176
- // Keep the published network in sync with the injected context (or clear it).
177
188
  (0, network_context_1.setActiveNetwork)(context?.cardanoClient.network ?? null);
178
189
  logger.debug('Application context reset');
179
190
  }
180
191
  /**
181
- * Create a test context with specific backends and transaction builder
182
- * Used by integration tests to create isolated test instances
183
- * @param backends Array of backend names to use (e.g., ['koios'], ['blockfrost'])
184
- * @param _txBuilderName Deprecated/ignored — Buildooor is the sole transaction builder (kept for signature compatibility)
185
- * @param protocolParams Optional protocol parameters (to skip backend call during init)
186
- * @returns Promise<AppContext> The created application context
192
+ * Create an isolated test context with the given backends.
193
+ * @param _txBuilderName ignored; Buildooor is the sole builder (kept for signature compatibility)
194
+ * @param protocolParams optional, skips the backend call during init
187
195
  */
188
- async function createTestContext(backends, _txBuilderName = 'buildooor', // kept for signature compat; Buildooor is the only builder
189
- protocolParams) {
196
+ async function createTestContext(backends, _txBuilderName = 'buildooor', protocolParams) {
190
197
  const config = {
191
198
  network: process_1.env.NETWORK || 'preview',
192
199
  backends,
@@ -194,6 +201,8 @@ protocolParams) {
194
201
  blockfrostCustomBackend: process_1.env.BLOCKFROST_CUSTOM_BACKEND || undefined,
195
202
  koiosApiKey: process_1.env.KOIOS_API_KEY || '',
196
203
  ogmiosUrl: process_1.env.OGMIOS_URL || '',
204
+ odatanoUrl: process_1.env.ODATANO_URL || undefined,
205
+ odatanoApiKey: process_1.env.ODATANO_API_KEY || undefined,
197
206
  transactionBuilders: ['buildooor'],
198
207
  primaryTimeoutMs: Number(process_1.env.PRIMARY_TIMEOUT_MS) || 30000, // || intentional: NaN (missing env var) falls back to default
199
208
  fallbackTimeoutMs: Number(process_1.env.FALLBACK_TIMEOUT_MS) || 60000,
@@ -201,19 +210,15 @@ protocolParams) {
201
210
  };
202
211
  return await initializeAppContext(config, protocolParams);
203
212
  }
204
- /**
205
- * Shutdown the application context (for cleanup in tests)
206
- * Closes all backend connections to allow process to exit cleanly
207
- */
213
+ /** Stop worker and crawler, then close all backend connections. */
208
214
  async function shutdownAppContext() {
209
- // Stop the wallet worker first — its in-flight submit must not hit a torn-down client.
215
+ // Worker and crawler first: their in-flight writes must not hit a torn-down client.
210
216
  try {
211
217
  await (0, wallet_worker_1.stopWalletWorker)();
212
218
  }
213
219
  catch (err) {
214
220
  logger.warn('Wallet worker shutdown failed (continuing):', err);
215
221
  }
216
- // Stop the crawler so its in-flight block writes don't hit a torn-down client.
217
222
  try {
218
223
  await (0, crawler_1.stopCrawler)();
219
224
  }
@@ -222,7 +227,6 @@ async function shutdownAppContext() {
222
227
  }
223
228
  if (appContext) {
224
229
  logger.info('Shutting down application context...');
225
- // Shutdown HSM signer if active
226
230
  const hsm = (0, hsm_signer_1.getHsmSigner)();
227
231
  if (hsm) {
228
232
  hsm.shutdown();
@@ -235,36 +239,29 @@ async function shutdownAppContext() {
235
239
  }
236
240
  }
237
241
  /**
238
- * Load and validate CardanoClientConfig from CDS config or environment variables.
239
- *
240
- * When used as a plugin, consumers configure via package.json:
241
- * { "cds": { "requires": { "odatano-core": { "network": "preview", "backends": ["blockfrost"], ... }}}}
242
- *
243
- * Priority: cds.env.requires["odatano-core"].X > process.env.X > default
244
- *
245
- * @returns validated CardanoClientConfig
246
- * @throws {Error} if any config value is invalid
242
+ * Load and validate CardanoClientConfig.
243
+ * Priority: cds.env.requires["odatano-core"].X > process.env.X > default.
244
+ * @throws {ConfigError} if any value is invalid
247
245
  */
248
246
  function loadConfigFromEnv() {
249
- // Check CDS plugin config first, fall back to env vars
250
- const cdsConfig = cds_1.default.env?.requires?.['odatano-core'] ?? {};
247
+ const cdsConfig = coreCdsConfig();
251
248
  const network = (cdsConfig.network || process_1.env.NETWORK || 'preview');
252
249
  if (!VALID_NETWORKS.includes(network)) {
253
250
  throw new errors_1.ConfigError(`Invalid NETWORK "${cdsConfig.network || process_1.env.NETWORK}". Must be one of: ${VALID_NETWORKS.join(', ')}`);
254
251
  }
255
- const backendStrings = cdsConfig.backends
256
- || (process_1.env.BACKENDS ? process_1.env.BACKENDS.split(',').map(b => b.trim()) : ['koios']);
252
+ const backendsRaw = cdsConfig.backends ?? process_1.env.BACKENDS;
253
+ const backendStrings = Array.isArray(backendsRaw) ? backendsRaw
254
+ : backendsRaw ? String(backendsRaw).split(',').map(b => b.trim()) : ['koios'];
257
255
  const invalidBackends = backendStrings.filter(b => !VALID_BACKENDS.includes(b));
258
256
  if (invalidBackends.length > 0) {
259
257
  throw new errors_1.ConfigError(`Invalid BACKENDS: "${invalidBackends.join(', ')}". Must be one of: ${VALID_BACKENDS.join(', ')}`);
260
258
  }
261
259
  const backends = backendStrings;
262
- // Buildooor is the sole transaction builder; any legacy txBuilders/TX_BUILDERS config is ignored.
260
+ // Buildooor is the sole transaction builder; txBuilders/TX_BUILDERS config is ignored.
263
261
  const txBuilders = ['buildooor'];
264
262
  const primaryTimeout = cdsConfig.primaryTimeoutMs ?? process_1.env.PRIMARY_TIMEOUT_MS;
265
263
  const fallbackTimeout = cdsConfig.fallbackTimeoutMs ?? process_1.env.FALLBACK_TIMEOUT_MS;
266
- // `!= null` not truthiness: a CDS-config numeric 0 is falsy, so `timeout && …`
267
- // skipped the <=0 check and 0 then silently became the default via `Number(0)||default`.
264
+ // `!= null`, not truthiness: a CDS-config 0 must reach the <= 0 check.
268
265
  if (primaryTimeout != null && isNaN(Number(primaryTimeout))) {
269
266
  throw new errors_1.ConfigError(`Invalid PRIMARY_TIMEOUT_MS "${primaryTimeout}". Must be a number.`);
270
267
  }
@@ -285,7 +282,17 @@ function loadConfigFromEnv() {
285
282
  }
286
283
  const koiosApiKey = cdsConfig.koiosApiKey || process_1.env.KOIOS_API_KEY || '';
287
284
  const ogmiosUrl = cdsConfig.ogmiosUrl || process_1.env.OGMIOS_URL || '';
288
- // Warn about missing API keys for selected backends
285
+ const odatanoUrl = cdsConfig.odatanoUrl || process_1.env.ODATANO_URL || '';
286
+ const odatanoApiKey = cdsConfig.odatanoApiKey || process_1.env.ODATANO_API_KEY || '';
287
+ if (odatanoUrl && !/^https?:\/\//i.test(odatanoUrl)) {
288
+ throw new errors_1.ConfigError(`Invalid ODATANO_URL "${odatanoUrl}". Must be an http(s) URL (e.g. https://api.preprod.odatano.dev).`);
289
+ }
290
+ if (backends.includes('odatano') && !odatanoUrl && network === 'mainnet') {
291
+ throw new errors_1.ConfigError('ODATANO_URL is required for the odatano backend on mainnet.');
292
+ }
293
+ if (backends.includes('odatano') && !odatanoApiKey) {
294
+ logger.warn('ODATANO_API_KEY is not set but odatano is listed in BACKENDS; the public API refuses calls without a key');
295
+ }
289
296
  if (backends.includes('blockfrost') && !blockfrostApiKey && !blockfrostCustomBackend) {
290
297
  logger.warn('Neither BLOCKFROST_API_KEY nor BLOCKFROST_CUSTOM_BACKEND is set but blockfrost is listed in BACKENDS');
291
298
  }
@@ -302,6 +309,8 @@ function loadConfigFromEnv() {
302
309
  blockfrostCustomBackend: blockfrostCustomBackend || undefined,
303
310
  koiosApiKey,
304
311
  ogmiosUrl,
312
+ odatanoUrl: odatanoUrl || undefined,
313
+ odatanoApiKey: odatanoApiKey || undefined,
305
314
  transactionBuilders: txBuilders,
306
315
  primaryTimeoutMs: Number(primaryTimeout) || 30000, // || intentional: NaN (missing config) falls back to default
307
316
  fallbackTimeoutMs: Number(fallbackTimeout) || 60000,
@@ -309,16 +318,11 @@ function loadConfigFromEnv() {
309
318
  };
310
319
  }
311
320
  /**
312
- * Load HSM configuration from CDS config or environment variables.
313
- * Returns undefined if HSM is not enabled.
314
- *
315
- * Plugin mode: cds.requires.odatano-core.hsm.enabled = true
316
- * Env mode: HSM_ENABLED=true
317
- *
318
- * @returns HsmConfig or undefined
321
+ * Load the HSM configuration (cds.requires.odatano-core.hsm.* or HSM_* env vars).
322
+ * Returns undefined when HSM is not enabled.
319
323
  */
320
324
  function loadHsmConfigFromEnv() {
321
- const cdsConfig = cds_1.default.env?.requires?.['odatano-core'] ?? {};
325
+ const cdsConfig = coreCdsConfig();
322
326
  const hsmCds = cdsConfig.hsm ?? {};
323
327
  const hsmEnabled = hsmCds.enabled === true || process_1.env.HSM_ENABLED === 'true';
324
328
  if (!hsmEnabled)
@@ -335,8 +339,7 @@ function loadHsmConfigFromEnv() {
335
339
  if (!Number.isInteger(slot) || slot < 0) {
336
340
  throw new errors_1.ConfigError(`Invalid HSM slot: "${hsmCds.slot ?? process_1.env.HSM_SLOT}" — must be a non-negative integer`);
337
341
  }
338
- // Fail-closed: HSM controls a real signing key. Require an explicit role gate so
339
- // that an authenticated user cannot drain the HSM-controlled wallet by default.
342
+ // Fail closed: the HSM holds a real signing key, so an explicit role gate is mandatory.
340
343
  const requiresRole = hsmCds.requiresRole || process_1.env.HSM_REQUIRES_ROLE || '';
341
344
  if (!requiresRole) {
342
345
  throw new errors_1.ConfigError('HSM_REQUIRES_ROLE (or cds.requires.odatano-core.hsm.requiresRole) is required when HSM is enabled — set it to the XSUAA scope name allowed to invoke HSM signing actions');
@@ -352,17 +355,13 @@ function loadHsmConfigFromEnv() {
352
355
  };
353
356
  }
354
357
  /**
355
- * Load the chain-crawler configuration from CDS config or environment variables.
356
- * Returns { enabled:false } when the crawler is not switched on (the default), so
357
- * existing deployments are unaffected.
358
- *
359
- * Plugin mode: cds.requires.odatano-core.crawler.{enabled,startSlot,startBlockHash,...}
360
- * Env mode: CRAWLER_ENABLED / CRAWLER_START_SLOT / CRAWLER_START_HASH / ...
358
+ * Load the chain-crawler configuration (cds.requires.odatano-core.crawler.* or CRAWLER_* env vars).
359
+ * Returns { enabled: false } when the crawler is off (the default).
361
360
  */
362
361
  function loadCrawlerConfigFromEnv() {
363
- const cdsConfig = cds_1.default.env?.requires?.['odatano-core'] ?? {};
362
+ const cdsConfig = coreCdsConfig();
364
363
  const c = cdsConfig.crawler ?? {};
365
- // A CDS value, including explicit `false`, wins over the environment.
364
+ // A CDS value, including an explicit `false`, wins over the environment.
366
365
  const enabledRaw = c.enabled !== undefined ? c.enabled : process_1.env.CRAWLER_ENABLED;
367
366
  let enabled = false;
368
367
  if (enabledRaw === true || enabledRaw === 'true') {
@@ -389,13 +388,27 @@ function loadCrawlerConfigFromEnv() {
389
388
  if (!['ogmios', 'pagination', 'auto'].includes(source)) {
390
389
  throw new errors_1.ConfigError(`Invalid CRAWLER_SOURCE "${source}". Must be one of: ogmios, pagination, auto.`);
391
390
  }
392
- return { enabled, startSlot, startBlockHash, startHeight, source, batchSize, confirmationDepth, pollIntervalMs };
391
+ // Analytics coverage: mint/burn and the bare catalogue are free by-products of a crawled
392
+ // block and on by default; enrichment and epoch snapshots cost provider calls and are opt-in.
393
+ const assetHistory = crawlerBoolean(c.assetHistory ?? process_1.env.CRAWLER_ASSET_HISTORY, 'CRAWLER_ASSET_HISTORY', true);
394
+ const assetCatalogue = (c.assetCatalogue ?? process_1.env.CRAWLER_ASSET_CATALOGUE ?? 'bare');
395
+ if (!VALID_ASSET_CATALOGUE_MODES.includes(assetCatalogue)) {
396
+ throw new errors_1.ConfigError(`Invalid CRAWLER_ASSET_CATALOGUE "${assetCatalogue}". Must be one of: ${VALID_ASSET_CATALOGUE_MODES.join(', ')}.`);
397
+ }
398
+ const assetEnrichRate = crawlerInteger(c.assetEnrichRate ?? process_1.env.CRAWLER_ASSET_ENRICH_RATE, 'CRAWLER_ASSET_ENRICH_RATE', CRAWLER_LIMITS.assetEnrichRate.min, CRAWLER_LIMITS.assetEnrichRate.max, 2);
399
+ const epochSnapshots = crawlerBoolean(c.epochSnapshots ?? process_1.env.CRAWLER_EPOCH_SNAPSHOTS, 'CRAWLER_EPOCH_SNAPSHOTS', false);
400
+ // Certificates + withdrawals are block content (no extra request) but opt-in to keep write volume stable.
401
+ const certificates = crawlerBoolean(c.certificates ?? process_1.env.CRAWLER_CERTIFICATES, 'CRAWLER_CERTIFICATES', false);
402
+ // UTxO set: opt-in, inert until a snapshot has been imported (importUtxoSet).
403
+ const utxoSet = crawlerBoolean(c.utxoSet ?? process_1.env.CRAWLER_UTXO_SET, 'CRAWLER_UTXO_SET', false);
404
+ // Crawled chain answers misses with 404 instead of a provider call.
405
+ const authoritative = crawlerBoolean(c.authoritative ?? process_1.env.CRAWLER_AUTHORITATIVE, 'CRAWLER_AUTHORITATIVE', false);
406
+ return {
407
+ enabled, startSlot, startBlockHash, startHeight, source, batchSize, confirmationDepth, pollIntervalMs,
408
+ assetHistory, assetCatalogue, assetEnrichRate, epochSnapshots, certificates, utxoSet, authoritative,
409
+ };
393
410
  }
394
- /**
395
- * Start the chain crawler if it is enabled and the app context is ready. Never throws
396
- * (crawler failure must not affect request serving) — errors are logged. Idempotent:
397
- * startCrawler() is a no-op when one is already running.
398
- */
411
+ /** Start the crawler if enabled and the app context is ready. Never throws; idempotent. */
399
412
  async function startCrawlerIfConfigured() {
400
413
  if (process_1.env.SKIP_AUTO_INIT === 'true' || !appContext)
401
414
  return;
@@ -430,14 +443,11 @@ const WALLET_WORKER_LIMITS = {
430
443
  maxAttempts: { min: 1, max: 10 },
431
444
  };
432
445
  /**
433
- * Load the wallet-worker configuration from CDS config or environment variables.
434
- * Returns { enabled:false } when the worker is not switched on (the default).
435
- *
436
- * Plugin mode: cds.requires.odatano-core.walletWorker.{enabled,wallets,...}
437
- * Env mode: WALLET_WORKER_ENABLED / WALLET_WORKER_WALLETS (JSON) / ...
446
+ * Load the wallet-worker configuration (cds.requires.odatano-core.walletWorker.* or WALLET_WORKER_* env vars).
447
+ * Returns { enabled: false } when the worker is off (the default).
438
448
  */
439
449
  function loadWalletWorkerConfigFromEnv() {
440
- const cdsConfig = cds_1.default.env?.requires?.['odatano-core'] ?? {};
450
+ const cdsConfig = coreCdsConfig();
441
451
  const w = cdsConfig.walletWorker ?? {};
442
452
  const enabledRaw = w.enabled !== undefined ? w.enabled : process_1.env.WALLET_WORKER_ENABLED;
443
453
  let enabled = false;
@@ -503,11 +513,7 @@ function loadWalletWorkerConfigFromEnv() {
503
513
  resubmitOnRollback,
504
514
  };
505
515
  }
506
- /**
507
- * Start the wallet worker if it is enabled and the app context is ready. Never
508
- * throws (worker failure must not affect request serving) — errors are logged.
509
- * Idempotent: startWalletWorker() is a no-op when one is already running.
510
- */
516
+ /** Start the wallet worker if enabled and the app context is ready. Never throws; idempotent. */
511
517
  async function startWalletWorkerIfConfigured() {
512
518
  if (process_1.env.SKIP_AUTO_INIT === 'true' || !appContext)
513
519
  return;
@@ -535,15 +541,16 @@ async function startWalletWorkerIfConfigured() {
535
541
  }
536
542
  }
537
543
  /**
538
- * Re-drive deferred submissions that were claimed (status 'submitting' with
539
- * persisted signedTxCbor) but whose detached submit never ran because the
540
- * process died first (KNOWN_ISSUES #11, Layer 2). Idempotent — an already
541
- * submitted tx finalizes via the TransactionAlreadySubmittedError path.
542
- * Non-fatal, mirrors startCrawlerIfConfigured/startWalletWorkerIfConfigured.
544
+ * Re-drive deferred submissions claimed as 'submitting' whose detached submit never ran
545
+ * (process died first). Idempotent: an already submitted tx finalizes via
546
+ * TransactionAlreadySubmittedError. Never throws.
543
547
  */
544
548
  async function redriveInterruptedSubmissionsIfConfigured() {
545
549
  if (process_1.env.SKIP_AUTO_INIT === 'true' || !appContext)
546
550
  return;
551
+ // Without a database there are no signing requests to re-drive
552
+ if (!cds_1.default.db)
553
+ return;
547
554
  try {
548
555
  const { redriveInterruptedSubmissions } = require('./blockchain/signing/submission-finalizer');
549
556
  const attempted = await redriveInterruptedSubmissions();
@@ -554,20 +561,16 @@ async function redriveInterruptedSubmissionsIfConfigured() {
554
561
  logger.error('Failed to re-drive interrupted submissions (non-fatal):', err);
555
562
  }
556
563
  }
557
- // Bootstrap hook - runs when CAP server has loaded all services
564
+ // Standalone bootstrap; skipped when the plugin already initialized the context.
558
565
  cds_1.default.on('served', async () => {
559
- // Skip if already initialized by plugin (src/plugin.ts runs first)
560
566
  if (appContext)
561
567
  return;
562
- // Skip auto-initialization when SKIP_AUTO_INIT is set (e.g., for tests with mocked backends)
568
+ // SKIP_AUTO_INIT: tests with mocked backends
563
569
  if (process_1.env.SKIP_AUTO_INIT === 'true') {
564
570
  logger.info('Skipping auto-initialization (SKIP_AUTO_INIT=true)');
565
571
  return;
566
572
  }
567
- // NOTE: config loading is INSIDE the try — loadConfigFromEnv/loadHsmConfigFromEnv
568
- // throw ConfigError synchronously (missing HSM_PIN, bad slot, no requiresRole…).
569
- // Outside the try that would crash the host app's bootstrap in plugin mode,
570
- // violating the plugin contract ("never throw on failure").
573
+ // Config loading stays inside the try: a ConfigError must never crash the host app.
571
574
  let config;
572
575
  try {
573
576
  config = loadConfigFromEnv();
@@ -578,25 +581,19 @@ cds_1.default.on('served', async () => {
578
581
  logger.info('CAP server bootstrap complete');
579
582
  }
580
583
  catch (err) {
581
- // Don't throw - initialization failure shouldn't crash the host app (plugin contract).
582
- // Capture the cause so getAppContext() can surface a structured 503 with diagnostics
583
- // instead of the raw "Application not initialized" Error landing as a generic 500.
584
+ // Never throw; keep the cause so getAppContext() surfaces a structured 503.
584
585
  bootstrapError = err instanceof Error ? err : new Error(String(err));
585
- // Write to stderr directly so the cause stays visible even when test runners
586
- // suppress console.error (vitest.setup.ts in this repo silences it).
586
+ // stderr directly: the cause stays visible when a test runner silences console.error.
587
587
  const where = config ? `backends={${config.backends.join(',')}} network=${config.network}` : 'config load';
588
588
  const msg = err instanceof Error ? `${err.name}: ${err.message}\n${err.stack ?? ''}` : String(err);
589
589
  process.stderr.write(`[ODATANO] Failed to initialize blockchain components — ${where}\n${msg}\n`);
590
590
  logger.error('Failed to initialize blockchain components:', err);
591
591
  }
592
- // Start the pre-sync crawler if configured (standalone mode). Non-fatal.
592
+ // Optional subsystems; each is non-fatal.
593
593
  await startCrawlerIfConfigured();
594
- // Start the wallet worker if configured (standalone mode). Non-fatal.
595
594
  await startWalletWorkerIfConfigured();
596
- // Re-drive deferred submissions interrupted by a restart (standalone mode). Non-fatal.
597
595
  await redriveInterruptedSubmissionsIfConfigured();
598
596
  });
599
- // Shutdown hook - runs when CAP server is shutting down (e.g., cds.shutdown() in tests)
600
597
  cds_1.default.on('shutdown', async () => {
601
598
  await shutdownAppContext();
602
599
  });
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Agent-grant feature switch from `cds.requires.odatano-core.agentGrants`, else the environment
3
+ * (AGENT_GRANTS_ENABLED, AGENT_GRANTS_DELEGATE, AGENT_GRANT_ADMIN_RATE_LIMIT). Own module because
4
+ * src/plugin.ts reads it at plugin load, before any blockchain module is required.
5
+ */
6
+ export interface AgentGrantsConfig {
7
+ enabled: boolean;
8
+ /** CAP auth kind the transport middleware delegates to for non-token requests. */
9
+ delegate: string;
10
+ /** Grant administration calls per principal per hour (integer >= 1). */
11
+ adminRateLimit: number;
12
+ }
13
+ export declare const AGENT_GRANTS_DELEGATES: readonly string[];
14
+ export declare const AGENT_GRANT_ADMIN_RATE_LIMIT_DEFAULT = 10;
15
+ /**
16
+ * Grant-administration calls per principal per hour: `agentGrants.adminRateLimit`, then
17
+ * `AGENT_GRANT_ADMIN_RATE_LIMIT`, default 10. An unusable value is logged and falls back, never disables the feature.
18
+ */
19
+ export declare function loadGrantAdminRateLimit(env?: Record<string, string | undefined>): number;
20
+ export declare const AGENT_TOKEN_CACHE_MS_DEFAULT = 10000;
21
+ /**
22
+ * How long the transport lane reuses a resolved grant row before re-reading the DB: `agentGrants.tokenCacheMs`,
23
+ * then `AGENT_TOKEN_CACHE_MS`, default 10 s, 0 disables. Bounds how late a revoke on another replica takes effect.
24
+ */
25
+ export declare function loadTokenCacheMs(env?: Record<string, string | undefined>): number;
26
+ /** The configured `cds.requires.auth` as an object (the shorthand `"auth": "xsuaa"` is a string). */
27
+ export declare function configuredAuth(): Record<string, unknown>;
28
+ /** A host-configured custom `cds.requires.auth.impl` (not this package's middleware); the lane wraps it. */
29
+ export declare function customAuthImpl(auth?: Record<string, unknown>): string | null;
30
+ export declare function loadAgentGrantsConfig(env?: Record<string, string | undefined>): AgentGrantsConfig;
31
+ /**
32
+ * Switch agent grants on when configured: installs @odatano/cap-auth with the `x-agent-token` lane
33
+ * (previous strategy kept as delegate) and attaches the enforcement hook to each service on `serving`.
34
+ * Called from src/plugin.ts and srv/server.ts, before cds.server() builds middlewares. Never throws.
35
+ */
36
+ export declare function activateAgentGrants(): boolean;
37
+ //# sourceMappingURL=agent-grants-config.d.ts.map