@odatano/core 1.11.0 → 2.0.0-rc.10

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 (133) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +255 -0
  2. package/@cds-models/CardanoAgentService/index.js +36 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +177 -0
  4. package/@cds-models/CardanoIndexerService/index.js +27 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +693 -2172
  6. package/@cds-models/CardanoODataService/index.js +88 -390
  7. package/@cds-models/CardanoSignService/index.d.ts +448 -1576
  8. package/@cds-models/CardanoSignService/index.js +62 -293
  9. package/@cds-models/CardanoTransactionService/index.d.ts +437 -1494
  10. package/@cds-models/CardanoTransactionService/index.js +60 -271
  11. package/@cds-models/CardanoWorkerService/index.d.ts +224 -0
  12. package/@cds-models/CardanoWorkerService/index.js +32 -0
  13. package/@cds-models/_/index.d.ts +70 -40
  14. package/@cds-models/_/index.js +17 -32
  15. package/@cds-models/cds/outbox/index.d.ts +28 -0
  16. package/@cds-models/index.d.ts +225 -522
  17. package/@cds-models/index.js +35 -218
  18. package/@cds-models/odatano/cardano/index.d.ts +919 -2884
  19. package/@cds-models/odatano/cardano/index.js +115 -536
  20. package/@cds-models/sap/common/index.d.ts +196 -600
  21. package/@cds-models/sap/common/index.js +28 -269
  22. package/README.md +194 -102
  23. package/db/schema.cds +388 -1
  24. package/db/types.cds +48 -0
  25. package/package.json +48 -33
  26. package/src/index.d.ts +7 -1
  27. package/src/index.js +30 -2
  28. package/src/plugin.js +33 -20
  29. package/srv/blockchain/backends/blockfrost-backend.d.ts +21 -2
  30. package/srv/blockchain/backends/blockfrost-backend.js +69 -25
  31. package/srv/blockchain/backends/cardano-backend.d.ts +69 -0
  32. package/srv/blockchain/backends/cardano-backend.js +13 -0
  33. package/srv/blockchain/backends/koios-backend.d.ts +26 -2
  34. package/srv/blockchain/backends/koios-backend.js +148 -25
  35. package/srv/blockchain/backends/ogmios-backend.d.ts +60 -9
  36. package/srv/blockchain/backends/ogmios-backend.js +326 -10
  37. package/srv/blockchain/cardano-client.d.ts +19 -0
  38. package/srv/blockchain/cardano-client.js +36 -0
  39. package/srv/blockchain/cardano-indexer.d.ts +50 -1
  40. package/srv/blockchain/cardano-indexer.js +193 -0
  41. package/srv/blockchain/crawler/crawler.d.ts +176 -0
  42. package/srv/blockchain/crawler/crawler.js +744 -0
  43. package/srv/blockchain/crawler/hooks.d.ts +43 -0
  44. package/srv/blockchain/crawler/hooks.js +62 -0
  45. package/srv/blockchain/crawler/index.d.ts +35 -0
  46. package/srv/blockchain/crawler/index.js +168 -0
  47. package/srv/blockchain/crawler/sync-state.d.ts +106 -0
  48. package/srv/blockchain/crawler/sync-state.js +287 -0
  49. package/srv/blockchain/signing/hsm-signer.d.ts +45 -0
  50. package/srv/blockchain/signing/hsm-signer.js +8 -1
  51. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +20 -0
  52. package/srv/blockchain/transaction-building/buildooor-tx.js +104 -20
  53. package/srv/blockchain/wallet-worker/build-request.d.ts +26 -0
  54. package/srv/blockchain/wallet-worker/build-request.js +370 -0
  55. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +117 -0
  56. package/srv/blockchain/wallet-worker/confirmation-tracker.js +290 -0
  57. package/srv/blockchain/wallet-worker/index.d.ts +14 -0
  58. package/srv/blockchain/wallet-worker/index.js +80 -0
  59. package/srv/blockchain/wallet-worker/job-store.d.ts +272 -0
  60. package/srv/blockchain/wallet-worker/job-store.js +597 -0
  61. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +43 -0
  62. package/srv/blockchain/wallet-worker/lease-heartbeat.js +99 -0
  63. package/srv/blockchain/wallet-worker/signers.d.ts +57 -0
  64. package/srv/blockchain/wallet-worker/signers.js +131 -0
  65. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +145 -0
  66. package/srv/blockchain/wallet-worker/wallet-worker.js +542 -0
  67. package/srv/cardano-agent-service.cds +150 -0
  68. package/srv/cardano-agent-service.d.ts +2 -0
  69. package/srv/cardano-agent-service.js +16 -0
  70. package/srv/cardano-indexer-service.cds +106 -0
  71. package/srv/cardano-indexer-service.d.ts +2 -0
  72. package/srv/cardano-indexer-service.js +79 -0
  73. package/srv/cardano-service.js +79 -4
  74. package/srv/cardano-sign-service.cds +200 -180
  75. package/srv/cardano-tx-service.cds +32 -26
  76. package/srv/cardano-tx-service.d.ts +1 -11
  77. package/srv/cardano-tx-service.js +107 -200
  78. package/srv/cardano-worker-service.cds +125 -0
  79. package/srv/cardano-worker-service.d.ts +2 -0
  80. package/srv/cardano-worker-service.js +199 -0
  81. package/srv/server.d.ts +34 -2
  82. package/srv/server.js +246 -36
  83. package/srv/utils/agent-grants-config.d.ts +65 -0
  84. package/srv/utils/agent-grants-config.js +148 -0
  85. package/srv/utils/agent-grants.d.ts +314 -0
  86. package/srv/utils/agent-grants.js +821 -0
  87. package/srv/utils/agent-token-auth.d.ts +19 -0
  88. package/srv/utils/agent-token-auth.js +81 -0
  89. package/srv/utils/collections.d.ts +13 -0
  90. package/srv/utils/collections.js +24 -0
  91. package/srv/utils/crypto.d.ts +16 -0
  92. package/srv/utils/crypto.js +75 -0
  93. package/srv/utils/db-sanitize.d.ts +40 -0
  94. package/srv/utils/db-sanitize.js +98 -0
  95. package/srv/utils/error-codes.d.ts +6 -0
  96. package/srv/utils/error-codes.js +6 -0
  97. package/srv/utils/errors.d.ts +12 -0
  98. package/srv/utils/errors.js +45 -0
  99. package/srv/utils/liveness.d.ts +23 -0
  100. package/srv/utils/liveness.js +49 -0
  101. package/srv/utils/mappers.d.ts +27 -0
  102. package/srv/utils/mappers.js +80 -10
  103. package/srv/utils/rate-limiter.d.ts +57 -0
  104. package/srv/utils/rate-limiter.js +126 -0
  105. package/srv/utils/service-events.d.ts +26 -0
  106. package/srv/utils/service-events.js +46 -0
  107. package/srv/utils/tx-request-parsers.d.ts +71 -0
  108. package/srv/utils/tx-request-parsers.js +202 -0
  109. package/srv/utils/tx-utils.d.ts +2 -1
  110. package/srv/utils/tx-utils.js +3 -2
  111. package/srv/utils/types.d.ts +17 -1
  112. package/@cds-models/CardanoODataService/index.d.ts.map +0 -1
  113. package/@cds-models/CardanoODataService/index.js.map +0 -1
  114. package/@cds-models/CardanoODataService/index.ts +0 -776
  115. package/@cds-models/CardanoSignService/index.d.ts.map +0 -1
  116. package/@cds-models/CardanoSignService/index.js.map +0 -1
  117. package/@cds-models/CardanoSignService/index.ts +0 -569
  118. package/@cds-models/CardanoTransactionService/index.d.ts.map +0 -1
  119. package/@cds-models/CardanoTransactionService/index.js.map +0 -1
  120. package/@cds-models/CardanoTransactionService/index.ts +0 -526
  121. package/@cds-models/_/index.d.ts.map +0 -1
  122. package/@cds-models/_/index.js.map +0 -1
  123. package/@cds-models/_/index.ts +0 -96
  124. package/@cds-models/cds/outbox/index.ts +0 -27
  125. package/@cds-models/index.d.ts.map +0 -1
  126. package/@cds-models/index.js.map +0 -1
  127. package/@cds-models/index.ts +0 -245
  128. package/@cds-models/odatano/cardano/index.d.ts.map +0 -1
  129. package/@cds-models/odatano/cardano/index.js.map +0 -1
  130. package/@cds-models/odatano/cardano/index.ts +0 -789
  131. package/@cds-models/sap/common/index.d.ts.map +0 -1
  132. package/@cds-models/sap/common/index.js.map +0 -1
  133. package/@cds-models/sap/common/index.ts +0 -249
@@ -13,161 +13,10 @@ const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
13
13
  const mappers_1 = require("./utils/mappers");
14
14
  const server_1 = require("./server");
15
15
  const const_1 = require("./utils/const");
16
+ const tx_request_parsers_1 = require("./utils/tx-request-parsers");
16
17
  const VALID_DERIVE_NETWORKS = ['mainnet', 'preview', 'preprod'];
17
18
  const { SELECT, UPDATE } = cds_1.default.ql;
18
19
  const logger = cds_1.default.log('CardanoTxService');
19
- /**
20
- * Parse and validate a JSON array of UTxO refs ({txHash, outputIndex}) — the shared
21
- * shape of forceInputsJson and referenceInputsJson (CIP-31). Returns { parsed } on
22
- * success (undefined for absent/empty input → treated as no-op) or { error } on
23
- * validation failure. Error messages reference the entry name derived from fieldName.
24
- */
25
- function parseUtxoRefArray(json, fieldName) {
26
- if (!json)
27
- return { parsed: undefined };
28
- const entryName = fieldName.replace(/Json$/, '');
29
- const jsonResult = (0, validators_1.validateJsonWithLimits)(json, fieldName);
30
- if (!jsonResult.valid)
31
- return { error: jsonResult.error };
32
- if (!Array.isArray(jsonResult.parsed))
33
- return { error: `${fieldName} must be a JSON array` };
34
- if (jsonResult.parsed.length === 0)
35
- return { parsed: undefined };
36
- const refs = [];
37
- for (const rawEntry of jsonResult.parsed) {
38
- if (!rawEntry || typeof rawEntry !== 'object') {
39
- return { error: `Each ${entryName} entry must be an object with txHash and outputIndex` };
40
- }
41
- const entry = rawEntry;
42
- if (typeof entry.txHash !== 'string' || !(0, validators_1.isTxHash)(entry.txHash)) {
43
- return { error: `Each ${entryName} entry must have a valid 64-hex txHash` };
44
- }
45
- const idx = entry.outputIndex;
46
- if (typeof idx !== 'number' || !Number.isInteger(idx) || idx < 0) {
47
- return { error: `Each ${entryName} entry must have a non-negative integer outputIndex` };
48
- }
49
- refs.push({ txHash: entry.txHash, outputIndex: idx });
50
- }
51
- return { parsed: refs };
52
- }
53
- /**
54
- * Parse and validate requiredSignersJson (array of 56-hex Ed25519 key hashes).
55
- * Same result contract as the other parse* helpers.
56
- */
57
- function parseRequiredSigners(requiredSignersJson) {
58
- if (!requiredSignersJson)
59
- return { parsed: undefined };
60
- const jsonResult = (0, validators_1.validateJsonWithLimits)(requiredSignersJson, 'requiredSignersJson');
61
- if (!jsonResult.valid)
62
- return { error: jsonResult.error };
63
- try {
64
- return { parsed: (0, validators_1.validateRequiredSigners)(jsonResult.parsed) };
65
- }
66
- catch (err) {
67
- return { error: err instanceof Error ? err.message : String(err) };
68
- }
69
- }
70
- /**
71
- * Parse and validate an assetsJson array ({unit, quantity} entries) with the same
72
- * per-entry strictness as parseExtraOutputs — unchecked entries previously flowed
73
- * into the builder and surfaced as 500s.
74
- */
75
- function parseAssetsArray(assetsJson, fieldName) {
76
- if (!assetsJson)
77
- return { parsed: undefined };
78
- const jsonResult = (0, validators_1.validateJsonWithLimits)(assetsJson, fieldName);
79
- if (!jsonResult.valid)
80
- return { error: jsonResult.error };
81
- if (!Array.isArray(jsonResult.parsed))
82
- return { error: `${fieldName} must be a JSON array` };
83
- const out = [];
84
- for (let i = 0; i < jsonResult.parsed.length; i++) {
85
- const a = jsonResult.parsed[i];
86
- if (!a || typeof a !== 'object') {
87
- return { error: `${fieldName}[${i}] must be an object` };
88
- }
89
- if (typeof a.unit !== 'string' || a.unit.toLowerCase() === 'lovelace' || !(0, validators_1.isAssetUnit)(a.unit)) {
90
- return { error: `${fieldName}[${i}].unit must be a valid asset unit (policyId + assetName hex)` };
91
- }
92
- if (typeof a.quantity !== 'string' || !/^\d+$/.test(a.quantity) || a.quantity === '0') {
93
- return { error: `${fieldName}[${i}].quantity must be a positive integer string` };
94
- }
95
- out.push({ unit: a.unit, quantity: a.quantity });
96
- }
97
- return { parsed: out };
98
- }
99
- /** Upper bound on extra outputs per transaction (defence against tx-size blow-up). */
100
- const MAX_EXTRA_OUTPUTS = 32;
101
- /**
102
- * Parse and validate extraOutputsJson. Returns { parsed } on success (possibly undefined
103
- * for empty array → no-op) or { error } on validation failure.
104
- */
105
- function parseExtraOutputs(extraOutputsJson) {
106
- if (!extraOutputsJson)
107
- return { parsed: undefined };
108
- const jsonResult = (0, validators_1.validateJsonWithLimits)(extraOutputsJson, 'extraOutputsJson');
109
- if (!jsonResult.valid)
110
- return { error: jsonResult.error };
111
- if (!Array.isArray(jsonResult.parsed))
112
- return { error: 'extraOutputsJson must be a JSON array' };
113
- if (jsonResult.parsed.length === 0)
114
- return { parsed: undefined };
115
- if (jsonResult.parsed.length > MAX_EXTRA_OUTPUTS) {
116
- return { error: `extraOutputsJson exceeds maximum of ${MAX_EXTRA_OUTPUTS} entries` };
117
- }
118
- const out = [];
119
- for (let i = 0; i < jsonResult.parsed.length; i++) {
120
- const entry = jsonResult.parsed[i];
121
- if (!entry || typeof entry !== 'object') {
122
- return { error: `extraOutputs[${i}] must be an object` };
123
- }
124
- if (typeof entry.address !== 'string' || !(0, validators_1.isValidBech32Address)(entry.address)) {
125
- return { error: `extraOutputs[${i}].address is not a valid Bech32 address` };
126
- }
127
- if (typeof entry.lovelaceAmount !== 'string' || !/^\d+$/.test(entry.lovelaceAmount) || entry.lovelaceAmount === '0') {
128
- return { error: `extraOutputs[${i}].lovelaceAmount must be a positive integer string` };
129
- }
130
- let assets;
131
- if (entry.assets !== undefined && entry.assets !== null) {
132
- if (!Array.isArray(entry.assets)) {
133
- return { error: `extraOutputs[${i}].assets must be an array` };
134
- }
135
- assets = [];
136
- for (let j = 0; j < entry.assets.length; j++) {
137
- const a = entry.assets[j];
138
- if (!a || typeof a !== 'object') {
139
- return { error: `extraOutputs[${i}].assets[${j}] must be an object` };
140
- }
141
- if (typeof a.unit !== 'string' || a.unit.toLowerCase() === 'lovelace' || !(0, validators_1.isAssetUnit)(a.unit)) {
142
- return { error: `extraOutputs[${i}].assets[${j}].unit must be a valid asset unit (policyId + assetName hex)` };
143
- }
144
- if (typeof a.quantity !== 'string' || !/^\d+$/.test(a.quantity) || a.quantity === '0') {
145
- return { error: `extraOutputs[${i}].assets[${j}].quantity must be a positive integer string` };
146
- }
147
- assets.push({ unit: a.unit, quantity: a.quantity });
148
- }
149
- }
150
- let inlineDatum;
151
- if (entry.inlineDatumJson !== undefined && entry.inlineDatumJson !== null) {
152
- if (typeof entry.inlineDatumJson !== 'string') {
153
- return { error: `extraOutputs[${i}].inlineDatumJson must be a JSON string` };
154
- }
155
- const datumResult = (0, validators_1.validateJsonWithLimits)(entry.inlineDatumJson, `extraOutputs[${i}].inlineDatumJson`);
156
- if (!datumResult.valid)
157
- return { error: datumResult.error };
158
- inlineDatum = datumResult.parsed;
159
- }
160
- let referenceScript;
161
- if (entry.referenceScriptHex !== undefined && entry.referenceScriptHex !== null) {
162
- if (typeof entry.referenceScriptHex !== 'string' || !(0, validators_1.isValidCbor)(entry.referenceScriptHex)) {
163
- return { error: `extraOutputs[${i}].referenceScriptHex must be even-length hex` };
164
- }
165
- referenceScript = entry.referenceScriptHex;
166
- }
167
- out.push({ address: entry.address, lovelaceAmount: entry.lovelaceAmount, assets, inlineDatum, referenceScript });
168
- }
169
- return { parsed: out };
170
- }
171
20
  /**
172
21
  * Cardano Transaction Service Implementation
173
22
  * Handles transaction building and submission operations & some additional data queries.
@@ -191,7 +40,7 @@ module.exports = (srv) => {
191
40
  // parse optional output datum
192
41
  const cleanData = { ...req.data };
193
42
  // parse optional forceInputsJson
194
- const forceInputsResult = parseUtxoRefArray(forceInputsJson, 'forceInputsJson');
43
+ const forceInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(forceInputsJson, 'forceInputsJson');
195
44
  if (forceInputsResult.error)
196
45
  return (0, errors_1.rejectInvalid)(req, 'BuildSimpleAdaTransaction', forceInputsResult.error, 'forceInputsJson');
197
46
  cleanData.forceInputs = forceInputsResult.parsed;
@@ -204,7 +53,7 @@ module.exports = (srv) => {
204
53
  delete cleanData.outputDatumJson;
205
54
  }
206
55
  // parse optional assets JSON (for locking native assets at script addresses)
207
- const assetsResult = parseAssetsArray(assetsJson, 'assetsJson');
56
+ const assetsResult = (0, tx_request_parsers_1.parseAssetsArray)(assetsJson, 'assetsJson');
208
57
  if (assetsResult.error)
209
58
  return (0, errors_1.rejectInvalid)(req, 'BuildSimpleAdaTransaction', assetsResult.error, 'assetsJson');
210
59
  if (assetsResult.parsed) {
@@ -268,7 +117,7 @@ module.exports = (srv) => {
268
117
  });
269
118
  /**
270
119
  * Build a transaction with metadata
271
- * @param req - CDS request object (with senderAddress, recipientAddress, lovelaceAmount, metadataJson, changeAddress)
120
+ * @param req - CDS request object
272
121
  * @returns {TransactionBuild} Transaction build details
273
122
  */
274
123
  srv.on('BuildTransactionWithMetadata', async (req) => {
@@ -289,7 +138,7 @@ module.exports = (srv) => {
289
138
  });
290
139
  /**
291
140
  * Build a multi-asset transaction
292
- * @param req - CDS request object (with senderAddress, recipientAddress, lovelaceAmount, assetsJson, changeAddress)
141
+ * @param req CDS request object
293
142
  * @returns {TransactionBuild} Transaction build details
294
143
  */
295
144
  srv.on('BuildMultiAssetTransaction', async (req) => {
@@ -301,17 +150,17 @@ module.exports = (srv) => {
301
150
  return (0, errors_1.rejectInvalid)(req, 'BuildMultiAssetTransaction', 'Invalid changeAddress format', 'changeAddress');
302
151
  }
303
152
  // Parse and validate assetsJson entries (unit + quantity, like parseExtraOutputs)
304
- const assetsResult = parseAssetsArray(assetsJson, 'assetsJson');
153
+ const assetsResult = (0, tx_request_parsers_1.parseAssetsArray)(assetsJson, 'assetsJson');
305
154
  if (assetsResult.error)
306
155
  return (0, errors_1.rejectInvalid)(req, 'BuildMultiAssetTransaction', assetsResult.error, 'assetsJson');
307
156
  const parsedAssets = assetsResult.parsed;
308
157
  if (!parsedAssets || parsedAssets.length === 0) {
309
158
  return (0, errors_1.rejectInvalid)(req, 'BuildMultiAssetTransaction', 'assetsJson must contain at least one asset', 'assetsJson');
310
159
  }
311
- // Validation BEFORE handleRequest (convention) — build the clean request object up front
160
+ // Validation BEFORE handleRequest
312
161
  const cleanData = { ...req.data };
313
162
  delete cleanData.assetsJson;
314
- // parse optional output datum (for locking assets at script addresses)
163
+ // parse optional output datum
315
164
  if (outputDatumJson) {
316
165
  const jsonResult = (0, validators_1.validateJsonWithLimits)(outputDatumJson, 'outputDatumJson');
317
166
  if (!jsonResult.valid)
@@ -333,11 +182,11 @@ module.exports = (srv) => {
333
182
  });
334
183
  /**
335
184
  * Build a minting transaction
336
- * @param req - CDS request object (with senderAddress, recipientAddress, lovelaceAmount, mintActionsJson, mintingPolicyScript, changeAddress)
185
+ * @param req CDS request object
337
186
  * @returns {TransactionBuild} Transaction build details
338
187
  */
339
188
  srv.on('BuildMintTransaction', async (req) => {
340
- const { senderAddress, recipientAddress, lovelaceAmount, mintActionsJson, mintingPolicyScript, requiredSignersJson, scriptParamsJson, inlineDatumJson, mintRedeemerJson, lockOnScript, forceInputsJson, referenceInputsJson, referenceScriptHex, metadataJson, validityStartMs, validityEndMs } = req.data;
189
+ const { senderAddress, recipientAddress, lovelaceAmount, mintActionsJson, mintingPolicyScript, requiredSignersJson, scriptParamsJson, inlineDatumJson, mintRedeemerJson, lockOnScript, forceInputsJson, referenceInputsJson, referenceScriptHex, extraOutputsJson, metadataJson, validityStartMs, validityEndMs } = req.data;
341
190
  // validate inputs (includes JSON and CBOR validation)
342
191
  const errors = (0, validators_1.validateTransactionInputs)({ senderAddress, recipientAddress, lovelaceAmount, mintActionsJson, mintingPolicyScript, referenceScriptHex, metadataJson, validityStartMs, validityEndMs }, ['senderAddress', 'recipientAddress', 'lovelaceAmount', 'mintActionsJson', 'mintingPolicyScript']);
343
192
  (0, errors_1.throwIfValidationErrors)(req, 'BuildMintTransaction', errors);
@@ -349,21 +198,41 @@ module.exports = (srv) => {
349
198
  if (!Array.isArray(parsedMintActionsRaw)) {
350
199
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', 'mintActionsJson must be a JSON array', 'mintActionsJson');
351
200
  }
352
- const parsedMintActions = parsedMintActionsRaw.map((action) => {
201
+ const parsedMintActions = parsedMintActionsRaw.map((action, actionIndex) => {
353
202
  if (!action || typeof action !== 'object') {
354
203
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', 'Each mint action must be an object with assetUnit and quantity', 'mintActionsJson');
355
204
  }
356
- // assetUnit is normally a full policyId+assetName hex. Exception (BUG 7):
357
- // when scriptParamsJson is provided, a bare assetName (shorter than a full
358
- // unit) is accepted here and expanded to policyId+assetName once the policy
359
- // script is parameterized below — mirrors the expansion's own < MIN_FULL_ASSET_UNIT_LENGTH guard.
360
- const bareAssetNameForExpansion = !!scriptParamsJson &&
205
+ // Multi-policy mint FR: optional per-action mintingPolicyScript + redeemerJson.
206
+ const policyFields = (0, tx_request_parsers_1.parseMintActionPolicyFields)(action, actionIndex);
207
+ if (policyFields.error) {
208
+ return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', policyFields.error, 'mintActionsJson');
209
+ }
210
+ let actionPolicyId;
211
+ if (policyFields.script) {
212
+ try {
213
+ actionPolicyId = cardano_ledger_ts_1.Script.fromCbor(Buffer.from(policyFields.script, 'hex')).hash.toString();
214
+ }
215
+ catch (err) {
216
+ const errMsg = err instanceof Error ? err.message : String(err);
217
+ return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', `mintActions[${actionIndex}].mintingPolicyScript is not a valid Plutus script: ${errMsg}`, 'mintActionsJson');
218
+ }
219
+ }
220
+ const bareAssetNameForExpansion = (!!scriptParamsJson || !!actionPolicyId) &&
361
221
  typeof action.assetUnit === 'string' &&
362
222
  action.assetUnit.length < const_1.MIN_FULL_ASSET_UNIT_LENGTH &&
363
223
  action.assetUnit.length % 2 === 0 &&
364
224
  /^[0-9a-fA-F]*$/.test(action.assetUnit);
365
225
  if (typeof action.assetUnit !== 'string' || (!(0, validators_1.isAssetUnit)(action.assetUnit) && !bareAssetNameForExpansion)) {
366
- 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');
226
+ 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');
227
+ }
228
+ let assetUnit = action.assetUnit;
229
+ if (actionPolicyId) {
230
+ if (assetUnit.length < const_1.MIN_FULL_ASSET_UNIT_LENGTH) {
231
+ assetUnit = actionPolicyId + assetUnit;
232
+ }
233
+ else if (!assetUnit.toLowerCase().startsWith(actionPolicyId)) {
234
+ return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', `mintActions[${actionIndex}].assetUnit "${assetUnit}" does not start with its own policy id ${actionPolicyId}`, 'mintActionsJson');
235
+ }
367
236
  }
368
237
  if (typeof action.quantity !== 'string') {
369
238
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', 'Each mint action must have a string quantity', 'mintActionsJson');
@@ -372,14 +241,20 @@ module.exports = (srv) => {
372
241
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', `Invalid quantity format: "${action.quantity}" — must be an integer string`, 'mintActionsJson');
373
242
  }
374
243
  try {
375
- return { ...action, quantity: BigInt(action.quantity) };
244
+ return {
245
+ assetUnit,
246
+ quantity: BigInt(action.quantity),
247
+ ...(action.redeemer !== undefined ? { redeemer: action.redeemer } : {}),
248
+ ...(policyFields.script ? { mintingPolicyScript: policyFields.script } : {}),
249
+ ...(policyFields.redeemer !== undefined ? { redeemerJson: policyFields.redeemer } : {})
250
+ };
376
251
  }
377
252
  catch {
378
253
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', `Invalid quantity: "${action.quantity}" — cannot parse as integer`, 'mintActionsJson');
379
254
  }
380
255
  });
381
256
  // Parse and validate optional requiredSignersJson
382
- const requiredSignersResult = parseRequiredSigners(requiredSignersJson);
257
+ const requiredSignersResult = (0, tx_request_parsers_1.parseRequiredSigners)(requiredSignersJson);
383
258
  if (requiredSignersResult.error)
384
259
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', requiredSignersResult.error, 'requiredSignersJson');
385
260
  const requiredSigners = requiredSignersResult.parsed;
@@ -414,19 +289,23 @@ module.exports = (srv) => {
414
289
  if (lockOnScript && (!scriptParams || scriptParams.length === 0)) {
415
290
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', 'lockOnScript requires scriptParamsJson to derive script address', 'lockOnScript');
416
291
  }
292
+ // Parse and validate optional extraOutputsJson (FR-2 on mint: each minted
293
+ // token can sit on its own output with its own inline datum)
294
+ const extraOutputsResult = (0, tx_request_parsers_1.parseExtraOutputs)(extraOutputsJson);
295
+ if (extraOutputsResult.error)
296
+ return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', extraOutputsResult.error, 'extraOutputsJson');
297
+ const extraOutputs = extraOutputsResult.parsed;
417
298
  // Parse and validate optional forceInputsJson
418
- const forceInputsResult = parseUtxoRefArray(forceInputsJson, 'forceInputsJson');
299
+ const forceInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(forceInputsJson, 'forceInputsJson');
419
300
  if (forceInputsResult.error)
420
301
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', forceInputsResult.error, 'forceInputsJson');
421
302
  const forceInputs = forceInputsResult.parsed;
422
303
  // Parse and validate optional referenceInputsJson (CIP-31)
423
- const refInputsResult = parseUtxoRefArray(referenceInputsJson, 'referenceInputsJson');
304
+ const refInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(referenceInputsJson, 'referenceInputsJson');
424
305
  if (refInputsResult.error)
425
306
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', refInputsResult.error, 'referenceInputsJson');
426
307
  const referenceInputs = refInputsResult.parsed;
427
- // Parse and validate optional metadataJson (auxiliary_data on the mint tx).
428
- // validateTransactionInputs has already JSON-validated the string; re-parse here
429
- // and enforce the label-object shape that the builder's metadata mapper expects.
308
+ // Parse and validate optional metadataJson
430
309
  let parsedMetadata;
431
310
  if (metadataJson) {
432
311
  try {
@@ -453,6 +332,7 @@ module.exports = (srv) => {
453
332
  delete cleanData.lockOnScript;
454
333
  delete cleanData.forceInputsJson;
455
334
  delete cleanData.referenceInputsJson;
335
+ delete cleanData.extraOutputsJson;
456
336
  if (parsedMetadata) {
457
337
  cleanData.metadataJson = parsedMetadata;
458
338
  }
@@ -497,14 +377,9 @@ module.exports = (srv) => {
497
377
  // invalid script CBOR — skip the prefix check; the builder rejects it with its own message
498
378
  }
499
379
  }
500
- // BUG 9 fix: the builder mints every action under the policy script's hash and
501
- // parseAssetUnit silently discards the unit's first 56 hex chars. A bare asset name
502
- // of 29-32 bytes is length-indistinguishable from a full unit, so a mismatched
503
- // prefix would mint a truncated name. At this point every action holds a full
504
- // unit (bare names were expanded above), so all of them must carry the policyId.
505
380
  if (effectivePolicyId) {
506
381
  const policyId = effectivePolicyId;
507
- const mismatch = parsedMintActions.find((action) => !action.assetUnit.toLowerCase().startsWith(policyId));
382
+ const mismatch = parsedMintActions.find((action) => !action.mintingPolicyScript && !action.assetUnit.toLowerCase().startsWith(policyId));
508
383
  if (mismatch) {
509
384
  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');
510
385
  }
@@ -517,7 +392,8 @@ module.exports = (srv) => {
517
392
  inlineDatum,
518
393
  mintRedeemer,
519
394
  forceInputs,
520
- referenceInputs
395
+ referenceInputs,
396
+ extraOutputs
521
397
  });
522
398
  // Post-build: compute CIP-14 fingerprint and scriptAddress
523
399
  if (buildResult.scriptHash) {
@@ -525,12 +401,15 @@ module.exports = (srv) => {
525
401
  const updates = {};
526
402
  // CIP-14 asset fingerprint for the first minted asset. The unit is always a
527
403
  // full policyId+assetName here: bare names were expanded before the build and
528
- // the BUG 9 prefix check rejected everything else (a 56-hex unit is an empty
529
- // asset name, not a bare 28-byte name).
404
+ // the prefix checks rejected everything else (a 56-hex unit is an empty
405
+ // asset name, not a bare 28-byte name). The policy id comes from the UNIT,
406
+ // not from buildResult.scriptHash: with a per-action mintingPolicyScript the
407
+ // first action may mint under a different policy than the top-level script.
530
408
  if (parsedMintActions.length > 0) {
531
409
  const firstAssetUnit = parsedMintActions[0].assetUnit;
410
+ const firstPolicyId = firstAssetUnit.slice(0, const_1.POLICY_ID_HEX_LENGTH);
532
411
  const assetNameHex = firstAssetUnit.slice(const_1.POLICY_ID_HEX_LENGTH);
533
- buildResult.fingerprint = (0, mappers_1.computeCip14Fingerprint)(policyId, assetNameHex);
412
+ buildResult.fingerprint = (0, mappers_1.computeCip14Fingerprint)(firstPolicyId, assetNameHex);
534
413
  updates.fingerprint = buildResult.fingerprint;
535
414
  }
536
415
  // lockOnScript: persist the derived script address on the build record (only when scriptParams were applied)
@@ -568,7 +447,7 @@ module.exports = (srv) => {
568
447
  // Parse optional datum JSON
569
448
  const parsedDatum = datumJson ? JSON.parse(datumJson) : undefined;
570
449
  // Parse and validate optional requiredSignersJson
571
- const requiredSignersResult = parseRequiredSigners(requiredSignersJson);
450
+ const requiredSignersResult = (0, tx_request_parsers_1.parseRequiredSigners)(requiredSignersJson);
572
451
  if (requiredSignersResult.error)
573
452
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', requiredSignersResult.error, 'requiredSignersJson');
574
453
  const requiredSigners = requiredSignersResult.parsed;
@@ -596,22 +475,21 @@ module.exports = (srv) => {
596
475
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', 'lockOnScript requires scriptParamsJson to derive script address', 'lockOnScript');
597
476
  }
598
477
  // Parse and validate optional forceInputsJson
599
- const forceInputsResult = parseUtxoRefArray(forceInputsJson, 'forceInputsJson');
478
+ const forceInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(forceInputsJson, 'forceInputsJson');
600
479
  if (forceInputsResult.error)
601
480
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', forceInputsResult.error, 'forceInputsJson');
602
481
  const forceInputs = forceInputsResult.parsed;
603
482
  // Parse and validate optional referenceInputsJson (CIP-31)
604
- const refInputsResult = parseUtxoRefArray(referenceInputsJson, 'referenceInputsJson');
483
+ const refInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(referenceInputsJson, 'referenceInputsJson');
605
484
  if (refInputsResult.error)
606
485
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', refInputsResult.error, 'referenceInputsJson');
607
486
  const referenceInputs = refInputsResult.parsed;
608
487
  // Parse and validate optional extraOutputsJson
609
- const extraOutputsResult = parseExtraOutputs(extraOutputsJson);
488
+ const extraOutputsResult = (0, tx_request_parsers_1.parseExtraOutputs)(extraOutputsJson);
610
489
  if (extraOutputsResult.error)
611
490
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', extraOutputsResult.error, 'extraOutputsJson');
612
491
  const extraOutputs = extraOutputsResult.parsed;
613
- // FR-1: Optional combined spend+mint parameters. mintActionsJson triggers the combined flow;
614
- // mintingPolicyScript is required alongside it. mintRedeemerJson is optional.
492
+ // Optional combined spend+mint parameters
615
493
  let parsedMintActions;
616
494
  let parsedMintRedeemer;
617
495
  if (mintActionsJson) {
@@ -624,7 +502,7 @@ module.exports = (srv) => {
624
502
  if (!Array.isArray(mintJson.parsed)) {
625
503
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', 'mintActionsJson must be a JSON array', 'mintActionsJson');
626
504
  }
627
- parsedMintActions = mintJson.parsed.map((rawAction) => {
505
+ parsedMintActions = mintJson.parsed.map((rawAction, actionIndex) => {
628
506
  if (!rawAction || typeof rawAction !== 'object') {
629
507
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', 'Each mint action must be an object with assetUnit and quantity', 'mintActionsJson');
630
508
  }
@@ -635,18 +513,45 @@ module.exports = (srv) => {
635
513
  if (typeof action.assetUnit !== 'string') {
636
514
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', 'Each mint action must have assetUnit string', 'mintActionsJson');
637
515
  }
638
- // same rule as BuildMintTransaction: full policyId+assetName unit, OR a bare
639
- // assetName hex destined for policyId expansion (only possible when the policy
640
- // is the script-params-applied validator — see expansion below)
641
- const bareAssetNameForExpansion = !!scriptParamsJson &&
642
- mintingPolicyScript === validatorScript &&
516
+ // Multi-policy mint FR: optional per-action mintingPolicyScript + redeemerJson
517
+ // (same rules as BuildMintTransaction).
518
+ const policyFields = (0, tx_request_parsers_1.parseMintActionPolicyFields)(action, actionIndex);
519
+ if (policyFields.error) {
520
+ return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', policyFields.error, 'mintActionsJson');
521
+ }
522
+ let actionPolicyId;
523
+ if (policyFields.script) {
524
+ try {
525
+ actionPolicyId = cardano_ledger_ts_1.Script.fromCbor(Buffer.from(policyFields.script, 'hex')).hash.toString();
526
+ }
527
+ catch (err) {
528
+ const errMsg = err instanceof Error ? err.message : String(err);
529
+ return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', `mintActions[${actionIndex}].mintingPolicyScript is not a valid Plutus script: ${errMsg}`, 'mintActionsJson');
530
+ }
531
+ }
532
+ const bareAssetNameForExpansion = ((!!scriptParamsJson && mintingPolicyScript === validatorScript) || !!actionPolicyId) &&
643
533
  action.assetUnit.length < const_1.MIN_FULL_ASSET_UNIT_LENGTH &&
644
534
  action.assetUnit.length % 2 === 0 &&
645
535
  /^[0-9a-fA-F]*$/.test(action.assetUnit);
646
536
  if (!(0, validators_1.isAssetUnit)(action.assetUnit) && !bareAssetNameForExpansion) {
647
- 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');
537
+ 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');
648
538
  }
649
- return { assetUnit: action.assetUnit, quantity: BigInt(action.quantity) };
539
+ let assetUnit = action.assetUnit;
540
+ if (actionPolicyId) {
541
+ if (assetUnit.length < const_1.MIN_FULL_ASSET_UNIT_LENGTH) {
542
+ assetUnit = actionPolicyId + assetUnit;
543
+ }
544
+ else if (!assetUnit.toLowerCase().startsWith(actionPolicyId)) {
545
+ return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', `mintActions[${actionIndex}].assetUnit "${assetUnit}" does not start with its own policy id ${actionPolicyId}`, 'mintActionsJson');
546
+ }
547
+ }
548
+ return {
549
+ assetUnit,
550
+ quantity: BigInt(action.quantity),
551
+ ...(typeof action.redeemer === 'number' ? { redeemer: action.redeemer } : {}),
552
+ ...(policyFields.script ? { mintingPolicyScript: policyFields.script } : {}),
553
+ ...(policyFields.redeemer !== undefined ? { redeemerJson: policyFields.redeemer } : {})
554
+ };
650
555
  });
651
556
  if (mintRedeemerJson) {
652
557
  const mrJson = (0, validators_1.validateJsonWithLimits)(mintRedeemerJson, 'mintRedeemerJson');
@@ -707,7 +612,9 @@ module.exports = (srv) => {
707
612
  }
708
613
  if (mintPolicyId) {
709
614
  const policyId = mintPolicyId;
710
- const mismatch = parsedMintActions.find((action) => !action.assetUnit.toLowerCase().startsWith(policyId));
615
+ // Actions with their own per-action script were already checked
616
+ // against THAT script's policy id during parsing.
617
+ const mismatch = parsedMintActions.find((action) => !action.mintingPolicyScript && !action.assetUnit.toLowerCase().startsWith(policyId));
711
618
  if (mismatch) {
712
619
  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');
713
620
  }
@@ -0,0 +1,125 @@
1
+ using {odatano.cardano as db} from '../db/schema';
2
+
3
+ /**
4
+ * Cardano Wallet Worker Service (v2.0)
5
+ *
6
+ * Control + observability surface for the wallet worker / job engine:
7
+ * - job submission (async build → sign → submit → confirm from server-side wallets)
8
+ * - job status polling + cancellation
9
+ * - read-only projections of jobs and registered worker wallets
10
+ * - pause/resume of the local worker instance (admin)
11
+ *
12
+ * Security note: SubmitWalletJob executes value transfers with server-held keys —
13
+ * the service requires authentication throughout; control actions and foreign-job
14
+ * visibility are gated behind the Admin role. Jobs on HSM-backed wallets addition-
15
+ * ally require the configured hsm.requiresRole (HSM_REQUIRES_ROLE), the same gate
16
+ * the synchronous SignWithHsm path enforces. Keys are NEVER accepted or exposed
17
+ * through this surface.
18
+ */
19
+ @requires: 'authenticated-user'
20
+ service CardanoWorkerService @(impl: './cardano-worker-service') {
21
+
22
+ @readonly
23
+ @title : 'Wallet Jobs'
24
+ @description: 'Asynchronous wallet-worker jobs. Non-admin callers see their own jobs only.'
25
+ @restrict : [
26
+ { grant: 'READ', to: 'Admin' },
27
+ { grant: 'READ', where: 'createdBy = $user' }
28
+ ]
29
+ // dedupKey is the internal backing column of the idempotency constraint.
30
+ entity WalletJobs as projection on db.CardanoWalletJobs excluding { dedupKey };
31
+
32
+ @readonly
33
+ @title : 'Worker Wallets'
34
+ @description: 'Registered server-side worker wallets (addresses and stats only — no key material, no lease internals)'
35
+ entity WorkerWallets as projection on db.CardanoWorkerWallets excluding { leaseOwner, leaseUntil };
36
+
37
+ @title : 'Wallet Job Submission Result'
38
+ type JobSubmissionResult {
39
+ jobId : UUID;
40
+ status : String(12);
41
+ deduplicated : Boolean;
42
+ }
43
+
44
+ @title : 'Wallet Job Status'
45
+ type JobStatus {
46
+ jobId : UUID;
47
+ walletId : String(50);
48
+ kind : String(12);
49
+ status : String(12);
50
+ attempt : Integer;
51
+ txHash : String(64);
52
+ fee : String;
53
+ errorCode : String(50);
54
+ errorMessage : String(500);
55
+ submittedAt : Timestamp;
56
+ confirmedAt : Timestamp;
57
+ finishedAt : Timestamp;
58
+ }
59
+
60
+ @title : 'Worker Status'
61
+ type WorkerStatus {
62
+ running : Boolean;
63
+ wallets : many String;
64
+ executing : many String;
65
+ awaitingConfirmation : Integer;
66
+ pendingJobs : Integer;
67
+ }
68
+
69
+ /**
70
+ * Terminal job outcomes. Subscribing removes the need for a GetJobStatus poll loop:
71
+ * (await cds.connect.to('CardanoWorkerService')).on('jobConfirmed', ({ data }) => …)
72
+ */
73
+ event jobConfirmed {
74
+ jobId : UUID;
75
+ walletId : String(50);
76
+ kind : String(12);
77
+ txHash : String(64);
78
+ }
79
+
80
+ event jobFailed {
81
+ jobId : UUID;
82
+ walletId : String(50);
83
+ kind : String(12);
84
+ txHash : String(64); // null when the job never reached the chain
85
+ errorCode : String(50);
86
+ errorMessage : String(500);
87
+ }
88
+
89
+ @title : 'Submit Wallet Job'
90
+ @description: 'Queue an asynchronous transaction job for a worker wallet. Returns immediately with a jobId; poll GetJobStatus for the outcome. The request JSON is the same payload shape as the corresponding Build* action; senderAddress is always overridden with the wallet address.'
91
+ action SubmitWalletJob(
92
+ @title: 'Wallet Id' walletId : String(50),
93
+ @title: 'Job Kind' kind : String(12),
94
+ @title: 'Request JSON' requestJson : LargeString,
95
+ @title: 'Idempotency Key' idempotencyKey : String(100),
96
+ @title: 'Priority' priority : Integer,
97
+ @title: 'Not Before' notBefore : Timestamp
98
+ ) returns JobSubmissionResult;
99
+
100
+ @title : 'Cancel Job'
101
+ @description: 'Cancel a still-pending job. Jobs that started building may already reach the chain and cannot be cancelled.'
102
+ action CancelJob(
103
+ @title: 'Job Id' jobId : UUID
104
+ ) returns Boolean;
105
+
106
+ @title : 'Get Job Status'
107
+ @description: 'Current lifecycle state of a wallet job (non-admins: own jobs only)'
108
+ function GetJobStatus(
109
+ @title: 'Job Id' jobId : UUID
110
+ ) returns JobStatus;
111
+
112
+ @title : 'Get Worker Status'
113
+ @description: 'Live worker summary: running state, wallets, in-flight executions, confirmation backlog, queue depth'
114
+ function GetWorkerStatus() returns WorkerStatus;
115
+
116
+ @title : 'Pause Worker'
117
+ @description: 'Stop the local worker instance (finishes in-flight steps; queued jobs stay pending).'
118
+ @requires : 'Admin'
119
+ action PauseWorker() returns Boolean;
120
+
121
+ @title : 'Resume Worker'
122
+ @description: 'Start/restart the local worker instance using the configured wallets.'
123
+ @requires : 'Admin'
124
+ action ResumeWorker() returns Boolean;
125
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=cardano-worker-service.d.ts.map