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

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 (138) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +251 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +139 -2
  4. package/@cds-models/CardanoIndexerService/index.js +18 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +231 -6
  6. package/@cds-models/CardanoODataService/index.js +27 -0
  7. package/@cds-models/CardanoSignService/index.d.ts +5 -2
  8. package/@cds-models/CardanoTransactionService/index.d.ts +9 -9
  9. package/@cds-models/odatano/cardano/index.d.ts +323 -6
  10. package/@cds-models/odatano/cardano/index.js +33 -0
  11. package/README.md +195 -136
  12. package/db/schema.cds +2133 -1633
  13. package/package.json +181 -173
  14. package/scripts/migrate-slot-leader.mjs +104 -0
  15. package/scripts/migrate-txseq.mjs +147 -0
  16. package/src/index.d.ts +10 -10
  17. package/src/index.js +24 -14
  18. package/src/plugin.js +39 -52
  19. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  20. package/srv/blockchain/backends/blockfrost-backend.js +45 -158
  21. package/srv/blockchain/backends/cardano-backend.d.ts +83 -158
  22. package/srv/blockchain/backends/cardano-backend.js +14 -5
  23. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  24. package/srv/blockchain/backends/koios-backend.js +293 -203
  25. package/srv/blockchain/backends/ogmios-backend.d.ts +69 -94
  26. package/srv/blockchain/backends/ogmios-backend.js +319 -185
  27. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  28. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  29. package/srv/blockchain/cardano-client.d.ts +57 -204
  30. package/srv/blockchain/cardano-client.js +94 -226
  31. package/srv/blockchain/cardano-indexer.d.ts +176 -240
  32. package/srv/blockchain/cardano-indexer.js +615 -338
  33. package/srv/blockchain/cardano-tx-builder.d.ts +29 -82
  34. package/srv/blockchain/cardano-tx-builder.js +88 -128
  35. package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
  36. package/srv/blockchain/crawler/certificate-backfill.js +150 -0
  37. package/srv/blockchain/crawler/crawler.d.ts +121 -53
  38. package/srv/blockchain/crawler/crawler.js +403 -89
  39. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  40. package/srv/blockchain/crawler/index.d.ts +5 -0
  41. package/srv/blockchain/crawler/index.js +35 -7
  42. package/srv/blockchain/crawler/sync-state.d.ts +44 -28
  43. package/srv/blockchain/crawler/sync-state.js +115 -43
  44. package/srv/blockchain/crawler/utxo-set-import.d.ts +69 -0
  45. package/srv/blockchain/crawler/utxo-set-import.js +269 -0
  46. package/srv/blockchain/ledger-state.d.ts +80 -0
  47. package/srv/blockchain/ledger-state.js +383 -0
  48. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  49. package/srv/blockchain/signing/cose-verifier.js +6 -12
  50. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  51. package/srv/blockchain/signing/external-signer.js +19 -122
  52. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  53. package/srv/blockchain/signing/hsm-signer.js +23 -63
  54. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  55. package/srv/blockchain/signing/signature-verifier.js +13 -54
  56. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  57. package/srv/blockchain/signing/submission-finalizer.js +16 -48
  58. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +71 -160
  59. package/srv/blockchain/transaction-building/buildooor-tx.js +185 -260
  60. package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
  61. package/srv/blockchain/transaction-rows.d.ts +12 -0
  62. package/srv/blockchain/transaction-rows.js +42 -0
  63. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  64. package/srv/blockchain/wallet-worker/build-request.js +39 -23
  65. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  66. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  67. package/srv/blockchain/wallet-worker/index.js +2 -8
  68. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  69. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  70. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  71. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  72. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  73. package/srv/blockchain/wallet-worker/signers.js +3 -8
  74. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  75. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  76. package/srv/cardano-agent-service.cds +146 -0
  77. package/srv/cardano-agent-service.d.ts +2 -0
  78. package/srv/cardano-agent-service.js +12 -0
  79. package/srv/cardano-indexer-service.cds +164 -73
  80. package/srv/cardano-indexer-service.js +156 -11
  81. package/srv/cardano-service.cds +45 -0
  82. package/srv/cardano-service.js +38 -96
  83. package/srv/cardano-sign-service.cds +200 -180
  84. package/srv/cardano-sign-service.js +55 -173
  85. package/srv/cardano-tx-service.cds +32 -26
  86. package/srv/cardano-tx-service.js +136 -196
  87. package/srv/cardano-worker-service.js +7 -15
  88. package/srv/server.d.ts +28 -86
  89. package/srv/server.js +95 -128
  90. package/srv/utils/agent-grants-config.d.ts +37 -0
  91. package/srv/utils/agent-grants-config.js +138 -0
  92. package/srv/utils/agent-grants.d.ts +262 -0
  93. package/srv/utils/agent-grants.js +914 -0
  94. package/srv/utils/agent-token-auth.d.ts +16 -0
  95. package/srv/utils/agent-token-auth.js +78 -0
  96. package/srv/utils/backend-request-handler.d.ts +2 -16
  97. package/srv/utils/backend-request-handler.js +3 -18
  98. package/srv/utils/collections.d.ts +4 -8
  99. package/srv/utils/collections.js +4 -8
  100. package/srv/utils/const.d.ts +19 -68
  101. package/srv/utils/const.js +20 -69
  102. package/srv/utils/crypto.d.ts +3 -12
  103. package/srv/utils/crypto.js +5 -18
  104. package/srv/utils/db-indexes.d.ts +25 -0
  105. package/srv/utils/db-indexes.js +93 -0
  106. package/srv/utils/db-sanitize.d.ts +27 -0
  107. package/srv/utils/db-sanitize.js +85 -0
  108. package/srv/utils/epoch-slots.d.ts +13 -0
  109. package/srv/utils/epoch-slots.js +25 -0
  110. package/srv/utils/error-codes.d.ts +18 -73
  111. package/srv/utils/error-codes.js +17 -70
  112. package/srv/utils/errors.d.ts +36 -179
  113. package/srv/utils/errors.js +62 -220
  114. package/srv/utils/liveness.d.ts +16 -0
  115. package/srv/utils/liveness.js +41 -0
  116. package/srv/utils/mappers.d.ts +89 -214
  117. package/srv/utils/mappers.js +289 -301
  118. package/srv/utils/network-context.js +2 -11
  119. package/srv/utils/pg-order-nulls.d.ts +14 -0
  120. package/srv/utils/pg-order-nulls.js +57 -0
  121. package/srv/utils/plutus-placeholders.d.ts +6 -18
  122. package/srv/utils/plutus-placeholders.js +6 -20
  123. package/srv/utils/rate-limiter.d.ts +46 -0
  124. package/srv/utils/rate-limiter.js +116 -0
  125. package/srv/utils/service-events.d.ts +2 -22
  126. package/srv/utils/service-events.js +3 -23
  127. package/srv/utils/signing-helper.d.ts +3 -18
  128. package/srv/utils/signing-helper.js +10 -32
  129. package/srv/utils/tx-build-helper.d.ts +18 -92
  130. package/srv/utils/tx-build-helper.js +32 -123
  131. package/srv/utils/tx-request-parsers.d.ts +14 -20
  132. package/srv/utils/tx-request-parsers.js +33 -20
  133. package/srv/utils/tx-utils.d.ts +4 -23
  134. package/srv/utils/tx-utils.js +12 -41
  135. package/srv/utils/types.d.ts +114 -169
  136. package/srv/utils/types.js +2 -6
  137. package/srv/utils/validators.d.ts +19 -89
  138. 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,126 +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
  }
13
+ /** Agent-grant feature switch; its own module so src/plugin.ts can read it at load. */
14
+ export { loadAgentGrantsConfig, activateAgentGrants } from './utils/agent-grants-config';
16
15
  /**
17
- * Get the application context (must be called after bootstrap)
18
- * @throws {ProviderUnavailableError} 503 when uninitialized — request handlers using
19
- * handleRequest/mapError translate this into a clean 503 response instead of a raw 500.
20
- * 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.
21
18
  */
22
19
  export declare function getAppContext(): AppContext;
23
- /**
24
- * Get the CardanoIndexer instance
25
- * Convenience function for services
26
- */
27
20
  export declare function getCardanoIndexer(): CardanoIndexer;
28
- /**
29
- * Get the CardanoClient instance
30
- * Convenience function for services
31
- */
32
21
  export declare function getCardanoClient(): CardanoClient;
33
- /**
34
- * Get the CardanoTransactionBuilder instance
35
- * Convenience function for services and plugin consumers
36
- */
37
22
  export declare function getCardanoTxBuilder(): CardanoTransactionBuilder;
38
- /**
39
- * Get the HSM configuration (if HSM is enabled).
40
- * Used by sign service to check requiresRole.
41
- */
23
+ /** HSM configuration when enabled; the sign service reads requiresRole from it. */
42
24
  export declare function getHsmConfig(): HsmConfig | undefined;
43
25
  /**
44
- * Initialize from a pre-built config (used by plugin's src/index.ts)
45
- * @param config - validated CardanoClientConfig
46
- * @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().
47
28
  */
48
29
  export declare function initializeFromConfig(config: CardanoClientConfig, protocolParams?: LedgerProtocolParameters, hsmConfig?: HsmConfig): Promise<void>;
49
- /**
50
- * Reset the application context (for testing only)
51
- * Allows tests to inject their own instances
52
- */
30
+ /** Reset the application context (tests only); lets tests inject their own instances. */
53
31
  export declare function resetAppContext(context: AppContext | null): void;
54
32
  /**
55
- * Create a test context with specific backends and transaction builder
56
- * Used by integration tests to create isolated test instances
57
- * @param backends Array of backend names to use (e.g., ['koios'], ['blockfrost'])
58
- * @param _txBuilderName Deprecated/ignored — Buildooor is the sole transaction builder (kept for signature compatibility)
59
- * @param protocolParams Optional protocol parameters (to skip backend call during init)
60
- * @returns Promise<AppContext> The created application context
61
- */
62
- export declare function createTestContext(backends: BackendName[], _txBuilderName?: TransactionBuilderName, // kept for signature compat; Buildooor is the only builder
63
- protocolParams?: LedgerProtocolParameters): Promise<AppContext>;
64
- /**
65
- * Shutdown the application context (for cleanup in tests)
66
- * 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
67
36
  */
37
+ export declare function createTestContext(backends: BackendName[], _txBuilderName?: TransactionBuilderName, protocolParams?: LedgerProtocolParameters): Promise<AppContext>;
38
+ /** Stop worker and crawler, then close all backend connections. */
68
39
  export declare function shutdownAppContext(): Promise<void>;
69
40
  /**
70
- * Load and validate CardanoClientConfig from CDS config or environment variables.
71
- *
72
- * When used as a plugin, consumers configure via package.json:
73
- * { "cds": { "requires": { "odatano-core": { "network": "preview", "backends": ["blockfrost"], ... }}}}
74
- *
75
- * Priority: cds.env.requires["odatano-core"].X > process.env.X > default
76
- *
77
- * @returns validated CardanoClientConfig
78
- * @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
79
44
  */
80
45
  export declare function loadConfigFromEnv(): CardanoClientConfig;
81
46
  /**
82
- * Load HSM configuration from CDS config or environment variables.
83
- * Returns undefined if HSM is not enabled.
84
- *
85
- * Plugin mode: cds.requires.odatano-core.hsm.enabled = true
86
- * Env mode: HSM_ENABLED=true
87
- *
88
- * @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.
89
49
  */
90
50
  export declare function loadHsmConfigFromEnv(): HsmConfig | undefined;
91
51
  /**
92
- * Load the chain-crawler configuration from CDS config or environment variables.
93
- * Returns { enabled:false } when the crawler is not switched on (the default), so
94
- * existing deployments are unaffected.
95
- *
96
- * Plugin mode: cds.requires.odatano-core.crawler.{enabled,startSlot,startBlockHash,...}
97
- * 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).
98
54
  */
99
55
  export declare function loadCrawlerConfigFromEnv(): CrawlerConfig;
100
- /**
101
- * Start the chain crawler if it is enabled and the app context is ready. Never throws
102
- * (crawler failure must not affect request serving) — errors are logged. Idempotent:
103
- * startCrawler() is a no-op when one is already running.
104
- */
56
+ /** Start the crawler if enabled and the app context is ready. Never throws; idempotent. */
105
57
  export declare function startCrawlerIfConfigured(): Promise<void>;
106
58
  /**
107
- * Load the wallet-worker configuration from CDS config or environment variables.
108
- * Returns { enabled:false } when the worker is not switched on (the default).
109
- *
110
- * Plugin mode: cds.requires.odatano-core.walletWorker.{enabled,wallets,...}
111
- * 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).
112
61
  */
113
62
  export declare function loadWalletWorkerConfigFromEnv(): WalletWorkerConfig;
114
- /**
115
- * Start the wallet worker if it is enabled and the app context is ready. Never
116
- * throws (worker failure must not affect request serving) — errors are logged.
117
- * Idempotent: startWalletWorker() is a no-op when one is already running.
118
- */
63
+ /** Start the wallet worker if enabled and the app context is ready. Never throws; idempotent. */
119
64
  export declare function startWalletWorkerIfConfigured(): Promise<void>;
120
65
  /**
121
- * Re-drive deferred submissions that were claimed (status 'submitting' with
122
- * persisted signedTxCbor) but whose detached submit never ran because the
123
- * process died first (KNOWN_ISSUES #11, Layer 2). Idempotent — an already
124
- * submitted tx finalizes via the TransactionAlreadySubmittedError path.
125
- * 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.
126
69
  */
127
70
  export declare function redriveInterruptedSubmissionsIfConfigured(): Promise<void>;
128
- export {};
129
71
  //# sourceMappingURL=server.d.ts.map
package/srv/server.js CHANGED
@@ -3,6 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.activateAgentGrants = exports.loadAgentGrantsConfig = void 0;
6
7
  exports.getAppContext = getAppContext;
7
8
  exports.getCardanoIndexer = getCardanoIndexer;
8
9
  exports.getCardanoClient = getCardanoClient;
@@ -26,8 +27,12 @@ const cardano_tx_builder_1 = require("./blockchain/cardano-tx-builder");
26
27
  const hsm_signer_1 = require("./blockchain/signing/hsm-signer");
27
28
  const errors_1 = require("./utils/errors");
28
29
  const network_context_1 = require("./utils/network-context");
30
+ const db_sanitize_1 = require("./utils/db-sanitize");
31
+ const db_indexes_1 = require("./utils/db-indexes");
32
+ const pg_order_nulls_1 = require("./utils/pg-order-nulls");
29
33
  const crawler_1 = require("./blockchain/crawler");
30
34
  const wallet_worker_1 = require("./blockchain/wallet-worker");
35
+ const agent_grants_config_1 = require("./utils/agent-grants-config");
31
36
  const process_1 = require("process");
32
37
  const logger = cds_1.default.log('ODATANO');
33
38
  const VALID_NETWORKS = ['mainnet', 'preview', 'preprod'];
@@ -36,7 +41,19 @@ const CRAWLER_LIMITS = {
36
41
  batchSize: { min: 1, max: 100 },
37
42
  confirmationDepth: { min: 0, max: 2160 },
38
43
  pollIntervalMs: { min: 1000, max: 3_600_000 },
44
+ assetEnrichRate: { min: 1, max: 20 },
39
45
  };
46
+ const VALID_ASSET_CATALOGUE_MODES = ['off', 'bare', 'enrich'];
47
+ /** Parse a boolean crawler flag that defaults to `fallback` when unset. */
48
+ function crawlerBoolean(raw, name, fallback) {
49
+ if (raw === undefined || raw === null)
50
+ return fallback;
51
+ if (raw === true || raw === 'true')
52
+ return true;
53
+ if (raw === false || raw === 'false')
54
+ return false;
55
+ throw new errors_1.ConfigError(`Invalid ${name} "${String(raw)}". Must be true or false.`);
56
+ }
40
57
  /** Parse an integer without allowing JavaScript's lossy/implicit coercions. */
41
58
  function crawlerInteger(raw, name, min, max, defaultValue) {
42
59
  if (raw == null)
@@ -54,24 +71,30 @@ function crawlerInteger(raw, name, min, max, defaultValue) {
54
71
  let appContext = null;
55
72
  let bootstrapError = null;
56
73
  /**
57
- * Initialize the application context with blockchain components
58
- * Called once during CAP server startup via cds.on('served')
59
- * @param config - CardanoClientConfig
60
- * @param protocolParams - Optional protocol parameters (for tests to skip backend call)
74
+ * Initialize the application context; every start path (standalone hook, plugin) comes through here.
75
+ * @param protocolParams - optional, lets tests skip the backend call
61
76
  */
62
77
  async function initializeAppContext(config, protocolParams, hsmConfig) {
63
78
  logger.debug('Initializing blockchain components...');
64
- // Create CardanoClient from configuration
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.
81
+ (0, pg_order_nulls_1.installPostgresOrderNulls)();
82
+ try {
83
+ await (0, db_indexes_1.ensureDbIndexes)();
84
+ }
85
+ catch (err) {
86
+ logger.warn('secondary indexes not ensured (non-fatal):', err);
87
+ }
65
88
  const cardanoClient = new cardano_client_1.CardanoClient(config);
66
- // Publish the active network for leaf utilities (e.g. network-aware validators)
67
- // without forcing them to import this module / the full server graph.
89
+ // Lets leaf utilities (network-aware validators) read the network without importing this module.
68
90
  (0, network_context_1.setActiveNetwork)(config.network);
69
- // Create CardanoTransactionBuilder with the client
70
91
  const cardanoTxBuilder = new cardano_tx_builder_1.CardanoTransactionBuilder(cardanoClient);
71
92
  await cardanoTxBuilder.init(protocolParams);
72
- // Create CardanoIndexer with client and transaction builder
93
+ // PostgreSQL rejects U+0000 in text/JSON; one db-level `before` hook covers every write.
94
+ if ((0, db_sanitize_1.installDbSanitizer)())
95
+ logger.debug('DB NUL sanitizer installed');
73
96
  const cardanoIndexer = new cardano_indexer_1.CardanoIndexer(cardanoClient, cardanoTxBuilder);
74
- // Initialize HSM signer if configured (failure is non-fatal — won't crash the app)
97
+ // HSM signer failure is non-fatal
75
98
  if (hsmConfig?.enabled) {
76
99
  try {
77
100
  const hsmSigner = new hsm_signer_1.HsmSigner(hsmConfig);
@@ -91,11 +114,16 @@ async function initializeAppContext(config, protocolParams, hsmConfig) {
91
114
  cardanoTxBuilder,
92
115
  };
93
116
  }
117
+ /** Agent-grant feature switch; its own module so src/plugin.ts can read it at load. */
118
+ var agent_grants_config_2 = require("./utils/agent-grants-config");
119
+ Object.defineProperty(exports, "loadAgentGrantsConfig", { enumerable: true, get: function () { return agent_grants_config_2.loadAgentGrantsConfig; } });
120
+ Object.defineProperty(exports, "activateAgentGrants", { enumerable: true, get: function () { return agent_grants_config_2.activateAgentGrants; } });
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.
123
+ (0, agent_grants_config_1.activateAgentGrants)();
94
124
  /**
95
- * Get the application context (must be called after bootstrap)
96
- * @throws {ProviderUnavailableError} 503 when uninitialized — request handlers using
97
- * handleRequest/mapError translate this into a clean 503 response instead of a raw 500.
98
- * If bootstrap actively failed, the cause is appended to the message.
125
+ * The application context.
126
+ * @throws {ProviderUnavailableError} 503 when uninitialized; a bootstrap failure is appended as cause.
99
127
  */
100
128
  function getAppContext() {
101
129
  if (!appContext) {
@@ -107,45 +135,25 @@ function getAppContext() {
107
135
  }
108
136
  return appContext;
109
137
  }
110
- /**
111
- * Get the CardanoIndexer instance
112
- * Convenience function for services
113
- */
114
138
  function getCardanoIndexer() {
115
139
  return getAppContext().cardanoIndexer;
116
140
  }
117
- /**
118
- * Get the CardanoClient instance
119
- * Convenience function for services
120
- */
121
141
  function getCardanoClient() {
122
142
  return getAppContext().cardanoClient;
123
143
  }
124
- /**
125
- * Get the CardanoTransactionBuilder instance
126
- * Convenience function for services and plugin consumers
127
- */
128
144
  function getCardanoTxBuilder() {
129
145
  return getAppContext().cardanoTxBuilder;
130
146
  }
131
147
  let hsmConfigInstance;
132
- /**
133
- * Get the HSM configuration (if HSM is enabled).
134
- * Used by sign service to check requiresRole.
135
- */
148
+ /** HSM configuration when enabled; the sign service reads requiresRole from it. */
136
149
  function getHsmConfig() {
137
150
  return hsmConfigInstance;
138
151
  }
139
152
  /**
140
- * Initialize from a pre-built config (used by plugin's src/index.ts)
141
- * @param config - validated CardanoClientConfig
142
- * @param protocolParams - Optional protocol parameters (for tests)
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().
143
155
  */
144
156
  async function initializeFromConfig(config, protocolParams, hsmConfig) {
145
- // Idempotent: a previous call (plugin's cds.on('served'), server.ts's served hook,
146
- // or an earlier programmatic initialize()) already built the context. Direct callers
147
- // such as @odatano/x402's bridge must not produce a duplicate CardanoClient.
148
- // Tests that need to reinitialize should use resetAppContext() / createTestContext().
149
157
  if (appContext) {
150
158
  logger.debug('initializeFromConfig: appContext already initialized, skipping');
151
159
  return;
@@ -156,37 +164,27 @@ async function initializeFromConfig(config, protocolParams, hsmConfig) {
156
164
  bootstrapError = null;
157
165
  }
158
166
  catch (err) {
159
- // Capture the cause so getAppContext() surfaces a structured 503 with diagnostics
160
- // even in PLUGIN mode (src/plugin.ts only logs the error) — previously bootstrapError
161
- // stayed null there and the failure showed up as a causeless "not initialized".
167
+ // Keep the cause so getAppContext() can surface a structured 503 in plugin mode too.
162
168
  bootstrapError = err instanceof Error ? err : new Error(String(err));
163
- throw err; // still propagate so the plugin/programmatic caller sees it
169
+ throw err;
164
170
  }
165
171
  }
166
- /**
167
- * Reset the application context (for testing only)
168
- * Allows tests to inject their own instances
169
- */
172
+ /** Reset the application context (tests only); lets tests inject their own instances. */
170
173
  function resetAppContext(context) {
171
174
  if (process.env.NODE_ENV === 'production') {
172
175
  throw new Error('resetAppContext() is not available in production');
173
176
  }
174
177
  appContext = context;
175
178
  bootstrapError = null;
176
- // Keep the published network in sync with the injected context (or clear it).
177
179
  (0, network_context_1.setActiveNetwork)(context?.cardanoClient.network ?? null);
178
180
  logger.debug('Application context reset');
179
181
  }
180
182
  /**
181
- * Create a test context with specific backends and transaction builder
182
- * Used by integration tests to create isolated test instances
183
- * @param backends Array of backend names to use (e.g., ['koios'], ['blockfrost'])
184
- * @param _txBuilderName Deprecated/ignored — Buildooor is the sole transaction builder (kept for signature compatibility)
185
- * @param protocolParams Optional protocol parameters (to skip backend call during init)
186
- * @returns Promise<AppContext> The created application context
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
187
186
  */
188
- async function createTestContext(backends, _txBuilderName = 'buildooor', // kept for signature compat; Buildooor is the only builder
189
- protocolParams) {
187
+ async function createTestContext(backends, _txBuilderName = 'buildooor', protocolParams) {
190
188
  const config = {
191
189
  network: process_1.env.NETWORK || 'preview',
192
190
  backends,
@@ -201,19 +199,15 @@ protocolParams) {
201
199
  };
202
200
  return await initializeAppContext(config, protocolParams);
203
201
  }
204
- /**
205
- * Shutdown the application context (for cleanup in tests)
206
- * Closes all backend connections to allow process to exit cleanly
207
- */
202
+ /** Stop worker and crawler, then close all backend connections. */
208
203
  async function shutdownAppContext() {
209
- // 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.
210
205
  try {
211
206
  await (0, wallet_worker_1.stopWalletWorker)();
212
207
  }
213
208
  catch (err) {
214
209
  logger.warn('Wallet worker shutdown failed (continuing):', err);
215
210
  }
216
- // Stop the crawler so its in-flight block writes don't hit a torn-down client.
217
211
  try {
218
212
  await (0, crawler_1.stopCrawler)();
219
213
  }
@@ -222,7 +216,6 @@ async function shutdownAppContext() {
222
216
  }
223
217
  if (appContext) {
224
218
  logger.info('Shutting down application context...');
225
- // Shutdown HSM signer if active
226
219
  const hsm = (0, hsm_signer_1.getHsmSigner)();
227
220
  if (hsm) {
228
221
  hsm.shutdown();
@@ -235,18 +228,11 @@ async function shutdownAppContext() {
235
228
  }
236
229
  }
237
230
  /**
238
- * Load and validate CardanoClientConfig from CDS config or environment variables.
239
- *
240
- * When used as a plugin, consumers configure via package.json:
241
- * { "cds": { "requires": { "odatano-core": { "network": "preview", "backends": ["blockfrost"], ... }}}}
242
- *
243
- * Priority: cds.env.requires["odatano-core"].X > process.env.X > default
244
- *
245
- * @returns validated CardanoClientConfig
246
- * @throws {Error} if any config value is invalid
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
247
234
  */
248
235
  function loadConfigFromEnv() {
249
- // Check CDS plugin config first, fall back to env vars
250
236
  const cdsConfig = cds_1.default.env?.requires?.['odatano-core'] ?? {};
251
237
  const network = (cdsConfig.network || process_1.env.NETWORK || 'preview');
252
238
  if (!VALID_NETWORKS.includes(network)) {
@@ -259,12 +245,11 @@ function loadConfigFromEnv() {
259
245
  throw new errors_1.ConfigError(`Invalid BACKENDS: "${invalidBackends.join(', ')}". Must be one of: ${VALID_BACKENDS.join(', ')}`);
260
246
  }
261
247
  const backends = backendStrings;
262
- // 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.
263
249
  const txBuilders = ['buildooor'];
264
250
  const primaryTimeout = cdsConfig.primaryTimeoutMs ?? process_1.env.PRIMARY_TIMEOUT_MS;
265
251
  const fallbackTimeout = cdsConfig.fallbackTimeoutMs ?? process_1.env.FALLBACK_TIMEOUT_MS;
266
- // `!= null` not truthiness: a CDS-config numeric 0 is falsy, so `timeout && …`
267
- // skipped the <=0 check and 0 then silently became the default via `Number(0)||default`.
252
+ // `!= null`, not truthiness: a CDS-config 0 must reach the <= 0 check.
268
253
  if (primaryTimeout != null && isNaN(Number(primaryTimeout))) {
269
254
  throw new errors_1.ConfigError(`Invalid PRIMARY_TIMEOUT_MS "${primaryTimeout}". Must be a number.`);
270
255
  }
@@ -285,7 +270,6 @@ function loadConfigFromEnv() {
285
270
  }
286
271
  const koiosApiKey = cdsConfig.koiosApiKey || process_1.env.KOIOS_API_KEY || '';
287
272
  const ogmiosUrl = cdsConfig.ogmiosUrl || process_1.env.OGMIOS_URL || '';
288
- // Warn about missing API keys for selected backends
289
273
  if (backends.includes('blockfrost') && !blockfrostApiKey && !blockfrostCustomBackend) {
290
274
  logger.warn('Neither BLOCKFROST_API_KEY nor BLOCKFROST_CUSTOM_BACKEND is set but blockfrost is listed in BACKENDS');
291
275
  }
@@ -309,13 +293,8 @@ function loadConfigFromEnv() {
309
293
  };
310
294
  }
311
295
  /**
312
- * Load HSM configuration from CDS config or environment variables.
313
- * Returns undefined if HSM is not enabled.
314
- *
315
- * Plugin mode: cds.requires.odatano-core.hsm.enabled = true
316
- * Env mode: HSM_ENABLED=true
317
- *
318
- * @returns HsmConfig or undefined
296
+ * Load the HSM configuration (cds.requires.odatano-core.hsm.* or HSM_* env vars).
297
+ * Returns undefined when HSM is not enabled.
319
298
  */
320
299
  function loadHsmConfigFromEnv() {
321
300
  const cdsConfig = cds_1.default.env?.requires?.['odatano-core'] ?? {};
@@ -335,8 +314,7 @@ function loadHsmConfigFromEnv() {
335
314
  if (!Number.isInteger(slot) || slot < 0) {
336
315
  throw new errors_1.ConfigError(`Invalid HSM slot: "${hsmCds.slot ?? process_1.env.HSM_SLOT}" — must be a non-negative integer`);
337
316
  }
338
- // Fail-closed: HSM controls a real signing key. Require an explicit role gate so
339
- // that an authenticated user cannot drain the HSM-controlled wallet by default.
317
+ // Fail closed: the HSM holds a real signing key, so an explicit role gate is mandatory.
340
318
  const requiresRole = hsmCds.requiresRole || process_1.env.HSM_REQUIRES_ROLE || '';
341
319
  if (!requiresRole) {
342
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');
@@ -352,17 +330,13 @@ function loadHsmConfigFromEnv() {
352
330
  };
353
331
  }
354
332
  /**
355
- * Load the chain-crawler configuration from CDS config or environment variables.
356
- * Returns { enabled:false } when the crawler is not switched on (the default), so
357
- * existing deployments are unaffected.
358
- *
359
- * Plugin mode: cds.requires.odatano-core.crawler.{enabled,startSlot,startBlockHash,...}
360
- * Env mode: CRAWLER_ENABLED / CRAWLER_START_SLOT / CRAWLER_START_HASH / ...
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).
361
335
  */
362
336
  function loadCrawlerConfigFromEnv() {
363
337
  const cdsConfig = cds_1.default.env?.requires?.['odatano-core'] ?? {};
364
338
  const c = cdsConfig.crawler ?? {};
365
- // A CDS value, including explicit `false`, wins over the environment.
339
+ // A CDS value, including an explicit `false`, wins over the environment.
366
340
  const enabledRaw = c.enabled !== undefined ? c.enabled : process_1.env.CRAWLER_ENABLED;
367
341
  let enabled = false;
368
342
  if (enabledRaw === true || enabledRaw === 'true') {
@@ -389,13 +363,25 @@ function loadCrawlerConfigFromEnv() {
389
363
  if (!['ogmios', 'pagination', 'auto'].includes(source)) {
390
364
  throw new errors_1.ConfigError(`Invalid CRAWLER_SOURCE "${source}". Must be one of: ogmios, pagination, auto.`);
391
365
  }
392
- return { enabled, startSlot, startBlockHash, startHeight, source, batchSize, confirmationDepth, pollIntervalMs };
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.
368
+ const assetHistory = crawlerBoolean(c.assetHistory ?? process_1.env.CRAWLER_ASSET_HISTORY, 'CRAWLER_ASSET_HISTORY', true);
369
+ const assetCatalogue = (c.assetCatalogue ?? process_1.env.CRAWLER_ASSET_CATALOGUE ?? 'bare');
370
+ if (!VALID_ASSET_CATALOGUE_MODES.includes(assetCatalogue)) {
371
+ throw new errors_1.ConfigError(`Invalid CRAWLER_ASSET_CATALOGUE "${assetCatalogue}". Must be one of: ${VALID_ASSET_CATALOGUE_MODES.join(', ')}.`);
372
+ }
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);
374
+ const epochSnapshots = crawlerBoolean(c.epochSnapshots ?? process_1.env.CRAWLER_EPOCH_SNAPSHOTS, 'CRAWLER_EPOCH_SNAPSHOTS', false);
375
+ // Certificates + withdrawals are block content (no extra request) but opt-in to keep write volume stable.
376
+ const certificates = crawlerBoolean(c.certificates ?? process_1.env.CRAWLER_CERTIFICATES, 'CRAWLER_CERTIFICATES', false);
377
+ // UTxO set: opt-in, inert until a snapshot has been imported (importUtxoSet).
378
+ const utxoSet = crawlerBoolean(c.utxoSet ?? process_1.env.CRAWLER_UTXO_SET, 'CRAWLER_UTXO_SET', false);
379
+ return {
380
+ enabled, startSlot, startBlockHash, startHeight, source, batchSize, confirmationDepth, pollIntervalMs,
381
+ assetHistory, assetCatalogue, assetEnrichRate, epochSnapshots, certificates, utxoSet,
382
+ };
393
383
  }
394
- /**
395
- * Start the chain crawler if it is enabled and the app context is ready. Never throws
396
- * (crawler failure must not affect request serving) — errors are logged. Idempotent:
397
- * startCrawler() is a no-op when one is already running.
398
- */
384
+ /** Start the crawler if enabled and the app context is ready. Never throws; idempotent. */
399
385
  async function startCrawlerIfConfigured() {
400
386
  if (process_1.env.SKIP_AUTO_INIT === 'true' || !appContext)
401
387
  return;
@@ -430,11 +416,8 @@ const WALLET_WORKER_LIMITS = {
430
416
  maxAttempts: { min: 1, max: 10 },
431
417
  };
432
418
  /**
433
- * Load the wallet-worker configuration from CDS config or environment variables.
434
- * Returns { enabled:false } when the worker is not switched on (the default).
435
- *
436
- * Plugin mode: cds.requires.odatano-core.walletWorker.{enabled,wallets,...}
437
- * Env mode: WALLET_WORKER_ENABLED / WALLET_WORKER_WALLETS (JSON) / ...
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).
438
421
  */
439
422
  function loadWalletWorkerConfigFromEnv() {
440
423
  const cdsConfig = cds_1.default.env?.requires?.['odatano-core'] ?? {};
@@ -503,11 +486,7 @@ function loadWalletWorkerConfigFromEnv() {
503
486
  resubmitOnRollback,
504
487
  };
505
488
  }
506
- /**
507
- * Start the wallet worker if it is enabled and the app context is ready. Never
508
- * throws (worker failure must not affect request serving) — errors are logged.
509
- * Idempotent: startWalletWorker() is a no-op when one is already running.
510
- */
489
+ /** Start the wallet worker if enabled and the app context is ready. Never throws; idempotent. */
511
490
  async function startWalletWorkerIfConfigured() {
512
491
  if (process_1.env.SKIP_AUTO_INIT === 'true' || !appContext)
513
492
  return;
@@ -535,11 +514,9 @@ async function startWalletWorkerIfConfigured() {
535
514
  }
536
515
  }
537
516
  /**
538
- * Re-drive deferred submissions that were claimed (status 'submitting' with
539
- * persisted signedTxCbor) but whose detached submit never ran because the
540
- * process died first (KNOWN_ISSUES #11, Layer 2). Idempotent — an already
541
- * submitted tx finalizes via the TransactionAlreadySubmittedError path.
542
- * Non-fatal, mirrors startCrawlerIfConfigured/startWalletWorkerIfConfigured.
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.
543
520
  */
544
521
  async function redriveInterruptedSubmissionsIfConfigured() {
545
522
  if (process_1.env.SKIP_AUTO_INIT === 'true' || !appContext)
@@ -554,20 +531,16 @@ async function redriveInterruptedSubmissionsIfConfigured() {
554
531
  logger.error('Failed to re-drive interrupted submissions (non-fatal):', err);
555
532
  }
556
533
  }
557
- // Bootstrap hook - runs when CAP server has loaded all services
534
+ // Standalone bootstrap; skipped when the plugin already initialized the context.
558
535
  cds_1.default.on('served', async () => {
559
- // Skip if already initialized by plugin (src/plugin.ts runs first)
560
536
  if (appContext)
561
537
  return;
562
- // Skip auto-initialization when SKIP_AUTO_INIT is set (e.g., for tests with mocked backends)
538
+ // SKIP_AUTO_INIT: tests with mocked backends
563
539
  if (process_1.env.SKIP_AUTO_INIT === 'true') {
564
540
  logger.info('Skipping auto-initialization (SKIP_AUTO_INIT=true)');
565
541
  return;
566
542
  }
567
- // NOTE: config loading is INSIDE the try — loadConfigFromEnv/loadHsmConfigFromEnv
568
- // throw ConfigError synchronously (missing HSM_PIN, bad slot, no requiresRole…).
569
- // Outside the try that would crash the host app's bootstrap in plugin mode,
570
- // violating the plugin contract ("never throw on failure").
543
+ // Config loading stays inside the try: a ConfigError must never crash the host app.
571
544
  let config;
572
545
  try {
573
546
  config = loadConfigFromEnv();
@@ -578,25 +551,19 @@ cds_1.default.on('served', async () => {
578
551
  logger.info('CAP server bootstrap complete');
579
552
  }
580
553
  catch (err) {
581
- // Don't throw - initialization failure shouldn't crash the host app (plugin contract).
582
- // Capture the cause so getAppContext() can surface a structured 503 with diagnostics
583
- // instead of the raw "Application not initialized" Error landing as a generic 500.
554
+ // Never throw; keep the cause so getAppContext() surfaces a structured 503.
584
555
  bootstrapError = err instanceof Error ? err : new Error(String(err));
585
- // Write to stderr directly so the cause stays visible even when test runners
586
- // suppress console.error (vitest.setup.ts in this repo silences it).
556
+ // stderr directly: the cause stays visible when a test runner silences console.error.
587
557
  const where = config ? `backends={${config.backends.join(',')}} network=${config.network}` : 'config load';
588
558
  const msg = err instanceof Error ? `${err.name}: ${err.message}\n${err.stack ?? ''}` : String(err);
589
559
  process.stderr.write(`[ODATANO] Failed to initialize blockchain components — ${where}\n${msg}\n`);
590
560
  logger.error('Failed to initialize blockchain components:', err);
591
561
  }
592
- // Start the pre-sync crawler if configured (standalone mode). Non-fatal.
562
+ // Optional subsystems; each is non-fatal.
593
563
  await startCrawlerIfConfigured();
594
- // Start the wallet worker if configured (standalone mode). Non-fatal.
595
564
  await startWalletWorkerIfConfigured();
596
- // Re-drive deferred submissions interrupted by a restart (standalone mode). Non-fatal.
597
565
  await redriveInterruptedSubmissionsIfConfigured();
598
566
  });
599
- // Shutdown hook - runs when CAP server is shutting down (e.g., cds.shutdown() in tests)
600
567
  cds_1.default.on('shutdown', async () => {
601
568
  await shutdownAppContext();
602
569
  });