@odatano/core 2.0.0-rc.3 → 2.0.0-rc.30

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 (162) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +251 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +357 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +194 -2
  6. package/@cds-models/CardanoIndexerService/index.js +25 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +294 -7
  8. package/@cds-models/CardanoODataService/index.js +33 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +28 -3
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +52 -19
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/index.d.ts +18 -0
  14. package/@cds-models/index.js +3 -0
  15. package/@cds-models/odatano/cardano/index.d.ts +408 -7
  16. package/@cds-models/odatano/cardano/index.js +42 -0
  17. package/README.md +64 -5
  18. package/db/schema.cds +677 -13
  19. package/db/types.cds +27 -0
  20. package/package.json +182 -173
  21. package/scripts/migrate-slot-leader.mjs +104 -0
  22. package/scripts/migrate-txseq.mjs +147 -0
  23. package/src/index.d.ts +11 -10
  24. package/src/index.js +28 -14
  25. package/src/plugin.js +39 -52
  26. package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
  27. package/srv/blockchain/backends/blockfrost-backend.js +49 -160
  28. package/srv/blockchain/backends/cardano-backend.d.ts +104 -158
  29. package/srv/blockchain/backends/cardano-backend.js +19 -5
  30. package/srv/blockchain/backends/koios-backend.d.ts +126 -60
  31. package/srv/blockchain/backends/koios-backend.js +356 -217
  32. package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
  33. package/srv/blockchain/backends/odatano-backend.js +170 -0
  34. package/srv/blockchain/backends/ogmios-backend.d.ts +162 -94
  35. package/srv/blockchain/backends/ogmios-backend.js +548 -197
  36. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
  37. package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
  38. package/srv/blockchain/cardano-client.d.ts +78 -205
  39. package/srv/blockchain/cardano-client.js +186 -242
  40. package/srv/blockchain/cardano-indexer.d.ts +302 -242
  41. package/srv/blockchain/cardano-indexer.js +1191 -362
  42. package/srv/blockchain/cardano-tx-builder.d.ts +43 -81
  43. package/srv/blockchain/cardano-tx-builder.js +177 -132
  44. package/srv/blockchain/crawler/certificate-backfill.d.ts +67 -0
  45. package/srv/blockchain/crawler/certificate-backfill.js +169 -0
  46. package/srv/blockchain/crawler/crawler.d.ts +139 -54
  47. package/srv/blockchain/crawler/crawler.js +478 -96
  48. package/srv/blockchain/crawler/hooks.d.ts +3 -14
  49. package/srv/blockchain/crawler/index.d.ts +5 -0
  50. package/srv/blockchain/crawler/index.js +35 -7
  51. package/srv/blockchain/crawler/sync-state.d.ts +46 -28
  52. package/srv/blockchain/crawler/sync-state.js +128 -43
  53. package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
  54. package/srv/blockchain/crawler/transaction-backfill.js +283 -0
  55. package/srv/blockchain/crawler/utxo-set-import.d.ts +78 -0
  56. package/srv/blockchain/crawler/utxo-set-import.js +363 -0
  57. package/srv/blockchain/ledger-state.d.ts +101 -0
  58. package/srv/blockchain/ledger-state.js +432 -0
  59. package/srv/blockchain/pending-spends.d.ts +28 -0
  60. package/srv/blockchain/pending-spends.js +89 -0
  61. package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
  62. package/srv/blockchain/signing/cose-verifier.js +6 -12
  63. package/srv/blockchain/signing/external-signer.d.ts +16 -113
  64. package/srv/blockchain/signing/external-signer.js +19 -122
  65. package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
  66. package/srv/blockchain/signing/hsm-signer.js +23 -63
  67. package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
  68. package/srv/blockchain/signing/signature-verifier.js +13 -54
  69. package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
  70. package/srv/blockchain/signing/submission-finalizer.js +16 -49
  71. package/srv/blockchain/stored-chain.d.ts +33 -0
  72. package/srv/blockchain/stored-chain.js +234 -0
  73. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +108 -160
  74. package/srv/blockchain/transaction-building/buildooor-tx.js +620 -285
  75. package/srv/blockchain/transaction-building/caller-datums.d.ts +17 -0
  76. package/srv/blockchain/transaction-building/caller-datums.js +50 -0
  77. package/srv/blockchain/transaction-building/cardano-tx.d.ts +10 -35
  78. package/srv/blockchain/transaction-rows.d.ts +12 -0
  79. package/srv/blockchain/transaction-rows.js +43 -0
  80. package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
  81. package/srv/blockchain/wallet-worker/build-request.js +48 -24
  82. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
  84. package/srv/blockchain/wallet-worker/index.js +2 -8
  85. package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
  86. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  87. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
  88. package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
  89. package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
  90. package/srv/blockchain/wallet-worker/signers.js +3 -8
  91. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
  92. package/srv/blockchain/wallet-worker/wallet-worker.js +40 -91
  93. package/srv/cardano-agent-service.cds +146 -0
  94. package/srv/cardano-agent-service.d.ts +2 -0
  95. package/srv/cardano-agent-service.js +12 -0
  96. package/srv/cardano-backend-service.cds +52 -0
  97. package/srv/cardano-backend-service.d.ts +2 -0
  98. package/srv/cardano-backend-service.js +244 -0
  99. package/srv/cardano-indexer-service.cds +201 -73
  100. package/srv/cardano-indexer-service.js +280 -11
  101. package/srv/cardano-service.cds +56 -1
  102. package/srv/cardano-service.js +52 -113
  103. package/srv/cardano-sign-service.cds +200 -180
  104. package/srv/cardano-sign-service.js +55 -173
  105. package/srv/cardano-tx-service.cds +439 -364
  106. package/srv/cardano-tx-service.js +305 -209
  107. package/srv/cardano-ui.cds +16 -16
  108. package/srv/cardano-worker-service.js +7 -15
  109. package/srv/cbor/parse.js +13 -1
  110. package/srv/server.d.ts +28 -86
  111. package/srv/server.js +127 -135
  112. package/srv/utils/agent-grants-config.d.ts +37 -0
  113. package/srv/utils/agent-grants-config.js +138 -0
  114. package/srv/utils/agent-grants.d.ts +262 -0
  115. package/srv/utils/agent-grants.js +922 -0
  116. package/srv/utils/agent-token-auth.d.ts +16 -0
  117. package/srv/utils/agent-token-auth.js +78 -0
  118. package/srv/utils/backend-request-handler.d.ts +2 -16
  119. package/srv/utils/backend-request-handler.js +3 -18
  120. package/srv/utils/collections.d.ts +4 -8
  121. package/srv/utils/collections.js +4 -8
  122. package/srv/utils/const.d.ts +30 -67
  123. package/srv/utils/const.js +32 -72
  124. package/srv/utils/crypto.d.ts +3 -12
  125. package/srv/utils/crypto.js +5 -18
  126. package/srv/utils/db-indexes.d.ts +25 -0
  127. package/srv/utils/db-indexes.js +94 -0
  128. package/srv/utils/db-sanitize.d.ts +27 -0
  129. package/srv/utils/db-sanitize.js +85 -0
  130. package/srv/utils/epoch-slots.d.ts +13 -0
  131. package/srv/utils/epoch-slots.js +25 -0
  132. package/srv/utils/error-codes.d.ts +20 -73
  133. package/srv/utils/error-codes.js +19 -70
  134. package/srv/utils/errors.d.ts +50 -177
  135. package/srv/utils/errors.js +94 -218
  136. package/srv/utils/liveness.d.ts +16 -0
  137. package/srv/utils/liveness.js +40 -0
  138. package/srv/utils/mappers.d.ts +128 -214
  139. package/srv/utils/mappers.js +354 -299
  140. package/srv/utils/network-context.js +2 -11
  141. package/srv/utils/pg-inline-json.d.ts +8 -0
  142. package/srv/utils/pg-inline-json.js +62 -0
  143. package/srv/utils/pg-order-nulls.d.ts +14 -0
  144. package/srv/utils/pg-order-nulls.js +56 -0
  145. package/srv/utils/plutus-placeholders.d.ts +23 -16
  146. package/srv/utils/plutus-placeholders.js +63 -27
  147. package/srv/utils/rate-limiter.d.ts +46 -0
  148. package/srv/utils/rate-limiter.js +116 -0
  149. package/srv/utils/service-events.d.ts +2 -22
  150. package/srv/utils/service-events.js +3 -23
  151. package/srv/utils/signing-helper.d.ts +3 -18
  152. package/srv/utils/signing-helper.js +10 -32
  153. package/srv/utils/tx-build-helper.d.ts +26 -92
  154. package/srv/utils/tx-build-helper.js +68 -123
  155. package/srv/utils/tx-request-parsers.d.ts +107 -21
  156. package/srv/utils/tx-request-parsers.js +433 -34
  157. package/srv/utils/tx-utils.d.ts +4 -23
  158. package/srv/utils/tx-utils.js +12 -41
  159. package/srv/utils/types.d.ts +238 -169
  160. package/srv/utils/types.js +2 -6
  161. package/srv/utils/validators.d.ts +24 -90
  162. package/srv/utils/validators.js +50 -147
@@ -17,42 +17,46 @@ const tx_request_parsers_1 = require("./utils/tx-request-parsers");
17
17
  const VALID_DERIVE_NETWORKS = ['mainnet', 'preview', 'preprod'];
18
18
  const { SELECT, UPDATE } = cds_1.default.ql;
19
19
  const logger = cds_1.default.log('CardanoTxService');
20
- /**
21
- * Cardano Transaction Service Implementation
22
- * Handles transaction building and submission operations & some additional data queries.
23
- */
20
+ /** CardanoTransactionService handlers: transaction building, submission and script helpers. */
24
21
  module.exports = (srv) => {
25
22
  logger.debug('Module loaded - registering handlers');
26
23
  const { TransactionBuilds, TransactionSubmissions, AddressTransactionBuilds } = require('#cds-models/CardanoTransactionService');
27
- /**
28
- * Build a simple ADA-only transaction
29
- * @param req - CDS request object (with senderAddress, recipientAddress, lovelaceAmount, changeAddress)
30
- * @returns {TransactionBuild} Transaction build details
31
- */
24
+ // BuildSimpleAdaTransaction — ADA (optionally with assets / datum) to one recipient or a script.
32
25
  srv.on('BuildSimpleAdaTransaction', async (req) => {
33
26
  const { senderAddress, recipientAddress, lovelaceAmount, outputDatumJson, assetsJson, forceInputsJson, validatorScript, scriptParamsJson, lockOnScript, referenceScriptHex, validityStartMs, validityEndMs } = req.data;
34
- // validate inputs
35
27
  const errors = (0, validators_1.validateTransactionInputs)({ senderAddress, recipientAddress, lovelaceAmount, referenceScriptHex, validityStartMs, validityEndMs }, ['senderAddress', 'recipientAddress', 'lovelaceAmount']);
36
28
  (0, errors_1.throwIfValidationErrors)(req, 'BuildSimpleAdaTransaction', errors);
37
29
  if (req.data.changeAddress && !(0, validators_1.isValidBech32Address)(req.data.changeAddress)) {
38
30
  return (0, errors_1.rejectInvalid)(req, 'BuildSimpleAdaTransaction', 'Invalid changeAddress format', 'changeAddress');
39
31
  }
40
- // parse optional output datum
41
32
  const cleanData = { ...req.data };
42
- // parse optional forceInputsJson
43
33
  const forceInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(forceInputsJson, 'forceInputsJson');
44
34
  if (forceInputsResult.error)
45
35
  return (0, errors_1.rejectInvalid)(req, 'BuildSimpleAdaTransaction', forceInputsResult.error, 'forceInputsJson');
46
36
  cleanData.forceInputs = forceInputsResult.parsed;
47
37
  delete cleanData.forceInputsJson;
38
+ const protectInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(req.data.protectInputsJson, 'protectInputsJson');
39
+ if (protectInputsResult.error)
40
+ return (0, errors_1.rejectInvalid)(req, 'BuildSimpleAdaTransaction', protectInputsResult.error, 'protectInputsJson');
41
+ cleanData.protectInputs = protectInputsResult.parsed;
42
+ delete cleanData.protectInputsJson;
48
43
  if (outputDatumJson) {
49
- const jsonResult = (0, validators_1.validateJsonWithLimits)(outputDatumJson, 'outputDatumJson');
44
+ const jsonResult = (0, validators_1.validatePlutusJson)(outputDatumJson, 'outputDatumJson');
50
45
  if (!jsonResult.valid)
51
46
  return (0, errors_1.rejectInvalid)(req, 'BuildSimpleAdaTransaction', jsonResult.error, 'outputDatumJson');
52
47
  cleanData.outputDatum = jsonResult.parsed;
53
48
  delete cleanData.outputDatumJson;
54
49
  }
55
- // parse optional assets JSON (for locking native assets at script addresses)
50
+ delete cleanData.outputDatumCbor;
51
+ if (req.data.outputDatumCbor != null) {
52
+ if (outputDatumJson)
53
+ return (0, errors_1.rejectInvalid)(req, 'BuildSimpleAdaTransaction', 'outputDatumJson and outputDatumCbor exclude each other; pass one', 'outputDatumCbor');
54
+ const cbor = (0, tx_request_parsers_1.parsePlutusCbor)(req.data.outputDatumCbor, 'outputDatumCbor');
55
+ if (cbor.error)
56
+ return (0, errors_1.rejectInvalid)(req, 'BuildSimpleAdaTransaction', cbor.error, 'outputDatumCbor');
57
+ cleanData.outputDatumCbor = cbor.hex;
58
+ }
59
+ // Native assets to lock at a script address
56
60
  const assetsResult = (0, tx_request_parsers_1.parseAssetsArray)(assetsJson, 'assetsJson');
57
61
  if (assetsResult.error)
58
62
  return (0, errors_1.rejectInvalid)(req, 'BuildSimpleAdaTransaction', assetsResult.error, 'assetsJson');
@@ -60,10 +64,10 @@ module.exports = (srv) => {
60
64
  cleanData.assets = assetsResult.parsed;
61
65
  delete cleanData.assetsJson;
62
66
  }
63
- // parse optional scriptParamsJson (for parameterized validators)
67
+ // Parameters for a parameterized validator
64
68
  let scriptParams;
65
69
  if (scriptParamsJson) {
66
- const jsonResult = (0, validators_1.validateJsonWithLimits)(scriptParamsJson, 'scriptParamsJson');
70
+ const jsonResult = (0, validators_1.validatePlutusJson)(scriptParamsJson, 'scriptParamsJson');
67
71
  if (!jsonResult.valid)
68
72
  return (0, errors_1.rejectInvalid)(req, 'BuildSimpleAdaTransaction', jsonResult.error, 'scriptParamsJson');
69
73
  scriptParams = jsonResult.parsed;
@@ -71,11 +75,10 @@ module.exports = (srv) => {
71
75
  return (0, errors_1.rejectInvalid)(req, 'BuildSimpleAdaTransaction', 'scriptParamsJson must be a JSON array', 'scriptParamsJson');
72
76
  }
73
77
  }
74
- // lockOnScript requires a validatorScript to derive the target address from
75
78
  if (lockOnScript && !validatorScript) {
76
79
  return (0, errors_1.rejectInvalid)(req, 'BuildSimpleAdaTransaction', 'lockOnScript requires validatorScript to derive the script address', 'validatorScript');
77
80
  }
78
- // Pre-compute script hash + address when lockOnScript is set; override recipient before build.
81
+ // lockOnScript: derive script hash + address and override the recipient before the build.
79
82
  let derivedScriptHash;
80
83
  let derivedScriptAddress;
81
84
  if (lockOnScript && validatorScript) {
@@ -99,11 +102,10 @@ module.exports = (srv) => {
99
102
  cleanData.referenceScript = referenceScriptHex;
100
103
  }
101
104
  delete cleanData.referenceScriptHex;
102
- // handle the request / building the transaction / indexing the build result / returning build details
103
105
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
104
106
  logger.debug({ senderAddress, recipientAddress: cleanData.recipientAddress, lovelaceAmount, hasDatum: !!outputDatumJson, hasAssets: !!assetsJson, lockOnScript: !!lockOnScript }, 'Building simple ADA transaction');
105
107
  const buildResult = await (0, server_1.getCardanoIndexer)().indexSimpleBuildResult(db, cleanData);
106
- // Persist derived script address + hash on the build record when lockOnScript was applied
108
+ // Persist the derived script address + hash on the build record
107
109
  if (lockOnScript && derivedScriptHash && derivedScriptAddress && buildResult.id) {
108
110
  buildResult.scriptHash = derivedScriptHash;
109
111
  buildResult.scriptAddress = derivedScriptAddress;
@@ -115,41 +117,29 @@ module.exports = (srv) => {
115
117
  return buildResult;
116
118
  });
117
119
  });
118
- /**
119
- * Build a transaction with metadata
120
- * @param req - CDS request object (with senderAddress, recipientAddress, lovelaceAmount, metadataJson, changeAddress)
121
- * @returns {TransactionBuild} Transaction build details
122
- */
120
+ // BuildTransactionWithMetadata — ADA transfer with auxiliary metadata.
123
121
  srv.on('BuildTransactionWithMetadata', async (req) => {
124
122
  const { senderAddress, recipientAddress, lovelaceAmount, metadataJson } = req.data;
125
- // validate inputs (includes JSON parsing validation)
126
123
  const errors = (0, validators_1.validateTransactionInputs)({ senderAddress, recipientAddress, lovelaceAmount, metadataJson }, ['senderAddress', 'recipientAddress', 'lovelaceAmount', 'metadataJson']);
127
124
  (0, errors_1.throwIfValidationErrors)(req, 'BuildTransactionWithMetadata', errors);
128
125
  if (req.data.changeAddress && !(0, validators_1.isValidBech32Address)(req.data.changeAddress)) {
129
126
  return (0, errors_1.rejectInvalid)(req, 'BuildTransactionWithMetadata', 'Invalid changeAddress format', 'changeAddress');
130
127
  }
131
- // Parse metadataJson (already validated as valid JSON)
128
+ // Already validated as JSON above
132
129
  const parsedMetadata = JSON.parse(metadataJson);
133
- // handle the request / building the transaction / indexing the build result / returning build details
134
130
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
135
131
  logger.debug({ senderAddress, recipientAddress, lovelaceAmount, metadataKeyCount: Object.keys(parsedMetadata).length }, 'Building transaction with metadata');
136
132
  return await (0, server_1.getCardanoIndexer)().indexMetadataBuildResult(db, { ...req.data, metadataJson: parsedMetadata });
137
133
  });
138
134
  });
139
- /**
140
- * Build a multi-asset transaction
141
- * @param req - CDS request object (with senderAddress, recipientAddress, lovelaceAmount, assetsJson, changeAddress)
142
- * @returns {TransactionBuild} Transaction build details
143
- */
135
+ // BuildMultiAssetTransaction — ADA plus native assets to one recipient.
144
136
  srv.on('BuildMultiAssetTransaction', async (req) => {
145
137
  const { senderAddress, recipientAddress, lovelaceAmount, assetsJson, outputDatumJson, referenceScriptHex, validityStartMs, validityEndMs } = req.data;
146
- // validate inputs (includes JSON parsing validation)
147
138
  const errors = (0, validators_1.validateTransactionInputs)({ senderAddress, recipientAddress, lovelaceAmount, assetsJson, referenceScriptHex, validityStartMs, validityEndMs }, ['senderAddress', 'recipientAddress', 'lovelaceAmount', 'assetsJson']);
148
139
  (0, errors_1.throwIfValidationErrors)(req, 'BuildMultiAssetTransaction', errors);
149
140
  if (req.data.changeAddress && !(0, validators_1.isValidBech32Address)(req.data.changeAddress)) {
150
141
  return (0, errors_1.rejectInvalid)(req, 'BuildMultiAssetTransaction', 'Invalid changeAddress format', 'changeAddress');
151
142
  }
152
- // Parse and validate assetsJson entries (unit + quantity, like parseExtraOutputs)
153
143
  const assetsResult = (0, tx_request_parsers_1.parseAssetsArray)(assetsJson, 'assetsJson');
154
144
  if (assetsResult.error)
155
145
  return (0, errors_1.rejectInvalid)(req, 'BuildMultiAssetTransaction', assetsResult.error, 'assetsJson');
@@ -157,22 +147,28 @@ module.exports = (srv) => {
157
147
  if (!parsedAssets || parsedAssets.length === 0) {
158
148
  return (0, errors_1.rejectInvalid)(req, 'BuildMultiAssetTransaction', 'assetsJson must contain at least one asset', 'assetsJson');
159
149
  }
160
- // Validation BEFORE handleRequest (convention) — build the clean request object up front
161
150
  const cleanData = { ...req.data };
162
151
  delete cleanData.assetsJson;
163
- // parse optional output datum (for locking assets at script addresses)
164
152
  if (outputDatumJson) {
165
- const jsonResult = (0, validators_1.validateJsonWithLimits)(outputDatumJson, 'outputDatumJson');
153
+ const jsonResult = (0, validators_1.validatePlutusJson)(outputDatumJson, 'outputDatumJson');
166
154
  if (!jsonResult.valid)
167
155
  return (0, errors_1.rejectInvalid)(req, 'BuildMultiAssetTransaction', jsonResult.error, 'outputDatumJson');
168
156
  cleanData.outputDatum = jsonResult.parsed;
169
157
  delete cleanData.outputDatumJson;
170
158
  }
159
+ delete cleanData.outputDatumCbor;
160
+ if (req.data.outputDatumCbor != null) {
161
+ if (outputDatumJson)
162
+ return (0, errors_1.rejectInvalid)(req, 'BuildMultiAssetTransaction', 'outputDatumJson and outputDatumCbor exclude each other; pass one', 'outputDatumCbor');
163
+ const cbor = (0, tx_request_parsers_1.parsePlutusCbor)(req.data.outputDatumCbor, 'outputDatumCbor');
164
+ if (cbor.error)
165
+ return (0, errors_1.rejectInvalid)(req, 'BuildMultiAssetTransaction', cbor.error, 'outputDatumCbor');
166
+ cleanData.outputDatumCbor = cbor.hex;
167
+ }
171
168
  if (referenceScriptHex) {
172
169
  cleanData.referenceScript = referenceScriptHex;
173
170
  }
174
171
  delete cleanData.referenceScriptHex;
175
- // handle the request / building the transaction / indexing the build result / returning build details
176
172
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
177
173
  logger.debug({ senderAddress, recipientAddress, lovelaceAmount, assets: parsedAssets, hasDatum: !!outputDatumJson }, 'Building multi-asset transaction');
178
174
  const result = await (0, server_1.getCardanoIndexer)().indexMultiAssetBuildResult(db, { ...cleanData, assets: parsedAssets });
@@ -180,39 +176,54 @@ module.exports = (srv) => {
180
176
  return result;
181
177
  });
182
178
  });
183
- /**
184
- * Build a minting transaction
185
- * @param req - CDS request object (with senderAddress, recipientAddress, lovelaceAmount, mintActionsJson, mintingPolicyScript, changeAddress)
186
- * @returns {TransactionBuild} Transaction build details
187
- */
179
+ // BuildMintTransaction — mint/burn under one or more Plutus policies.
188
180
  srv.on('BuildMintTransaction', async (req) => {
189
- const { senderAddress, recipientAddress, lovelaceAmount, mintActionsJson, mintingPolicyScript, requiredSignersJson, scriptParamsJson, inlineDatumJson, mintRedeemerJson, lockOnScript, forceInputsJson, referenceInputsJson, referenceScriptHex, metadataJson, validityStartMs, validityEndMs } = req.data;
190
- // validate inputs (includes JSON and CBOR validation)
181
+ const { senderAddress, recipientAddress, lovelaceAmount, mintActionsJson, mintingPolicyScript, requiredSignersJson, scriptParamsJson, inlineDatumJson, mintRedeemerJson, lockOnScript, forceInputsJson, referenceInputsJson, referenceScriptHex, extraOutputsJson, metadataJson, validityStartMs, validityEndMs } = req.data;
191
182
  const errors = (0, validators_1.validateTransactionInputs)({ senderAddress, recipientAddress, lovelaceAmount, mintActionsJson, mintingPolicyScript, referenceScriptHex, metadataJson, validityStartMs, validityEndMs }, ['senderAddress', 'recipientAddress', 'lovelaceAmount', 'mintActionsJson', 'mintingPolicyScript']);
192
183
  (0, errors_1.throwIfValidationErrors)(req, 'BuildMintTransaction', errors);
193
184
  if (req.data.changeAddress && !(0, validators_1.isValidBech32Address)(req.data.changeAddress)) {
194
185
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', 'Invalid changeAddress format', 'changeAddress');
195
186
  }
196
- // Parse mintActionsJson and convert quantity strings to bigint
187
+ // Mint actions: quantities become bigint; bare asset names are expanded with the policy id.
197
188
  const parsedMintActionsRaw = JSON.parse(mintActionsJson);
198
189
  if (!Array.isArray(parsedMintActionsRaw)) {
199
190
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', 'mintActionsJson must be a JSON array', 'mintActionsJson');
200
191
  }
201
- const parsedMintActions = parsedMintActionsRaw.map((action) => {
192
+ const parsedMintActions = parsedMintActionsRaw.map((action, actionIndex) => {
202
193
  if (!action || typeof action !== 'object') {
203
194
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', 'Each mint action must be an object with assetUnit and quantity', 'mintActionsJson');
204
195
  }
205
- // assetUnit is normally a full policyId+assetName hex. Exception (BUG 7):
206
- // when scriptParamsJson is provided, a bare assetName (shorter than a full
207
- // unit) is accepted here and expanded to policyId+assetName once the policy
208
- // script is parameterized below — mirrors the expansion's own < MIN_FULL_ASSET_UNIT_LENGTH guard.
209
- const bareAssetNameForExpansion = !!scriptParamsJson &&
196
+ // Optional per-action mintingPolicyScript + redeemerJson
197
+ const policyFields = (0, tx_request_parsers_1.parseMintActionPolicyFields)(action, actionIndex);
198
+ if (policyFields.error) {
199
+ return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', policyFields.error, 'mintActionsJson');
200
+ }
201
+ let actionPolicyId;
202
+ if (policyFields.script) {
203
+ try {
204
+ actionPolicyId = cardano_ledger_ts_1.Script.fromCbor(Buffer.from(policyFields.script, 'hex')).hash.toString();
205
+ }
206
+ catch (err) {
207
+ const errMsg = err instanceof Error ? err.message : String(err);
208
+ return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', `mintActions[${actionIndex}].mintingPolicyScript is not a valid Plutus script: ${errMsg}`, 'mintActionsJson');
209
+ }
210
+ }
211
+ const bareAssetNameForExpansion = (!!scriptParamsJson || !!actionPolicyId) &&
210
212
  typeof action.assetUnit === 'string' &&
211
213
  action.assetUnit.length < const_1.MIN_FULL_ASSET_UNIT_LENGTH &&
212
214
  action.assetUnit.length % 2 === 0 &&
213
215
  /^[0-9a-fA-F]*$/.test(action.assetUnit);
214
216
  if (typeof action.assetUnit !== 'string' || (!(0, validators_1.isAssetUnit)(action.assetUnit) && !bareAssetNameForExpansion)) {
215
- return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', `Invalid assetUnit: "${action.assetUnit}" — must be policyId+assetName hex (or a bare assetName hex when scriptParamsJson is set)`, 'mintActionsJson');
217
+ return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', `Invalid assetUnit: "${action.assetUnit}" — must be policyId+assetName hex (or a bare assetName hex when scriptParamsJson or a per-action mintingPolicyScript is set)`, 'mintActionsJson');
218
+ }
219
+ let assetUnit = action.assetUnit;
220
+ if (actionPolicyId) {
221
+ if (assetUnit.length < const_1.MIN_FULL_ASSET_UNIT_LENGTH) {
222
+ assetUnit = actionPolicyId + assetUnit;
223
+ }
224
+ else if (!assetUnit.toLowerCase().startsWith(actionPolicyId)) {
225
+ return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', `mintActions[${actionIndex}].assetUnit "${assetUnit}" does not start with its own policy id ${actionPolicyId}`, 'mintActionsJson');
226
+ }
216
227
  }
217
228
  if (typeof action.quantity !== 'string') {
218
229
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', 'Each mint action must have a string quantity', 'mintActionsJson');
@@ -221,21 +232,25 @@ module.exports = (srv) => {
221
232
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', `Invalid quantity format: "${action.quantity}" — must be an integer string`, 'mintActionsJson');
222
233
  }
223
234
  try {
224
- return { ...action, quantity: BigInt(action.quantity) };
235
+ return {
236
+ assetUnit,
237
+ quantity: BigInt(action.quantity),
238
+ ...(action.redeemer !== undefined ? { redeemer: action.redeemer } : {}),
239
+ ...(policyFields.script ? { mintingPolicyScript: policyFields.script } : {}),
240
+ ...(policyFields.redeemer !== undefined ? { redeemerJson: policyFields.redeemer } : {})
241
+ };
225
242
  }
226
243
  catch {
227
244
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', `Invalid quantity: "${action.quantity}" — cannot parse as integer`, 'mintActionsJson');
228
245
  }
229
246
  });
230
- // Parse and validate optional requiredSignersJson
231
247
  const requiredSignersResult = (0, tx_request_parsers_1.parseRequiredSigners)(requiredSignersJson);
232
248
  if (requiredSignersResult.error)
233
249
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', requiredSignersResult.error, 'requiredSignersJson');
234
250
  const requiredSigners = requiredSignersResult.parsed;
235
- // Parse and validate optional scriptParamsJson
236
251
  let scriptParams;
237
252
  if (scriptParamsJson) {
238
- const jsonResult = (0, validators_1.validateJsonWithLimits)(scriptParamsJson, 'scriptParamsJson');
253
+ const jsonResult = (0, validators_1.validatePlutusJson)(scriptParamsJson, 'scriptParamsJson');
239
254
  if (!jsonResult.valid)
240
255
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', jsonResult.error, 'scriptParamsJson');
241
256
  scriptParams = jsonResult.parsed;
@@ -243,39 +258,41 @@ module.exports = (srv) => {
243
258
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', 'scriptParamsJson must be a JSON array', 'scriptParamsJson');
244
259
  }
245
260
  }
246
- // Parse and validate optional inlineDatumJson
247
261
  let inlineDatum;
248
262
  if (inlineDatumJson) {
249
- const jsonResult = (0, validators_1.validateJsonWithLimits)(inlineDatumJson, 'inlineDatumJson');
263
+ const jsonResult = (0, validators_1.validatePlutusJson)(inlineDatumJson, 'inlineDatumJson');
250
264
  if (!jsonResult.valid)
251
265
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', jsonResult.error, 'inlineDatumJson');
252
266
  inlineDatum = jsonResult.parsed;
253
267
  }
254
- // Parse and validate optional mintRedeemerJson
255
268
  let mintRedeemer;
256
269
  if (mintRedeemerJson) {
257
- const jsonResult = (0, validators_1.validateJsonWithLimits)(mintRedeemerJson, 'mintRedeemerJson');
270
+ const jsonResult = (0, validators_1.validatePlutusJson)(mintRedeemerJson, 'mintRedeemerJson');
258
271
  if (!jsonResult.valid)
259
272
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', jsonResult.error, 'mintRedeemerJson');
260
273
  mintRedeemer = jsonResult.parsed;
261
274
  }
262
- // Validate lockOnScript requires scriptParamsJson
263
275
  if (lockOnScript && (!scriptParams || scriptParams.length === 0)) {
264
276
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', 'lockOnScript requires scriptParamsJson to derive script address', 'lockOnScript');
265
277
  }
266
- // Parse and validate optional forceInputsJson
278
+ // extraOutputsJson: each minted token can sit on its own output with its own inline datum
279
+ const extraOutputsResult = (0, tx_request_parsers_1.parseExtraOutputs)(extraOutputsJson);
280
+ if (extraOutputsResult.error)
281
+ return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', extraOutputsResult.error, 'extraOutputsJson');
282
+ const extraOutputs = extraOutputsResult.parsed;
267
283
  const forceInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(forceInputsJson, 'forceInputsJson');
268
284
  if (forceInputsResult.error)
269
285
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', forceInputsResult.error, 'forceInputsJson');
270
286
  const forceInputs = forceInputsResult.parsed;
271
- // Parse and validate optional referenceInputsJson (CIP-31)
287
+ const protectInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(req.data.protectInputsJson, 'protectInputsJson');
288
+ if (protectInputsResult.error)
289
+ return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', protectInputsResult.error, 'protectInputsJson');
290
+ const protectInputs = protectInputsResult.parsed;
291
+ // CIP-31 reference inputs
272
292
  const refInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(referenceInputsJson, 'referenceInputsJson');
273
293
  if (refInputsResult.error)
274
294
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', refInputsResult.error, 'referenceInputsJson');
275
295
  const referenceInputs = refInputsResult.parsed;
276
- // Parse and validate optional metadataJson (auxiliary_data on the mint tx).
277
- // validateTransactionInputs has already JSON-validated the string; re-parse here
278
- // and enforce the label-object shape that the builder's metadata mapper expects.
279
296
  let parsedMetadata;
280
297
  if (metadataJson) {
281
298
  try {
@@ -289,10 +306,8 @@ module.exports = (srv) => {
289
306
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', 'metadataJson must be an object with numeric label keys', 'metadataJson');
290
307
  }
291
308
  }
292
- // handle the request / building the transaction / indexing the build result / returning build details
293
309
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
294
310
  logger.debug({ senderAddress, recipientAddress, lovelaceAmount, mintActions: parsedMintActions, forceInputs: forceInputs?.length ?? 0, referenceInputs: referenceInputs?.length ?? 0, hasMetadata: !!parsedMetadata }, 'Building minting transaction');
295
- // Create clean request object with parsed mintActions (remove mintActionsJson, add mintActions)
296
311
  const cleanData = { ...req.data };
297
312
  delete cleanData.mintActionsJson;
298
313
  delete cleanData.requiredSignersJson;
@@ -301,7 +316,9 @@ module.exports = (srv) => {
301
316
  delete cleanData.mintRedeemerJson;
302
317
  delete cleanData.lockOnScript;
303
318
  delete cleanData.forceInputsJson;
319
+ delete cleanData.protectInputsJson;
304
320
  delete cleanData.referenceInputsJson;
321
+ delete cleanData.extraOutputsJson;
305
322
  if (parsedMetadata) {
306
323
  cleanData.metadataJson = parsedMetadata;
307
324
  }
@@ -312,13 +329,12 @@ module.exports = (srv) => {
312
329
  cleanData.referenceScript = referenceScriptHex;
313
330
  }
314
331
  delete cleanData.referenceScriptHex;
315
- // Apply script parameters if provided (for parameterized validators)
332
+ // Parameterized policy: apply params, then expand bare asset names with the applied hash.
316
333
  let finalMintingPolicyScript = mintingPolicyScript;
317
334
  let effectivePolicyId;
318
335
  if (scriptParams && scriptParams.length > 0) {
319
336
  try {
320
337
  finalMintingPolicyScript = (0, tx_build_helper_1.applyScriptParameters)(mintingPolicyScript, scriptParams);
321
- // BUG 7 fix: expand assetName-only entries to full assetUnit using the applied script's policyId.
322
338
  const appliedScript = cardano_ledger_ts_1.Script.fromCbor(Buffer.from(finalMintingPolicyScript, 'hex'));
323
339
  effectivePolicyId = appliedScript.hash.toString();
324
340
  }
@@ -331,7 +347,7 @@ module.exports = (srv) => {
331
347
  action.assetUnit = effectivePolicyId + action.assetUnit;
332
348
  }
333
349
  }
334
- // lockOnScript: route output to the enterprise script address derived from applied script hash
350
+ // lockOnScript: route the output to the enterprise address of the applied script
335
351
  if (lockOnScript) {
336
352
  const scriptAddr = (0, mappers_1.scriptHashToEnterpriseAddress)(effectivePolicyId, (0, server_1.getCardanoClient)().network);
337
353
  cleanData.recipientAddress = scriptAddr;
@@ -343,17 +359,13 @@ module.exports = (srv) => {
343
359
  effectivePolicyId = cardano_ledger_ts_1.Script.fromCbor(Buffer.from(mintingPolicyScript, 'hex')).hash.toString();
344
360
  }
345
361
  catch {
346
- // invalid script CBOR — skip the prefix check; the builder rejects it with its own message
362
+ // Invalid script CBOR: skip the prefix check, the builder rejects it with its own message.
347
363
  }
348
364
  }
349
- // BUG 9 fix: the builder mints every action under the policy script's hash and
350
- // parseAssetUnit silently discards the unit's first 56 hex chars. A bare asset name
351
- // of 29-32 bytes is length-indistinguishable from a full unit, so a mismatched
352
- // prefix would mint a truncated name. At this point every action holds a full
353
- // unit (bare names were expanded above), so all of them must carry the policyId.
365
+ // Every action without its own policy must carry the top-level policy id prefix.
354
366
  if (effectivePolicyId) {
355
367
  const policyId = effectivePolicyId;
356
- const mismatch = parsedMintActions.find((action) => !action.assetUnit.toLowerCase().startsWith(policyId));
368
+ const mismatch = parsedMintActions.find((action) => !action.mintingPolicyScript && !action.assetUnit.toLowerCase().startsWith(policyId));
357
369
  if (mismatch) {
358
370
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', `assetUnit "${mismatch.assetUnit}" does not start with the minting policy id ${policyId} — pass the full unit as policyId+assetName (asset names longer than 28 bytes cannot be passed bare)`, 'mintActionsJson');
359
371
  }
@@ -366,23 +378,24 @@ module.exports = (srv) => {
366
378
  inlineDatum,
367
379
  mintRedeemer,
368
380
  forceInputs,
369
- referenceInputs
381
+ protectInputs,
382
+ referenceInputs,
383
+ extraOutputs
370
384
  });
371
- // Post-build: compute CIP-14 fingerprint and scriptAddress
385
+ // Post-build: CIP-14 fingerprint and scriptAddress
372
386
  if (buildResult.scriptHash) {
373
387
  const policyId = buildResult.scriptHash;
374
388
  const updates = {};
375
- // CIP-14 asset fingerprint for the first minted asset. The unit is always a
376
- // full policyId+assetName here: bare names were expanded before the build and
377
- // the BUG 9 prefix check rejected everything else (a 56-hex unit is an empty
378
- // asset name, not a bare 28-byte name).
389
+ // Fingerprint of the first minted asset. The policy id is taken from the unit, not from
390
+ // buildResult.scriptHash: a per-action policy may differ from the top-level script.
379
391
  if (parsedMintActions.length > 0) {
380
392
  const firstAssetUnit = parsedMintActions[0].assetUnit;
393
+ const firstPolicyId = firstAssetUnit.slice(0, const_1.POLICY_ID_HEX_LENGTH);
381
394
  const assetNameHex = firstAssetUnit.slice(const_1.POLICY_ID_HEX_LENGTH);
382
- buildResult.fingerprint = (0, mappers_1.computeCip14Fingerprint)(policyId, assetNameHex);
395
+ buildResult.fingerprint = (0, mappers_1.computeCip14Fingerprint)(firstPolicyId, assetNameHex);
383
396
  updates.fingerprint = buildResult.fingerprint;
384
397
  }
385
- // lockOnScript: persist the derived script address on the build record (only when scriptParams were applied)
398
+ // lockOnScript: persist the derived script address on the build record
386
399
  if (lockOnScript && scriptParams && scriptParams.length > 0) {
387
400
  buildResult.scriptAddress = (0, mappers_1.scriptHashToEnterpriseAddress)(policyId, (0, server_1.getCardanoClient)().network);
388
401
  updates.scriptAddress = buildResult.scriptAddress;
@@ -395,36 +408,27 @@ module.exports = (srv) => {
395
408
  return buildResult;
396
409
  });
397
410
  });
398
- /**
399
- * Build a Plutus spending transaction (consume UTxO at script address)
400
- * @param req - CDS request object (with senderAddress, recipientAddress, lovelaceAmount, validatorScript, scriptTxHash, scriptOutputIndex, redeemerJson, datumJson, changeAddress)
401
- * @returns {TransactionBuild} Transaction build details
402
- */
411
+ // BuildPlutusSpendTransaction — consume a UTxO at a script address, optionally minting too.
403
412
  srv.on('BuildPlutusSpendTransaction', async (req) => {
404
413
  const { senderAddress, recipientAddress, lovelaceAmount, validatorScript, scriptTxHash, scriptOutputIndex, redeemerJson, datumJson, requiredSignersJson, scriptParamsJson, inlineDatumJson, lockOnScript, forceInputsJson, extraOutputsJson, mintActionsJson, mintingPolicyScript, mintRedeemerJson, referenceInputsJson, referenceScriptHex, validityStartMs, validityEndMs } = req.data;
405
- // Validate inputs
406
414
  const errors = (0, validators_1.validateTransactionInputs)({ senderAddress, recipientAddress, lovelaceAmount, validatorScript, scriptTxHash, scriptOutputIndex, redeemerJson, datumJson, referenceScriptHex, validityStartMs, validityEndMs }, ['senderAddress', 'recipientAddress', 'lovelaceAmount', 'validatorScript', 'scriptTxHash', 'redeemerJson']);
407
415
  (0, errors_1.throwIfValidationErrors)(req, 'BuildPlutusSpendTransaction', errors);
408
416
  if (req.data.changeAddress && !(0, validators_1.isValidBech32Address)(req.data.changeAddress)) {
409
417
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', 'Invalid changeAddress format', 'changeAddress');
410
418
  }
411
- // Validate scriptOutputIndex separately (it's a number, not caught by required-fields check for empty string)
419
+ // A number: not covered by the required-fields check
412
420
  if (scriptOutputIndex === undefined || scriptOutputIndex === null) {
413
421
  return (0, errors_1.rejectMissing)(req, 'BuildPlutusSpendTransaction', 'scriptOutputIndex');
414
422
  }
415
- // Parse redeemer JSON
416
423
  const parsedRedeemer = JSON.parse(redeemerJson);
417
- // Parse optional datum JSON
418
424
  const parsedDatum = datumJson ? JSON.parse(datumJson) : undefined;
419
- // Parse and validate optional requiredSignersJson
420
425
  const requiredSignersResult = (0, tx_request_parsers_1.parseRequiredSigners)(requiredSignersJson);
421
426
  if (requiredSignersResult.error)
422
427
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', requiredSignersResult.error, 'requiredSignersJson');
423
428
  const requiredSigners = requiredSignersResult.parsed;
424
- // Parse and validate optional scriptParamsJson
425
429
  let scriptParams;
426
430
  if (scriptParamsJson) {
427
- const jsonResult = (0, validators_1.validateJsonWithLimits)(scriptParamsJson, 'scriptParamsJson');
431
+ const jsonResult = (0, validators_1.validatePlutusJson)(scriptParamsJson, 'scriptParamsJson');
428
432
  if (!jsonResult.valid)
429
433
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', jsonResult.error, 'scriptParamsJson');
430
434
  scriptParams = jsonResult.parsed;
@@ -432,35 +436,34 @@ module.exports = (srv) => {
432
436
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', 'scriptParamsJson must be a JSON array', 'scriptParamsJson');
433
437
  }
434
438
  }
435
- // Parse and validate optional inlineDatumJson
436
439
  let inlineDatum;
437
440
  if (inlineDatumJson) {
438
- const jsonResult = (0, validators_1.validateJsonWithLimits)(inlineDatumJson, 'inlineDatumJson');
441
+ const jsonResult = (0, validators_1.validatePlutusJson)(inlineDatumJson, 'inlineDatumJson');
439
442
  if (!jsonResult.valid)
440
443
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', jsonResult.error, 'inlineDatumJson');
441
444
  inlineDatum = jsonResult.parsed;
442
445
  }
443
- // Validate lockOnScript requires scriptParamsJson
444
446
  if (lockOnScript && (!scriptParams || scriptParams.length === 0)) {
445
447
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', 'lockOnScript requires scriptParamsJson to derive script address', 'lockOnScript');
446
448
  }
447
- // Parse and validate optional forceInputsJson
448
449
  const forceInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(forceInputsJson, 'forceInputsJson');
449
450
  if (forceInputsResult.error)
450
451
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', forceInputsResult.error, 'forceInputsJson');
451
452
  const forceInputs = forceInputsResult.parsed;
452
- // Parse and validate optional referenceInputsJson (CIP-31)
453
+ const protectInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(req.data.protectInputsJson, 'protectInputsJson');
454
+ if (protectInputsResult.error)
455
+ return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', protectInputsResult.error, 'protectInputsJson');
456
+ const protectInputs = protectInputsResult.parsed;
457
+ // CIP-31 reference inputs
453
458
  const refInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(referenceInputsJson, 'referenceInputsJson');
454
459
  if (refInputsResult.error)
455
460
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', refInputsResult.error, 'referenceInputsJson');
456
461
  const referenceInputs = refInputsResult.parsed;
457
- // Parse and validate optional extraOutputsJson
458
462
  const extraOutputsResult = (0, tx_request_parsers_1.parseExtraOutputs)(extraOutputsJson);
459
463
  if (extraOutputsResult.error)
460
464
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', extraOutputsResult.error, 'extraOutputsJson');
461
465
  const extraOutputs = extraOutputsResult.parsed;
462
- // FR-1: Optional combined spend+mint parameters. mintActionsJson triggers the combined flow;
463
- // mintingPolicyScript is required alongside it. mintRedeemerJson is optional.
466
+ // Optional combined spend+mint parameters
464
467
  let parsedMintActions;
465
468
  let parsedMintRedeemer;
466
469
  if (mintActionsJson) {
@@ -473,7 +476,7 @@ module.exports = (srv) => {
473
476
  if (!Array.isArray(mintJson.parsed)) {
474
477
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', 'mintActionsJson must be a JSON array', 'mintActionsJson');
475
478
  }
476
- parsedMintActions = mintJson.parsed.map((rawAction) => {
479
+ parsedMintActions = mintJson.parsed.map((rawAction, actionIndex) => {
477
480
  if (!rawAction || typeof rawAction !== 'object') {
478
481
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', 'Each mint action must be an object with assetUnit and quantity', 'mintActionsJson');
479
482
  }
@@ -484,21 +487,47 @@ module.exports = (srv) => {
484
487
  if (typeof action.assetUnit !== 'string') {
485
488
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', 'Each mint action must have assetUnit string', 'mintActionsJson');
486
489
  }
487
- // same rule as BuildMintTransaction: full policyId+assetName unit, OR a bare
488
- // assetName hex destined for policyId expansion (only possible when the policy
489
- // is the script-params-applied validator — see expansion below)
490
- const bareAssetNameForExpansion = !!scriptParamsJson &&
491
- mintingPolicyScript === validatorScript &&
490
+ // Optional per-action mintingPolicyScript + redeemerJson (same rules as BuildMintTransaction)
491
+ const policyFields = (0, tx_request_parsers_1.parseMintActionPolicyFields)(action, actionIndex);
492
+ if (policyFields.error) {
493
+ return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', policyFields.error, 'mintActionsJson');
494
+ }
495
+ let actionPolicyId;
496
+ if (policyFields.script) {
497
+ try {
498
+ actionPolicyId = cardano_ledger_ts_1.Script.fromCbor(Buffer.from(policyFields.script, 'hex')).hash.toString();
499
+ }
500
+ catch (err) {
501
+ const errMsg = err instanceof Error ? err.message : String(err);
502
+ return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', `mintActions[${actionIndex}].mintingPolicyScript is not a valid Plutus script: ${errMsg}`, 'mintActionsJson');
503
+ }
504
+ }
505
+ const bareAssetNameForExpansion = ((!!scriptParamsJson && mintingPolicyScript === validatorScript) || !!actionPolicyId) &&
492
506
  action.assetUnit.length < const_1.MIN_FULL_ASSET_UNIT_LENGTH &&
493
507
  action.assetUnit.length % 2 === 0 &&
494
508
  /^[0-9a-fA-F]*$/.test(action.assetUnit);
495
509
  if (!(0, validators_1.isAssetUnit)(action.assetUnit) && !bareAssetNameForExpansion) {
496
- return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', `Invalid assetUnit: "${action.assetUnit}" — must be policyId+assetName hex (or a bare assetName hex when scriptParamsJson is set and the policy equals the validator)`, 'mintActionsJson');
510
+ return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', `Invalid assetUnit: "${action.assetUnit}" — must be policyId+assetName hex (or a bare assetName hex when a per-action mintingPolicyScript is set, or scriptParamsJson is set and the policy equals the validator)`, 'mintActionsJson');
511
+ }
512
+ let assetUnit = action.assetUnit;
513
+ if (actionPolicyId) {
514
+ if (assetUnit.length < const_1.MIN_FULL_ASSET_UNIT_LENGTH) {
515
+ assetUnit = actionPolicyId + assetUnit;
516
+ }
517
+ else if (!assetUnit.toLowerCase().startsWith(actionPolicyId)) {
518
+ return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', `mintActions[${actionIndex}].assetUnit "${assetUnit}" does not start with its own policy id ${actionPolicyId}`, 'mintActionsJson');
519
+ }
497
520
  }
498
- return { assetUnit: action.assetUnit, quantity: BigInt(action.quantity) };
521
+ return {
522
+ assetUnit,
523
+ quantity: BigInt(action.quantity),
524
+ ...(typeof action.redeemer === 'number' ? { redeemer: action.redeemer } : {}),
525
+ ...(policyFields.script ? { mintingPolicyScript: policyFields.script } : {}),
526
+ ...(policyFields.redeemer !== undefined ? { redeemerJson: policyFields.redeemer } : {})
527
+ };
499
528
  });
500
529
  if (mintRedeemerJson) {
501
- const mrJson = (0, validators_1.validateJsonWithLimits)(mintRedeemerJson, 'mintRedeemerJson');
530
+ const mrJson = (0, validators_1.validatePlutusJson)(mintRedeemerJson, 'mintRedeemerJson');
502
531
  if (!mrJson.valid)
503
532
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', mrJson.error, 'mintRedeemerJson');
504
533
  parsedMintRedeemer = mrJson.parsed;
@@ -509,7 +538,6 @@ module.exports = (srv) => {
509
538
  }
510
539
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
511
540
  logger.debug({ senderAddress, recipientAddress, lovelaceAmount, scriptTxHash, scriptOutputIndex }, 'Building Plutus spending transaction');
512
- // Apply script parameters if provided (for parameterized validators)
513
541
  let finalValidatorScript = validatorScript;
514
542
  if (scriptParams && scriptParams.length > 0) {
515
543
  try {
@@ -520,8 +548,8 @@ module.exports = (srv) => {
520
548
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', `Failed to apply script parameters: ${errMsg}`, 'scriptParamsJson');
521
549
  }
522
550
  }
523
- // FR-1: when the mint policy is byte-equal to the validator (multi-purpose script),
524
- // re-use the script-params-applied validator hex. Otherwise pass the policy through unchanged.
551
+ // A mint policy byte-equal to the validator (multi-purpose script) reuses the
552
+ // params-applied validator hex; any other policy passes through unchanged.
525
553
  let finalMintingPolicyScript;
526
554
  if (parsedMintActions) {
527
555
  finalMintingPolicyScript = (mintingPolicyScript === validatorScript)
@@ -542,21 +570,20 @@ module.exports = (srv) => {
542
570
  }
543
571
  }
544
572
  }
545
- // BUG 9 fix: same policyId-prefix check as BuildMintTransaction — the builder
546
- // mints every action under the mint script's hash and parseAssetUnit silently
547
- // discards the unit's first 56 hex chars, so a mismatched prefix would mint a
548
- // truncated asset name.
573
+ // Policy-id prefix check as in BuildMintTransaction: the builder discards the unit's
574
+ // first 56 hex chars, so a mismatched prefix would mint a truncated asset name.
549
575
  if (finalMintingPolicyScript) {
550
576
  let mintPolicyId;
551
577
  try {
552
578
  mintPolicyId = cardano_ledger_ts_1.Script.fromCbor(Buffer.from(finalMintingPolicyScript, 'hex')).hash.toString();
553
579
  }
554
580
  catch {
555
- // invalid script CBOR — skip the prefix check; the builder rejects it with its own message
581
+ // Invalid script CBOR: skip the prefix check, the builder rejects it with its own message.
556
582
  }
557
583
  if (mintPolicyId) {
558
584
  const policyId = mintPolicyId;
559
- const mismatch = parsedMintActions.find((action) => !action.assetUnit.toLowerCase().startsWith(policyId));
585
+ // Actions with a per-action script were already checked against that policy id.
586
+ const mismatch = parsedMintActions.find((action) => !action.mintingPolicyScript && !action.assetUnit.toLowerCase().startsWith(policyId));
560
587
  if (mismatch) {
561
588
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', `assetUnit "${mismatch.assetUnit}" does not start with the minting policy id ${policyId} — pass the full unit as policyId+assetName (asset names longer than 28 bytes cannot be passed bare)`, 'mintActionsJson');
562
589
  }
@@ -577,6 +604,7 @@ module.exports = (srv) => {
577
604
  requiredSigners,
578
605
  inlineDatum,
579
606
  forceInputs,
607
+ protectInputs,
580
608
  referenceInputs,
581
609
  extraOutputs,
582
610
  mintActions: parsedMintActions,
@@ -591,12 +619,13 @@ module.exports = (srv) => {
591
619
  delete cleanData.inlineDatumJson;
592
620
  delete cleanData.lockOnScript;
593
621
  delete cleanData.forceInputsJson;
622
+ delete cleanData.protectInputsJson;
594
623
  delete cleanData.referenceInputsJson;
595
624
  delete cleanData.extraOutputsJson;
596
625
  delete cleanData.mintActionsJson;
597
626
  delete cleanData.mintRedeemerJson;
598
627
  delete cleanData.referenceScriptHex;
599
- // lockOnScript: route continuing output to enterprise script address
628
+ // lockOnScript: route the continuing output to the enterprise script address
600
629
  if (lockOnScript && scriptParams && scriptParams.length > 0) {
601
630
  try {
602
631
  const appliedScript = cardano_ledger_ts_1.Script.fromCbor(Buffer.from(finalValidatorScript, 'hex'));
@@ -611,7 +640,7 @@ module.exports = (srv) => {
611
640
  }
612
641
  }
613
642
  const buildResult = await (0, server_1.getCardanoIndexer)().indexPlutusSpendBuildResult(db, cleanData);
614
- // lockOnScript: persist the derived script address on the build record (only when scriptParams were applied)
643
+ // lockOnScript: persist the derived script address on the build record
615
644
  if (lockOnScript && scriptParams && scriptParams.length > 0 && buildResult.scriptHash && buildResult.id) {
616
645
  const scriptAddr = (0, mappers_1.scriptHashToEnterpriseAddress)(buildResult.scriptHash, (0, server_1.getCardanoClient)().network);
617
646
  buildResult.scriptAddress = scriptAddr;
@@ -621,17 +650,130 @@ module.exports = (srv) => {
621
650
  return buildResult;
622
651
  });
623
652
  });
624
- /**
625
- * Get build details for previously built transaction
626
- * @param req - CDS request object (with buildId)
627
- * @returns {TransactionBuild} Transaction build details
628
- */
653
+ // BuildPlutusTransaction — several script UTxOs in one transaction, each with its own redeemer.
654
+ srv.on('BuildPlutusTransaction', async (req) => {
655
+ const { senderAddress, changeAddress, scriptInputsJson, outputsJson, referenceInputsJson, forceInputsJson, protectInputsJson, withdrawalsJson, certificatesJson, requiredSignersJson, mintActionsJson, validityStartMs, validityEndMs } = req.data;
656
+ const action = 'BuildPlutusTransaction';
657
+ const errors = (0, validators_1.validateTransactionInputs)({ senderAddress, validityStartMs, validityEndMs }, ['senderAddress']);
658
+ (0, errors_1.throwIfValidationErrors)(req, action, errors);
659
+ if (changeAddress && !(0, validators_1.isValidBech32Address)(changeAddress)) {
660
+ return (0, errors_1.rejectInvalid)(req, action, 'Invalid changeAddress format', 'changeAddress');
661
+ }
662
+ const scriptInputsResult = (0, tx_request_parsers_1.parseScriptInputs)(scriptInputsJson);
663
+ if (scriptInputsResult.error)
664
+ return (0, errors_1.rejectInvalid)(req, action, scriptInputsResult.error, 'scriptInputsJson');
665
+ if (!outputsJson)
666
+ return (0, errors_1.rejectMissing)(req, action, 'outputsJson');
667
+ const outputsResult = (0, tx_request_parsers_1.parseOutputList)(outputsJson, 'outputsJson');
668
+ if (outputsResult.error)
669
+ return (0, errors_1.rejectInvalid)(req, action, outputsResult.error, 'outputsJson');
670
+ if (!outputsResult.parsed)
671
+ return (0, errors_1.rejectInvalid)(req, action, 'outputsJson must list at least one output', 'outputsJson');
672
+ const refInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(referenceInputsJson, 'referenceInputsJson');
673
+ if (refInputsResult.error)
674
+ return (0, errors_1.rejectInvalid)(req, action, refInputsResult.error, 'referenceInputsJson');
675
+ const forceInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(forceInputsJson, 'forceInputsJson');
676
+ if (forceInputsResult.error)
677
+ return (0, errors_1.rejectInvalid)(req, action, forceInputsResult.error, 'forceInputsJson');
678
+ const protectInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(protectInputsJson, 'protectInputsJson');
679
+ if (protectInputsResult.error)
680
+ return (0, errors_1.rejectInvalid)(req, action, protectInputsResult.error, 'protectInputsJson');
681
+ const withdrawalsResult = (0, tx_request_parsers_1.parseWithdrawals)(withdrawalsJson);
682
+ if (withdrawalsResult.error)
683
+ return (0, errors_1.rejectInvalid)(req, action, withdrawalsResult.error, 'withdrawalsJson');
684
+ const certificatesResult = (0, tx_request_parsers_1.parseCertificates)(certificatesJson);
685
+ if (certificatesResult.error)
686
+ return (0, errors_1.rejectInvalid)(req, action, certificatesResult.error, 'certificatesJson');
687
+ const signersResult = (0, tx_request_parsers_1.parseRequiredSigners)(requiredSignersJson);
688
+ if (signersResult.error)
689
+ return (0, errors_1.rejectInvalid)(req, action, signersResult.error, 'requiredSignersJson');
690
+ const mintResult = (0, tx_request_parsers_1.parsePolicyMintActions)(mintActionsJson);
691
+ if (mintResult.error)
692
+ return (0, errors_1.rejectInvalid)(req, action, mintResult.error, 'mintActionsJson');
693
+ // Script params are applied here, so the builder sees the final validators
694
+ const scriptInputs = [];
695
+ for (const [i, si] of scriptInputsResult.parsed.entries()) {
696
+ let validatorScript = si.validatorScript;
697
+ if (validatorScript && si.scriptParams) {
698
+ try {
699
+ validatorScript = (0, tx_build_helper_1.applyScriptParameters)(validatorScript, si.scriptParams);
700
+ }
701
+ catch (err) {
702
+ const errMsg = err instanceof Error ? err.message : String(err);
703
+ return (0, errors_1.rejectInvalid)(req, action, `scriptInputs[${i}]: failed to apply script parameters: ${errMsg}`, 'scriptInputsJson');
704
+ }
705
+ }
706
+ scriptInputs.push({
707
+ txHash: si.txHash,
708
+ outputIndex: si.outputIndex,
709
+ ...(validatorScript ? { validatorScript } : { referenceScript: si.referenceScript }),
710
+ redeemer: si.redeemer,
711
+ ...(si.redeemerCbor ? { redeemerCbor: si.redeemerCbor } : {}),
712
+ ...(si.datum !== undefined ? { datum: si.datum } : {}),
713
+ ...(si.datumCbor ? { datumCbor: si.datumCbor } : {}),
714
+ });
715
+ }
716
+ // Same for the staking scripts of withdrawals and certificates
717
+ const stakingWitness = (w, at, field) => {
718
+ let stakingScript = w.stakingScript;
719
+ if (stakingScript && w.scriptParams) {
720
+ try {
721
+ stakingScript = (0, tx_build_helper_1.applyScriptParameters)(stakingScript, w.scriptParams);
722
+ }
723
+ catch (err) {
724
+ const errMsg = err instanceof Error ? err.message : String(err);
725
+ return { error: (0, errors_1.rejectInvalid)(req, action, `${at}: failed to apply script parameters: ${errMsg}`, field) };
726
+ }
727
+ }
728
+ return {
729
+ parsed: {
730
+ ...(stakingScript ? { stakingScript } : {}),
731
+ ...(w.referenceScript ? { referenceScript: w.referenceScript } : {}),
732
+ ...(w.redeemer !== undefined ? { redeemer: w.redeemer } : {}),
733
+ ...(w.redeemerCbor ? { redeemerCbor: w.redeemerCbor } : {}),
734
+ },
735
+ };
736
+ };
737
+ const withdrawals = [];
738
+ for (const [i, w] of (withdrawalsResult.parsed ?? []).entries()) {
739
+ const witness = stakingWitness(w, `withdrawals[${i}]`, 'withdrawalsJson');
740
+ if ('error' in witness)
741
+ return witness.error;
742
+ withdrawals.push({ rewardAddress: w.rewardAddress, lovelace: w.lovelace, ...witness.parsed });
743
+ }
744
+ const certificates = [];
745
+ for (const [i, c] of (certificatesResult.parsed ?? []).entries()) {
746
+ const witness = stakingWitness(c, `certificates[${i}]`, 'certificatesJson');
747
+ if ('error' in witness)
748
+ return witness.error;
749
+ certificates.push({ type: c.type, stakeAddress: c.stakeAddress, ...(c.deposit ? { deposit: c.deposit } : {}), ...witness.parsed });
750
+ }
751
+ const buildReq = {
752
+ network: (0, server_1.getCardanoClient)().network,
753
+ senderAddress,
754
+ ...(changeAddress ? { changeAddress } : {}),
755
+ scriptInputs,
756
+ outputs: outputsResult.parsed,
757
+ referenceInputs: refInputsResult.parsed,
758
+ forceInputs: forceInputsResult.parsed,
759
+ protectInputs: protectInputsResult.parsed,
760
+ ...(withdrawals.length > 0 ? { withdrawals } : {}),
761
+ ...(certificates.length > 0 ? { certificates } : {}),
762
+ requiredSigners: signersResult.parsed,
763
+ mintActions: mintResult.parsed,
764
+ validityStartMs,
765
+ validityEndMs,
766
+ };
767
+ return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
768
+ logger.debug({ senderAddress, scriptInputs: scriptInputs.length, outputs: buildReq.outputs.length }, 'Building multi-script Plutus transaction');
769
+ return (0, server_1.getCardanoIndexer)().indexPlutusBuildResult(db, buildReq);
770
+ });
771
+ });
772
+ // GetBuildDetails — an existing transaction build by id.
629
773
  srv.on('GetBuildDetails', async (req) => {
630
774
  const { buildId } = req.data;
631
- // Validate inputs
632
775
  const errors = (0, validators_1.validateTransactionInputs)({ buildId }, ['buildId']);
633
776
  (0, errors_1.throwIfValidationErrors)(req, 'GetBuildDetails', errors);
634
- // handle the request / fetching the build details
635
777
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
636
778
  const existing = await db.run(SELECT.one.from(TransactionBuilds).where({ id: buildId }));
637
779
  if (!existing)
@@ -639,13 +781,8 @@ module.exports = (srv) => {
639
781
  return existing;
640
782
  });
641
783
  });
642
- /**
643
- * Set up a collateral UTxO for Plutus transactions.
644
- * Checks if the address already has >= 2 UTxOs with >= 5 ADA each.
645
- * If not, builds a self-send transaction to create a 5 ADA collateral UTxO.
646
- * @param req - CDS request object (with address)
647
- * @returns {TransactionBuild} Transaction build details for the collateral setup
648
- */
784
+ // SetCollateral — collateral is available when the builders would find it: an ADA-only UTxO of
785
+ // >= 5 ADA without a reference script, plus another UTxO to fund with; otherwise a self-send creates one.
649
786
  srv.on('SetCollateral', async (req) => {
650
787
  const { address } = req.data;
651
788
  if (!address)
@@ -654,17 +791,15 @@ module.exports = (srv) => {
654
791
  return (0, errors_1.rejectInvalid)(req, 'SetCollateral', 'Invalid Bech32 address format', 'address');
655
792
  }
656
793
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
657
- // Inside handleRequest: getCardanoClient() throwing (e.g. uninitialized after
658
- // a failed bootstrap → ProviderUnavailableError) and backend errors from
659
- // getAddressUtxos both get caught and properly mapped via mapError.
660
- // Use rejectInvalid (throws BackendError 400) instead of req.reject so
661
- // mapError sees a typed BackendError and preserves the 400 status.
662
- const utxos = await (0, server_1.getCardanoClient)().getAddressUtxos(address);
794
+ // Inside handleRequest use rejectInvalid (typed BackendError 400), not req.reject,
795
+ // so mapError preserves the status.
796
+ const ledger = await (0, server_1.getCardanoIndexer)().resolveAddressUtxos(db, address);
797
+ const utxos = (0, server_1.getCardanoClient)().pendingSpends?.apply(address, ledger) ?? ledger;
663
798
  if (utxos.length === 0) {
664
799
  return (0, errors_1.rejectInvalid)(req, 'SetCollateral', 'No UTxOs found at address', 'address');
665
800
  }
666
- const qualifyingUtxos = utxos.filter(u => (0, tx_build_helper_1.getLovelace)(u) >= const_1.COLLATERAL_LOVELACE);
667
- if (qualifyingUtxos.length >= 2) {
801
+ const qualifyingUtxos = utxos.filter(u => (0, tx_build_helper_1.isCollateralCandidate)(u) && (0, tx_build_helper_1.getLovelace)(u) >= const_1.COLLATERAL_LOVELACE);
802
+ if (qualifyingUtxos.length >= 1 && utxos.length >= 2) {
668
803
  return {
669
804
  id: cds_1.default.utils.uuid(),
670
805
  network: (0, server_1.getCardanoClient)().network,
@@ -687,32 +822,24 @@ module.exports = (srv) => {
687
822
  return { ...result, collateralAvailable: false };
688
823
  });
689
824
  });
690
- /**
691
- * Submit signed transaction built previously
692
- * Handler validates, checks build exists, submits to blockchain, delegates persistence to indexer
693
- * @param req - CDS request object (with buildId, signedTxCbor)
694
- * @returns {TransactionSubmission} Transaction submission details
695
- */
825
+ // SubmitTransaction — submit the signed CBOR of a previous build.
696
826
  srv.on('SubmitTransaction', async (req) => {
697
827
  logger.debug('SubmitTransaction Action handler called');
698
828
  const { buildId, signedTxCbor } = req.data;
699
- // Validate inputs (includes CBOR format validation)
700
829
  const errors = (0, validators_1.validateTransactionInputs)({ buildId, signedTxCbor }, ['buildId', 'signedTxCbor']);
701
830
  (0, errors_1.throwIfValidationErrors)(req, 'SubmitTransaction', errors);
702
831
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
703
832
  logger.debug({ buildId }, 'Submitting signed transaction');
704
- // Validate build exists
705
833
  const existing = await db.run(SELECT.one.from(TransactionBuilds).where({ id: buildId }));
706
834
  if (!existing)
707
835
  throw new errors_1.NotFoundError(`Build '${buildId}'`);
708
- // Verify the signed CBOR is for this build (audit-trail integrity)
836
+ // The signed CBOR must belong to this build (audit-trail integrity)
709
837
  const signedTxHash = (0, tx_build_helper_1.getTxHashFromCbor)(signedTxCbor);
710
838
  if (signedTxHash !== existing.txBodyHash) {
711
839
  return (0, errors_1.rejectInvalid)(req, 'SubmitTransaction', `signedTxCbor hash '${signedTxHash}' does not match build txBodyHash '${existing.txBodyHash}'`, 'signedTxCbor');
712
840
  }
713
- // Use txBodyHash from build
714
841
  const txHash = existing.txBodyHash;
715
- // Two-phase submit: persist with 'pending', then submit to blockchain
842
+ // Two-phase submit: persist as 'pending', then submit
716
843
  const submissionRecord = await (0, server_1.getCardanoIndexer)().persistTransactionSubmission(db, {
717
844
  signedTxCbor,
718
845
  txHash,
@@ -723,9 +850,8 @@ module.exports = (srv) => {
723
850
  logger.info({ txHash }, 'Transaction submitted to blockchain');
724
851
  await (0, server_1.getCardanoIndexer)().updateSubmissionStatus(db, submissionRecord.id, 'submitted');
725
852
  submissionRecord.status = 'submitted';
726
- // Invalidate stale UTxO cache: spent input refs + output addresses from
727
- // the signed CBOR, plus the build's sender address. Best-effort — a
728
- // failure here must not fail the already-successful submit.
853
+ // Best-effort UTxO cache invalidation (spent inputs, output addresses, sender);
854
+ // a failure must not fail the successful submit.
729
855
  try {
730
856
  const addrBuild = await db.run(SELECT.one.from(AddressTransactionBuilds).where({ txBuild_id: buildId }));
731
857
  await (0, server_1.getCardanoIndexer)().invalidateUtxoCacheForTx(db, (0, tx_build_helper_1.extractTxCacheTargets)(signedTxCbor), addrBuild?.address_address ? [addrBuild.address_address] : []);
@@ -743,29 +869,20 @@ module.exports = (srv) => {
743
869
  return submissionRecord;
744
870
  });
745
871
  });
746
- /**
747
- * Submit signed transaction without prior build
748
- * Handler validates, submits to blockchain, delegates persistence to indexer
749
- * Two-phase: persist with 'pending' first, then update to 'submitted' or 'failed'
750
- * @param req - CDS request object (with signedTxCbor, network)
751
- * @returns {TransactionSubmission} Transaction submission details
752
- */
872
+ // SubmitSignedTransaction — submit externally built signed CBOR (no prior build).
753
873
  srv.on('SubmitSignedTransaction', async (req) => {
754
874
  logger.debug('SubmitSignedTransaction Action handler called');
755
875
  const { signedTxCbor, network } = req.data;
756
- // Validate inputs (includes CBOR format validation)
757
876
  const errors = (0, validators_1.validateTransactionInputs)({ signedTxCbor }, ['signedTxCbor']);
758
877
  (0, errors_1.throwIfValidationErrors)(req, 'SubmitSignedTransaction', errors);
759
878
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
760
- // The declared network param was previously ignored — verify it against the
761
- // configured network so a caller targeting the wrong deployment gets a clear 400.
879
+ // A caller targeting the wrong deployment gets a clear 400
762
880
  const configuredNetwork = (0, server_1.getCardanoClient)().network;
763
881
  if (network && network !== configuredNetwork) {
764
882
  return (0, errors_1.rejectInvalid)(req, 'SubmitSignedTransaction', `network '${network}' does not match this deployment's network '${configuredNetwork}'`, 'network');
765
883
  }
766
- // Extract txHash from signed CBOR
767
884
  const txHash = (0, tx_build_helper_1.getTxHashFromCbor)(signedTxCbor);
768
- // Two-phase submit: persist with 'pending', then submit to blockchain
885
+ // Two-phase submit: persist as 'pending', then submit
769
886
  const submissionRecord = await (0, server_1.getCardanoIndexer)().persistTransactionSubmission(db, {
770
887
  signedTxCbor,
771
888
  txHash,
@@ -776,7 +893,7 @@ module.exports = (srv) => {
776
893
  logger.info({ txHash }, 'External transaction submitted');
777
894
  await (0, server_1.getCardanoIndexer)().updateSubmissionStatus(db, submissionRecord.id, 'submitted');
778
895
  submissionRecord.status = 'submitted';
779
- // Invalidate stale UTxO cache (spent inputs + output addresses) — best-effort
896
+ // Best-effort UTxO cache invalidation
780
897
  try {
781
898
  await (0, server_1.getCardanoIndexer)().invalidateUtxoCacheForTx(db, (0, tx_build_helper_1.extractTxCacheTargets)(signedTxCbor));
782
899
  }
@@ -793,24 +910,18 @@ module.exports = (srv) => {
793
910
  return submissionRecord;
794
911
  });
795
912
  });
796
- /**
797
- * Check submission status (bound action on TransactionSubmissions)
798
- * @flow.status validates @from: [#submitted] automatically (409 if wrong state)
799
- * Queries blockchain for transaction confirmation and updates status accordingly
800
- * @param req - CDS request with entity key in params
801
- * @returns {TransactionSubmission} The updated transaction submission status
802
- */
913
+ // CheckSubmissionStatus — bound action; the @from: [#submitted] state gate is enforced by CAP.
803
914
  srv.on('CheckSubmissionStatus', async (req) => {
804
915
  logger.debug('CheckSubmissionStatus Action handler called');
805
916
  const { id: submissionId } = req.params[0];
806
- // @from: [#submitted] validated by framework — no manual status check needed
807
917
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
808
918
  const submission = await db.run(SELECT.one.from(TransactionSubmissions).where({ id: submissionId }));
809
919
  if (!submission)
810
920
  throw new errors_1.NotFoundError(`Submission '${submissionId}'`);
811
- // Query blockchain for confirmation
812
921
  try {
813
- const txDetails = await (0, server_1.getCardanoClient)().getTransaction(submission.txHash);
922
+ // the local index first (filled by the crawler), then the backends
923
+ const txDetails = await (0, server_1.getCardanoIndexer)().findIndexedTransaction(db, submission.txHash)
924
+ ?? await (0, server_1.getCardanoClient)().getTransaction(submission.txHash);
814
925
  if (txDetails) {
815
926
  await db.run(UPDATE.entity(TransactionSubmissions)
816
927
  .set({ status: 'confirmed' })
@@ -822,11 +933,10 @@ module.exports = (srv) => {
822
933
  catch (err) {
823
934
  const errMsg = err instanceof Error ? err.message : String(err);
824
935
  if (err instanceof errors_1.NotFoundError || err?.statusCode === 404) {
825
- // Transaction genuinely not yet confirmed on chain
826
936
  logger.debug({ submissionId, txHash: submission.txHash }, 'Transaction not yet confirmed on chain');
827
937
  }
828
938
  else {
829
- // Provider error — don't mask as "pending", let caller know
939
+ // A provider error must not be masked as "pending"
830
940
  logger.warn({ submissionId, txHash: submission.txHash, error: errMsg }, 'Failed to check transaction confirmation status');
831
941
  throw err;
832
942
  }
@@ -834,28 +944,19 @@ module.exports = (srv) => {
834
944
  return submission;
835
945
  });
836
946
  });
837
- /**
838
- * Get all existing transaction builds by address
839
- * @param req - CDS request object (with address)
840
- * @returns {AddressTransactionBuilds} Address transaction build associations
841
- */
947
+ // GetTransactionBuildsByAddress — address ↔ build associations.
842
948
  srv.on('GetTransactionBuildsByAddress', async (req) => {
843
949
  logger.debug('GetTransactionBuildsByAddress Action handler called');
844
950
  const { address } = req.data;
845
- // Validate inputs
846
951
  if (!address)
847
952
  return (0, errors_1.rejectMissing)(req, 'GetTransactionBuildsByAddress', 'address');
848
953
  if (!(0, validators_1.isValidBech32Address)(address))
849
954
  return (0, errors_1.rejectInvalid)(req, 'GetTransactionBuildsByAddress', 'Invalid bech32 address format', 'address');
850
- // Fetch the address-build associations
851
955
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
852
956
  return db.run(SELECT.from(AddressTransactionBuilds).where({ address_address: address }));
853
957
  });
854
958
  });
855
- /**
856
- * Derive the enterprise script address + script hash for a validator script,
857
- * optionally after applying PlutusData parameters. No transaction is built.
858
- */
959
+ // DeriveScriptAddress — enterprise address + hash of a validator, optionally parameterized.
859
960
  srv.on('DeriveScriptAddress', async (req) => {
860
961
  const { validatorScript, scriptParamsJson, network } = req.data;
861
962
  if (!validatorScript)
@@ -865,7 +966,7 @@ module.exports = (srv) => {
865
966
  }
866
967
  let scriptParams;
867
968
  if (scriptParamsJson) {
868
- const jsonResult = (0, validators_1.validateJsonWithLimits)(scriptParamsJson, 'scriptParamsJson');
969
+ const jsonResult = (0, validators_1.validatePlutusJson)(scriptParamsJson, 'scriptParamsJson');
869
970
  if (!jsonResult.valid)
870
971
  return (0, errors_1.rejectInvalid)(req, 'DeriveScriptAddress', jsonResult.error, 'scriptParamsJson');
871
972
  if (!Array.isArray(jsonResult.parsed)) {
@@ -877,9 +978,7 @@ module.exports = (srv) => {
877
978
  return (0, errors_1.rejectInvalid)(req, 'DeriveScriptAddress', `Invalid network "${network}". Must be one of: ${VALID_DERIVE_NETWORKS.join(', ')}`, 'network');
878
979
  }
879
980
  return (0, backend_request_handler_1.handleRequest)(req, async () => {
880
- // getCardanoClient() throws ProviderUnavailableError (503) when the app context
881
- // is uninitialized. Resolving the network outside the inner CBOR try/catch
882
- // keeps that 503 distinct from the 400 used for malformed validatorScript bytes.
981
+ // Resolved outside the CBOR try/catch so an uninitialized client stays a 503, not a 400.
883
982
  const targetNetwork = network
884
983
  ? network
885
984
  : (0, server_1.getCardanoClient)().network;
@@ -897,10 +996,7 @@ module.exports = (srv) => {
897
996
  }
898
997
  });
899
998
  });
900
- /**
901
- * Extract the 28-byte payment credential (key hash or script hash) from a Bech32
902
- * Cardano address. Pure local decoding — no blockchain call.
903
- */
999
+ // ExtractPaymentKeyHash — 28-byte payment credential of a bech32 address; pure local decoding.
904
1000
  srv.on('ExtractPaymentKeyHash', async (req) => {
905
1001
  const { address } = req.data;
906
1002
  if (!address)
@@ -911,7 +1007,7 @@ module.exports = (srv) => {
911
1007
  try {
912
1008
  const decoded = bech32_1.bech32.decode(address, const_1.BECH32_MAX_LENGTH);
913
1009
  const bytes = Buffer.from(bech32_1.bech32.fromWords(decoded.words));
914
- // Cardano address: 1 header byte + 28-byte payment credential + (optional 28-byte stake credential)
1010
+ // 1 header byte + 28-byte payment credential (+ optional 28-byte stake credential)
915
1011
  if (bytes.length < 29) {
916
1012
  return (0, errors_1.rejectInvalid)(req, 'ExtractPaymentKeyHash', 'Address is too short to contain a payment credential', 'address');
917
1013
  }