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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +1 -5
  2. package/@cds-models/CardanoIndexerService/index.d.ts +51 -2
  3. package/@cds-models/CardanoIndexerService/index.js +7 -0
  4. package/package.json +1 -1
  5. package/src/index.d.ts +4 -10
  6. package/src/index.js +6 -16
  7. package/src/plugin.js +11 -27
  8. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  9. package/srv/blockchain/backends/blockfrost-backend.js +39 -150
  10. package/srv/blockchain/backends/cardano-backend.d.ts +53 -171
  11. package/srv/blockchain/backends/cardano-backend.js +1 -5
  12. package/srv/blockchain/backends/koios-backend.d.ts +26 -71
  13. package/srv/blockchain/backends/koios-backend.js +50 -132
  14. package/srv/blockchain/backends/ogmios-backend.d.ts +43 -124
  15. package/srv/blockchain/backends/ogmios-backend.js +71 -179
  16. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +12 -57
  17. package/srv/blockchain/backends/ogmios-frame-guard.js +27 -66
  18. package/srv/blockchain/cardano-client.d.ts +43 -216
  19. package/srv/blockchain/cardano-client.js +49 -234
  20. package/srv/blockchain/cardano-indexer.d.ts +79 -357
  21. package/srv/blockchain/cardano-indexer.js +98 -406
  22. package/srv/blockchain/cardano-tx-builder.d.ts +19 -84
  23. package/srv/blockchain/cardano-tx-builder.js +21 -107
  24. package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
  25. package/srv/blockchain/crawler/certificate-backfill.js +150 -0
  26. package/srv/blockchain/crawler/crawler.d.ts +41 -145
  27. package/srv/blockchain/crawler/crawler.js +57 -172
  28. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  29. package/srv/blockchain/crawler/index.d.ts +2 -6
  30. package/srv/blockchain/crawler/index.js +4 -9
  31. package/srv/blockchain/crawler/sync-state.d.ts +17 -39
  32. package/srv/blockchain/crawler/sync-state.js +23 -55
  33. package/srv/blockchain/crawler/utxo-set-import.d.ts +5 -22
  34. package/srv/blockchain/crawler/utxo-set-import.js +8 -28
  35. package/srv/blockchain/ledger-state.d.ts +3 -12
  36. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  37. package/srv/blockchain/signing/cose-verifier.js +6 -12
  38. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  39. package/srv/blockchain/signing/external-signer.js +19 -122
  40. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  41. package/srv/blockchain/signing/hsm-signer.js +23 -63
  42. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  43. package/srv/blockchain/signing/signature-verifier.js +13 -54
  44. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  45. package/srv/blockchain/signing/submission-finalizer.js +16 -48
  46. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +65 -174
  47. package/srv/blockchain/transaction-building/buildooor-tx.js +107 -266
  48. package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
  49. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  50. package/srv/blockchain/wallet-worker/build-request.js +9 -22
  51. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +12 -35
  52. package/srv/blockchain/wallet-worker/confirmation-tracker.js +16 -32
  53. package/srv/blockchain/wallet-worker/index.js +2 -8
  54. package/srv/blockchain/wallet-worker/job-store.d.ts +33 -111
  55. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  56. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  57. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  58. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  59. package/srv/blockchain/wallet-worker/signers.js +3 -8
  60. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  61. package/srv/blockchain/wallet-worker/wallet-worker.js +34 -90
  62. package/srv/cardano-agent-service.cds +1 -5
  63. package/srv/cardano-agent-service.js +3 -7
  64. package/srv/cardano-indexer-service.cds +32 -4
  65. package/srv/cardano-indexer-service.js +83 -15
  66. package/srv/cardano-service.js +36 -98
  67. package/srv/cardano-sign-service.cds +1 -1
  68. package/srv/cardano-sign-service.js +55 -173
  69. package/srv/cardano-tx-service.cds +1 -1
  70. package/srv/cardano-tx-service.js +54 -174
  71. package/srv/cardano-worker-service.js +7 -15
  72. package/srv/server.d.ts +27 -86
  73. package/srv/server.js +52 -148
  74. package/srv/utils/agent-grants-config.d.ts +11 -50
  75. package/srv/utils/agent-grants-config.js +12 -45
  76. package/srv/utils/agent-grants.d.ts +34 -123
  77. package/srv/utils/agent-grants.js +57 -156
  78. package/srv/utils/agent-token-auth.d.ts +2 -5
  79. package/srv/utils/agent-token-auth.js +2 -5
  80. package/srv/utils/backend-request-handler.d.ts +2 -16
  81. package/srv/utils/backend-request-handler.js +3 -18
  82. package/srv/utils/collections.d.ts +4 -8
  83. package/srv/utils/collections.js +4 -8
  84. package/srv/utils/const.d.ts +19 -68
  85. package/srv/utils/const.js +20 -69
  86. package/srv/utils/crypto.d.ts +3 -12
  87. package/srv/utils/crypto.js +5 -18
  88. package/srv/utils/db-indexes.d.ts +2 -7
  89. package/srv/utils/db-indexes.js +7 -34
  90. package/srv/utils/db-sanitize.d.ts +5 -18
  91. package/srv/utils/db-sanitize.js +6 -19
  92. package/srv/utils/error-codes.d.ts +18 -73
  93. package/srv/utils/error-codes.js +17 -70
  94. package/srv/utils/errors.d.ts +29 -191
  95. package/srv/utils/errors.js +44 -229
  96. package/srv/utils/liveness.d.ts +2 -9
  97. package/srv/utils/liveness.js +3 -11
  98. package/srv/utils/mappers.d.ts +50 -298
  99. package/srv/utils/mappers.js +80 -386
  100. package/srv/utils/network-context.js +2 -11
  101. package/srv/utils/pg-order-nulls.js +4 -23
  102. package/srv/utils/plutus-placeholders.d.ts +6 -18
  103. package/srv/utils/plutus-placeholders.js +6 -20
  104. package/srv/utils/rate-limiter.d.ts +6 -17
  105. package/srv/utils/rate-limiter.js +5 -15
  106. package/srv/utils/service-events.d.ts +2 -22
  107. package/srv/utils/service-events.js +3 -23
  108. package/srv/utils/signing-helper.d.ts +3 -18
  109. package/srv/utils/signing-helper.js +10 -32
  110. package/srv/utils/tx-build-helper.d.ts +18 -92
  111. package/srv/utils/tx-build-helper.js +32 -123
  112. package/srv/utils/tx-request-parsers.d.ts +7 -26
  113. package/srv/utils/tx-request-parsers.js +7 -26
  114. package/srv/utils/tx-utils.d.ts +4 -23
  115. package/srv/utils/tx-utils.js +12 -41
  116. package/srv/utils/types.d.ts +67 -206
  117. package/srv/utils/types.js +2 -6
  118. package/srv/utils/validators.d.ts +19 -89
  119. package/srv/utils/validators.js +31 -138
@@ -13,22 +13,16 @@ const job_store_1 = require("./blockchain/wallet-worker/job-store");
13
13
  const server_1 = require("./server");
14
14
  const logger = cds_1.default.log('CardanoWorkerService');
15
15
  /**
16
- * CardanoWorkerService handlers — thin control surface over the wallet-worker
17
- * singleton (srv/blockchain/wallet-worker). Engine logic lives there; this only
18
- * validates inputs, inserts/reads job rows and starts/stops the worker.
19
- *
20
- * Validation rejections happen BEFORE handleRequest (project convention); the
21
- * job INSERT runs on the request's ambient transaction (NIGHTGATE lesson 1).
16
+ * CardanoWorkerService handlers: control surface over the wallet-worker singleton
17
+ * (srv/blockchain/wallet-worker). Validates inputs, inserts/reads job rows, starts/stops
18
+ * the worker. The job INSERT runs on the request's ambient transaction.
22
19
  */
23
20
  function isAdmin(req) {
24
21
  return req.user?.is?.('Admin') ?? false;
25
22
  }
26
23
  /**
27
- * A job on an HSM-backed wallet spends the same server-held key as the synchronous
28
- * SignWithHsm path, so it inherits that path's role gate (enforceHsmRole in
29
- * cardano-sign-service.ts) — 'authenticated-user' alone must not reach the HSM.
30
- * Returns the role the caller is missing, or null when the wallet is not HSM-backed,
31
- * no role is configured, or the caller holds it.
24
+ * HSM-backed wallets inherit the SignWithHsm role gate (enforceHsmRole in the sign service).
25
+ * Returns the role the caller is missing, or null when not HSM-backed, no role configured, or held.
32
26
  */
33
27
  function missingHsmRole(req, signerType) {
34
28
  if (signerType !== 'hsm')
@@ -125,10 +119,8 @@ module.exports = (srv) => {
125
119
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
126
120
  const job = await (0, job_store_1.getJobById)(db, jobId);
127
121
  if (!job || (!isAdmin(req) && job.createdBy !== req.user?.id)) {
128
- // Same 404 for "not found" and "not yours" — no existence oracle.
129
- // THROW, don't req.reject: we are inside handleRequest, whose catch would
130
- // see a plain CAP error and remap it to 500 (mapError). A BackendError
131
- // carries its status through.
122
+ // Same 404 for "not found" and "not yours" (no existence oracle). Throw, don't
123
+ // req.reject: inside handleRequest a plain CAP error is remapped to 500.
132
124
  throw new errors_1.NotFoundError(`Job ${jobId}`);
133
125
  }
134
126
  const cancelled = await (0, job_store_1.markCancelled)(db, jobId);
package/srv/server.d.ts CHANGED
@@ -4,127 +4,68 @@ import { CardanoTransactionBuilder } from './blockchain/cardano-tx-builder';
4
4
  import type { LedgerProtocolParameters, HsmConfig } from './utils/types';
5
5
  import type { CrawlerConfig } from './blockchain/crawler/crawler';
6
6
  import type { WalletWorkerConfig } from './blockchain/wallet-worker';
7
- /**
8
- * Application context holding initialized blockchain components
9
- * These are created once during CAP bootstrap and shared across services
10
- */
7
+ /** Blockchain components created once at bootstrap and shared across services. */
11
8
  interface AppContext {
12
9
  cardanoClient: CardanoClient;
13
10
  cardanoIndexer: CardanoIndexer;
14
11
  cardanoTxBuilder: CardanoTransactionBuilder;
15
12
  }
16
- /** Agent-grant feature switch (AGENT_GRANTS_DESIGN.md); lives in its own module so src/plugin.ts can read it at load. */
13
+ /** Agent-grant feature switch; its own module so src/plugin.ts can read it at load. */
17
14
  export { loadAgentGrantsConfig, activateAgentGrants } from './utils/agent-grants-config';
18
15
  /**
19
- * Get the application context (must be called after bootstrap)
20
- * @throws {ProviderUnavailableError} 503 when uninitialized — request handlers using
21
- * handleRequest/mapError translate this into a clean 503 response instead of a raw 500.
22
- * If bootstrap actively failed, the cause is appended to the message.
16
+ * The application context.
17
+ * @throws {ProviderUnavailableError} 503 when uninitialized; a bootstrap failure is appended as cause.
23
18
  */
24
19
  export declare function getAppContext(): AppContext;
25
- /**
26
- * Get the CardanoIndexer instance
27
- * Convenience function for services
28
- */
29
20
  export declare function getCardanoIndexer(): CardanoIndexer;
30
- /**
31
- * Get the CardanoClient instance
32
- * Convenience function for services
33
- */
34
21
  export declare function getCardanoClient(): CardanoClient;
35
- /**
36
- * Get the CardanoTransactionBuilder instance
37
- * Convenience function for services and plugin consumers
38
- */
39
22
  export declare function getCardanoTxBuilder(): CardanoTransactionBuilder;
40
- /**
41
- * Get the HSM configuration (if HSM is enabled).
42
- * Used by sign service to check requiresRole.
43
- */
23
+ /** HSM configuration when enabled; the sign service reads requiresRole from it. */
44
24
  export declare function getHsmConfig(): HsmConfig | undefined;
45
25
  /**
46
- * Initialize from a pre-built config (used by plugin's src/index.ts)
47
- * @param config - validated CardanoClientConfig
48
- * @param protocolParams - Optional protocol parameters (for tests)
26
+ * Initialize from a pre-built config (plugin path). Idempotent: a second call must not
27
+ * create a duplicate CardanoClient; tests reinitialize via resetAppContext() / createTestContext().
49
28
  */
50
29
  export declare function initializeFromConfig(config: CardanoClientConfig, protocolParams?: LedgerProtocolParameters, hsmConfig?: HsmConfig): Promise<void>;
51
- /**
52
- * Reset the application context (for testing only)
53
- * Allows tests to inject their own instances
54
- */
30
+ /** Reset the application context (tests only); lets tests inject their own instances. */
55
31
  export declare function resetAppContext(context: AppContext | null): void;
56
32
  /**
57
- * Create a test context with specific backends and transaction builder
58
- * Used by integration tests to create isolated test instances
59
- * @param backends Array of backend names to use (e.g., ['koios'], ['blockfrost'])
60
- * @param _txBuilderName Deprecated/ignored — Buildooor is the sole transaction builder (kept for signature compatibility)
61
- * @param protocolParams Optional protocol parameters (to skip backend call during init)
62
- * @returns Promise<AppContext> The created application context
63
- */
64
- export declare function createTestContext(backends: BackendName[], _txBuilderName?: TransactionBuilderName, // kept for signature compat; Buildooor is the only builder
65
- protocolParams?: LedgerProtocolParameters): Promise<AppContext>;
66
- /**
67
- * Shutdown the application context (for cleanup in tests)
68
- * Closes all backend connections to allow process to exit cleanly
33
+ * Create an isolated test context with the given backends.
34
+ * @param _txBuilderName ignored; Buildooor is the sole builder (kept for signature compatibility)
35
+ * @param protocolParams optional, skips the backend call during init
69
36
  */
37
+ export declare function createTestContext(backends: BackendName[], _txBuilderName?: TransactionBuilderName, protocolParams?: LedgerProtocolParameters): Promise<AppContext>;
38
+ /** Stop worker and crawler, then close all backend connections. */
70
39
  export declare function shutdownAppContext(): Promise<void>;
71
40
  /**
72
- * Load and validate CardanoClientConfig from CDS config or environment variables.
73
- *
74
- * When used as a plugin, consumers configure via package.json:
75
- * { "cds": { "requires": { "odatano-core": { "network": "preview", "backends": ["blockfrost"], ... }}}}
76
- *
77
- * Priority: cds.env.requires["odatano-core"].X > process.env.X > default
78
- *
79
- * @returns validated CardanoClientConfig
80
- * @throws {Error} if any config value is invalid
41
+ * Load and validate CardanoClientConfig.
42
+ * Priority: cds.env.requires["odatano-core"].X > process.env.X > default.
43
+ * @throws {ConfigError} if any value is invalid
81
44
  */
82
45
  export declare function loadConfigFromEnv(): CardanoClientConfig;
83
46
  /**
84
- * Load HSM configuration from CDS config or environment variables.
85
- * Returns undefined if HSM is not enabled.
86
- *
87
- * Plugin mode: cds.requires.odatano-core.hsm.enabled = true
88
- * Env mode: HSM_ENABLED=true
89
- *
90
- * @returns HsmConfig or undefined
47
+ * Load the HSM configuration (cds.requires.odatano-core.hsm.* or HSM_* env vars).
48
+ * Returns undefined when HSM is not enabled.
91
49
  */
92
50
  export declare function loadHsmConfigFromEnv(): HsmConfig | undefined;
93
51
  /**
94
- * Load the chain-crawler configuration from CDS config or environment variables.
95
- * Returns { enabled:false } when the crawler is not switched on (the default), so
96
- * existing deployments are unaffected.
97
- *
98
- * Plugin mode: cds.requires.odatano-core.crawler.{enabled,startSlot,startBlockHash,...}
99
- * Env mode: CRAWLER_ENABLED / CRAWLER_START_SLOT / CRAWLER_START_HASH / ...
52
+ * Load the chain-crawler configuration (cds.requires.odatano-core.crawler.* or CRAWLER_* env vars).
53
+ * Returns { enabled: false } when the crawler is off (the default).
100
54
  */
101
55
  export declare function loadCrawlerConfigFromEnv(): CrawlerConfig;
102
- /**
103
- * Start the chain crawler if it is enabled and the app context is ready. Never throws
104
- * (crawler failure must not affect request serving) — errors are logged. Idempotent:
105
- * startCrawler() is a no-op when one is already running.
106
- */
56
+ /** Start the crawler if enabled and the app context is ready. Never throws; idempotent. */
107
57
  export declare function startCrawlerIfConfigured(): Promise<void>;
108
58
  /**
109
- * Load the wallet-worker configuration from CDS config or environment variables.
110
- * Returns { enabled:false } when the worker is not switched on (the default).
111
- *
112
- * Plugin mode: cds.requires.odatano-core.walletWorker.{enabled,wallets,...}
113
- * Env mode: WALLET_WORKER_ENABLED / WALLET_WORKER_WALLETS (JSON) / ...
59
+ * Load the wallet-worker configuration (cds.requires.odatano-core.walletWorker.* or WALLET_WORKER_* env vars).
60
+ * Returns { enabled: false } when the worker is off (the default).
114
61
  */
115
62
  export declare function loadWalletWorkerConfigFromEnv(): WalletWorkerConfig;
116
- /**
117
- * Start the wallet worker if it is enabled and the app context is ready. Never
118
- * throws (worker failure must not affect request serving) — errors are logged.
119
- * Idempotent: startWalletWorker() is a no-op when one is already running.
120
- */
63
+ /** Start the wallet worker if enabled and the app context is ready. Never throws; idempotent. */
121
64
  export declare function startWalletWorkerIfConfigured(): Promise<void>;
122
65
  /**
123
- * Re-drive deferred submissions that were claimed (status 'submitting' with
124
- * persisted signedTxCbor) but whose detached submit never ran because the
125
- * process died first (KNOWN_ISSUES #11, Layer 2). Idempotent — an already
126
- * submitted tx finalizes via the TransactionAlreadySubmittedError path.
127
- * Non-fatal, mirrors startCrawlerIfConfigured/startWalletWorkerIfConfigured.
66
+ * Re-drive deferred submissions claimed as 'submitting' whose detached submit never ran
67
+ * (process died first). Idempotent: an already submitted tx finalizes via
68
+ * TransactionAlreadySubmittedError. Never throws.
128
69
  */
129
70
  export declare function redriveInterruptedSubmissionsIfConfigured(): Promise<void>;
130
71
  //# sourceMappingURL=server.d.ts.map
package/srv/server.js CHANGED
@@ -71,42 +71,30 @@ function crawlerInteger(raw, name, min, max, defaultValue) {
71
71
  let appContext = null;
72
72
  let bootstrapError = null;
73
73
  /**
74
- * Initialize the application context with blockchain components
75
- * Called once during CAP server startup via cds.on('served')
76
- * @param config - CardanoClientConfig
77
- * @param protocolParams - Optional protocol parameters (for tests to skip backend call)
74
+ * Initialize the application context; every start path (standalone hook, plugin) comes through here.
75
+ * @param protocolParams - optional, lets tests skip the backend call
78
76
  */
79
77
  async function initializeAppContext(config, protocolParams, hsmConfig) {
80
78
  logger.debug('Initializing blockchain components...');
81
- // Database first, on every start path: the standalone served hook and the
82
- // plugin's initializeFromConfig both come through here (rc.17 had these in
83
- // initializeFromConfig only, so the standalone image never ran them).
84
- // ORDER BY on Postgres without a NULLS clause for key / NOT NULL columns, so
85
- // the indexes serve `$top` and `$orderby` reads (srv/utils/pg-order-nulls.ts).
79
+ // Database first. Postgres ORDER BY without a NULLS clause on key / NOT NULL columns so
80
+ // the indexes serve `$top` / `$orderby`; then the secondary indexes the model cannot declare.
86
81
  (0, pg_order_nulls_1.installPostgresOrderNulls)();
87
- // The secondary indexes the model cannot declare (srv/utils/db-indexes.ts):
88
- // idempotent, never fatal, before anything reads.
89
82
  try {
90
83
  await (0, db_indexes_1.ensureDbIndexes)();
91
84
  }
92
85
  catch (err) {
93
86
  logger.warn('secondary indexes not ensured (non-fatal):', err);
94
87
  }
95
- // Create CardanoClient from configuration
96
88
  const cardanoClient = new cardano_client_1.CardanoClient(config);
97
- // Publish the active network for leaf utilities (e.g. network-aware validators)
98
- // without forcing them to import this module / the full server graph.
89
+ // Lets leaf utilities (network-aware validators) read the network without importing this module.
99
90
  (0, network_context_1.setActiveNetwork)(config.network);
100
- // Create CardanoTransactionBuilder with the client
101
91
  const cardanoTxBuilder = new cardano_tx_builder_1.CardanoTransactionBuilder(cardanoClient);
102
92
  await cardanoTxBuilder.init(protocolParams);
103
- // PostgreSQL rejects U+0000 in text/JSON. One db-level `before` hook covers every
104
- // write of this plugin — crawler bulk UPSERTs and the lazy indexing paths alike.
93
+ // PostgreSQL rejects U+0000 in text/JSON; one db-level `before` hook covers every write.
105
94
  if ((0, db_sanitize_1.installDbSanitizer)())
106
95
  logger.debug('DB NUL sanitizer installed');
107
- // Create CardanoIndexer with client and transaction builder
108
96
  const cardanoIndexer = new cardano_indexer_1.CardanoIndexer(cardanoClient, cardanoTxBuilder);
109
- // Initialize HSM signer if configured (failure is non-fatal — won't crash the app)
97
+ // HSM signer failure is non-fatal
110
98
  if (hsmConfig?.enabled) {
111
99
  try {
112
100
  const hsmSigner = new hsm_signer_1.HsmSigner(hsmConfig);
@@ -126,21 +114,16 @@ async function initializeAppContext(config, protocolParams, hsmConfig) {
126
114
  cardanoTxBuilder,
127
115
  };
128
116
  }
129
- /** Agent-grant feature switch (AGENT_GRANTS_DESIGN.md); lives in its own module so src/plugin.ts can read it at load. */
117
+ /** Agent-grant feature switch; its own module so src/plugin.ts can read it at load. */
130
118
  var agent_grants_config_2 = require("./utils/agent-grants-config");
131
119
  Object.defineProperty(exports, "loadAgentGrantsConfig", { enumerable: true, get: function () { return agent_grants_config_2.loadAgentGrantsConfig; } });
132
120
  Object.defineProperty(exports, "activateAgentGrants", { enumerable: true, get: function () { return agent_grants_config_2.activateAgentGrants; } });
133
- // Standalone mode (`cds serve` / `cds watch` in this project): CAP loads
134
- // cds-plugin.js only from dependencies, so src/plugin.ts never runs here and
135
- // agent grants would stay off regardless of AGENT_GRANTS_ENABLED. bin/serve.js
136
- // imports this file before cds.server() instantiates the middlewares, so the
137
- // auth impl can still be swapped. Idempotent: a no-op after the plugin's call.
121
+ // Standalone mode never loads src/plugin.ts, so swap the auth impl here as well
122
+ // (bin/serve.js imports this file before the middlewares exist). Idempotent.
138
123
  (0, agent_grants_config_1.activateAgentGrants)();
139
124
  /**
140
- * Get the application context (must be called after bootstrap)
141
- * @throws {ProviderUnavailableError} 503 when uninitialized — request handlers using
142
- * handleRequest/mapError translate this into a clean 503 response instead of a raw 500.
143
- * If bootstrap actively failed, the cause is appended to the message.
125
+ * The application context.
126
+ * @throws {ProviderUnavailableError} 503 when uninitialized; a bootstrap failure is appended as cause.
144
127
  */
145
128
  function getAppContext() {
146
129
  if (!appContext) {
@@ -152,45 +135,25 @@ function getAppContext() {
152
135
  }
153
136
  return appContext;
154
137
  }
155
- /**
156
- * Get the CardanoIndexer instance
157
- * Convenience function for services
158
- */
159
138
  function getCardanoIndexer() {
160
139
  return getAppContext().cardanoIndexer;
161
140
  }
162
- /**
163
- * Get the CardanoClient instance
164
- * Convenience function for services
165
- */
166
141
  function getCardanoClient() {
167
142
  return getAppContext().cardanoClient;
168
143
  }
169
- /**
170
- * Get the CardanoTransactionBuilder instance
171
- * Convenience function for services and plugin consumers
172
- */
173
144
  function getCardanoTxBuilder() {
174
145
  return getAppContext().cardanoTxBuilder;
175
146
  }
176
147
  let hsmConfigInstance;
177
- /**
178
- * Get the HSM configuration (if HSM is enabled).
179
- * Used by sign service to check requiresRole.
180
- */
148
+ /** HSM configuration when enabled; the sign service reads requiresRole from it. */
181
149
  function getHsmConfig() {
182
150
  return hsmConfigInstance;
183
151
  }
184
152
  /**
185
- * Initialize from a pre-built config (used by plugin's src/index.ts)
186
- * @param config - validated CardanoClientConfig
187
- * @param protocolParams - Optional protocol parameters (for tests)
153
+ * Initialize from a pre-built config (plugin path). Idempotent: a second call must not
154
+ * create a duplicate CardanoClient; tests reinitialize via resetAppContext() / createTestContext().
188
155
  */
189
156
  async function initializeFromConfig(config, protocolParams, hsmConfig) {
190
- // Idempotent: a previous call (plugin's cds.on('served'), server.ts's served hook,
191
- // or an earlier programmatic initialize()) already built the context. Direct callers
192
- // such as @odatano/x402's bridge must not produce a duplicate CardanoClient.
193
- // Tests that need to reinitialize should use resetAppContext() / createTestContext().
194
157
  if (appContext) {
195
158
  logger.debug('initializeFromConfig: appContext already initialized, skipping');
196
159
  return;
@@ -201,37 +164,27 @@ async function initializeFromConfig(config, protocolParams, hsmConfig) {
201
164
  bootstrapError = null;
202
165
  }
203
166
  catch (err) {
204
- // Capture the cause so getAppContext() surfaces a structured 503 with diagnostics
205
- // even in PLUGIN mode (src/plugin.ts only logs the error) — previously bootstrapError
206
- // stayed null there and the failure showed up as a causeless "not initialized".
167
+ // Keep the cause so getAppContext() can surface a structured 503 in plugin mode too.
207
168
  bootstrapError = err instanceof Error ? err : new Error(String(err));
208
- throw err; // still propagate so the plugin/programmatic caller sees it
169
+ throw err;
209
170
  }
210
171
  }
211
- /**
212
- * Reset the application context (for testing only)
213
- * Allows tests to inject their own instances
214
- */
172
+ /** Reset the application context (tests only); lets tests inject their own instances. */
215
173
  function resetAppContext(context) {
216
174
  if (process.env.NODE_ENV === 'production') {
217
175
  throw new Error('resetAppContext() is not available in production');
218
176
  }
219
177
  appContext = context;
220
178
  bootstrapError = null;
221
- // Keep the published network in sync with the injected context (or clear it).
222
179
  (0, network_context_1.setActiveNetwork)(context?.cardanoClient.network ?? null);
223
180
  logger.debug('Application context reset');
224
181
  }
225
182
  /**
226
- * Create a test context with specific backends and transaction builder
227
- * Used by integration tests to create isolated test instances
228
- * @param backends Array of backend names to use (e.g., ['koios'], ['blockfrost'])
229
- * @param _txBuilderName Deprecated/ignored — Buildooor is the sole transaction builder (kept for signature compatibility)
230
- * @param protocolParams Optional protocol parameters (to skip backend call during init)
231
- * @returns Promise<AppContext> The created application context
183
+ * Create an isolated test context with the given backends.
184
+ * @param _txBuilderName ignored; Buildooor is the sole builder (kept for signature compatibility)
185
+ * @param protocolParams optional, skips the backend call during init
232
186
  */
233
- async function createTestContext(backends, _txBuilderName = 'buildooor', // kept for signature compat; Buildooor is the only builder
234
- protocolParams) {
187
+ async function createTestContext(backends, _txBuilderName = 'buildooor', protocolParams) {
235
188
  const config = {
236
189
  network: process_1.env.NETWORK || 'preview',
237
190
  backends,
@@ -246,19 +199,15 @@ protocolParams) {
246
199
  };
247
200
  return await initializeAppContext(config, protocolParams);
248
201
  }
249
- /**
250
- * Shutdown the application context (for cleanup in tests)
251
- * Closes all backend connections to allow process to exit cleanly
252
- */
202
+ /** Stop worker and crawler, then close all backend connections. */
253
203
  async function shutdownAppContext() {
254
- // Stop the wallet worker first — its in-flight submit must not hit a torn-down client.
204
+ // Worker and crawler first: their in-flight writes must not hit a torn-down client.
255
205
  try {
256
206
  await (0, wallet_worker_1.stopWalletWorker)();
257
207
  }
258
208
  catch (err) {
259
209
  logger.warn('Wallet worker shutdown failed (continuing):', err);
260
210
  }
261
- // Stop the crawler so its in-flight block writes don't hit a torn-down client.
262
211
  try {
263
212
  await (0, crawler_1.stopCrawler)();
264
213
  }
@@ -267,7 +216,6 @@ async function shutdownAppContext() {
267
216
  }
268
217
  if (appContext) {
269
218
  logger.info('Shutting down application context...');
270
- // Shutdown HSM signer if active
271
219
  const hsm = (0, hsm_signer_1.getHsmSigner)();
272
220
  if (hsm) {
273
221
  hsm.shutdown();
@@ -280,18 +228,11 @@ async function shutdownAppContext() {
280
228
  }
281
229
  }
282
230
  /**
283
- * Load and validate CardanoClientConfig from CDS config or environment variables.
284
- *
285
- * When used as a plugin, consumers configure via package.json:
286
- * { "cds": { "requires": { "odatano-core": { "network": "preview", "backends": ["blockfrost"], ... }}}}
287
- *
288
- * Priority: cds.env.requires["odatano-core"].X > process.env.X > default
289
- *
290
- * @returns validated CardanoClientConfig
291
- * @throws {Error} if any config value is invalid
231
+ * Load and validate CardanoClientConfig.
232
+ * Priority: cds.env.requires["odatano-core"].X > process.env.X > default.
233
+ * @throws {ConfigError} if any value is invalid
292
234
  */
293
235
  function loadConfigFromEnv() {
294
- // Check CDS plugin config first, fall back to env vars
295
236
  const cdsConfig = cds_1.default.env?.requires?.['odatano-core'] ?? {};
296
237
  const network = (cdsConfig.network || process_1.env.NETWORK || 'preview');
297
238
  if (!VALID_NETWORKS.includes(network)) {
@@ -304,12 +245,11 @@ function loadConfigFromEnv() {
304
245
  throw new errors_1.ConfigError(`Invalid BACKENDS: "${invalidBackends.join(', ')}". Must be one of: ${VALID_BACKENDS.join(', ')}`);
305
246
  }
306
247
  const backends = backendStrings;
307
- // Buildooor is the sole transaction builder; any legacy txBuilders/TX_BUILDERS config is ignored.
248
+ // Buildooor is the sole transaction builder; txBuilders/TX_BUILDERS config is ignored.
308
249
  const txBuilders = ['buildooor'];
309
250
  const primaryTimeout = cdsConfig.primaryTimeoutMs ?? process_1.env.PRIMARY_TIMEOUT_MS;
310
251
  const fallbackTimeout = cdsConfig.fallbackTimeoutMs ?? process_1.env.FALLBACK_TIMEOUT_MS;
311
- // `!= null` not truthiness: a CDS-config numeric 0 is falsy, so `timeout && …`
312
- // skipped the <=0 check and 0 then silently became the default via `Number(0)||default`.
252
+ // `!= null`, not truthiness: a CDS-config 0 must reach the <= 0 check.
313
253
  if (primaryTimeout != null && isNaN(Number(primaryTimeout))) {
314
254
  throw new errors_1.ConfigError(`Invalid PRIMARY_TIMEOUT_MS "${primaryTimeout}". Must be a number.`);
315
255
  }
@@ -330,7 +270,6 @@ function loadConfigFromEnv() {
330
270
  }
331
271
  const koiosApiKey = cdsConfig.koiosApiKey || process_1.env.KOIOS_API_KEY || '';
332
272
  const ogmiosUrl = cdsConfig.ogmiosUrl || process_1.env.OGMIOS_URL || '';
333
- // Warn about missing API keys for selected backends
334
273
  if (backends.includes('blockfrost') && !blockfrostApiKey && !blockfrostCustomBackend) {
335
274
  logger.warn('Neither BLOCKFROST_API_KEY nor BLOCKFROST_CUSTOM_BACKEND is set but blockfrost is listed in BACKENDS');
336
275
  }
@@ -354,13 +293,8 @@ function loadConfigFromEnv() {
354
293
  };
355
294
  }
356
295
  /**
357
- * Load HSM configuration from CDS config or environment variables.
358
- * Returns undefined if HSM is not enabled.
359
- *
360
- * Plugin mode: cds.requires.odatano-core.hsm.enabled = true
361
- * Env mode: HSM_ENABLED=true
362
- *
363
- * @returns HsmConfig or undefined
296
+ * Load the HSM configuration (cds.requires.odatano-core.hsm.* or HSM_* env vars).
297
+ * Returns undefined when HSM is not enabled.
364
298
  */
365
299
  function loadHsmConfigFromEnv() {
366
300
  const cdsConfig = cds_1.default.env?.requires?.['odatano-core'] ?? {};
@@ -380,8 +314,7 @@ function loadHsmConfigFromEnv() {
380
314
  if (!Number.isInteger(slot) || slot < 0) {
381
315
  throw new errors_1.ConfigError(`Invalid HSM slot: "${hsmCds.slot ?? process_1.env.HSM_SLOT}" — must be a non-negative integer`);
382
316
  }
383
- // Fail-closed: HSM controls a real signing key. Require an explicit role gate so
384
- // that an authenticated user cannot drain the HSM-controlled wallet by default.
317
+ // Fail closed: the HSM holds a real signing key, so an explicit role gate is mandatory.
385
318
  const requiresRole = hsmCds.requiresRole || process_1.env.HSM_REQUIRES_ROLE || '';
386
319
  if (!requiresRole) {
387
320
  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');
@@ -397,17 +330,13 @@ function loadHsmConfigFromEnv() {
397
330
  };
398
331
  }
399
332
  /**
400
- * Load the chain-crawler configuration from CDS config or environment variables.
401
- * Returns { enabled:false } when the crawler is not switched on (the default), so
402
- * existing deployments are unaffected.
403
- *
404
- * Plugin mode: cds.requires.odatano-core.crawler.{enabled,startSlot,startBlockHash,...}
405
- * Env mode: CRAWLER_ENABLED / CRAWLER_START_SLOT / CRAWLER_START_HASH / ...
333
+ * Load the chain-crawler configuration (cds.requires.odatano-core.crawler.* or CRAWLER_* env vars).
334
+ * Returns { enabled: false } when the crawler is off (the default).
406
335
  */
407
336
  function loadCrawlerConfigFromEnv() {
408
337
  const cdsConfig = cds_1.default.env?.requires?.['odatano-core'] ?? {};
409
338
  const c = cdsConfig.crawler ?? {};
410
- // A CDS value, including explicit `false`, wins over the environment.
339
+ // A CDS value, including an explicit `false`, wins over the environment.
411
340
  const enabledRaw = c.enabled !== undefined ? c.enabled : process_1.env.CRAWLER_ENABLED;
412
341
  let enabled = false;
413
342
  if (enabledRaw === true || enabledRaw === 'true') {
@@ -434,9 +363,8 @@ function loadCrawlerConfigFromEnv() {
434
363
  if (!['ogmios', 'pagination', 'auto'].includes(source)) {
435
364
  throw new errors_1.ConfigError(`Invalid CRAWLER_SOURCE "${source}". Must be one of: ogmios, pagination, auto.`);
436
365
  }
437
- // Analytics coverage. Mint/burn and the bare catalogue are on by default: both are
438
- // by-products of a block the crawler already holds and add no provider traffic. The two
439
- // that do cost network — background enrichment and the epoch snapshots — are opt-in.
366
+ // Analytics coverage: mint/burn and the bare catalogue are free by-products of a crawled
367
+ // block and on by default; enrichment and epoch snapshots cost provider calls and are opt-in.
440
368
  const assetHistory = crawlerBoolean(c.assetHistory ?? process_1.env.CRAWLER_ASSET_HISTORY, 'CRAWLER_ASSET_HISTORY', true);
441
369
  const assetCatalogue = (c.assetCatalogue ?? process_1.env.CRAWLER_ASSET_CATALOGUE ?? 'bare');
442
370
  if (!VALID_ASSET_CATALOGUE_MODES.includes(assetCatalogue)) {
@@ -444,21 +372,16 @@ function loadCrawlerConfigFromEnv() {
444
372
  }
445
373
  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);
446
374
  const epochSnapshots = crawlerBoolean(c.epochSnapshots ?? process_1.env.CRAWLER_EPOCH_SNAPSHOTS, 'CRAWLER_EPOCH_SNAPSHOTS', false);
447
- // Certificates + withdrawals: block content on Ogmios chain-sync and Koios, no extra request;
448
- // opt-in like the other coverage knobs so an existing deployment's write volume does not change.
375
+ // Certificates + withdrawals are block content (no extra request) but opt-in to keep write volume stable.
449
376
  const certificates = crawlerBoolean(c.certificates ?? process_1.env.CRAWLER_CERTIFICATES, 'CRAWLER_CERTIFICATES', false);
450
- // UTxO set: opt-in, and inert until a snapshot has been imported (importUtxoSet).
377
+ // UTxO set: opt-in, inert until a snapshot has been imported (importUtxoSet).
451
378
  const utxoSet = crawlerBoolean(c.utxoSet ?? process_1.env.CRAWLER_UTXO_SET, 'CRAWLER_UTXO_SET', false);
452
379
  return {
453
380
  enabled, startSlot, startBlockHash, startHeight, source, batchSize, confirmationDepth, pollIntervalMs,
454
381
  assetHistory, assetCatalogue, assetEnrichRate, epochSnapshots, certificates, utxoSet,
455
382
  };
456
383
  }
457
- /**
458
- * Start the chain crawler if it is enabled and the app context is ready. Never throws
459
- * (crawler failure must not affect request serving) — errors are logged. Idempotent:
460
- * startCrawler() is a no-op when one is already running.
461
- */
384
+ /** Start the crawler if enabled and the app context is ready. Never throws; idempotent. */
462
385
  async function startCrawlerIfConfigured() {
463
386
  if (process_1.env.SKIP_AUTO_INIT === 'true' || !appContext)
464
387
  return;
@@ -493,11 +416,8 @@ const WALLET_WORKER_LIMITS = {
493
416
  maxAttempts: { min: 1, max: 10 },
494
417
  };
495
418
  /**
496
- * Load the wallet-worker configuration from CDS config or environment variables.
497
- * Returns { enabled:false } when the worker is not switched on (the default).
498
- *
499
- * Plugin mode: cds.requires.odatano-core.walletWorker.{enabled,wallets,...}
500
- * Env mode: WALLET_WORKER_ENABLED / WALLET_WORKER_WALLETS (JSON) / ...
419
+ * Load the wallet-worker configuration (cds.requires.odatano-core.walletWorker.* or WALLET_WORKER_* env vars).
420
+ * Returns { enabled: false } when the worker is off (the default).
501
421
  */
502
422
  function loadWalletWorkerConfigFromEnv() {
503
423
  const cdsConfig = cds_1.default.env?.requires?.['odatano-core'] ?? {};
@@ -566,11 +486,7 @@ function loadWalletWorkerConfigFromEnv() {
566
486
  resubmitOnRollback,
567
487
  };
568
488
  }
569
- /**
570
- * Start the wallet worker if it is enabled and the app context is ready. Never
571
- * throws (worker failure must not affect request serving) — errors are logged.
572
- * Idempotent: startWalletWorker() is a no-op when one is already running.
573
- */
489
+ /** Start the wallet worker if enabled and the app context is ready. Never throws; idempotent. */
574
490
  async function startWalletWorkerIfConfigured() {
575
491
  if (process_1.env.SKIP_AUTO_INIT === 'true' || !appContext)
576
492
  return;
@@ -598,11 +514,9 @@ async function startWalletWorkerIfConfigured() {
598
514
  }
599
515
  }
600
516
  /**
601
- * Re-drive deferred submissions that were claimed (status 'submitting' with
602
- * persisted signedTxCbor) but whose detached submit never ran because the
603
- * process died first (KNOWN_ISSUES #11, Layer 2). Idempotent — an already
604
- * submitted tx finalizes via the TransactionAlreadySubmittedError path.
605
- * Non-fatal, mirrors startCrawlerIfConfigured/startWalletWorkerIfConfigured.
517
+ * Re-drive deferred submissions claimed as 'submitting' whose detached submit never ran
518
+ * (process died first). Idempotent: an already submitted tx finalizes via
519
+ * TransactionAlreadySubmittedError. Never throws.
606
520
  */
607
521
  async function redriveInterruptedSubmissionsIfConfigured() {
608
522
  if (process_1.env.SKIP_AUTO_INIT === 'true' || !appContext)
@@ -617,20 +531,16 @@ async function redriveInterruptedSubmissionsIfConfigured() {
617
531
  logger.error('Failed to re-drive interrupted submissions (non-fatal):', err);
618
532
  }
619
533
  }
620
- // Bootstrap hook - runs when CAP server has loaded all services
534
+ // Standalone bootstrap; skipped when the plugin already initialized the context.
621
535
  cds_1.default.on('served', async () => {
622
- // Skip if already initialized by plugin (src/plugin.ts runs first)
623
536
  if (appContext)
624
537
  return;
625
- // Skip auto-initialization when SKIP_AUTO_INIT is set (e.g., for tests with mocked backends)
538
+ // SKIP_AUTO_INIT: tests with mocked backends
626
539
  if (process_1.env.SKIP_AUTO_INIT === 'true') {
627
540
  logger.info('Skipping auto-initialization (SKIP_AUTO_INIT=true)');
628
541
  return;
629
542
  }
630
- // NOTE: config loading is INSIDE the try — loadConfigFromEnv/loadHsmConfigFromEnv
631
- // throw ConfigError synchronously (missing HSM_PIN, bad slot, no requiresRole…).
632
- // Outside the try that would crash the host app's bootstrap in plugin mode,
633
- // violating the plugin contract ("never throw on failure").
543
+ // Config loading stays inside the try: a ConfigError must never crash the host app.
634
544
  let config;
635
545
  try {
636
546
  config = loadConfigFromEnv();
@@ -641,25 +551,19 @@ cds_1.default.on('served', async () => {
641
551
  logger.info('CAP server bootstrap complete');
642
552
  }
643
553
  catch (err) {
644
- // Don't throw - initialization failure shouldn't crash the host app (plugin contract).
645
- // Capture the cause so getAppContext() can surface a structured 503 with diagnostics
646
- // instead of the raw "Application not initialized" Error landing as a generic 500.
554
+ // Never throw; keep the cause so getAppContext() surfaces a structured 503.
647
555
  bootstrapError = err instanceof Error ? err : new Error(String(err));
648
- // Write to stderr directly so the cause stays visible even when test runners
649
- // suppress console.error (vitest.setup.ts in this repo silences it).
556
+ // stderr directly: the cause stays visible when a test runner silences console.error.
650
557
  const where = config ? `backends={${config.backends.join(',')}} network=${config.network}` : 'config load';
651
558
  const msg = err instanceof Error ? `${err.name}: ${err.message}\n${err.stack ?? ''}` : String(err);
652
559
  process.stderr.write(`[ODATANO] Failed to initialize blockchain components — ${where}\n${msg}\n`);
653
560
  logger.error('Failed to initialize blockchain components:', err);
654
561
  }
655
- // Start the pre-sync crawler if configured (standalone mode). Non-fatal.
562
+ // Optional subsystems; each is non-fatal.
656
563
  await startCrawlerIfConfigured();
657
- // Start the wallet worker if configured (standalone mode). Non-fatal.
658
564
  await startWalletWorkerIfConfigured();
659
- // Re-drive deferred submissions interrupted by a restart (standalone mode). Non-fatal.
660
565
  await redriveInterruptedSubmissionsIfConfigured();
661
566
  });
662
- // Shutdown hook - runs when CAP server is shutting down (e.g., cds.shutdown() in tests)
663
567
  cds_1.default.on('shutdown', async () => {
664
568
  await shutdownAppContext();
665
569
  });