@odatano/core 2.0.0-rc.2 → 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 (132) 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 +224 -0
  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 +316 -0
  10. package/@cds-models/odatano/cardano/index.js +33 -0
  11. package/README.md +195 -136
  12. package/db/schema.cds +2121 -1633
  13. package/package.json +179 -173
  14. package/src/index.d.ts +10 -10
  15. package/src/index.js +24 -14
  16. package/src/plugin.js +39 -52
  17. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  18. package/srv/blockchain/backends/blockfrost-backend.js +45 -158
  19. package/srv/blockchain/backends/cardano-backend.d.ts +78 -158
  20. package/srv/blockchain/backends/cardano-backend.js +14 -5
  21. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  22. package/srv/blockchain/backends/koios-backend.js +292 -202
  23. package/srv/blockchain/backends/ogmios-backend.d.ts +59 -96
  24. package/srv/blockchain/backends/ogmios-backend.js +241 -153
  25. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  26. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  27. package/srv/blockchain/cardano-client.d.ts +50 -205
  28. package/srv/blockchain/cardano-client.js +80 -224
  29. package/srv/blockchain/cardano-indexer.d.ts +146 -244
  30. package/srv/blockchain/cardano-indexer.js +442 -285
  31. package/srv/blockchain/cardano-tx-builder.d.ts +19 -84
  32. package/srv/blockchain/cardano-tx-builder.js +21 -107
  33. package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
  34. package/srv/blockchain/crawler/certificate-backfill.js +150 -0
  35. package/srv/blockchain/crawler/crawler.d.ts +121 -53
  36. package/srv/blockchain/crawler/crawler.js +402 -82
  37. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  38. package/srv/blockchain/crawler/index.d.ts +5 -0
  39. package/srv/blockchain/crawler/index.js +35 -7
  40. package/srv/blockchain/crawler/sync-state.d.ts +44 -28
  41. package/srv/blockchain/crawler/sync-state.js +115 -43
  42. package/srv/blockchain/crawler/utxo-set-import.d.ts +69 -0
  43. package/srv/blockchain/crawler/utxo-set-import.js +269 -0
  44. package/srv/blockchain/ledger-state.d.ts +80 -0
  45. package/srv/blockchain/ledger-state.js +383 -0
  46. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  47. package/srv/blockchain/signing/cose-verifier.js +6 -12
  48. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  49. package/srv/blockchain/signing/external-signer.js +19 -122
  50. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  51. package/srv/blockchain/signing/hsm-signer.js +23 -63
  52. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  53. package/srv/blockchain/signing/signature-verifier.js +13 -54
  54. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  55. package/srv/blockchain/signing/submission-finalizer.js +16 -48
  56. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +71 -160
  57. package/srv/blockchain/transaction-building/buildooor-tx.js +185 -260
  58. package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
  59. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  60. package/srv/blockchain/wallet-worker/build-request.js +39 -23
  61. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  62. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  63. package/srv/blockchain/wallet-worker/index.js +2 -8
  64. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  65. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  66. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  67. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  68. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  69. package/srv/blockchain/wallet-worker/signers.js +3 -8
  70. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  71. package/srv/blockchain/wallet-worker/wallet-worker.js +34 -90
  72. package/srv/cardano-agent-service.cds +146 -0
  73. package/srv/cardano-agent-service.d.ts +2 -0
  74. package/srv/cardano-agent-service.js +12 -0
  75. package/srv/cardano-indexer-service.cds +164 -73
  76. package/srv/cardano-indexer-service.js +156 -11
  77. package/srv/cardano-service.cds +45 -0
  78. package/srv/cardano-service.js +38 -96
  79. package/srv/cardano-sign-service.cds +200 -180
  80. package/srv/cardano-sign-service.js +55 -173
  81. package/srv/cardano-tx-service.cds +32 -26
  82. package/srv/cardano-tx-service.js +133 -195
  83. package/srv/cardano-worker-service.js +7 -15
  84. package/srv/server.d.ts +28 -86
  85. package/srv/server.js +95 -128
  86. package/srv/utils/agent-grants-config.d.ts +37 -0
  87. package/srv/utils/agent-grants-config.js +138 -0
  88. package/srv/utils/agent-grants.d.ts +262 -0
  89. package/srv/utils/agent-grants.js +914 -0
  90. package/srv/utils/agent-token-auth.d.ts +16 -0
  91. package/srv/utils/agent-token-auth.js +78 -0
  92. package/srv/utils/backend-request-handler.d.ts +2 -16
  93. package/srv/utils/backend-request-handler.js +3 -18
  94. package/srv/utils/collections.d.ts +4 -8
  95. package/srv/utils/collections.js +4 -8
  96. package/srv/utils/const.d.ts +19 -68
  97. package/srv/utils/const.js +20 -69
  98. package/srv/utils/crypto.d.ts +3 -12
  99. package/srv/utils/crypto.js +5 -18
  100. package/srv/utils/db-indexes.d.ts +25 -0
  101. package/srv/utils/db-indexes.js +89 -0
  102. package/srv/utils/db-sanitize.d.ts +27 -0
  103. package/srv/utils/db-sanitize.js +85 -0
  104. package/srv/utils/error-codes.d.ts +18 -73
  105. package/srv/utils/error-codes.js +17 -70
  106. package/srv/utils/errors.d.ts +34 -178
  107. package/srv/utils/errors.js +55 -217
  108. package/srv/utils/liveness.d.ts +16 -0
  109. package/srv/utils/liveness.js +41 -0
  110. package/srv/utils/mappers.d.ts +82 -210
  111. package/srv/utils/mappers.js +272 -293
  112. package/srv/utils/network-context.js +2 -11
  113. package/srv/utils/pg-order-nulls.d.ts +14 -0
  114. package/srv/utils/pg-order-nulls.js +57 -0
  115. package/srv/utils/plutus-placeholders.d.ts +6 -18
  116. package/srv/utils/plutus-placeholders.js +6 -20
  117. package/srv/utils/rate-limiter.d.ts +46 -0
  118. package/srv/utils/rate-limiter.js +116 -0
  119. package/srv/utils/service-events.d.ts +2 -22
  120. package/srv/utils/service-events.js +3 -23
  121. package/srv/utils/signing-helper.d.ts +3 -18
  122. package/srv/utils/signing-helper.js +10 -32
  123. package/srv/utils/tx-build-helper.d.ts +18 -92
  124. package/srv/utils/tx-build-helper.js +32 -123
  125. package/srv/utils/tx-request-parsers.d.ts +14 -20
  126. package/srv/utils/tx-request-parsers.js +33 -20
  127. package/srv/utils/tx-utils.d.ts +4 -23
  128. package/srv/utils/tx-utils.js +12 -41
  129. package/srv/utils/types.d.ts +112 -169
  130. package/srv/utils/types.js +2 -6
  131. package/srv/utils/validators.d.ts +19 -89
  132. package/srv/utils/validators.js +31 -138
@@ -2,112 +2,47 @@ import type { CardanoClient } from './cardano-client';
2
2
  import type { TxBuildRequest, TxBuildResult, LedgerProtocolParameters } from '../utils/types';
3
3
  import type { CardanoTxBuilder } from './transaction-building/cardano-tx';
4
4
  import { LedgerProtocolParameter } from '#cds-models/CardanoODataService';
5
- /**
6
- * CardanoTransactionBuilder - High-level transaction builder that utilizes specific CardanoTxBuilder implementations
7
- * to build various types of Cardano transactions.
8
- */
5
+ /** High-level transaction builder delegating to the Buildooor `CardanoTxBuilder`. */
9
6
  export declare class CardanoTransactionBuilder {
10
7
  private client;
11
8
  private txBuilder;
12
9
  private initialized;
13
- /**
14
- * Create a new CardanoTransactionBuilder instance
15
- * @param client - The CardanoClient instance for UTxO fetching
16
- */
10
+ /** @param client UTxO source for coin selection */
17
11
  constructor(client: CardanoClient);
18
- /**
19
- * Initialize the transaction builder
20
- * @param protocolParams - Optional protocol parameters (if not provided, fetched from backend)
21
- */
12
+ /** @param protocolParams optional; fetched from the backend when omitted */
22
13
  init(protocolParams?: LedgerProtocolParameters): Promise<void>;
23
- /**
24
- * Ensure the builder is initialized and return it (lazy init)
25
- * @returns {Promise<CardanoTxBuilder>} initialized builder
26
- * @throws {Error} if builder cannot be initialized
27
- */
14
+ /** Lazily initialize and return the builder. */
28
15
  private ensureInitialized;
29
- /**
30
- * Reset the transaction builder (useful for testing)
31
- */
16
+ /** Reset the builder (testing). */
32
17
  reset(): void;
33
- /**
34
- * Set the transaction builder directly (for testing)
35
- * @param builder - The builder to set
36
- */
18
+ /** Set the builder directly (testing). */
37
19
  setBuilder(builder: CardanoTxBuilder): void;
38
- /**
39
- * Build a simple ADA transfer transaction
40
- * @param req transaction build request
41
- * @param protocolParameters current protocol parameters
42
- * @returns {Promise<TxBuildResult>} transaction build result
43
- */
20
+ /** Build a simple ADA transfer transaction. */
44
21
  buildSimpleAdaTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
45
- /**
46
- * Build a transaction with Metadata (for both simple and multi-asset transactions)
47
- * @param req transaction build request
48
- * @param protocolParameters current protocol parameters
49
- * @returns {Promise<TxBuildResult>} transaction build result
50
- */
22
+ /** Build a transaction with metadata (simple or multi-asset). */
51
23
  buildTransactionWithMetadata(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
52
- /**
53
- * Build a multi-asset transaction
54
- * @param req transaction build request
55
- * @param protocolParameters current protocol parameters
56
- * @returns {Promise<TxBuildResult>} transaction build result
57
- */
24
+ /** Build a multi-asset transaction. */
58
25
  buildMultiAssetTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
59
- /**
60
- * Build a minting transaction
61
- * @param req transaction build request
62
- * @param protocolParameters current protocol parameters
63
- * @returns {Promise<TxBuildResult>} transaction build result
64
- */
26
+ /** Build a minting transaction. */
65
27
  buildMintTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
66
- /**
67
- * Build a Plutus spending transaction (consume UTxO at script address)
68
- * @param req transaction build request
69
- * @param protocolParameters current protocol parameters
70
- * @returns {Promise<TxBuildResult>} transaction build result
71
- */
28
+ /** Build a Plutus spending transaction (consume a UTxO at a script address). */
72
29
  buildPlutusSpendTransaction(req: TxBuildRequest, protocolParameters: LedgerProtocolParameter): Promise<TxBuildResult>;
73
30
  /**
74
- * Verify that a transaction output resolved via getTransaction is still unspent,
75
- * by checking the live UTxO set of its address. getTransaction only proves the
76
- * output EXISTED — a spent output would otherwise surface as a cryptic node-side
77
- * rejection at submit instead of a clear 400 here.
78
- *
79
- * Lookup failures are logged and tolerated (the check is best-effort; refusing to
80
- * build on a flaky backend would be a new failure mode).
31
+ * Verify that an output resolved via getTransaction is still unspent against the live UTxO
32
+ * set of its address (getTransaction only proves it existed). Lookup failures are tolerated.
81
33
  */
82
34
  private _assertUnspent;
83
- /**
84
- * Resolve forced-input refs (consumed) to full UTxO records.
85
- * Thin wrapper over _resolveInputRefs — see it for behaviour.
86
- */
35
+ /** Resolve forced-input refs (consumed) to full UTxO records. */
87
36
  private _resolveForceInputs;
88
- /**
89
- * Resolve CIP-31 reference input refs (read-only, NOT merged into the
90
- * coin-selection set) to full UTxO records.
91
- */
37
+ /** Resolve CIP-31 reference-input refs (read-only, not merged into the coin-selection set). */
92
38
  private _resolveReferenceInputs;
93
39
  /**
94
- * Resolve a list of {txHash, outputIndex} refs to full UTxO records.
95
- * Prefers matching against already-known UTxOs to avoid extra backend calls;
96
- * otherwise fetches the producing transaction and verifies the output is
97
- * unspent. Throws TransactionValidationError (labelled by `kind`) if any ref
98
- * cannot be resolved (missing or spent). Deduplicates refs before lookup.
99
- *
100
- * @param refs input refs from the request
101
- * @param knownUtxos UTxOs already fetched (cheap-match pool)
102
- * @param kind label used in error messages / the spent-check
103
- * @returns resolved UTxOs, in the same order as the deduped refs
40
+ * Resolve {txHash, outputIndex} refs to full UTxO records: known UTxOs first, otherwise the
41
+ * producing transaction plus an unspent check. Throws TransactionValidationError (labelled
42
+ * by `kind`) for a missing or spent ref. Refs are deduplicated; order is preserved.
104
43
  */
105
44
  private _resolveInputRefs;
106
- /**
107
- * Fetch UTxOs for a given address
108
- * @param address bech32 address
109
- * @returns {Promise<UTxO[]>} list of UTxOs
110
- */
45
+ /** Fetch the UTxOs of an address; throws InsufficientFundsError when it has none. */
111
46
  private _fetchUtxosForAddress;
112
47
  }
113
48
  //# sourceMappingURL=cardano-tx-builder.d.ts.map
@@ -8,26 +8,17 @@ const cds_1 = __importDefault(require("@sap/cds"));
8
8
  const buildooor_tx_1 = require("./transaction-building/buildooor-tx");
9
9
  const errors_1 = require("../utils/errors");
10
10
  const logger = cds_1.default.log('CardanoTransactionBuilder');
11
- /**
12
- * CardanoTransactionBuilder - High-level transaction builder that utilizes specific CardanoTxBuilder implementations
13
- * to build various types of Cardano transactions.
14
- */
11
+ /** High-level transaction builder delegating to the Buildooor `CardanoTxBuilder`. */
15
12
  class CardanoTransactionBuilder {
16
13
  client;
17
14
  txBuilder;
18
15
  initialized = false;
19
- /**
20
- * Create a new CardanoTransactionBuilder instance
21
- * @param client - The CardanoClient instance for UTxO fetching
22
- */
16
+ /** @param client UTxO source for coin selection */
23
17
  constructor(client) {
24
18
  this.client = client;
25
19
  logger.debug('CardanoTransactionBuilder instance created');
26
20
  }
27
- /**
28
- * Initialize the transaction builder
29
- * @param protocolParams - Optional protocol parameters (if not provided, fetched from backend)
30
- */
21
+ /** @param protocolParams optional; fetched from the backend when omitted */
31
22
  async init(protocolParams) {
32
23
  if (this.initialized && this.txBuilder)
33
24
  return;
@@ -37,42 +28,27 @@ class CardanoTransactionBuilder {
37
28
  this.initialized = true;
38
29
  logger.debug(`Initialized with builder: ${this.txBuilder.name}`);
39
30
  }
40
- /**
41
- * Ensure the builder is initialized and return it (lazy init)
42
- * @returns {Promise<CardanoTxBuilder>} initialized builder
43
- * @throws {Error} if builder cannot be initialized
44
- */
31
+ /** Lazily initialize and return the builder. */
45
32
  async ensureInitialized() {
46
33
  if (!this.initialized || !this.txBuilder) {
47
34
  await this.init();
48
35
  }
49
36
  return this.txBuilder;
50
37
  }
51
- /**
52
- * Reset the transaction builder (useful for testing)
53
- */
38
+ /** Reset the builder (testing). */
54
39
  reset() {
55
40
  this.txBuilder = undefined;
56
41
  this.initialized = false;
57
42
  logger.debug(`Builder reset`);
58
43
  }
59
- /**
60
- * Set the transaction builder directly (for testing)
61
- * @param builder - The builder to set
62
- */
44
+ /** Set the builder directly (testing). */
63
45
  setBuilder(builder) {
64
46
  this.txBuilder = builder;
65
47
  this.initialized = true;
66
48
  }
67
- /**
68
- * Build a simple ADA transfer transaction
69
- * @param req transaction build request
70
- * @param protocolParameters current protocol parameters
71
- * @returns {Promise<TxBuildResult>} transaction build result
72
- */
49
+ /** Build a simple ADA transfer transaction. */
73
50
  async buildSimpleAdaTransaction(req, protocolParameters) {
74
51
  const builder = await this.ensureInitialized();
75
- // prepare the transaction build context
76
52
  const senderUtxos = await this._fetchUtxosForAddress(req.senderAddress);
77
53
  const forcedUtxos = await this._resolveForceInputs(req.forceInputs ?? [], senderUtxos);
78
54
  const txContext = {
@@ -80,21 +56,13 @@ class CardanoTransactionBuilder {
80
56
  protocolParameters: protocolParameters
81
57
  };
82
58
  logger.debug(`Prepared build context: ${txContext.utxos.length} UTxOs for coin selection (${forcedUtxos.length} forced)`);
83
- // Build the unsigned transfer transaction
84
59
  const txBuildResult = await builder.buildUnsignedTransfer(req, txContext);
85
60
  logger.debug(`Built simple ADA transaction successfully.`);
86
- // Return the transaction build result
87
61
  return txBuildResult;
88
62
  }
89
- /**
90
- * Build a transaction with Metadata (for both simple and multi-asset transactions)
91
- * @param req transaction build request
92
- * @param protocolParameters current protocol parameters
93
- * @returns {Promise<TxBuildResult>} transaction build result
94
- */
63
+ /** Build a transaction with metadata (simple or multi-asset). */
95
64
  async buildTransactionWithMetadata(req, protocolParameters) {
96
65
  const builder = await this.ensureInitialized();
97
- // Prepare the transaction build context
98
66
  const senderUtxos = await this._fetchUtxosForAddress(req.senderAddress);
99
67
  const forcedUtxos = await this._resolveForceInputs(req.forceInputs ?? [], senderUtxos);
100
68
  const txContext = {
@@ -102,24 +70,16 @@ class CardanoTransactionBuilder {
102
70
  protocolParameters: protocolParameters
103
71
  };
104
72
  logger.debug(`Prepared build context: ${txContext.utxos.length} UTxOs for coin selection (${forcedUtxos.length} forced)`);
105
- // Build the unsigned transaction with metadata
106
73
  const txBuildResult = await builder.buildUnsignedTransactionWithMetadata(req, txContext);
107
74
  logger.debug(`Built transaction with metadata successfully.`);
108
- // Return the transaction build result
109
75
  return txBuildResult;
110
76
  }
111
- /**
112
- * Build a multi-asset transaction
113
- * @param req transaction build request
114
- * @param protocolParameters current protocol parameters
115
- * @returns {Promise<TxBuildResult>} transaction build result
116
- */
77
+ /** Build a multi-asset transaction. */
117
78
  async buildMultiAssetTransaction(req, protocolParameters) {
118
79
  if (!req.assets || req.assets.length === 0) {
119
80
  throw new Error('[CardanoTransactionBuilder] buildMultiAssetTransaction requires assets to be specified');
120
81
  }
121
82
  const builder = await this.ensureInitialized();
122
- // Prepare the transaction build context
123
83
  const senderUtxos = await this._fetchUtxosForAddress(req.senderAddress);
124
84
  const forcedUtxos = await this._resolveForceInputs(req.forceInputs ?? [], senderUtxos);
125
85
  const txContext = {
@@ -127,30 +87,21 @@ class CardanoTransactionBuilder {
127
87
  protocolParameters: protocolParameters
128
88
  };
129
89
  logger.debug(`Prepared build context: ${txContext.utxos.length} UTxOs for coin selection (${forcedUtxos.length} forced)`);
130
- // Build the unsigned transfer transaction (unified with simple ADA transfer)
131
90
  const txBuildResult = await builder.buildUnsignedTransfer(req, txContext);
132
91
  logger.debug(`Built multi-asset transaction successfully.`);
133
92
  return txBuildResult;
134
93
  }
135
- /**
136
- * Build a minting transaction
137
- * @param req transaction build request
138
- * @param protocolParameters current protocol parameters
139
- * @returns {Promise<TxBuildResult>} transaction build result
140
- */
94
+ /** Build a minting transaction. */
141
95
  async buildMintTransaction(req, protocolParameters) {
142
- // Validate mint-specific required fields
143
96
  if (!req.mintActions || req.mintActions.length === 0) {
144
97
  throw new Error('[CardanoTransactionBuilder] buildMintTransaction requires mintActions to be specified');
145
98
  }
146
99
  if (!req.mintingPolicyScript) {
147
100
  throw new Error('[CardanoTransactionBuilder] buildMintTransaction requires mintingPolicyScript to be specified');
148
101
  }
149
- // Type is now narrowed to TxBuildMintRequest
150
102
  const mintReq = req;
151
103
  const builder = await this.ensureInitialized();
152
104
  const cardanoClient = this.client;
153
- // Prepare the transaction build context
154
105
  const senderUtxos = await this._fetchUtxosForAddress(req.senderAddress);
155
106
  const forcedUtxos = await this._resolveForceInputs(req.forceInputs ?? [], senderUtxos);
156
107
  // Resolve CIP-31 reference inputs (read-only, not consumed — kept separate from coin-selection set)
@@ -171,18 +122,11 @@ class CardanoTransactionBuilder {
171
122
  else {
172
123
  logger.debug(`Ogmios not available - using default execution units`);
173
124
  }
174
- // Build the unsigned minting transaction
175
125
  const txBuildResult = await builder.buildUnsignedMintTransaction(mintReq, txContext);
176
126
  logger.debug(`Built minting transaction successfully.`);
177
- // Return the transaction build result
178
127
  return txBuildResult;
179
128
  }
180
- /**
181
- * Build a Plutus spending transaction (consume UTxO at script address)
182
- * @param req transaction build request
183
- * @param protocolParameters current protocol parameters
184
- * @returns {Promise<TxBuildResult>} transaction build result
185
- */
129
+ /** Build a Plutus spending transaction (consume a UTxO at a script address). */
186
130
  async buildPlutusSpendTransaction(req, protocolParameters) {
187
131
  if (!req.plutusScriptExecution) {
188
132
  throw new Error('[CardanoTransactionBuilder] buildPlutusSpendTransaction requires plutusScriptExecution to be specified');
@@ -192,16 +136,11 @@ class CardanoTransactionBuilder {
192
136
  const cardanoClient = this.client;
193
137
  // Fetch sender UTxOs for fee payment
194
138
  const senderUtxos = await this._fetchUtxosForAddress(req.senderAddress);
195
- // Fetch the script UTxO separately (it's at the script address, not sender address)
196
- // We include it in the UTxO set so the builder can find it
139
+ // The script UTxO sits at the script address; add it so the builder can find it
197
140
  const scriptRef = spendReq.plutusScriptExecution.scriptUtxo;
198
141
  const allUtxos = [...senderUtxos];
199
- // Check if the script UTxO is already in sender UTxOs (unlikely but possible)
200
142
  const alreadyIncluded = senderUtxos.some(u => u.txHash === scriptRef.txHash && u.outputIndex === scriptRef.outputIndex);
201
143
  if (!alreadyIncluded) {
202
- // Fetch script UTxO via transaction lookup - the backend needs to provide it
203
- // For now, we create a minimal UTxO entry from what we know
204
- // The actual UTxO data will be resolved by the backend during tx building
205
144
  logger.debug(`Script UTxO ${scriptRef.txHash}#${scriptRef.outputIndex} not in sender UTxOs - fetching from backend`);
206
145
  const tx = await cardanoClient.getTransaction(scriptRef.txHash);
207
146
  const scriptOutput = tx.outputs?.find(o => o.outputIndex === scriptRef.outputIndex);
@@ -247,13 +186,8 @@ class CardanoTransactionBuilder {
247
186
  return txBuildResult;
248
187
  }
249
188
  /**
250
- * Verify that a transaction output resolved via getTransaction is still unspent,
251
- * by checking the live UTxO set of its address. getTransaction only proves the
252
- * output EXISTED — a spent output would otherwise surface as a cryptic node-side
253
- * rejection at submit instead of a clear 400 here.
254
- *
255
- * Lookup failures are logged and tolerated (the check is best-effort; refusing to
256
- * build on a flaky backend would be a new failure mode).
189
+ * Verify that an output resolved via getTransaction is still unspent against the live UTxO
190
+ * set of its address (getTransaction only proves it existed). Lookup failures are tolerated.
257
191
  */
258
192
  async _assertUnspent(ref, address, kind, liveUtxoCache) {
259
193
  let live;
@@ -276,31 +210,18 @@ class CardanoTransactionBuilder {
276
210
  throw new errors_1.TransactionValidationError(`${kind} ${ref.txHash}#${ref.outputIndex} is already spent`);
277
211
  }
278
212
  }
279
- /**
280
- * Resolve forced-input refs (consumed) to full UTxO records.
281
- * Thin wrapper over _resolveInputRefs — see it for behaviour.
282
- */
213
+ /** Resolve forced-input refs (consumed) to full UTxO records. */
283
214
  _resolveForceInputs(refs, senderUtxos) {
284
215
  return this._resolveInputRefs(refs, senderUtxos, 'forceInput');
285
216
  }
286
- /**
287
- * Resolve CIP-31 reference input refs (read-only, NOT merged into the
288
- * coin-selection set) to full UTxO records.
289
- */
217
+ /** Resolve CIP-31 reference-input refs (read-only, not merged into the coin-selection set). */
290
218
  _resolveReferenceInputs(refs, knownUtxos) {
291
219
  return this._resolveInputRefs(refs, knownUtxos, 'referenceInput');
292
220
  }
293
221
  /**
294
- * Resolve a list of {txHash, outputIndex} refs to full UTxO records.
295
- * Prefers matching against already-known UTxOs to avoid extra backend calls;
296
- * otherwise fetches the producing transaction and verifies the output is
297
- * unspent. Throws TransactionValidationError (labelled by `kind`) if any ref
298
- * cannot be resolved (missing or spent). Deduplicates refs before lookup.
299
- *
300
- * @param refs input refs from the request
301
- * @param knownUtxos UTxOs already fetched (cheap-match pool)
302
- * @param kind label used in error messages / the spent-check
303
- * @returns resolved UTxOs, in the same order as the deduped refs
222
+ * Resolve {txHash, outputIndex} refs to full UTxO records: known UTxOs first, otherwise the
223
+ * producing transaction plus an unspent check. Throws TransactionValidationError (labelled
224
+ * by `kind`) for a missing or spent ref. Refs are deduplicated; order is preserved.
304
225
  */
305
226
  async _resolveInputRefs(refs, knownUtxos, kind) {
306
227
  if (!refs || refs.length === 0)
@@ -349,11 +270,7 @@ class CardanoTransactionBuilder {
349
270
  }
350
271
  return resolved;
351
272
  }
352
- /**
353
- * Fetch UTxOs for a given address
354
- * @param address bech32 address
355
- * @returns {Promise<UTxO[]>} list of UTxOs
356
- */
273
+ /** Fetch the UTxOs of an address; throws InsufficientFundsError when it has none. */
357
274
  async _fetchUtxosForAddress(address) {
358
275
  logger.debug(`Fetching UTxOs for address: ${address}`);
359
276
  const utxos = await this.client.getAddressUtxos(address);
@@ -365,10 +282,7 @@ class CardanoTransactionBuilder {
365
282
  }
366
283
  }
367
284
  exports.CardanoTransactionBuilder = CardanoTransactionBuilder;
368
- /**
369
- * Merge two UTxO lists, skipping refs already present in the first.
370
- * Used to add forced UTxOs to a context without duplicating existing entries.
371
- */
285
+ /** Merge two UTxO lists, skipping refs already present in the first. */
372
286
  function mergeUtxosUnique(base, extra) {
373
287
  if (extra.length === 0)
374
288
  return base;
@@ -0,0 +1,45 @@
1
+ import type { Transaction as CapTransaction } from '@sap/cds';
2
+ import type { CardanoClient } from '../cardano-client';
3
+ import type { ChainPoint } from '../backends/cardano-backend';
4
+ /**
5
+ * Fills `TransactionCertificates` and `TransactionWithdrawals` for blocks the crawl already
6
+ * holds, from a second chain-sync stream. Only those two tables are written, keyed so a
7
+ * repeat is idempotent; the cursor, the block and transaction rows stay untouched and the
8
+ * live crawler keeps its own stream. A block the index does not know (rolled back since) is
9
+ * skipped, so no row can point at a transaction that is not there.
10
+ */
11
+ export declare class CertificateBackfillError extends Error {
12
+ constructor(message: string);
13
+ }
14
+ export interface CertificateBackfillProgress {
15
+ /** Slot of the last block handled. */
16
+ atSlot: number;
17
+ blocks: number;
18
+ transactions: number;
19
+ certificates: number;
20
+ withdrawals: number;
21
+ }
22
+ export interface CertificateBackfillOptions {
23
+ client: CardanoClient;
24
+ /** First slot to cover; the stream intersects at the newest indexed block before it. */
25
+ fromSlot: number;
26
+ /** Last slot to cover; the stream ends at the first block past it. */
27
+ toSlot: number;
28
+ /** Rows are written per batch of blocks; smaller batches show progress sooner. */
29
+ batchBlocks?: number;
30
+ onProgress?: (p: CertificateBackfillProgress) => void;
31
+ }
32
+ export interface CertificateBackfillResult extends CertificateBackfillProgress {
33
+ fromSlot: number;
34
+ toSlot: number;
35
+ /** The chain point the stream started after. */
36
+ intersection: ChainPoint | 'origin';
37
+ }
38
+ /**
39
+ * Newest indexed block strictly before `slot` inside the crawled range; the crawler's own
40
+ * start point when none is. Lazily indexed blocks below the crawl start are never picked:
41
+ * they may lie far back or on a fork the node no longer knows.
42
+ */
43
+ export declare function intersectionBefore(db: CapTransaction, slot: number): Promise<ChainPoint | 'origin'>;
44
+ export declare function backfillCertificates(opts: CertificateBackfillOptions): Promise<CertificateBackfillResult>;
45
+ //# sourceMappingURL=certificate-backfill.d.ts.map
@@ -0,0 +1,150 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.CertificateBackfillError = void 0;
7
+ exports.intersectionBefore = intersectionBefore;
8
+ exports.backfillCertificates = backfillCertificates;
9
+ const cds_1 = __importDefault(require("@sap/cds"));
10
+ const mappers_1 = require("../../utils/mappers");
11
+ const sync_state_1 = require("./sync-state");
12
+ const cardano_1 = require("#cds-models/odatano/cardano");
13
+ const { SELECT, UPSERT } = cds_1.default.ql;
14
+ const logger = cds_1.default.log('CertificateBackfill');
15
+ /**
16
+ * Fills `TransactionCertificates` and `TransactionWithdrawals` for blocks the crawl already
17
+ * holds, from a second chain-sync stream. Only those two tables are written, keyed so a
18
+ * repeat is idempotent; the cursor, the block and transaction rows stay untouched and the
19
+ * live crawler keeps its own stream. A block the index does not know (rolled back since) is
20
+ * skipped, so no row can point at a transaction that is not there.
21
+ */
22
+ class CertificateBackfillError extends Error {
23
+ constructor(message) {
24
+ super(message);
25
+ this.name = 'CertificateBackfillError';
26
+ }
27
+ }
28
+ exports.CertificateBackfillError = CertificateBackfillError;
29
+ /**
30
+ * Newest indexed block strictly before `slot` inside the crawled range; the crawler's own
31
+ * start point when none is. Lazily indexed blocks below the crawl start are never picked:
32
+ * they may lie far back or on a fork the node no longer knows.
33
+ */
34
+ async function intersectionBefore(db, slot) {
35
+ const cursor = await (0, sync_state_1.readCursor)(db);
36
+ const floor = cursor?.startSlot ?? null;
37
+ const range = floor != null ? { between: floor, and: slot - 1 } : { '<': slot };
38
+ const row = floor != null && slot - 1 < floor ? null : (await db.run(SELECT.one.from(cardano_1.Block).columns('hash', 'slot', 'height').where({ slot: range }).orderBy('slot desc')));
39
+ if (row?.hash && row.slot != null)
40
+ return { slot: Number(row.slot), hash: row.hash, height: row.height == null ? undefined : Number(row.height) };
41
+ if (floor != null && cursor?.startBlockHash)
42
+ return { slot: floor, hash: cursor.startBlockHash };
43
+ return 'origin';
44
+ }
45
+ async function backfillCertificates(opts) {
46
+ const { client, fromSlot, toSlot } = opts;
47
+ if (!Number.isInteger(fromSlot) || !Number.isInteger(toSlot) || fromSlot < 0 || toSlot < fromSlot) {
48
+ throw new CertificateBackfillError(`Invalid slot range ${fromSlot}..${toSlot}`);
49
+ }
50
+ const backend = client.getChainSyncBackend();
51
+ if (!backend)
52
+ throw new CertificateBackfillError('No chain-sync backend available (the backfill streams from Ogmios).');
53
+ const batchBlocks = Math.max(1, opts.batchBlocks ?? 200);
54
+ const intersection = await cds_1.default.tx((tx) => intersectionBefore(tx, fromSlot));
55
+ const points = intersection === 'origin' ? 'origin' : [intersection];
56
+ const progress = { atSlot: intersection === 'origin' ? 0 : intersection.slot, blocks: 0, transactions: 0, certificates: 0, withdrawals: 0 };
57
+ let pending = [];
58
+ /**
59
+ * Writes a batch: the index's blocks of the batch's slot range are read once (a sequential
60
+ * index range, not one random lookup per block) and only rows of blocks the index holds
61
+ * are written; a block it never had (rolled back since) is skipped.
62
+ */
63
+ const flush = async () => {
64
+ if (!pending.length)
65
+ return;
66
+ const batch = pending;
67
+ pending = [];
68
+ const fromBatch = batch[0].slot, toBatch = batch[batch.length - 1].slot;
69
+ await cds_1.default.tx(async (tx) => {
70
+ const rows = (await tx.run(SELECT.from(cardano_1.Block).columns('hash').where({ slot: { between: fromBatch, and: toBatch } })));
71
+ const known = new Set(rows.map((r) => r.hash));
72
+ const certs = [], withdrawals = [];
73
+ for (const b of batch) {
74
+ if (!known.has(b.hash)) {
75
+ logger.warn(`Block ${b.hash} at slot ${b.slot} is not in the index — skipped`);
76
+ continue;
77
+ }
78
+ certs.push(...b.certs);
79
+ withdrawals.push(...b.withdrawals);
80
+ progress.blocks++;
81
+ progress.transactions += b.transactions;
82
+ progress.certificates += b.certs.length;
83
+ progress.withdrawals += b.withdrawals.length;
84
+ }
85
+ if (certs.length)
86
+ await tx.run(UPSERT.into(cardano_1.TransactionCertificates).entries(certs));
87
+ if (withdrawals.length)
88
+ await tx.run(UPSERT.into(cardano_1.TransactionWithdrawals).entries(withdrawals));
89
+ });
90
+ progress.atSlot = toBatch;
91
+ opts.onProgress?.({ ...progress });
92
+ };
93
+ let handle = null;
94
+ let settled = false;
95
+ const done = new Promise((resolve, reject) => {
96
+ const finish = (err) => {
97
+ if (settled)
98
+ return;
99
+ settled = true;
100
+ if (err)
101
+ reject(err);
102
+ else
103
+ resolve();
104
+ };
105
+ const onBlock = async (block, txs) => {
106
+ if (settled)
107
+ return;
108
+ const slot = block.slot ?? 0;
109
+ if (slot > toSlot) {
110
+ finish();
111
+ return;
112
+ }
113
+ if (slot < fromSlot)
114
+ return; // between the intersection and the range: skipped, not counted
115
+ pending.push({
116
+ hash: block.hash, slot, transactions: txs.length,
117
+ certs: txs.flatMap((t) => (0, mappers_1.mapTransactionCertificates)(t.hash, t.certificates ?? [])),
118
+ withdrawals: txs.flatMap((t) => (0, mappers_1.mapTransactionWithdrawals)(t.hash, t.withdrawals ?? [])),
119
+ });
120
+ if (pending.length >= batchBlocks)
121
+ await flush();
122
+ if (slot === toSlot)
123
+ finish();
124
+ };
125
+ backend.openChainSync(points, {
126
+ rollForward: (block, txs) => onBlock(block, txs).catch(finish),
127
+ // The handshake acknowledges the intersection; a reorg mid-run is the crawler's to undo,
128
+ // it deletes the rows of the rolled-back transactions.
129
+ rollBackward: async () => undefined,
130
+ onError: async (err) => finish(err),
131
+ }).then((h) => { handle = h; if (settled)
132
+ void h.close().catch(() => undefined); }, finish);
133
+ });
134
+ try {
135
+ await done;
136
+ await flush();
137
+ }
138
+ finally {
139
+ const h = handle;
140
+ if (h) {
141
+ try {
142
+ await h.close();
143
+ }
144
+ catch { /* best effort */ }
145
+ }
146
+ }
147
+ logger.info(`Certificate backfill ${fromSlot}..${toSlot}: ${progress.blocks} blocks, ${progress.certificates} certificates, ${progress.withdrawals} withdrawals`);
148
+ return { ...progress, fromSlot, toSlot, intersection };
149
+ }
150
+ //# sourceMappingURL=certificate-backfill.js.map