@odatano/core 2.0.0-rc.1 → 2.0.0-rc.11

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 (66) 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 +37 -2
  4. package/@cds-models/CardanoIndexerService/index.js +4 -0
  5. package/@cds-models/CardanoSignService/index.d.ts +5 -2
  6. package/@cds-models/CardanoTransactionService/index.d.ts +9 -9
  7. package/@cds-models/odatano/cardano/index.d.ts +86 -0
  8. package/@cds-models/odatano/cardano/index.js +6 -0
  9. package/README.md +62 -4
  10. package/db/schema.cds +105 -0
  11. package/package.json +9 -3
  12. package/src/index.d.ts +6 -0
  13. package/src/index.js +21 -1
  14. package/src/plugin.js +33 -30
  15. package/srv/blockchain/backends/blockfrost-backend.js +1 -10
  16. package/srv/blockchain/backends/koios-backend.js +1 -10
  17. package/srv/blockchain/backends/ogmios-backend.d.ts +29 -4
  18. package/srv/blockchain/backends/ogmios-backend.js +96 -7
  19. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +77 -0
  20. package/srv/blockchain/backends/ogmios-frame-guard.js +181 -0
  21. package/srv/blockchain/cardano-indexer.d.ts +18 -0
  22. package/srv/blockchain/cardano-indexer.js +58 -3
  23. package/srv/blockchain/crawler/crawler.d.ts +55 -0
  24. package/srv/blockchain/crawler/crawler.js +153 -3
  25. package/srv/blockchain/crawler/index.d.ts +9 -0
  26. package/srv/blockchain/crawler/index.js +37 -4
  27. package/srv/blockchain/crawler/sync-state.d.ts +13 -1
  28. package/srv/blockchain/crawler/sync-state.js +24 -2
  29. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +20 -0
  30. package/srv/blockchain/transaction-building/buildooor-tx.js +104 -20
  31. package/srv/blockchain/wallet-worker/build-request.js +35 -6
  32. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +32 -1
  33. package/srv/blockchain/wallet-worker/confirmation-tracker.js +91 -29
  34. package/srv/blockchain/wallet-worker/job-store.d.ts +11 -0
  35. package/srv/blockchain/wallet-worker/job-store.js +42 -9
  36. package/srv/cardano-agent-service.cds +150 -0
  37. package/srv/cardano-agent-service.d.ts +2 -0
  38. package/srv/cardano-agent-service.js +16 -0
  39. package/srv/cardano-indexer-service.cds +36 -3
  40. package/srv/cardano-indexer-service.js +3 -0
  41. package/srv/cardano-service.js +57 -3
  42. package/srv/cardano-sign-service.cds +200 -180
  43. package/srv/cardano-tx-service.cds +32 -26
  44. package/srv/cardano-tx-service.js +96 -38
  45. package/srv/cardano-worker-service.cds +125 -125
  46. package/srv/server.d.ts +2 -1
  47. package/srv/server.js +18 -34
  48. package/srv/utils/agent-grants-config.d.ts +65 -0
  49. package/srv/utils/agent-grants-config.js +148 -0
  50. package/srv/utils/agent-grants.d.ts +314 -0
  51. package/srv/utils/agent-grants.js +821 -0
  52. package/srv/utils/agent-token-auth.d.ts +19 -0
  53. package/srv/utils/agent-token-auth.js +81 -0
  54. package/srv/utils/db-sanitize.d.ts +40 -0
  55. package/srv/utils/db-sanitize.js +98 -0
  56. package/srv/utils/errors.d.ts +18 -0
  57. package/srv/utils/errors.js +24 -1
  58. package/srv/utils/liveness.d.ts +23 -0
  59. package/srv/utils/liveness.js +49 -0
  60. package/srv/utils/mappers.d.ts +27 -0
  61. package/srv/utils/mappers.js +67 -7
  62. package/srv/utils/rate-limiter.d.ts +57 -0
  63. package/srv/utils/rate-limiter.js +126 -0
  64. package/srv/utils/tx-request-parsers.d.ts +13 -0
  65. package/srv/utils/tx-request-parsers.js +32 -0
  66. package/srv/utils/types.d.ts +34 -0
@@ -117,7 +117,7 @@ module.exports = (srv) => {
117
117
  });
118
118
  /**
119
119
  * Build a transaction with metadata
120
- * @param req - CDS request object (with senderAddress, recipientAddress, lovelaceAmount, metadataJson, changeAddress)
120
+ * @param req - CDS request object
121
121
  * @returns {TransactionBuild} Transaction build details
122
122
  */
123
123
  srv.on('BuildTransactionWithMetadata', async (req) => {
@@ -138,7 +138,7 @@ module.exports = (srv) => {
138
138
  });
139
139
  /**
140
140
  * Build a multi-asset transaction
141
- * @param req - CDS request object (with senderAddress, recipientAddress, lovelaceAmount, assetsJson, changeAddress)
141
+ * @param req CDS request object
142
142
  * @returns {TransactionBuild} Transaction build details
143
143
  */
144
144
  srv.on('BuildMultiAssetTransaction', async (req) => {
@@ -157,10 +157,10 @@ module.exports = (srv) => {
157
157
  if (!parsedAssets || parsedAssets.length === 0) {
158
158
  return (0, errors_1.rejectInvalid)(req, 'BuildMultiAssetTransaction', 'assetsJson must contain at least one asset', 'assetsJson');
159
159
  }
160
- // Validation BEFORE handleRequest (convention) — build the clean request object up front
160
+ // Validation BEFORE handleRequest
161
161
  const cleanData = { ...req.data };
162
162
  delete cleanData.assetsJson;
163
- // parse optional output datum (for locking assets at script addresses)
163
+ // parse optional output datum
164
164
  if (outputDatumJson) {
165
165
  const jsonResult = (0, validators_1.validateJsonWithLimits)(outputDatumJson, 'outputDatumJson');
166
166
  if (!jsonResult.valid)
@@ -182,11 +182,11 @@ module.exports = (srv) => {
182
182
  });
183
183
  /**
184
184
  * Build a minting transaction
185
- * @param req - CDS request object (with senderAddress, recipientAddress, lovelaceAmount, mintActionsJson, mintingPolicyScript, changeAddress)
185
+ * @param req CDS request object
186
186
  * @returns {TransactionBuild} Transaction build details
187
187
  */
188
188
  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;
189
+ const { senderAddress, recipientAddress, lovelaceAmount, mintActionsJson, mintingPolicyScript, requiredSignersJson, scriptParamsJson, inlineDatumJson, mintRedeemerJson, lockOnScript, forceInputsJson, referenceInputsJson, referenceScriptHex, extraOutputsJson, metadataJson, validityStartMs, validityEndMs } = req.data;
190
190
  // validate inputs (includes JSON and CBOR validation)
191
191
  const errors = (0, validators_1.validateTransactionInputs)({ senderAddress, recipientAddress, lovelaceAmount, mintActionsJson, mintingPolicyScript, referenceScriptHex, metadataJson, validityStartMs, validityEndMs }, ['senderAddress', 'recipientAddress', 'lovelaceAmount', 'mintActionsJson', 'mintingPolicyScript']);
192
192
  (0, errors_1.throwIfValidationErrors)(req, 'BuildMintTransaction', errors);
@@ -198,21 +198,41 @@ module.exports = (srv) => {
198
198
  if (!Array.isArray(parsedMintActionsRaw)) {
199
199
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', 'mintActionsJson must be a JSON array', 'mintActionsJson');
200
200
  }
201
- const parsedMintActions = parsedMintActionsRaw.map((action) => {
201
+ const parsedMintActions = parsedMintActionsRaw.map((action, actionIndex) => {
202
202
  if (!action || typeof action !== 'object') {
203
203
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', 'Each mint action must be an object with assetUnit and quantity', 'mintActionsJson');
204
204
  }
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 &&
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) &&
210
221
  typeof action.assetUnit === 'string' &&
211
222
  action.assetUnit.length < const_1.MIN_FULL_ASSET_UNIT_LENGTH &&
212
223
  action.assetUnit.length % 2 === 0 &&
213
224
  /^[0-9a-fA-F]*$/.test(action.assetUnit);
214
225
  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');
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
+ }
216
236
  }
217
237
  if (typeof action.quantity !== 'string') {
218
238
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', 'Each mint action must have a string quantity', 'mintActionsJson');
@@ -221,7 +241,13 @@ module.exports = (srv) => {
221
241
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', `Invalid quantity format: "${action.quantity}" — must be an integer string`, 'mintActionsJson');
222
242
  }
223
243
  try {
224
- 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
+ };
225
251
  }
226
252
  catch {
227
253
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', `Invalid quantity: "${action.quantity}" — cannot parse as integer`, 'mintActionsJson');
@@ -263,6 +289,12 @@ module.exports = (srv) => {
263
289
  if (lockOnScript && (!scriptParams || scriptParams.length === 0)) {
264
290
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', 'lockOnScript requires scriptParamsJson to derive script address', 'lockOnScript');
265
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;
266
298
  // Parse and validate optional forceInputsJson
267
299
  const forceInputsResult = (0, tx_request_parsers_1.parseUtxoRefArray)(forceInputsJson, 'forceInputsJson');
268
300
  if (forceInputsResult.error)
@@ -273,9 +305,7 @@ module.exports = (srv) => {
273
305
  if (refInputsResult.error)
274
306
  return (0, errors_1.rejectInvalid)(req, 'BuildMintTransaction', refInputsResult.error, 'referenceInputsJson');
275
307
  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.
308
+ // Parse and validate optional metadataJson
279
309
  let parsedMetadata;
280
310
  if (metadataJson) {
281
311
  try {
@@ -302,6 +332,7 @@ module.exports = (srv) => {
302
332
  delete cleanData.lockOnScript;
303
333
  delete cleanData.forceInputsJson;
304
334
  delete cleanData.referenceInputsJson;
335
+ delete cleanData.extraOutputsJson;
305
336
  if (parsedMetadata) {
306
337
  cleanData.metadataJson = parsedMetadata;
307
338
  }
@@ -346,14 +377,9 @@ module.exports = (srv) => {
346
377
  // invalid script CBOR — skip the prefix check; the builder rejects it with its own message
347
378
  }
348
379
  }
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.
354
380
  if (effectivePolicyId) {
355
381
  const policyId = effectivePolicyId;
356
- const mismatch = parsedMintActions.find((action) => !action.assetUnit.toLowerCase().startsWith(policyId));
382
+ const mismatch = parsedMintActions.find((action) => !action.mintingPolicyScript && !action.assetUnit.toLowerCase().startsWith(policyId));
357
383
  if (mismatch) {
358
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');
359
385
  }
@@ -366,7 +392,8 @@ module.exports = (srv) => {
366
392
  inlineDatum,
367
393
  mintRedeemer,
368
394
  forceInputs,
369
- referenceInputs
395
+ referenceInputs,
396
+ extraOutputs
370
397
  });
371
398
  // Post-build: compute CIP-14 fingerprint and scriptAddress
372
399
  if (buildResult.scriptHash) {
@@ -374,12 +401,15 @@ module.exports = (srv) => {
374
401
  const updates = {};
375
402
  // CIP-14 asset fingerprint for the first minted asset. The unit is always a
376
403
  // 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).
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.
379
408
  if (parsedMintActions.length > 0) {
380
409
  const firstAssetUnit = parsedMintActions[0].assetUnit;
410
+ const firstPolicyId = firstAssetUnit.slice(0, const_1.POLICY_ID_HEX_LENGTH);
381
411
  const assetNameHex = firstAssetUnit.slice(const_1.POLICY_ID_HEX_LENGTH);
382
- buildResult.fingerprint = (0, mappers_1.computeCip14Fingerprint)(policyId, assetNameHex);
412
+ buildResult.fingerprint = (0, mappers_1.computeCip14Fingerprint)(firstPolicyId, assetNameHex);
383
413
  updates.fingerprint = buildResult.fingerprint;
384
414
  }
385
415
  // lockOnScript: persist the derived script address on the build record (only when scriptParams were applied)
@@ -459,8 +489,7 @@ module.exports = (srv) => {
459
489
  if (extraOutputsResult.error)
460
490
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', extraOutputsResult.error, 'extraOutputsJson');
461
491
  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.
492
+ // Optional combined spend+mint parameters
464
493
  let parsedMintActions;
465
494
  let parsedMintRedeemer;
466
495
  if (mintActionsJson) {
@@ -473,7 +502,7 @@ module.exports = (srv) => {
473
502
  if (!Array.isArray(mintJson.parsed)) {
474
503
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', 'mintActionsJson must be a JSON array', 'mintActionsJson');
475
504
  }
476
- parsedMintActions = mintJson.parsed.map((rawAction) => {
505
+ parsedMintActions = mintJson.parsed.map((rawAction, actionIndex) => {
477
506
  if (!rawAction || typeof rawAction !== 'object') {
478
507
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', 'Each mint action must be an object with assetUnit and quantity', 'mintActionsJson');
479
508
  }
@@ -484,18 +513,45 @@ module.exports = (srv) => {
484
513
  if (typeof action.assetUnit !== 'string') {
485
514
  return (0, errors_1.rejectInvalid)(req, 'BuildPlutusSpendTransaction', 'Each mint action must have assetUnit string', 'mintActionsJson');
486
515
  }
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 &&
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) &&
492
533
  action.assetUnit.length < const_1.MIN_FULL_ASSET_UNIT_LENGTH &&
493
534
  action.assetUnit.length % 2 === 0 &&
494
535
  /^[0-9a-fA-F]*$/.test(action.assetUnit);
495
536
  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');
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');
497
538
  }
498
- 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
+ };
499
555
  });
500
556
  if (mintRedeemerJson) {
501
557
  const mrJson = (0, validators_1.validateJsonWithLimits)(mintRedeemerJson, 'mintRedeemerJson');
@@ -556,7 +612,9 @@ module.exports = (srv) => {
556
612
  }
557
613
  if (mintPolicyId) {
558
614
  const policyId = mintPolicyId;
559
- 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));
560
618
  if (mismatch) {
561
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');
562
620
  }
@@ -1,125 +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
- }
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
+ }
package/srv/server.d.ts CHANGED
@@ -13,6 +13,8 @@ interface AppContext {
13
13
  cardanoIndexer: CardanoIndexer;
14
14
  cardanoTxBuilder: CardanoTransactionBuilder;
15
15
  }
16
+ /** Agent-grant feature switch (AGENT_GRANTS_DESIGN.md); lives in its own module so src/plugin.ts can read it at load. */
17
+ export { loadAgentGrantsConfig, activateAgentGrants } from './utils/agent-grants-config';
16
18
  /**
17
19
  * Get the application context (must be called after bootstrap)
18
20
  * @throws {ProviderUnavailableError} 503 when uninitialized — request handlers using
@@ -125,5 +127,4 @@ export declare function startWalletWorkerIfConfigured(): Promise<void>;
125
127
  * Non-fatal, mirrors startCrawlerIfConfigured/startWalletWorkerIfConfigured.
126
128
  */
127
129
  export declare function redriveInterruptedSubmissionsIfConfigured(): Promise<void>;
128
- export {};
129
130
  //# sourceMappingURL=server.d.ts.map
package/srv/server.js CHANGED
@@ -1,41 +1,9 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
36
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
4
  };
38
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.activateAgentGrants = exports.loadAgentGrantsConfig = void 0;
39
7
  exports.getAppContext = getAppContext;
40
8
  exports.getCardanoIndexer = getCardanoIndexer;
41
9
  exports.getCardanoClient = getCardanoClient;
@@ -59,8 +27,10 @@ const cardano_tx_builder_1 = require("./blockchain/cardano-tx-builder");
59
27
  const hsm_signer_1 = require("./blockchain/signing/hsm-signer");
60
28
  const errors_1 = require("./utils/errors");
61
29
  const network_context_1 = require("./utils/network-context");
30
+ const db_sanitize_1 = require("./utils/db-sanitize");
62
31
  const crawler_1 = require("./blockchain/crawler");
63
32
  const wallet_worker_1 = require("./blockchain/wallet-worker");
33
+ const agent_grants_config_1 = require("./utils/agent-grants-config");
64
34
  const process_1 = require("process");
65
35
  const logger = cds_1.default.log('ODATANO');
66
36
  const VALID_NETWORKS = ['mainnet', 'preview', 'preprod'];
@@ -102,6 +72,10 @@ async function initializeAppContext(config, protocolParams, hsmConfig) {
102
72
  // Create CardanoTransactionBuilder with the client
103
73
  const cardanoTxBuilder = new cardano_tx_builder_1.CardanoTransactionBuilder(cardanoClient);
104
74
  await cardanoTxBuilder.init(protocolParams);
75
+ // PostgreSQL rejects U+0000 in text/JSON. One db-level `before` hook covers every
76
+ // write of this plugin — crawler bulk UPSERTs and the lazy indexing paths alike.
77
+ if ((0, db_sanitize_1.installDbSanitizer)())
78
+ logger.debug('DB NUL sanitizer installed');
105
79
  // Create CardanoIndexer with client and transaction builder
106
80
  const cardanoIndexer = new cardano_indexer_1.CardanoIndexer(cardanoClient, cardanoTxBuilder);
107
81
  // Initialize HSM signer if configured (failure is non-fatal — won't crash the app)
@@ -124,6 +98,16 @@ async function initializeAppContext(config, protocolParams, hsmConfig) {
124
98
  cardanoTxBuilder,
125
99
  };
126
100
  }
101
+ /** Agent-grant feature switch (AGENT_GRANTS_DESIGN.md); lives in its own module so src/plugin.ts can read it at load. */
102
+ var agent_grants_config_2 = require("./utils/agent-grants-config");
103
+ Object.defineProperty(exports, "loadAgentGrantsConfig", { enumerable: true, get: function () { return agent_grants_config_2.loadAgentGrantsConfig; } });
104
+ Object.defineProperty(exports, "activateAgentGrants", { enumerable: true, get: function () { return agent_grants_config_2.activateAgentGrants; } });
105
+ // Standalone mode (`cds serve` / `cds watch` in this project): CAP loads
106
+ // cds-plugin.js only from dependencies, so src/plugin.ts never runs here and
107
+ // agent grants would stay off regardless of AGENT_GRANTS_ENABLED. bin/serve.js
108
+ // imports this file before cds.server() instantiates the middlewares, so the
109
+ // auth impl can still be swapped. Idempotent: a no-op after the plugin's call.
110
+ (0, agent_grants_config_1.activateAgentGrants)();
127
111
  /**
128
112
  * Get the application context (must be called after bootstrap)
129
113
  * @throws {ProviderUnavailableError} 503 when uninitialized — request handlers using
@@ -578,7 +562,7 @@ async function redriveInterruptedSubmissionsIfConfigured() {
578
562
  if (process_1.env.SKIP_AUTO_INIT === 'true' || !appContext)
579
563
  return;
580
564
  try {
581
- const { redriveInterruptedSubmissions } = await Promise.resolve().then(() => __importStar(require('./blockchain/signing/submission-finalizer')));
565
+ const { redriveInterruptedSubmissions } = require('./blockchain/signing/submission-finalizer');
582
566
  const attempted = await redriveInterruptedSubmissions();
583
567
  if (attempted > 0)
584
568
  logger.info(`Re-drove ${attempted} interrupted deferred submission(s)`);