@odatano/core 2.0.0-rc.5 → 2.0.0-rc.50

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 (208) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +99 -51
  2. package/@cds-models/CardanoAgentService/index.js +15 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +347 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +496 -11
  6. package/@cds-models/CardanoIndexerService/index.js +64 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +414 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +32 -19
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +58 -44
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +7 -22
  14. package/@cds-models/index.d.ts +101 -1
  15. package/@cds-models/index.js +16 -1
  16. package/@cds-models/odatano/cardano/index.d.ts +437 -32
  17. package/@cds-models/odatano/cardano/index.js +48 -0
  18. package/README.md +207 -167
  19. package/db/schema.cds +2402 -1705
  20. package/db/types.cds +446 -295
  21. package/package.json +41 -16
  22. package/scripts/migrate-schema.mjs +334 -0
  23. package/scripts/migrate-slot-leader.mjs +96 -0
  24. package/src/index.d.ts +20 -21
  25. package/src/index.js +45 -31
  26. package/src/plugin.js +17 -35
  27. package/srv/blockchain/asset-decimals.d.ts +7 -0
  28. package/srv/blockchain/asset-decimals.js +91 -0
  29. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -135
  30. package/srv/blockchain/backends/blockfrost-backend.js +66 -172
  31. package/srv/blockchain/backends/cardano-backend.d.ts +94 -186
  32. package/srv/blockchain/backends/cardano-backend.js +29 -5
  33. package/srv/blockchain/backends/koios-backend.d.ts +103 -168
  34. package/srv/blockchain/backends/koios-backend.js +428 -360
  35. package/srv/blockchain/backends/odatano-backend.d.ts +54 -0
  36. package/srv/blockchain/backends/odatano-backend.js +169 -0
  37. package/srv/blockchain/backends/ogmios-backend.d.ts +123 -190
  38. package/srv/blockchain/backends/ogmios-backend.js +637 -315
  39. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  40. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  41. package/srv/blockchain/cardano-client.d.ts +61 -241
  42. package/srv/blockchain/cardano-client.js +253 -293
  43. package/srv/blockchain/cardano-indexer.d.ts +282 -281
  44. package/srv/blockchain/cardano-indexer.js +1551 -484
  45. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  46. package/srv/blockchain/cardano-tx-builder.js +164 -140
  47. package/srv/blockchain/circuit-breaker.d.ts +1 -13
  48. package/srv/blockchain/circuit-breaker.js +5 -15
  49. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  50. package/srv/blockchain/crawler/account-snapshots.js +153 -0
  51. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +15 -0
  52. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  53. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +43 -0
  54. package/srv/blockchain/crawler/asset-registry-backfill.js +153 -0
  55. package/srv/blockchain/crawler/certificate-backfill.d.ts +52 -0
  56. package/srv/blockchain/crawler/certificate-backfill.js +162 -0
  57. package/srv/blockchain/crawler/crawler.d.ts +104 -81
  58. package/srv/blockchain/crawler/crawler.js +532 -160
  59. package/srv/blockchain/crawler/credential-backfill.d.ts +28 -0
  60. package/srv/blockchain/crawler/credential-backfill.js +124 -0
  61. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  62. package/srv/blockchain/crawler/index.d.ts +1 -8
  63. package/srv/blockchain/crawler/index.js +31 -17
  64. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  65. package/srv/blockchain/crawler/input-asset-copies.js +171 -0
  66. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
  67. package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
  68. package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
  69. package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
  70. package/srv/blockchain/crawler/sync-state.d.ts +27 -47
  71. package/srv/blockchain/crawler/sync-state.js +113 -63
  72. package/srv/blockchain/crawler/transaction-backfill.d.ts +44 -0
  73. package/srv/blockchain/crawler/transaction-backfill.js +278 -0
  74. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  75. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  76. package/srv/blockchain/ledger-state.d.ts +62 -0
  77. package/srv/blockchain/ledger-state.js +419 -0
  78. package/srv/blockchain/pending-spends.d.ts +16 -0
  79. package/srv/blockchain/pending-spends.js +81 -0
  80. package/srv/blockchain/pool-metadata.d.ts +15 -0
  81. package/srv/blockchain/pool-metadata.js +132 -0
  82. package/srv/blockchain/request-coalescer.d.ts +2 -16
  83. package/srv/blockchain/request-coalescer.js +2 -16
  84. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  85. package/srv/blockchain/signing/cose-verifier.js +146 -70
  86. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  87. package/srv/blockchain/signing/external-signer.js +17 -126
  88. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  89. package/srv/blockchain/signing/hsm-signer.js +28 -79
  90. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  91. package/srv/blockchain/signing/signature-verifier.js +70 -83
  92. package/srv/blockchain/signing/submission-finalizer.d.ts +23 -45
  93. package/srv/blockchain/signing/submission-finalizer.js +219 -86
  94. package/srv/blockchain/stored-chain.d.ts +20 -0
  95. package/srv/blockchain/stored-chain.js +237 -0
  96. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  97. package/srv/blockchain/transaction-building/buildooor-tx.js +652 -416
  98. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  99. package/srv/blockchain/transaction-presence.d.ts +5 -0
  100. package/srv/blockchain/transaction-presence.js +29 -0
  101. package/srv/blockchain/transaction-rows.d.ts +12 -0
  102. package/srv/blockchain/transaction-rows.js +44 -0
  103. package/srv/blockchain/wallet-worker/build-request.d.ts +5 -20
  104. package/srv/blockchain/wallet-worker/build-request.js +47 -30
  105. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -46
  106. package/srv/blockchain/wallet-worker/confirmation-tracker.js +25 -45
  107. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  108. package/srv/blockchain/wallet-worker/index.js +3 -11
  109. package/srv/blockchain/wallet-worker/job-store.d.ts +30 -148
  110. package/srv/blockchain/wallet-worker/job-store.js +101 -201
  111. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  112. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  113. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  114. package/srv/blockchain/wallet-worker/signers.js +4 -12
  115. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +8 -80
  116. package/srv/blockchain/wallet-worker/wallet-worker.js +107 -155
  117. package/srv/cardano-agent-service.cds +122 -84
  118. package/srv/cardano-agent-service.js +4 -9
  119. package/srv/cardano-backend-service.cds +78 -0
  120. package/srv/cardano-backend-service.d.ts +2 -0
  121. package/srv/cardano-backend-service.js +242 -0
  122. package/srv/cardano-indexer-service.cds +387 -73
  123. package/srv/cardano-indexer-service.d.ts +5 -1
  124. package/srv/cardano-indexer-service.js +532 -16
  125. package/srv/cardano-service.cds +424 -269
  126. package/srv/cardano-service.js +289 -201
  127. package/srv/cardano-sign-service.cds +201 -180
  128. package/srv/cardano-sign-service.js +71 -201
  129. package/srv/cardano-tx-service.cds +451 -370
  130. package/srv/cardano-tx-service.js +271 -289
  131. package/srv/cardano-ui.cds +16 -16
  132. package/srv/cardano-worker-service.cds +118 -125
  133. package/srv/cardano-worker-service.js +52 -61
  134. package/srv/cbor/cip68.d.ts +13 -0
  135. package/srv/cbor/cip68.js +56 -0
  136. package/srv/cbor/index.d.ts +3 -1
  137. package/srv/cbor/index.js +9 -1
  138. package/srv/cbor/parse.d.ts +30 -18
  139. package/srv/cbor/parse.js +44 -9
  140. package/srv/cbor/plutus-data-json.d.ts +20 -0
  141. package/srv/cbor/plutus-data-json.js +32 -0
  142. package/srv/config.d.ts +113 -0
  143. package/srv/config.js +409 -0
  144. package/srv/server.d.ts +15 -110
  145. package/srv/server.js +84 -404
  146. package/srv/utils/agent-access.d.ts +9 -0
  147. package/srv/utils/agent-access.js +67 -0
  148. package/srv/utils/agent-grants-config.d.ts +0 -46
  149. package/srv/utils/agent-grants-config.js +17 -85
  150. package/srv/utils/agent-grants.d.ts +106 -122
  151. package/srv/utils/agent-grants.js +538 -236
  152. package/srv/utils/agent-token-auth.d.ts +4 -99
  153. package/srv/utils/agent-token-auth.js +18 -182
  154. package/srv/utils/backend-request-handler.d.ts +3 -17
  155. package/srv/utils/backend-request-handler.js +3 -18
  156. package/srv/utils/collections.d.ts +3 -10
  157. package/srv/utils/collections.js +3 -10
  158. package/srv/utils/const.d.ts +23 -74
  159. package/srv/utils/const.js +32 -79
  160. package/srv/utils/crypto.d.ts +3 -12
  161. package/srv/utils/crypto.js +6 -21
  162. package/srv/utils/db-indexes.d.ts +27 -0
  163. package/srv/utils/db-indexes.js +120 -0
  164. package/srv/utils/db-sanitize.d.ts +20 -0
  165. package/srv/utils/db-sanitize.js +80 -0
  166. package/srv/utils/deep-json.d.ts +6 -0
  167. package/srv/utils/deep-json.js +240 -0
  168. package/srv/utils/epoch-slots.d.ts +13 -0
  169. package/srv/utils/epoch-slots.js +38 -0
  170. package/srv/utils/error-codes.d.ts +22 -75
  171. package/srv/utils/error-codes.js +23 -72
  172. package/srv/utils/errors.d.ts +46 -187
  173. package/srv/utils/errors.js +114 -230
  174. package/srv/utils/liveness.d.ts +12 -0
  175. package/srv/utils/liveness.js +35 -0
  176. package/srv/utils/mappers.d.ts +102 -223
  177. package/srv/utils/mappers.js +387 -316
  178. package/srv/utils/network-context.js +2 -13
  179. package/srv/utils/paging.d.ts +31 -0
  180. package/srv/utils/paging.js +43 -0
  181. package/srv/utils/pg-inline-json.d.ts +8 -0
  182. package/srv/utils/pg-inline-json.js +58 -0
  183. package/srv/utils/pg-order-nulls.d.ts +14 -0
  184. package/srv/utils/pg-order-nulls.js +54 -0
  185. package/srv/utils/plutus-placeholders.d.ts +16 -22
  186. package/srv/utils/plutus-placeholders.js +62 -33
  187. package/srv/utils/rate-limiter.d.ts +2 -21
  188. package/srv/utils/rate-limiter.js +5 -17
  189. package/srv/utils/readiness.d.ts +12 -0
  190. package/srv/utils/readiness.js +29 -0
  191. package/srv/utils/reference-script.d.ts +19 -0
  192. package/srv/utils/reference-script.js +84 -0
  193. package/srv/utils/result-numbers.d.ts +15 -0
  194. package/srv/utils/result-numbers.js +61 -0
  195. package/srv/utils/service-events.d.ts +0 -24
  196. package/srv/utils/service-events.js +3 -25
  197. package/srv/utils/signing-helper.d.ts +3 -20
  198. package/srv/utils/signing-helper.js +35 -64
  199. package/srv/utils/tx-build-helper.d.ts +10 -105
  200. package/srv/utils/tx-build-helper.js +81 -144
  201. package/srv/utils/tx-request-parsers.d.ts +82 -33
  202. package/srv/utils/tx-request-parsers.js +401 -49
  203. package/srv/utils/tx-utils.d.ts +3 -27
  204. package/srv/utils/tx-utils.js +32 -50
  205. package/srv/utils/types.d.ts +261 -191
  206. package/srv/utils/types.js +2 -6
  207. package/srv/utils/validators.d.ts +22 -92
  208. package/srv/utils/validators.js +50 -149
package/srv/server.js CHANGED
@@ -3,21 +3,17 @@ 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;
7
6
  exports.getAppContext = getAppContext;
8
7
  exports.getCardanoIndexer = getCardanoIndexer;
9
8
  exports.getCardanoClient = getCardanoClient;
10
9
  exports.getCardanoTxBuilder = getCardanoTxBuilder;
11
10
  exports.getHsmConfig = getHsmConfig;
11
+ exports.readinessParts = readinessParts;
12
12
  exports.initializeFromConfig = initializeFromConfig;
13
13
  exports.resetAppContext = resetAppContext;
14
14
  exports.createTestContext = createTestContext;
15
15
  exports.shutdownAppContext = shutdownAppContext;
16
- exports.loadConfigFromEnv = loadConfigFromEnv;
17
- exports.loadHsmConfigFromEnv = loadHsmConfigFromEnv;
18
- exports.loadCrawlerConfigFromEnv = loadCrawlerConfigFromEnv;
19
16
  exports.startCrawlerIfConfigured = startCrawlerIfConfigured;
20
- exports.loadWalletWorkerConfigFromEnv = loadWalletWorkerConfigFromEnv;
21
17
  exports.startWalletWorkerIfConfigured = startWalletWorkerIfConfigured;
22
18
  exports.redriveInterruptedSubmissionsIfConfigured = redriveInterruptedSubmissionsIfConfigured;
23
19
  const cds_1 = __importDefault(require("@sap/cds"));
@@ -27,53 +23,42 @@ const cardano_tx_builder_1 = require("./blockchain/cardano-tx-builder");
27
23
  const hsm_signer_1 = require("./blockchain/signing/hsm-signer");
28
24
  const errors_1 = require("./utils/errors");
29
25
  const network_context_1 = require("./utils/network-context");
26
+ const db_sanitize_1 = require("./utils/db-sanitize");
27
+ const db_indexes_1 = require("./utils/db-indexes");
28
+ const pg_order_nulls_1 = require("./utils/pg-order-nulls");
29
+ const pg_inline_json_1 = require("./utils/pg-inline-json");
30
30
  const crawler_1 = require("./blockchain/crawler");
31
31
  const wallet_worker_1 = require("./blockchain/wallet-worker");
32
32
  const agent_grants_config_1 = require("./utils/agent-grants-config");
33
- const process_1 = require("process");
33
+ const config_1 = require("./config");
34
34
  const logger = cds_1.default.log('ODATANO');
35
- const VALID_NETWORKS = ['mainnet', 'preview', 'preprod'];
36
- const VALID_BACKENDS = ['blockfrost', 'koios', 'ogmios'];
37
- const CRAWLER_LIMITS = {
38
- batchSize: { min: 1, max: 100 },
39
- confirmationDepth: { min: 0, max: 2160 },
40
- pollIntervalMs: { min: 1000, max: 3_600_000 },
41
- };
42
- /** Parse an integer without allowing JavaScript's lossy/implicit coercions. */
43
- function crawlerInteger(raw, name, min, max, defaultValue) {
44
- if (raw == null)
45
- return defaultValue;
46
- if ((typeof raw !== 'number' && typeof raw !== 'string')
47
- || (typeof raw === 'string' && raw.trim() === '')) {
48
- throw new errors_1.ConfigError(`Invalid ${name} "${String(raw)}". Must be an integer between ${min} and ${max}.`);
49
- }
50
- const parsed = typeof raw === 'number' ? raw : Number(raw);
51
- if (!Number.isSafeInteger(parsed) || parsed < min || parsed > max) {
52
- throw new errors_1.ConfigError(`Invalid ${name} "${String(raw)}". Must be an integer between ${min} and ${max}.`);
53
- }
54
- return parsed;
55
- }
56
35
  let appContext = null;
57
36
  let bootstrapError = null;
58
- /**
59
- * Initialize the application context with blockchain components
60
- * Called once during CAP server startup via cds.on('served')
61
- * @param config - CardanoClientConfig
62
- * @param protocolParams - Optional protocol parameters (for tests to skip backend call)
63
- */
37
+ /** Every start path, standalone hook and plugin, comes through here. */
64
38
  async function initializeAppContext(config, protocolParams, hsmConfig) {
65
39
  logger.debug('Initializing blockchain components...');
66
- // Create CardanoClient from configuration
40
+ // Database first. Postgres ORDER BY without a NULLS clause on key / NOT NULL columns so
41
+ // the indexes serve `$top` / `$orderby`, bulk rows inline instead of through a COPY buffer;
42
+ // then the secondary indexes the model cannot declare.
43
+ (0, pg_order_nulls_1.installPostgresOrderNulls)();
44
+ (0, pg_inline_json_1.installPostgresInlineJson)();
45
+ try {
46
+ await (0, db_indexes_1.ensureDbIndexes)();
47
+ }
48
+ catch (err) {
49
+ logger.warn('secondary indexes not ensured (non-fatal):', err);
50
+ }
67
51
  const cardanoClient = new cardano_client_1.CardanoClient(config);
68
- // Publish the active network for leaf utilities (e.g. network-aware validators)
69
- // without forcing them to import this module / the full server graph.
52
+ // Lets leaf utilities (network-aware validators) read the network without importing this module.
70
53
  (0, network_context_1.setActiveNetwork)(config.network);
71
- // Create CardanoTransactionBuilder with the client
72
54
  const cardanoTxBuilder = new cardano_tx_builder_1.CardanoTransactionBuilder(cardanoClient);
73
55
  await cardanoTxBuilder.init(protocolParams);
74
- // Create CardanoIndexer with client and transaction builder
56
+ // PostgreSQL rejects U+0000 in text/JSON; one db-level `before` hook covers every write.
57
+ if ((0, db_sanitize_1.installDbSanitizer)())
58
+ logger.debug('DB NUL sanitizer installed');
75
59
  const cardanoIndexer = new cardano_indexer_1.CardanoIndexer(cardanoClient, cardanoTxBuilder);
76
- // Initialize HSM signer if configured (failure is non-fatal — won't crash the app)
60
+ cardanoIndexer.setPoolMetadataFetch((0, config_1.loadPoolMetadataFetchFromEnv)());
61
+ // HSM signer failure is non-fatal
77
62
  if (hsmConfig?.enabled) {
78
63
  try {
79
64
  const hsmSigner = new hsm_signer_1.HsmSigner(hsmConfig);
@@ -93,22 +78,10 @@ async function initializeAppContext(config, protocolParams, hsmConfig) {
93
78
  cardanoTxBuilder,
94
79
  };
95
80
  }
96
- /** Agent-grant feature switch (AGENT_GRANTS_DESIGN.md); lives in its own module so src/plugin.ts can read it at load. */
97
- var agent_grants_config_2 = require("./utils/agent-grants-config");
98
- Object.defineProperty(exports, "loadAgentGrantsConfig", { enumerable: true, get: function () { return agent_grants_config_2.loadAgentGrantsConfig; } });
99
- Object.defineProperty(exports, "activateAgentGrants", { enumerable: true, get: function () { return agent_grants_config_2.activateAgentGrants; } });
100
- // Standalone mode (`cds serve` / `cds watch` in this project): CAP loads
101
- // cds-plugin.js only from dependencies, so src/plugin.ts never runs here and
102
- // agent grants would stay off regardless of AGENT_GRANTS_ENABLED. bin/serve.js
103
- // imports this file before cds.server() instantiates the middlewares, so the
104
- // auth impl can still be swapped. Idempotent: a no-op after the plugin's call.
81
+ // Standalone mode never loads src/plugin.ts, so swap the auth impl here as well
82
+ // (bin/serve.js imports this file before the middlewares exist). Idempotent.
105
83
  (0, agent_grants_config_1.activateAgentGrants)();
106
- /**
107
- * Get the application context (must be called after bootstrap)
108
- * @throws {ProviderUnavailableError} 503 when uninitialized — request handlers using
109
- * handleRequest/mapError translate this into a clean 503 response instead of a raw 500.
110
- * If bootstrap actively failed, the cause is appended to the message.
111
- */
84
+ /** Throws 503 when uninitialized, with a bootstrap failure appended as cause. */
112
85
  function getAppContext() {
113
86
  if (!appContext) {
114
87
  const base = 'Application not initialized. This should be called after cds.served event.';
@@ -119,45 +92,27 @@ function getAppContext() {
119
92
  }
120
93
  return appContext;
121
94
  }
122
- /**
123
- * Get the CardanoIndexer instance
124
- * Convenience function for services
125
- */
126
95
  function getCardanoIndexer() {
127
96
  return getAppContext().cardanoIndexer;
128
97
  }
129
- /**
130
- * Get the CardanoClient instance
131
- * Convenience function for services
132
- */
133
98
  function getCardanoClient() {
134
99
  return getAppContext().cardanoClient;
135
100
  }
136
- /**
137
- * Get the CardanoTransactionBuilder instance
138
- * Convenience function for services and plugin consumers
139
- */
140
101
  function getCardanoTxBuilder() {
141
102
  return getAppContext().cardanoTxBuilder;
142
103
  }
143
104
  let hsmConfigInstance;
144
- /**
145
- * Get the HSM configuration (if HSM is enabled).
146
- * Used by sign service to check requiresRole.
147
- */
105
+ /** HSM configuration when enabled; the sign service reads requiresRole from it. */
148
106
  function getHsmConfig() {
149
107
  return hsmConfigInstance;
150
108
  }
151
- /**
152
- * Initialize from a pre-built config (used by plugin's src/index.ts)
153
- * @param config - validated CardanoClientConfig
154
- * @param protocolParams - Optional protocol parameters (for tests)
155
- */
109
+ /** What getReadiness() reports about this process: the app context and, when configured, the HSM session. */
110
+ function readinessParts() {
111
+ return { context: appContext !== null, hsm: hsmConfigInstance ? (0, hsm_signer_1.getHsmSigner)()?.isConnected() === true : null };
112
+ }
113
+ // Plugin path. Idempotent, so a second call never creates a duplicate CardanoClient.
114
+ // Tests reinitialize with resetAppContext() or createTestContext().
156
115
  async function initializeFromConfig(config, protocolParams, hsmConfig) {
157
- // Idempotent: a previous call (plugin's cds.on('served'), server.ts's served hook,
158
- // or an earlier programmatic initialize()) already built the context. Direct callers
159
- // such as @odatano/x402's bridge must not produce a duplicate CardanoClient.
160
- // Tests that need to reinitialize should use resetAppContext() / createTestContext().
161
116
  if (appContext) {
162
117
  logger.debug('initializeFromConfig: appContext already initialized, skipping');
163
118
  return;
@@ -168,64 +123,43 @@ async function initializeFromConfig(config, protocolParams, hsmConfig) {
168
123
  bootstrapError = null;
169
124
  }
170
125
  catch (err) {
171
- // Capture the cause so getAppContext() surfaces a structured 503 with diagnostics
172
- // even in PLUGIN mode (src/plugin.ts only logs the error) — previously bootstrapError
173
- // stayed null there and the failure showed up as a causeless "not initialized".
126
+ // Keep the cause so getAppContext() can surface a structured 503 in plugin mode too.
174
127
  bootstrapError = err instanceof Error ? err : new Error(String(err));
175
- throw err; // still propagate so the plugin/programmatic caller sees it
128
+ throw err;
176
129
  }
177
130
  }
178
- /**
179
- * Reset the application context (for testing only)
180
- * Allows tests to inject their own instances
181
- */
131
+ /** Reset the application context (tests only); lets tests inject their own instances. */
182
132
  function resetAppContext(context) {
183
133
  if (process.env.NODE_ENV === 'production') {
184
134
  throw new Error('resetAppContext() is not available in production');
185
135
  }
186
136
  appContext = context;
187
137
  bootstrapError = null;
188
- // Keep the published network in sync with the injected context (or clear it).
189
138
  (0, network_context_1.setActiveNetwork)(context?.cardanoClient.network ?? null);
190
139
  logger.debug('Application context reset');
191
140
  }
192
- /**
193
- * Create a test context with specific backends and transaction builder
194
- * Used by integration tests to create isolated test instances
195
- * @param backends Array of backend names to use (e.g., ['koios'], ['blockfrost'])
196
- * @param _txBuilderName Deprecated/ignored — Buildooor is the sole transaction builder (kept for signature compatibility)
197
- * @param protocolParams Optional protocol parameters (to skip backend call during init)
198
- * @returns Promise<AppContext> The created application context
199
- */
200
- async function createTestContext(backends, _txBuilderName = 'buildooor', // kept for signature compat; Buildooor is the only builder
201
- protocolParams) {
202
- const config = {
203
- network: process_1.env.NETWORK || 'preview',
204
- backends,
205
- blockfrostApiKey: process_1.env.BLOCKFROST_API_KEY || '',
206
- blockfrostCustomBackend: process_1.env.BLOCKFROST_CUSTOM_BACKEND || undefined,
207
- koiosApiKey: process_1.env.KOIOS_API_KEY || '',
208
- ogmiosUrl: process_1.env.OGMIOS_URL || '',
209
- transactionBuilders: ['buildooor'],
210
- primaryTimeoutMs: Number(process_1.env.PRIMARY_TIMEOUT_MS) || 30000, // || intentional: NaN (missing env var) falls back to default
211
- fallbackTimeoutMs: Number(process_1.env.FALLBACK_TIMEOUT_MS) || 60000,
212
- indexTtlMs: Number(process_1.env.INDEX_TTL_MS) || 3600000,
213
- };
214
- return await initializeAppContext(config, protocolParams);
141
+ /** Isolated test context: the configuration of the environment with the given backends. */
142
+ async function createTestContext(backends, protocolParams) {
143
+ return await initializeAppContext({ ...(0, config_1.loadConfigFromEnv)(), backends }, protocolParams);
144
+ }
145
+ let shutdownInFlight = null;
146
+ /** Stop worker and crawler, then close all backend connections. Concurrent callers share one run. */
147
+ function shutdownAppContext() {
148
+ shutdownInFlight ??= runShutdown().finally(() => { shutdownInFlight = null; });
149
+ return shutdownInFlight;
215
150
  }
216
- /**
217
- * Shutdown the application context (for cleanup in tests)
218
- * Closes all backend connections to allow process to exit cleanly
219
- */
220
- async function shutdownAppContext() {
221
- // Stop the wallet worker first — its in-flight submit must not hit a torn-down client.
151
+ async function runShutdown() {
152
+ if (submissionReconcilerStarted) {
153
+ submissionFinalizer().stopSubmissionReconciler();
154
+ submissionReconcilerStarted = false;
155
+ }
156
+ // Worker and crawler first: their in-flight writes must not hit a torn-down client.
222
157
  try {
223
158
  await (0, wallet_worker_1.stopWalletWorker)();
224
159
  }
225
160
  catch (err) {
226
161
  logger.warn('Wallet worker shutdown failed (continuing):', err);
227
162
  }
228
- // Stop the crawler so its in-flight block writes don't hit a torn-down client.
229
163
  try {
230
164
  await (0, crawler_1.stopCrawler)();
231
165
  }
@@ -234,7 +168,6 @@ async function shutdownAppContext() {
234
168
  }
235
169
  if (appContext) {
236
170
  logger.info('Shutting down application context...');
237
- // Shutdown HSM signer if active
238
171
  const hsm = (0, hsm_signer_1.getHsmSigner)();
239
172
  if (hsm) {
240
173
  hsm.shutdown();
@@ -246,177 +179,16 @@ async function shutdownAppContext() {
246
179
  (0, network_context_1.setActiveNetwork)(null);
247
180
  }
248
181
  }
249
- /**
250
- * Load and validate CardanoClientConfig from CDS config or environment variables.
251
- *
252
- * When used as a plugin, consumers configure via package.json:
253
- * { "cds": { "requires": { "odatano-core": { "network": "preview", "backends": ["blockfrost"], ... }}}}
254
- *
255
- * Priority: cds.env.requires["odatano-core"].X > process.env.X > default
256
- *
257
- * @returns validated CardanoClientConfig
258
- * @throws {Error} if any config value is invalid
259
- */
260
- function loadConfigFromEnv() {
261
- // Check CDS plugin config first, fall back to env vars
262
- const cdsConfig = cds_1.default.env?.requires?.['odatano-core'] ?? {};
263
- const network = (cdsConfig.network || process_1.env.NETWORK || 'preview');
264
- if (!VALID_NETWORKS.includes(network)) {
265
- throw new errors_1.ConfigError(`Invalid NETWORK "${cdsConfig.network || process_1.env.NETWORK}". Must be one of: ${VALID_NETWORKS.join(', ')}`);
266
- }
267
- const backendStrings = cdsConfig.backends
268
- || (process_1.env.BACKENDS ? process_1.env.BACKENDS.split(',').map(b => b.trim()) : ['koios']);
269
- const invalidBackends = backendStrings.filter(b => !VALID_BACKENDS.includes(b));
270
- if (invalidBackends.length > 0) {
271
- throw new errors_1.ConfigError(`Invalid BACKENDS: "${invalidBackends.join(', ')}". Must be one of: ${VALID_BACKENDS.join(', ')}`);
272
- }
273
- const backends = backendStrings;
274
- // Buildooor is the sole transaction builder; any legacy txBuilders/TX_BUILDERS config is ignored.
275
- const txBuilders = ['buildooor'];
276
- const primaryTimeout = cdsConfig.primaryTimeoutMs ?? process_1.env.PRIMARY_TIMEOUT_MS;
277
- const fallbackTimeout = cdsConfig.fallbackTimeoutMs ?? process_1.env.FALLBACK_TIMEOUT_MS;
278
- // `!= null` not truthiness: a CDS-config numeric 0 is falsy, so `timeout && …`
279
- // skipped the <=0 check and 0 then silently became the default via `Number(0)||default`.
280
- if (primaryTimeout != null && isNaN(Number(primaryTimeout))) {
281
- throw new errors_1.ConfigError(`Invalid PRIMARY_TIMEOUT_MS "${primaryTimeout}". Must be a number.`);
282
- }
283
- if (primaryTimeout != null && Number(primaryTimeout) <= 0) {
284
- throw new errors_1.ConfigError(`Invalid PRIMARY_TIMEOUT_MS "${primaryTimeout}". Must be a positive number.`);
285
- }
286
- if (fallbackTimeout != null && isNaN(Number(fallbackTimeout))) {
287
- throw new errors_1.ConfigError(`Invalid FALLBACK_TIMEOUT_MS "${fallbackTimeout}". Must be a number.`);
288
- }
289
- if (fallbackTimeout != null && Number(fallbackTimeout) <= 0) {
290
- throw new errors_1.ConfigError(`Invalid FALLBACK_TIMEOUT_MS "${fallbackTimeout}". Must be a positive number.`);
291
- }
292
- const blockfrostApiKey = cdsConfig.blockfrostApiKey || process_1.env.BLOCKFROST_API_KEY || '';
293
- const blockfrostCustomBackend = cdsConfig.blockfrostCustomBackend || process_1.env.BLOCKFROST_CUSTOM_BACKEND || '';
294
- if (blockfrostCustomBackend && !/^https?:\/\//i.test(blockfrostCustomBackend)) {
295
- throw new errors_1.ConfigError(`Invalid BLOCKFROST_CUSTOM_BACKEND "${blockfrostCustomBackend}". Must be an http(s) URL ` +
296
- `(e.g. http://localhost:3010/api/v0).`);
297
- }
298
- const koiosApiKey = cdsConfig.koiosApiKey || process_1.env.KOIOS_API_KEY || '';
299
- const ogmiosUrl = cdsConfig.ogmiosUrl || process_1.env.OGMIOS_URL || '';
300
- // Warn about missing API keys for selected backends
301
- if (backends.includes('blockfrost') && !blockfrostApiKey && !blockfrostCustomBackend) {
302
- logger.warn('Neither BLOCKFROST_API_KEY nor BLOCKFROST_CUSTOM_BACKEND is set but blockfrost is listed in BACKENDS');
303
- }
304
- else if (backends.includes('blockfrost') && blockfrostCustomBackend) {
305
- logger.info(`Blockfrost will use customBackend: ${blockfrostCustomBackend}`);
306
- }
307
- if (backends.includes('ogmios') && !ogmiosUrl) {
308
- logger.warn('OGMIOS_URL is not set but ogmios is listed in BACKENDS');
309
- }
310
- return {
311
- network,
312
- backends,
313
- blockfrostApiKey,
314
- blockfrostCustomBackend: blockfrostCustomBackend || undefined,
315
- koiosApiKey,
316
- ogmiosUrl,
317
- transactionBuilders: txBuilders,
318
- primaryTimeoutMs: Number(primaryTimeout) || 30000, // || intentional: NaN (missing config) falls back to default
319
- fallbackTimeoutMs: Number(fallbackTimeout) || 60000,
320
- indexTtlMs: Number(cdsConfig.indexTtlMs ?? process_1.env.INDEX_TTL_MS) || 3600000,
321
- };
322
- }
323
- /**
324
- * Load HSM configuration from CDS config or environment variables.
325
- * Returns undefined if HSM is not enabled.
326
- *
327
- * Plugin mode: cds.requires.odatano-core.hsm.enabled = true
328
- * Env mode: HSM_ENABLED=true
329
- *
330
- * @returns HsmConfig or undefined
331
- */
332
- function loadHsmConfigFromEnv() {
333
- const cdsConfig = cds_1.default.env?.requires?.['odatano-core'] ?? {};
334
- const hsmCds = cdsConfig.hsm ?? {};
335
- const hsmEnabled = hsmCds.enabled === true || process_1.env.HSM_ENABLED === 'true';
336
- if (!hsmEnabled)
337
- return undefined;
338
- const pkcs11Module = hsmCds.pkcs11Module || process_1.env.HSM_PKCS11_MODULE || '';
339
- if (!pkcs11Module) {
340
- throw new errors_1.ConfigError('HSM_PKCS11_MODULE is required when HSM is enabled');
341
- }
342
- const pin = hsmCds.pin || process_1.env.HSM_PIN || '';
343
- if (!pin) {
344
- throw new errors_1.ConfigError('HSM_PIN is required when HSM is enabled');
345
- }
346
- const slot = Number(hsmCds.slot ?? process_1.env.HSM_SLOT ?? 0);
347
- if (!Number.isInteger(slot) || slot < 0) {
348
- throw new errors_1.ConfigError(`Invalid HSM slot: "${hsmCds.slot ?? process_1.env.HSM_SLOT}" — must be a non-negative integer`);
349
- }
350
- // Fail-closed: HSM controls a real signing key. Require an explicit role gate so
351
- // that an authenticated user cannot drain the HSM-controlled wallet by default.
352
- const requiresRole = hsmCds.requiresRole || process_1.env.HSM_REQUIRES_ROLE || '';
353
- if (!requiresRole) {
354
- 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');
355
- }
356
- return {
357
- enabled: true,
358
- pkcs11Module,
359
- slot,
360
- pin,
361
- keyId: hsmCds.keyId || process_1.env.HSM_KEY_ID,
362
- keyLabel: hsmCds.keyLabel || process_1.env.HSM_KEY_LABEL,
363
- requiresRole,
364
- };
365
- }
366
- /**
367
- * Load the chain-crawler configuration from CDS config or environment variables.
368
- * Returns { enabled:false } when the crawler is not switched on (the default), so
369
- * existing deployments are unaffected.
370
- *
371
- * Plugin mode: cds.requires.odatano-core.crawler.{enabled,startSlot,startBlockHash,...}
372
- * Env mode: CRAWLER_ENABLED / CRAWLER_START_SLOT / CRAWLER_START_HASH / ...
373
- */
374
- function loadCrawlerConfigFromEnv() {
375
- const cdsConfig = cds_1.default.env?.requires?.['odatano-core'] ?? {};
376
- const c = cdsConfig.crawler ?? {};
377
- // A CDS value, including explicit `false`, wins over the environment.
378
- const enabledRaw = c.enabled !== undefined ? c.enabled : process_1.env.CRAWLER_ENABLED;
379
- let enabled = false;
380
- if (enabledRaw === true || enabledRaw === 'true') {
381
- enabled = true;
382
- }
383
- else if (enabledRaw !== undefined && enabledRaw !== false && enabledRaw !== 'false') {
384
- throw new errors_1.ConfigError(`Invalid CRAWLER_ENABLED "${String(enabledRaw)}". Must be true or false.`);
385
- }
386
- const startSlot = crawlerInteger(c.startSlot ?? process_1.env.CRAWLER_START_SLOT, 'CRAWLER_START_SLOT', 0, Number.MAX_SAFE_INTEGER);
387
- const startHeight = crawlerInteger(c.startHeight ?? process_1.env.CRAWLER_START_HEIGHT, 'CRAWLER_START_HEIGHT', 0, Number.MAX_SAFE_INTEGER);
388
- const startBlockHashRaw = c.startBlockHash ?? process_1.env.CRAWLER_START_HASH;
389
- if (startBlockHashRaw != null && (typeof startBlockHashRaw !== 'string' || !/^[0-9a-f]{64}$/i.test(startBlockHashRaw.trim()))) {
390
- throw new errors_1.ConfigError('Invalid CRAWLER_START_HASH. Must be exactly 64 hexadecimal characters.');
391
- }
392
- const startBlockHash = startBlockHashRaw?.trim() || undefined;
393
- const source = (c.source ?? process_1.env.CRAWLER_SOURCE ?? 'auto');
394
- const batchSize = crawlerInteger(c.batchSize ?? process_1.env.CRAWLER_BATCH_SIZE, 'CRAWLER_BATCH_SIZE', CRAWLER_LIMITS.batchSize.min, CRAWLER_LIMITS.batchSize.max, 20);
395
- const confirmationDepth = crawlerInteger(c.confirmationDepth ?? process_1.env.CRAWLER_CONFIRMATION_DEPTH, 'CRAWLER_CONFIRMATION_DEPTH', CRAWLER_LIMITS.confirmationDepth.min, CRAWLER_LIMITS.confirmationDepth.max, 3);
396
- const pollIntervalMs = crawlerInteger(c.pollIntervalMs ?? process_1.env.CRAWLER_POLL_INTERVAL_MS, 'CRAWLER_POLL_INTERVAL_MS', CRAWLER_LIMITS.pollIntervalMs.min, CRAWLER_LIMITS.pollIntervalMs.max, 20_000);
397
- if (enabled && (startSlot == null || Number.isNaN(startSlot) || !startBlockHash)) {
398
- throw new errors_1.ConfigError('Crawler is enabled but no start block is configured — set crawler.startSlot + crawler.startBlockHash ' +
399
- '(or CRAWLER_START_SLOT + CRAWLER_START_HASH).');
400
- }
401
- if (!['ogmios', 'pagination', 'auto'].includes(source)) {
402
- throw new errors_1.ConfigError(`Invalid CRAWLER_SOURCE "${source}". Must be one of: ogmios, pagination, auto.`);
403
- }
404
- return { enabled, startSlot, startBlockHash, startHeight, source, batchSize, confirmationDepth, pollIntervalMs };
405
- }
406
- /**
407
- * Start the chain crawler if it is enabled and the app context is ready. Never throws
408
- * (crawler failure must not affect request serving) — errors are logged. Idempotent:
409
- * startCrawler() is a no-op when one is already running.
410
- */
182
+ /** Start the crawler if enabled and the app context is ready. Never throws; idempotent. */
411
183
  async function startCrawlerIfConfigured() {
412
- if (process_1.env.SKIP_AUTO_INIT === 'true' || !appContext)
184
+ if ((0, config_1.autoInitSkipped)() || !appContext)
413
185
  return;
414
186
  let config;
415
187
  try {
416
- config = loadCrawlerConfigFromEnv();
188
+ config = (0, config_1.loadCrawlerConfigFromEnv)();
417
189
  }
418
190
  catch (err) {
419
- logger.error('Invalid crawler configuration — crawler not started:', err);
191
+ logger.error('Invalid crawler configuration, crawler not started:', err);
420
192
  return;
421
193
  }
422
194
  if (!config.enabled)
@@ -434,101 +206,16 @@ async function startCrawlerIfConfigured() {
434
206
  logger.error('Failed to start chain crawler (non-fatal):', err);
435
207
  }
436
208
  }
437
- const WALLET_WORKER_LIMITS = {
438
- maxConcurrentWallets: { min: 1, max: 64 },
439
- confirmationDepth: { min: 1, max: 2160 },
440
- confirmationTimeoutMs: { min: 30_000, max: 86_400_000 },
441
- pollIntervalMs: { min: 500, max: 3_600_000 },
442
- maxAttempts: { min: 1, max: 10 },
443
- };
444
- /**
445
- * Load the wallet-worker configuration from CDS config or environment variables.
446
- * Returns { enabled:false } when the worker is not switched on (the default).
447
- *
448
- * Plugin mode: cds.requires.odatano-core.walletWorker.{enabled,wallets,...}
449
- * Env mode: WALLET_WORKER_ENABLED / WALLET_WORKER_WALLETS (JSON) / ...
450
- */
451
- function loadWalletWorkerConfigFromEnv() {
452
- const cdsConfig = cds_1.default.env?.requires?.['odatano-core'] ?? {};
453
- const w = cdsConfig.walletWorker ?? {};
454
- const enabledRaw = w.enabled !== undefined ? w.enabled : process_1.env.WALLET_WORKER_ENABLED;
455
- let enabled = false;
456
- if (enabledRaw === true || enabledRaw === 'true') {
457
- enabled = true;
458
- }
459
- else if (enabledRaw !== undefined && enabledRaw !== false && enabledRaw !== 'false') {
460
- throw new errors_1.ConfigError(`Invalid WALLET_WORKER_ENABLED "${String(enabledRaw)}". Must be true or false.`);
461
- }
462
- let walletsRaw = w.wallets ?? undefined;
463
- if (walletsRaw === undefined && process_1.env.WALLET_WORKER_WALLETS) {
464
- try {
465
- walletsRaw = JSON.parse(process_1.env.WALLET_WORKER_WALLETS);
466
- }
467
- catch {
468
- throw new errors_1.ConfigError('Invalid WALLET_WORKER_WALLETS — must be a JSON array of { walletId, signerType, keyEnv? }.');
469
- }
470
- }
471
- const wallets = [];
472
- if (walletsRaw !== undefined) {
473
- if (!Array.isArray(walletsRaw)) {
474
- throw new errors_1.ConfigError('Invalid walletWorker.wallets — must be an array of { walletId, signerType, keyEnv? }.');
475
- }
476
- for (const entry of walletsRaw) {
477
- const walletId = typeof entry?.walletId === 'string' ? entry.walletId.trim() : '';
478
- const signerType = entry?.signerType;
479
- if (!walletId || (signerType !== 'hsm' && signerType !== 'software')) {
480
- throw new errors_1.ConfigError(`Invalid wallet entry ${JSON.stringify(entry)} — walletId and signerType (hsm|software) are required.`);
481
- }
482
- if (signerType === 'software' && (typeof entry.keyEnv !== 'string' || !entry.keyEnv.trim())) {
483
- throw new errors_1.ConfigError(`Wallet "${walletId}" is signerType=software but has no keyEnv (name of the env var holding the signing key).`);
484
- }
485
- if (wallets.some((existing) => existing.walletId === walletId)) {
486
- throw new errors_1.ConfigError(`Duplicate walletId "${walletId}" in walletWorker.wallets.`);
487
- }
488
- wallets.push({ walletId, signerType, keyEnv: entry.keyEnv });
489
- }
490
- }
491
- const maxConcurrentWallets = crawlerInteger(w.maxConcurrentWallets ?? process_1.env.WALLET_WORKER_MAX_CONCURRENT, 'WALLET_WORKER_MAX_CONCURRENT', WALLET_WORKER_LIMITS.maxConcurrentWallets.min, WALLET_WORKER_LIMITS.maxConcurrentWallets.max, 4);
492
- const confirmationDepth = crawlerInteger(w.confirmationDepth ?? process_1.env.WALLET_WORKER_CONFIRMATION_DEPTH, 'WALLET_WORKER_CONFIRMATION_DEPTH', WALLET_WORKER_LIMITS.confirmationDepth.min, WALLET_WORKER_LIMITS.confirmationDepth.max, 3);
493
- const confirmationTimeoutMs = crawlerInteger(w.confirmationTimeoutMs ?? process_1.env.WALLET_WORKER_CONFIRMATION_TIMEOUT_MS, 'WALLET_WORKER_CONFIRMATION_TIMEOUT_MS', WALLET_WORKER_LIMITS.confirmationTimeoutMs.min, WALLET_WORKER_LIMITS.confirmationTimeoutMs.max, 600_000);
494
- const pollIntervalMs = crawlerInteger(w.pollIntervalMs ?? process_1.env.WALLET_WORKER_POLL_INTERVAL_MS, 'WALLET_WORKER_POLL_INTERVAL_MS', WALLET_WORKER_LIMITS.pollIntervalMs.min, WALLET_WORKER_LIMITS.pollIntervalMs.max, 2_000);
495
- const defaultMaxAttempts = crawlerInteger(w.defaultMaxAttempts ?? process_1.env.WALLET_WORKER_MAX_ATTEMPTS, 'WALLET_WORKER_MAX_ATTEMPTS', WALLET_WORKER_LIMITS.maxAttempts.min, WALLET_WORKER_LIMITS.maxAttempts.max, 3);
496
- const resubmitRaw = w.resubmitOnRollback !== undefined ? w.resubmitOnRollback : process_1.env.WALLET_WORKER_RESUBMIT_ON_ROLLBACK;
497
- let resubmitOnRollback = true;
498
- if (resubmitRaw === false || resubmitRaw === 'false') {
499
- resubmitOnRollback = false;
500
- }
501
- else if (resubmitRaw !== undefined && resubmitRaw !== true && resubmitRaw !== 'true') {
502
- throw new errors_1.ConfigError(`Invalid WALLET_WORKER_RESUBMIT_ON_ROLLBACK "${String(resubmitRaw)}". Must be true or false.`);
503
- }
504
- if (enabled && wallets.length === 0) {
505
- throw new errors_1.ConfigError('Wallet worker is enabled but no wallets are configured — set walletWorker.wallets (or WALLET_WORKER_WALLETS).');
506
- }
507
- return {
508
- enabled,
509
- wallets,
510
- maxConcurrentWallets,
511
- confirmationDepth,
512
- confirmationTimeoutMs,
513
- pollIntervalMs,
514
- defaultMaxAttempts,
515
- resubmitOnRollback,
516
- };
517
- }
518
- /**
519
- * Start the wallet worker if it is enabled and the app context is ready. Never
520
- * throws (worker failure must not affect request serving) — errors are logged.
521
- * Idempotent: startWalletWorker() is a no-op when one is already running.
522
- */
209
+ /** Start the wallet worker if enabled and the app context is ready. Never throws; idempotent. */
523
210
  async function startWalletWorkerIfConfigured() {
524
- if (process_1.env.SKIP_AUTO_INIT === 'true' || !appContext)
211
+ if ((0, config_1.autoInitSkipped)() || !appContext)
525
212
  return;
526
213
  let config;
527
214
  try {
528
- config = loadWalletWorkerConfigFromEnv();
215
+ config = (0, config_1.loadWalletWorkerConfigFromEnv)();
529
216
  }
530
217
  catch (err) {
531
- logger.error('Invalid wallet-worker configuration — worker not started:', err);
218
+ logger.error('Invalid wallet-worker configuration, worker not started:', err);
532
219
  return;
533
220
  }
534
221
  if (!config.enabled)
@@ -546,69 +233,62 @@ async function startWalletWorkerIfConfigured() {
546
233
  logger.error('Failed to start wallet worker (non-fatal):', err);
547
234
  }
548
235
  }
549
- /**
550
- * Re-drive deferred submissions that were claimed (status 'submitting' with
551
- * persisted signedTxCbor) but whose detached submit never ran because the
552
- * process died first (KNOWN_ISSUES #11, Layer 2). Idempotent — an already
553
- * submitted tx finalizes via the TransactionAlreadySubmittedError path.
554
- * Non-fatal, mirrors startCrawlerIfConfigured/startWalletWorkerIfConfigured.
555
- */
236
+ let submissionReconcilerStarted = false;
237
+ function submissionFinalizer() {
238
+ return require('./blockchain/signing/submission-finalizer');
239
+ }
240
+ // Resolves submits left open by a crash or by a submit without a verdict, now and then on a timer.
241
+ // Idempotent, because a transaction the node already holds finalizes as submitted. Never throws.
556
242
  async function redriveInterruptedSubmissionsIfConfigured() {
557
- if (process_1.env.SKIP_AUTO_INIT === 'true' || !appContext)
243
+ if ((0, config_1.autoInitSkipped)() || !appContext)
244
+ return;
245
+ // Without a database there are no signing requests to re-drive
246
+ if (!cds_1.default.db)
558
247
  return;
559
248
  try {
560
- const { redriveInterruptedSubmissions } = require('./blockchain/signing/submission-finalizer');
561
- const attempted = await redriveInterruptedSubmissions();
249
+ const attempted = await submissionFinalizer().redriveInterruptedSubmissions();
562
250
  if (attempted > 0)
563
- logger.info(`Re-drove ${attempted} interrupted deferred submission(s)`);
251
+ logger.info(`Resolved or retried ${attempted} open submission(s)`);
564
252
  }
565
253
  catch (err) {
566
254
  logger.error('Failed to re-drive interrupted submissions (non-fatal):', err);
567
255
  }
256
+ submissionFinalizer().startSubmissionReconciler();
257
+ submissionReconcilerStarted = true;
568
258
  }
569
- // Bootstrap hook - runs when CAP server has loaded all services
259
+ // Standalone bootstrap; skipped when the plugin already initialized the context.
570
260
  cds_1.default.on('served', async () => {
571
- // Skip if already initialized by plugin (src/plugin.ts runs first)
572
261
  if (appContext)
573
262
  return;
574
- // Skip auto-initialization when SKIP_AUTO_INIT is set (e.g., for tests with mocked backends)
575
- if (process_1.env.SKIP_AUTO_INIT === 'true') {
263
+ // SKIP_AUTO_INIT: tests with mocked backends
264
+ if ((0, config_1.autoInitSkipped)()) {
576
265
  logger.info('Skipping auto-initialization (SKIP_AUTO_INIT=true)');
577
266
  return;
578
267
  }
579
- // NOTE: config loading is INSIDE the try — loadConfigFromEnv/loadHsmConfigFromEnv
580
- // throw ConfigError synchronously (missing HSM_PIN, bad slot, no requiresRole…).
581
- // Outside the try that would crash the host app's bootstrap in plugin mode,
582
- // violating the plugin contract ("never throw on failure").
268
+ // Config loading stays inside the try: a ConfigError must never crash the host app.
583
269
  let config;
584
270
  try {
585
- config = loadConfigFromEnv();
586
- const hsmConfig = loadHsmConfigFromEnv();
271
+ config = (0, config_1.loadConfigFromEnv)();
272
+ const hsmConfig = (0, config_1.loadHsmConfigFromEnv)();
587
273
  hsmConfigInstance = hsmConfig;
588
274
  appContext = await initializeAppContext(config, undefined, hsmConfig);
589
275
  bootstrapError = null;
590
276
  logger.info('CAP server bootstrap complete');
591
277
  }
592
278
  catch (err) {
593
- // Don't throw - initialization failure shouldn't crash the host app (plugin contract).
594
- // Capture the cause so getAppContext() can surface a structured 503 with diagnostics
595
- // instead of the raw "Application not initialized" Error landing as a generic 500.
279
+ // Never throw; keep the cause so getAppContext() surfaces a structured 503.
596
280
  bootstrapError = err instanceof Error ? err : new Error(String(err));
597
- // Write to stderr directly so the cause stays visible even when test runners
598
- // suppress console.error (vitest.setup.ts in this repo silences it).
281
+ // stderr directly: the cause stays visible when a test runner silences console.error.
599
282
  const where = config ? `backends={${config.backends.join(',')}} network=${config.network}` : 'config load';
600
283
  const msg = err instanceof Error ? `${err.name}: ${err.message}\n${err.stack ?? ''}` : String(err);
601
- process.stderr.write(`[ODATANO] Failed to initialize blockchain components — ${where}\n${msg}\n`);
284
+ process.stderr.write(`[ODATANO] Failed to initialize blockchain components: ${where}\n${msg}\n`);
602
285
  logger.error('Failed to initialize blockchain components:', err);
603
286
  }
604
- // Start the pre-sync crawler if configured (standalone mode). Non-fatal.
287
+ // Optional subsystems; each is non-fatal.
605
288
  await startCrawlerIfConfigured();
606
- // Start the wallet worker if configured (standalone mode). Non-fatal.
607
289
  await startWalletWorkerIfConfigured();
608
- // Re-drive deferred submissions interrupted by a restart (standalone mode). Non-fatal.
609
290
  await redriveInterruptedSubmissionsIfConfigured();
610
291
  });
611
- // Shutdown hook - runs when CAP server is shutting down (e.g., cds.shutdown() in tests)
612
292
  cds_1.default.on('shutdown', async () => {
613
293
  await shutdownAppContext();
614
294
  });