@odatano/core 2.0.0-rc.31 → 2.0.0-rc.33

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 (36) hide show
  1. package/@cds-models/CardanoODataService/index.d.ts +11 -0
  2. package/@cds-models/CardanoODataService/index.js +1 -0
  3. package/@cds-models/index.d.ts +53 -0
  4. package/@cds-models/index.js +9 -0
  5. package/db/schema.cds +1 -1
  6. package/db/types.cds +83 -0
  7. package/package.json +1 -1
  8. package/src/index.d.ts +7 -1
  9. package/src/index.js +17 -1
  10. package/srv/blockchain/backends/blockfrost-backend.js +2 -1
  11. package/srv/blockchain/backends/koios-backend.js +22 -20
  12. package/srv/blockchain/backends/ogmios-backend.js +2 -1
  13. package/srv/blockchain/cardano-indexer.d.ts +10 -1
  14. package/srv/blockchain/cardano-indexer.js +47 -2
  15. package/srv/blockchain/signing/signature-verifier.d.ts +6 -1
  16. package/srv/blockchain/signing/signature-verifier.js +62 -24
  17. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +2 -0
  18. package/srv/blockchain/transaction-building/buildooor-tx.js +57 -23
  19. package/srv/cardano-service.cds +8 -1
  20. package/srv/cardano-service.js +8 -0
  21. package/srv/cardano-sign-service.js +2 -11
  22. package/srv/cardano-tx-service.cds +3 -3
  23. package/srv/cardano-tx-service.js +5 -2
  24. package/srv/cbor/index.d.ts +1 -1
  25. package/srv/cbor/parse.d.ts +25 -0
  26. package/srv/cbor/parse.js +49 -1
  27. package/srv/utils/epoch-slots.d.ts +8 -1
  28. package/srv/utils/epoch-slots.js +20 -2
  29. package/srv/utils/mappers.js +1 -1
  30. package/srv/utils/signing-helper.d.ts +6 -1
  31. package/srv/utils/signing-helper.js +33 -35
  32. package/srv/utils/tx-build-helper.d.ts +2 -1
  33. package/srv/utils/tx-build-helper.js +7 -1
  34. package/srv/utils/tx-request-parsers.d.ts +1 -1
  35. package/srv/utils/tx-request-parsers.js +4 -4
  36. package/srv/utils/types.d.ts +20 -1
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.SignatureVerifier = void 0;
7
+ exports.verifyTxWitnesses = verifyTxWitnesses;
7
8
  exports.getSignatureVerifier = getSignatureVerifier;
8
9
  const cds_1 = __importDefault(require("@sap/cds"));
9
10
  const cbor_1 = require("@harmoniclabs/cbor");
@@ -24,44 +25,83 @@ function computeBodyHash(txBytes) {
24
25
  return (0, uint8array_utils_1.toHex)((0, crypto_1.blake2b_256)(tx.array[0].subCborRef.toBuffer()));
25
26
  }
26
27
  /**
27
- * Extract vkey witnesses (raw public key + signature bytes) from a transaction's
28
- * witness set (CBOR array index 1, map key 0). Conway wraps the witness array in CBOR
29
- * tag 258 (set) — unwrapped here. Returns [] when the tx has no vkey witnesses.
28
+ * Read vkey witnesses (raw public key + signature bytes) from a transaction's witness set
29
+ * (CBOR array index 1, map key 0). Conway wraps the witness array in CBOR tag 258 (set),
30
+ * which is unwrapped here. `malformed` counts entries that are not a [vkey, signature] byte pair.
30
31
  */
31
- function extractVkeyWitnesses(txBytes) {
32
+ function readVkeyWitnesses(txBytes) {
32
33
  const tx = cbor_1.Cbor.parse(txBytes);
33
34
  if (!(tx instanceof cbor_1.CborArray) || !(tx.array[1] instanceof cbor_1.CborMap))
34
- return [];
35
+ return { witnesses: [], malformed: 0 };
35
36
  const entry = tx.array[1].map.find(e => e.k instanceof cbor_1.CborUInt && Number(e.k.num) === 0);
36
37
  if (!entry)
37
- return [];
38
+ return { witnesses: [], malformed: 0 };
38
39
  let arr = entry.v;
39
40
  if (arr instanceof cbor_1.CborTag)
40
41
  arr = arr.data;
41
42
  if (!(arr instanceof cbor_1.CborArray))
42
- return [];
43
- // Skip entries that are not a [vkey, signature] pair of byte strings instead of
44
- // surfacing an opaque TypeError.
43
+ return { witnesses: [], malformed: 0 };
45
44
  const witnesses = [];
46
- let skipped = 0;
47
- for (const pair of arr.array) {
45
+ let malformed = 0;
46
+ arr.array.forEach((pair, index) => {
48
47
  if (!(pair instanceof cbor_1.CborArray) || pair.array.length !== 2) {
49
- skipped++;
50
- continue;
48
+ malformed++;
49
+ return;
51
50
  }
52
51
  const [vk, sg] = pair.array;
53
52
  if (!(vk instanceof cbor_1.CborBytes) || !(sg instanceof cbor_1.CborBytes)) {
54
- skipped++;
55
- continue;
53
+ malformed++;
54
+ return;
56
55
  }
57
- witnesses.push({ pubKey: vk.bytes, signature: sg.bytes });
58
- }
59
- if (skipped > 0) {
56
+ witnesses.push({ index, pubKey: vk.bytes, signature: sg.bytes });
57
+ });
58
+ return { witnesses, malformed };
59
+ }
60
+ /** Well-formed vkey witnesses; [] when the tx has none. Malformed entries are skipped with a warning. */
61
+ function extractVkeyWitnesses(txBytes) {
62
+ const { witnesses, malformed } = readVkeyWitnesses(txBytes);
63
+ if (malformed > 0) {
60
64
  // not fatal, but a malformed witness in a signed tx is suspicious — surface it
61
- logger.warn(`Skipped ${skipped} malformed vkey witness entr${skipped === 1 ? 'y' : 'ies'} while verifying (expected [vkey, signature] byte pairs)`);
65
+ logger.warn(`Skipped ${malformed} malformed vkey witness entr${malformed === 1 ? 'y' : 'ies'} while verifying (expected [vkey, signature] byte pairs)`);
62
66
  }
63
67
  return witnesses;
64
68
  }
69
+ /** Ed25519 check of one witness over the body hash; false for a key or signature of the wrong length. */
70
+ function signatureValid(w, bodyHashBytes) {
71
+ try {
72
+ return (0, crypto_1.verifyEd25519Signature_sync)(w.signature, bodyHashBytes, w.pubKey);
73
+ }
74
+ catch {
75
+ return false;
76
+ }
77
+ }
78
+ /**
79
+ * Check every vkey witness of a signed tx against its body hash. Pure, needs no initialize().
80
+ * A tx without vkey witnesses is valid here; which keys had to sign is the caller's check.
81
+ */
82
+ function verifyTxWitnesses(signedTxCbor) {
83
+ const errors = [];
84
+ const signerKeyHashes = [];
85
+ let txBodyHash = null;
86
+ try {
87
+ const txBytes = (0, uint8array_utils_1.fromHex)(signedTxCbor);
88
+ txBodyHash = computeBodyHash(txBytes);
89
+ const bodyHashBytes = (0, uint8array_utils_1.fromHex)(txBodyHash);
90
+ const { witnesses, malformed } = readVkeyWitnesses(txBytes);
91
+ if (malformed > 0)
92
+ errors.push(`${malformed} vkey witness entr${malformed === 1 ? 'y is' : 'ies are'} not a [vkey, signature] byte pair`);
93
+ for (const w of witnesses) {
94
+ if (signatureValid(w, bodyHashBytes))
95
+ signerKeyHashes.push((0, uint8array_utils_1.toHex)((0, crypto_1.blake2b_224)(w.pubKey)));
96
+ else
97
+ errors.push(`Invalid signature at witness index ${w.index}`);
98
+ }
99
+ }
100
+ catch (error) {
101
+ errors.push(`Failed to read transaction: ${error instanceof Error ? error.message : String(error)}`);
102
+ }
103
+ return { valid: errors.length === 0, txBodyHash, signerKeyHashes, errors };
104
+ }
65
105
  /**
66
106
  * Verifies externally signed transactions without private keys: CBOR parse, body-hash
67
107
  * integrity against the build, required signers present, Ed25519 check per witness.
@@ -120,11 +160,9 @@ class SignatureVerifier {
120
160
  // verify each signature cryptographically against the transaction body hash
121
161
  if (vkeyWitnesses.length > 0) {
122
162
  const bodyHashBytes = (0, uint8array_utils_1.fromHex)(computedHash);
123
- for (let i = 0; i < vkeyWitnesses.length; i++) {
124
- const { pubKey, signature } = vkeyWitnesses[i];
125
- const isValidSig = (0, crypto_1.verifyEd25519Signature_sync)(signature, bodyHashBytes, pubKey);
126
- if (!isValidSig) {
127
- result.errorMessage = `Invalid signature at witness index ${i}. The signature does not match the transaction body.`;
163
+ for (const w of vkeyWitnesses) {
164
+ if (!signatureValid(w, bodyHashBytes)) {
165
+ result.errorMessage = `Invalid signature at witness index ${w.index}. The signature does not match the transaction body.`;
128
166
  logger.warn(result.errorMessage);
129
167
  return result;
130
168
  }
@@ -160,6 +160,8 @@ export declare class BuildooorTxBuilder implements CardanoTxBuilder {
160
160
  * Pick the smallest ADA-only UTxO covering COLLATERAL_LOVELACE as collateral and return the
161
161
  * rest as funding; excess above the floor goes back via collateralReturn when it meets min-ADA
162
162
  * (Buildooor sets no collateralReturn for ADA-only collateral). Throws without an ADA-only UTxO.
163
+ * When the rest cannot pay `requiredLovelace` plus fee and change, the collateral UTxO is
164
+ * funding too. The ledger allows one UTxO as input and as collateral.
163
165
  */
164
166
  private _setupCollateral;
165
167
  /** Build a Ledger Value from lovelace + optional multi-asset array */
@@ -225,13 +225,15 @@ class BuildooorTxBuilder {
225
225
  return this._buildResult(req, ctx, this._extractTxDetails(tx), { forcedInputsUsed: forcedInputs.length });
226
226
  }
227
227
  catch (err) {
228
- (0, tx_build_helper_1.mapBuilderError)(err);
228
+ // one requested output; Buildooor appends the change after it
229
+ (0, tx_build_helper_1.mapBuilderError)(err, undefined, undefined, 1);
229
230
  }
230
231
  }
231
232
  async buildUnsignedMintTransaction(req, ctx) {
232
233
  // Set once the collateral partition is known: it explains insufficient-funds rejections
233
234
  // that the builder's own message cannot attribute.
234
235
  let coinSelectionContext;
236
+ let requestedOutputs;
235
237
  try {
236
238
  this._ensureCurrentProtocolParameters(ctx);
237
239
  const recipientAddress = cardano_ledger_ts_1.Address.fromString(req.recipientAddress);
@@ -251,11 +253,6 @@ class BuildooorTxBuilder {
251
253
  // collateral and coin selection operate on the remainder only.
252
254
  const { forced, rest } = this._partitionForcedInputs(ctx.utxos, req.forceInputs, this._referencedKeys(ctx, req.referenceInputs), req.protectInputs);
253
255
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
254
- // Collateral + funding separation (from candidates only — forced inputs cannot double as collateral)
255
- const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest);
256
- coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
257
- const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
258
- const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
259
256
  // Funding must cover the lovelace plus, for extra outputs, their lovelace and any asset
260
257
  // demand the mint itself does not cover.
261
258
  let requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount));
@@ -263,6 +260,11 @@ class BuildooorTxBuilder {
263
260
  const { lovelace, assets } = this._extraOutputsFundingAfterMint(req.mintActions, req.extraOutputs);
264
261
  requiredFundingValue = cardano_ledger_ts_1.Value.add(requiredFundingValue, this._buildLedgerValue(lovelace, assets));
265
262
  }
263
+ // Collateral + funding separation (from candidates only — forced inputs cannot double as collateral)
264
+ const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest, requiredFundingValue.lovelaces);
265
+ coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
266
+ const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
267
+ const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
266
268
  const selectedFunding = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
267
269
  const inputs = [...forcedInputs, ...selectedFunding];
268
270
  logger.debug(`Coin selection: ${selectedFunding.length}/${allFundingInputs.length} UTxOs selected (${forcedInputs.length} forced) for mint`);
@@ -289,6 +291,7 @@ class BuildooorTxBuilder {
289
291
  const outputs = [this._buildTxOut(recipientAddress, outputValue, resolvedInlineDatum, refScript)];
290
292
  // Append extra outputs, each independently min-ADA checked.
291
293
  this._appendExtraOutputs(outputs, resolvedExtraOutputs);
294
+ requestedOutputs = outputs.length;
292
295
  // Mint entries; Buildooor ignores caller-supplied execution units, the real ones are
293
296
  // stamped post-build by _buildScriptTx.
294
297
  const mints = this._buildMintEntries(req.mintActions, (a, i) => ({ inline: this._mintActionScript(a, script, i) }), resolvedMintRedeemer, resolveCtx);
@@ -316,12 +319,13 @@ class BuildooorTxBuilder {
316
319
  return this._buildResult(req, ctx, this._extractTxDetails(tx), { scriptHash: script.hash.toString(), forcedInputsUsed: forcedInputs.length, referenceInputsUsed: readonlyRefInputs.length });
317
320
  }
318
321
  catch (err) {
319
- (0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext);
322
+ (0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext, requestedOutputs);
320
323
  }
321
324
  }
322
325
  async buildUnsignedPlutusSpendTransaction(req, ctx) {
323
326
  // See buildUnsignedMintTransaction — same collateral-partition context for rejections.
324
327
  let coinSelectionContext;
328
+ let requestedOutputs;
325
329
  try {
326
330
  this._ensureCurrentProtocolParameters(ctx);
327
331
  const { plutusScriptExecution } = req;
@@ -344,19 +348,21 @@ class BuildooorTxBuilder {
344
348
  const forceInputsFiltered = (req.forceInputs ?? []).filter(r => !(r.txHash === scriptUtxoRef.txHash && r.outputIndex === scriptUtxoRef.outputIndex));
345
349
  const { forced, rest } = this._partitionForcedInputs(senderUtxos, forceInputsFiltered, this._referencedKeys(ctx, req.referenceInputs), req.protectInputs);
346
350
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
347
- // Collateral + funding separation (from candidates only — forced inputs cannot double as collateral)
348
- const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest);
349
- coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
350
- const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
351
351
  // Funding covers fee + min change (the script UTxO covers the output) plus extra outputs;
352
352
  // assets the script UTxO already provides net out, so over-requesting is harmless.
353
- const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
354
353
  let requiredFundingValue = cardano_ledger_ts_1.Value.lovelaces(BigInt(req.lovelaceAmount || const_1.MIN_CHANGE_LOVELACE));
355
354
  if (req.extraOutputs && req.extraOutputs.length > 0) {
356
355
  for (const extra of req.extraOutputs) {
357
356
  requiredFundingValue = cardano_ledger_ts_1.Value.add(requiredFundingValue, this._buildLedgerValue(BigInt(extra.lovelaceAmount), extra.assets));
358
357
  }
359
358
  }
359
+ // Collateral + funding separation (from candidates only — forced inputs cannot double as collateral).
360
+ // The script UTxO pays its part of the outputs, so the collateral check counts only the rest.
361
+ const fundingGap = requiredFundingValue.lovelaces - (0, tx_build_helper_1.getLovelace)(scriptOdatanoUtxo);
362
+ const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest, fundingGap > 0n ? fundingGap : 0n);
363
+ coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
364
+ const fundingLedgerUtxos = fundingUtxos.map(utxo => this._mapMultiAssetUtxoToLedgerUtxo(utxo));
365
+ const allFundingInputs = fundingLedgerUtxos.map(utxo => ({ utxo }));
360
366
  const selectedFundingInputs = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
361
367
  logger.debug(`Coin selection: ${selectedFundingInputs.length}/${allFundingInputs.length} UTxOs selected (${forcedInputs.length} forced) for Plutus spend`);
362
368
  // Compute the final input order (Buildooor's lex sort) and resolve __INPUT_IDX__ placeholders
@@ -407,6 +413,7 @@ class BuildooorTxBuilder {
407
413
  const outputs = [this._buildTxOut(recipientAddress, outputValue, resolvedPrimaryInlineDatum, primaryRefScript)];
408
414
  // Append extra outputs, each independently min-ADA checked.
409
415
  this._appendExtraOutputs(outputs, resolvedExtraOutputs);
416
+ requestedOutputs = outputs.length;
410
417
  // Mint entries for the combined spend+mint; Buildooor ignores caller-supplied execution
411
418
  // units, the real ones are stamped post-build by _buildScriptTx.
412
419
  const mints = hasMint
@@ -441,7 +448,7 @@ class BuildooorTxBuilder {
441
448
  });
442
449
  }
443
450
  catch (err) {
444
- (0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext);
451
+ (0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext, requestedOutputs);
445
452
  }
446
453
  }
447
454
  /**
@@ -450,6 +457,7 @@ class BuildooorTxBuilder {
450
457
  */
451
458
  async buildUnsignedPlutusTransaction(req, ctx) {
452
459
  let coinSelectionContext;
460
+ let requestedOutputs;
453
461
  try {
454
462
  this._ensureCurrentProtocolParameters(ctx);
455
463
  const keyOf = (r) => `${r.txHash.toLowerCase()}#${r.outputIndex}`;
@@ -550,9 +558,6 @@ class BuildooorTxBuilder {
550
558
  const { forced, rest } = this._partitionForcedInputs(senderUtxos, (req.forceInputs ?? []).filter(r => !scriptKeys.has(keyOf(r))), this._referencedKeys(ctx, req.referenceInputs, req.scriptInputs.flatMap(s => (s.referenceScript ? [s.referenceScript] : []))), req.protectInputs);
551
559
  this._checkForeignForcedInputs(forced, req);
552
560
  const forcedInputs = forced.map(u => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(u) }));
553
- const { collateralUtxos, fundingUtxos, collateralReturn } = this._setupCollateral(rest);
554
- coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
555
- const allFundingInputs = fundingUtxos.map(utxo => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(utxo) }));
556
561
  // Funding covers only what the outputs need beyond the script inputs, forced inputs, mints and
557
562
  // withdrawals (keepRelevant adds its own lovelace margin for fee and change).
558
563
  const need = new Map();
@@ -581,6 +586,14 @@ class BuildooorTxBuilder {
581
586
  ? cardano_ledger_ts_1.Value.lovelaces(qty)
582
587
  : this._buildLedgerValue(0n, [{ unit, quantity: qty.toString() }]));
583
588
  }
589
+ // Collateral only when a Plutus script runs; Buildooor writes given collaterals into any body.
590
+ const runsScript = scriptEntries.length > 0 || mintEntries.length > 0 ||
591
+ [...withdrawalEntries, ...certEntries].some(e => e.script || e.refLedgerUtxo);
592
+ const { collateralUtxos, fundingUtxos, collateralReturn } = runsScript
593
+ ? this._setupCollateral(rest, requiredFundingValue.lovelaces)
594
+ : { collateralUtxos: [], fundingUtxos: rest, collateralReturn: undefined };
595
+ coinSelectionContext = this._collateralPartitionContext(collateralUtxos, fundingUtxos);
596
+ const allFundingInputs = fundingUtxos.map(utxo => ({ utxo: this._mapMultiAssetUtxoToLedgerUtxo(utxo) }));
584
597
  const selectedFundingInputs = this.txBuilder.keepRelevant(requiredFundingValue, allFundingInputs);
585
598
  // Reference inputs: the caller's, minus the reference-script UTxOs Buildooor adds itself
586
599
  const refScriptKeys = new Set([...scriptEntries, ...withdrawalEntries, ...certEntries, ...mintEntries].filter(e => e.refLedgerUtxo).map(e => keyOf({ txHash: e.refLedgerUtxo.utxoRef.id.toString(), outputIndex: e.refLedgerUtxo.utxoRef.index })));
@@ -618,6 +631,7 @@ class BuildooorTxBuilder {
618
631
  ...o,
619
632
  inlineDatum: o.inlineDatum !== undefined ? (0, plutus_placeholders_1.resolveIndexPlaceholders)(o.inlineDatum, resolveCtx) : undefined,
620
633
  })));
634
+ requestedOutputs = outputs.length;
621
635
  const mints = mintEntries.length > 0
622
636
  ? this._buildMintEntries(mintEntries.map(e => e.m), (_a, i) => (mintEntries[i].script ? { inline: mintEntries[i].script } : { ref: mintEntries[i].refLedgerUtxo }), undefined, resolveCtx)
623
637
  : undefined;
@@ -655,7 +669,15 @@ class BuildooorTxBuilder {
655
669
  throw new errors_1.TransactionValidationError(`transaction is ${details.sizeBytes} bytes, above the maximum of ${maxTxSize}` +
656
670
  (inline > 0 ? `; ${inline} script input(s) carry their validator inline, a referenceScript would move it out of the transaction` : ''));
657
671
  }
658
- const scriptHashes = scriptEntries.map(e => e.script ? e.script.hash.toString() : e.scriptHash);
672
+ // the first script that runs: a spend, else a mint policy, else a withdrawal or certificate script
673
+ const scriptHashes = [
674
+ ...scriptEntries.map(e => e.script ? e.script.hash.toString() : e.scriptHash),
675
+ ...mintEntries.map(e => e.policyId),
676
+ ...[...withdrawalEntries, ...certEntries].flatMap(e => {
677
+ const hash = e.script?.hash ?? e.refLedgerUtxo?.resolved.refScript?.hash;
678
+ return hash ? [hash.toString()] : [];
679
+ }),
680
+ ];
659
681
  logger.debug(`Built unsigned Plutus transaction with ${scriptInputs.length} script input(s), fee ${details.feeLovelace}`);
660
682
  return this._buildResult(req, ctx, details, {
661
683
  scriptHash: scriptHashes[0],
@@ -664,7 +686,7 @@ class BuildooorTxBuilder {
664
686
  });
665
687
  }
666
688
  catch (err) {
667
- (0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext);
689
+ (0, tx_build_helper_1.mapBuilderError)(err, undefined, coinSelectionContext, requestedOutputs);
668
690
  }
669
691
  }
670
692
  /**
@@ -1200,17 +1222,25 @@ class BuildooorTxBuilder {
1200
1222
  * message counts only the funding pool, so the reservation would otherwise be invisible.
1201
1223
  */
1202
1224
  _collateralPartitionContext(collateralUtxos, fundingUtxos) {
1203
- const collateralLovelace = collateralUtxos.reduce((s, u) => s + u.resolved.value.lovelaces, 0n);
1204
1225
  const fundingLovelace = fundingUtxos.reduce((s, u) => s + (0, tx_build_helper_1.getLovelace)(u), 0n);
1205
- return `${collateralUtxos.length} UTxO(s) with ${collateralLovelace} lovelace reserved as collateral; ` +
1206
- `${fundingUtxos.length} UTxO(s) with ${fundingLovelace} lovelace remained for coin selection`;
1226
+ if (collateralUtxos.length === 0) {
1227
+ return `no script runs, so no collateral; ${fundingUtxos.length} UTxO(s) with ${fundingLovelace} lovelace for coin selection`;
1228
+ }
1229
+ const collateralLovelace = collateralUtxos.reduce((s, u) => s + u.resolved.value.lovelaces, 0n);
1230
+ const collateralKeys = new Set(collateralUtxos.map(u => `${u.utxoRef.id.toString()}#${u.utxoRef.index}`));
1231
+ const alsoFunding = fundingUtxos.some(u => collateralKeys.has(`${u.txHash}#${u.outputIndex}`));
1232
+ return `${collateralUtxos.length} UTxO(s) with ${collateralLovelace} lovelace reserved as collateral` +
1233
+ `${alsoFunding ? ' and also offered as funding' : ''}; ` +
1234
+ `${fundingUtxos.length} UTxO(s) with ${fundingLovelace} lovelace for coin selection`;
1207
1235
  }
1208
1236
  /**
1209
1237
  * Pick the smallest ADA-only UTxO covering COLLATERAL_LOVELACE as collateral and return the
1210
1238
  * rest as funding; excess above the floor goes back via collateralReturn when it meets min-ADA
1211
1239
  * (Buildooor sets no collateralReturn for ADA-only collateral). Throws without an ADA-only UTxO.
1240
+ * When the rest cannot pay `requiredLovelace` plus fee and change, the collateral UTxO is
1241
+ * funding too. The ledger allows one UTxO as input and as collateral.
1212
1242
  */
1213
- _setupCollateral(utxos) {
1243
+ _setupCollateral(utxos, requiredLovelace) {
1214
1244
  // ADA-only and without a reference script (a deployed script is not collateral); SetCollateral uses the same rule
1215
1245
  const adaOnly = utxos.filter(tx_build_helper_1.isCollateralCandidate);
1216
1246
  if (adaOnly.length === 0) {
@@ -1227,7 +1257,11 @@ class BuildooorTxBuilder {
1227
1257
  `collateral floor — the node will reject the transaction if collateralPercentage × fee exceeds it`);
1228
1258
  }
1229
1259
  const collateralUtxos = [this._mapOdatanoUtxoToLedgerUtxo(chosen)];
1230
- const fundingUtxos = utxos.filter(u => !(u.txHash === chosen.txHash && u.outputIndex === chosen.outputIndex));
1260
+ const rest = utxos.filter(u => !(u.txHash === chosen.txHash && u.outputIndex === chosen.outputIndex));
1261
+ const restLovelace = rest.reduce((sum, u) => sum + (0, tx_build_helper_1.getLovelace)(u), 0n);
1262
+ const fundingUtxos = restLovelace >= requiredLovelace + const_1.FEE_BUFFER_LOVELACE + BigInt(const_1.MIN_CHANGE_LOVELACE)
1263
+ ? rest
1264
+ : [...rest, chosen];
1231
1265
  // Cap the at-risk amount at the floor: return the excess to the owner.
1232
1266
  let collateralReturn;
1233
1267
  const excess = (0, tx_build_helper_1.getLovelace)(chosen) - const_1.COLLATERAL_LOVELACE;
@@ -1,5 +1,5 @@
1
1
  using {odatano.cardano as db} from '../db/schema';
2
- using { Blake2b256, Bech32, AssetUnit, ParsedTransaction } from '../db/types';
2
+ using { Blake2b256, Bech32, AssetUnit, ParsedTransaction, TransactionConfirmations } from '../db/types';
3
3
 
4
4
  /**
5
5
  * Cardano OData Service
@@ -258,6 +258,13 @@ service CardanoODataService @(impl: './cardano-service') {
258
258
  @description: 'The unique identifier of the transaction'
259
259
  hash: Blake2b256) returns Transactions;
260
260
 
261
+ @title : 'Get Transaction Confirmations'
262
+ @description: 'Number of blocks on top of a transaction, its own block included; 0 while it is not on chain. Uses the crawled chain when the crawler is synced, else the backends.'
263
+ action GetTransactionConfirmations(
264
+ @title: 'Transaction Hash'
265
+ @description: 'The unique identifier of the transaction'
266
+ txHash: Blake2b256) returns TransactionConfirmations;
267
+
261
268
  @title : 'Get Transaction Metadata by Tx Hash'
262
269
  @description: 'Retrieve transaction metadata using the Transaction Hash'
263
270
  action GetMetadataByTxHash(
@@ -257,6 +257,14 @@ module.exports = (srv) => {
257
257
  // ---------------------------------------------------------------------------
258
258
  srv.on('READ', Transactions, indexOnMissRead(Transactions, 'hash', validators_1.isTxHash, (db, h) => indexer().indexTransaction(db, h), { errorMessage: 'Invalid transaction hash format' }));
259
259
  srv.on('GetTransactionByHash', indexOnMissAction('GetTransactionByHash', Transactions, 'hash', validators_1.isTxHash, (db, h) => indexer().indexTransaction(db, h), { errorMessage: 'Invalid transaction hash format' }));
260
+ srv.on('GetTransactionConfirmations', async (req) => {
261
+ const { txHash } = req.data;
262
+ if (!txHash)
263
+ (0, errors_1.rejectMissing)(req, 'GetTransactionConfirmations', 'txHash');
264
+ if (!(0, validators_1.isTxHash)(txHash))
265
+ (0, errors_1.rejectInvalid)(req, 'GetTransactionConfirmations', 'Invalid transaction hash format', 'txHash');
266
+ return (0, backend_request_handler_1.handleRequest)(req, (db) => indexer().resolveTransactionConfirmations(db, txHash));
267
+ });
260
268
  // ---------------------------------------------------------------------------
261
269
  // Transaction Metadata
262
270
  // ---------------------------------------------------------------------------
@@ -167,14 +167,7 @@ module.exports = (srv) => {
167
167
  (0, errors_1.rejectInvalid)(req, 'VerifySignature', `Signing request status is '${current?.status ?? 'unknown'}', expected 'pending'`, 'signingRequestId');
168
168
  }
169
169
  // A CIP-30 wallet returns only the witness set; cardano-cli a full signed tx.
170
- let fullSignedTxCbor;
171
- if ((0, signing_helper_1.isWitnessSetCbor)(signedTxCbor)) {
172
- fullSignedTxCbor = (0, signing_helper_1.combineTransactionWithWitnesses)(signingRequest.unsignedTxCbor, signedTxCbor);
173
- logger.debug({ signingRequestId }, 'Combined witness set with unsigned transaction for verification');
174
- }
175
- else {
176
- fullSignedTxCbor = signedTxCbor;
177
- }
170
+ const fullSignedTxCbor = (0, signing_helper_1.toSignedTransaction)(signingRequest.unsignedTxCbor, signedTxCbor);
178
171
  // Verification is bound to the keys that must witness this tx.
179
172
  const requiredSigners = await resolveRequiredSigners(db, signingRequest, TransactionBuilds);
180
173
  const signerModule = (0, external_signer_1.getExternalSignerModule)();
@@ -229,9 +222,7 @@ module.exports = (srv) => {
229
222
  (0, errors_1.rejectInvalid)(req, 'SubmitVerifiedTransaction', 'Signing request has no associated build', 'signingRequestId');
230
223
  }
231
224
  // CIP-30 witness set or full signed tx
232
- const fullSignedTxCbor = (0, signing_helper_1.isWitnessSetCbor)(signedTxCbor)
233
- ? (0, signing_helper_1.combineTransactionWithWitnesses)(signingRequest.unsignedTxCbor, signedTxCbor)
234
- : signedTxCbor;
225
+ const fullSignedTxCbor = (0, signing_helper_1.toSignedTransaction)(signingRequest.unsignedTxCbor, signedTxCbor);
235
226
  // Throws on failure; bound to the keys that must witness this tx.
236
227
  const requiredSigners = await resolveRequiredSigners(db, signingRequest, TransactionBuilds);
237
228
  const verificationResult = (0, external_signer_1.getExternalSignerModule)().verifyOrThrow(fullSignedTxCbor, signingRequest.txBodyHash, { requiredSigners });
@@ -268,7 +268,7 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
268
268
  @description: 'The unique identifier of the transaction build'
269
269
  buildId: UUID,
270
270
  @title: 'Signed Transaction CBOR'
271
- @description: 'The CBOR of the signed transaction'
271
+ @description: 'The signed transaction, or the witness set a CIP-30 wallet returns from signTx; a witness set is added to the build transaction'
272
272
  signedTxCbor: String) returns TransactionSubmissions;
273
273
 
274
274
  @title : 'Submit Signed Transaction'
@@ -355,7 +355,7 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
355
355
  validityEndMs: String) returns TransactionBuilds;
356
356
 
357
357
  @title : 'Build Plutus Transaction'
358
- @description: 'Spend several script UTxOs in one transaction, each with its own redeemer (inline validator or a reference-script UTxO). The outputs are built exactly in the given order, change comes after them. The execution units of every redeemer are returned under redeemers.'
358
+ @description: 'Spend script UTxOs, each with its own redeemer (inline validator or a reference-script UTxO), mint, withdraw and certify in one transaction; script inputs are optional, so a mint or a withdraw-zero alone works. Collateral is added only when a script runs. The outputs are built exactly in the given order, change comes after them. The execution units of every redeemer are returned under redeemers.'
359
359
  action BuildPlutusTransaction(
360
360
  @title: 'Sender Address'
361
361
  @description: 'Pays the fee, funds the rest and provides the ADA-only collateral'
@@ -364,7 +364,7 @@ service CardanoTransactionService @(impl: './cardano-tx-service') {
364
364
  @description: 'Receives the change; defaults to senderAddress'
365
365
  changeAddress: Bech32,
366
366
  @title: 'Script Inputs JSON'
367
- @description: 'Required JSON array, 1..16 entries: {txHash, outputIndex, validatorScript (CBOR hex) | referenceScript: {txHash, outputIndex}, scriptParamsJson?, redeemerJson | redeemerCbor, datumJson | datumCbor (hash datums only)}. The *Cbor forms take PlutusData CBOR hex byte for byte. In any redeemer or datum JSON, __INPUT_IDX:<txHash>#<n>__ resolves to the index in the final sorted inputs, __REF_IDX:<txHash>#<n>__ to the index in the sorted reference inputs (reference-script UTxOs included) and __WDRL_IDX:<credential hash>__ to the index in the withdrawals in ledger order.'
367
+ @description: 'Optional JSON array, 0..16 entries: {txHash, outputIndex, validatorScript (CBOR hex) | referenceScript: {txHash, outputIndex}, scriptParamsJson?, redeemerJson | redeemerCbor, datumJson | datumCbor (hash datums only)}. The *Cbor forms take PlutusData CBOR hex byte for byte. In any redeemer or datum JSON, __INPUT_IDX:<txHash>#<n>__ resolves to the index in the final sorted inputs, __REF_IDX:<txHash>#<n>__ to the index in the sorted reference inputs (reference-script UTxOs included) and __WDRL_IDX:<credential hash>__ to the index in the withdrawals in ledger order.'
368
368
  scriptInputsJson: String,
369
369
  @title: 'Outputs JSON'
370
370
  @description: 'Required JSON array of outputs in this order: {address, lovelaceAmount, assets?: [{unit, quantity}], inlineDatumJson? | inlineDatumCbor? | datumHash?, referenceScriptHex?}. Each is min-ADA checked; change is appended after them and never merged into one.'
@@ -12,6 +12,7 @@ const tx_build_helper_1 = require("./utils/tx-build-helper");
12
12
  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
+ const signing_helper_1 = require("./utils/signing-helper");
15
16
  const const_1 = require("./utils/const");
16
17
  const tx_request_parsers_1 = require("./utils/tx-request-parsers");
17
18
  const VALID_DERIVE_NETWORKS = ['mainnet', 'preview', 'preprod'];
@@ -825,14 +826,16 @@ module.exports = (srv) => {
825
826
  // SubmitTransaction — submit the signed CBOR of a previous build.
826
827
  srv.on('SubmitTransaction', async (req) => {
827
828
  logger.debug('SubmitTransaction Action handler called');
828
- const { buildId, signedTxCbor } = req.data;
829
- const errors = (0, validators_1.validateTransactionInputs)({ buildId, signedTxCbor }, ['buildId', 'signedTxCbor']);
829
+ const { buildId, signedTxCbor: signedInput } = req.data;
830
+ const errors = (0, validators_1.validateTransactionInputs)({ buildId, signedTxCbor: signedInput }, ['buildId', 'signedTxCbor']);
830
831
  (0, errors_1.throwIfValidationErrors)(req, 'SubmitTransaction', errors);
831
832
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
832
833
  logger.debug({ buildId }, 'Submitting signed transaction');
833
834
  const existing = await db.run(SELECT.one.from(TransactionBuilds).where({ id: buildId }));
834
835
  if (!existing)
835
836
  throw new errors_1.NotFoundError(`Build '${buildId}'`);
837
+ // A CIP-30 wallet returns only the witness set; cardano-cli a full signed tx.
838
+ const signedTxCbor = (0, signing_helper_1.toSignedTransaction)(existing.unsignedTxCbor, signedInput);
836
839
  // The signed CBOR must belong to this build (audit-trail integrity)
837
840
  const signedTxHash = (0, tx_build_helper_1.getTxHashFromCbor)(signedTxCbor);
838
841
  if (signedTxHash !== existing.txBodyHash) {
@@ -1,2 +1,2 @@
1
- export { parseTransaction, type ParsedTransaction, type ParsedInput, type ParsedOutput, type ParsedAsset, type ParsedWitnesses, } from './parse';
1
+ export { parseTransaction, type ParsedTransaction, type ParsedInput, type ParsedOutput, type ParsedAsset, type ParsedWitnesses, type ParsedWithdrawal, type ParsedCertificate, } from './parse';
2
2
  //# sourceMappingURL=index.d.ts.map
@@ -15,6 +15,19 @@ export interface ParsedOutput {
15
15
  datumHash: string | null;
16
16
  inlineDatumHex: string | null;
17
17
  referenceScriptHex: string | null;
18
+ /** Byte length of the output as it stands in the transaction. */
19
+ cborSize: number;
20
+ }
21
+ export interface ParsedWithdrawal {
22
+ /** Bech32 reward address. */
23
+ rewardAddress: string;
24
+ lovelace: string;
25
+ }
26
+ export interface ParsedCertificate {
27
+ /** Position in the body's certificate list. */
28
+ index: number;
29
+ /** Ledger certificate name, e.g. `StakeDelegation` or `RegistrationDrep`. */
30
+ type: string;
18
31
  }
19
32
  export interface ParsedWitnesses {
20
33
  vkeyCount: number;
@@ -35,6 +48,8 @@ export interface ParsedTransaction {
35
48
  * consumer needing that split must compare against the service network.
36
49
  */
37
50
  network: 'mainnet' | 'testnet' | null;
51
+ /** Body field 15: 1 = mainnet, 0 = testnet, null if absent. */
52
+ networkId: number | null;
38
53
  inputs: ParsedInput[];
39
54
  outputs: ParsedOutput[];
40
55
  /** Validity-interval start slot (decimal string) or `null` if absent. */
@@ -48,6 +63,16 @@ export interface ParsedTransaction {
48
63
  /** Metadata labels present (uint64 → decimal string); full payload via GetMetadataByTxHash for submitted txs. */
49
64
  metadataLabels: string[];
50
65
  collateral: ParsedInput[];
66
+ referenceInputs: ParsedInput[];
67
+ withdrawals: ParsedWithdrawal[];
68
+ certificates: ParsedCertificate[];
69
+ /** Number of votes over all voters; 0 if the body has no voting procedures. */
70
+ votingProcedures: number;
71
+ proposalProcedures: number;
72
+ /** Lovelace (decimal string) or `null` if absent. */
73
+ treasuryDonation: string | null;
74
+ /** Lovelace (decimal string) or `null` if absent. */
75
+ currentTreasuryValue: string | null;
51
76
  /** 28-byte Ed25519 key hashes listed in the tx body's required_signers field. */
52
77
  requiredSigners: string[];
53
78
  scriptDataHash: string | null;
package/srv/cbor/parse.js CHANGED
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.parseTransaction = parseTransaction;
4
4
  const buildooor_1 = require("@harmoniclabs/buildooor");
5
+ const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
5
6
  const cbor_1 = require("@harmoniclabs/cbor");
6
7
  const errors_1 = require("../utils/errors");
7
8
  const error_codes_1 = require("../utils/error-codes");
@@ -14,8 +15,12 @@ const error_codes_1 = require("../utils/error-codes");
14
15
  */
15
16
  function parseTransaction(cborHex) {
16
17
  let tx;
18
+ let raw;
17
19
  try {
18
- tx = buildooor_1.Tx.fromCbor(Buffer.from(cborHex, 'hex'));
20
+ // one decode for both readers; keepRef keeps the original bytes for the body hash and datums
21
+ const parsed = cbor_1.Cbor.parse(Buffer.from(cborHex, 'hex'), { keepRef: true });
22
+ tx = buildooor_1.Tx.fromCborObj(parsed);
23
+ raw = readBodyFields(parsed);
19
24
  }
20
25
  catch (e) {
21
26
  const msg = e instanceof Error ? e.message : String(e);
@@ -25,6 +30,7 @@ function parseTransaction(cborHex) {
25
30
  return {
26
31
  txHash: body.hash.toString(),
27
32
  network: normalizeNetwork(body.network),
33
+ networkId: raw.networkId,
28
34
  inputs: body.inputs.map(mapInput),
29
35
  outputs: body.outputs.map(mapOutput),
30
36
  validityStart: body.validityIntervalStart != null ? body.validityIntervalStart.toString() : null,
@@ -33,6 +39,16 @@ function parseTransaction(cborHex) {
33
39
  mint: mapMint(body.mint),
34
40
  metadataLabels: extractMetadataLabels(tx.auxiliaryData),
35
41
  collateral: (body.collateralInputs ?? []).map(mapInput),
42
+ referenceInputs: (body.refInputs ?? []).map(mapInput),
43
+ withdrawals: (body.withdrawals?.map ?? []).map((w) => ({
44
+ rewardAddress: w.rewardAccount.toString(),
45
+ lovelace: w.amount.toString(),
46
+ })),
47
+ certificates: (body.certs ?? []).map(mapCertificate),
48
+ votingProcedures: raw.votingProcedures,
49
+ proposalProcedures: raw.proposalProcedures,
50
+ treasuryDonation: raw.treasuryDonation,
51
+ currentTreasuryValue: raw.currentTreasuryValue,
36
52
  requiredSigners: (body.requiredSigners ?? []).map((s) => s.toString()),
37
53
  scriptDataHash: body.scriptDataHash ? body.scriptDataHash.toString() : null,
38
54
  witnesses: countWitnesses(tx.witnesses),
@@ -80,8 +96,40 @@ function mapOutput(out) {
80
96
  datumHash,
81
97
  inlineDatumHex,
82
98
  referenceScriptHex,
99
+ // the bytes as received; a re-encoding can be shorter
100
+ cborSize: out.cborRef ? out.cborRef.toBuffer().length : out.toCborBytes().length,
83
101
  };
84
102
  }
103
+ function mapCertificate(cert, index) {
104
+ return { index, type: (0, cardano_ledger_ts_1.certTypeToString)(cert.certType) };
105
+ }
106
+ /** Body fields 15 and 19 to 22 as they stand in the bytes. `Tx.fromCbor` drops 19 to 22 and maps any network byte other than 0 to mainnet. */
107
+ function readBodyFields(parsed) {
108
+ const body = parsed instanceof cbor_1.CborArray ? parsed.array[0] : undefined;
109
+ const field = (key) => body instanceof cbor_1.CborMap ? body.map.find(e => e.k instanceof cbor_1.CborUInt && e.k.num === BigInt(key))?.v : undefined;
110
+ const uint = (key) => {
111
+ const v = field(key);
112
+ return v instanceof cbor_1.CborUInt ? v.num : null;
113
+ };
114
+ // voting_procedures = { voter => { gov_action_id => voting_procedure } }
115
+ const voting = field(19);
116
+ const votes = voting instanceof cbor_1.CborMap
117
+ ? voting.map.reduce((n, e) => n + (e.v instanceof cbor_1.CborMap ? e.v.map.length : 0), 0)
118
+ : 0;
119
+ const networkId = uint(15);
120
+ return {
121
+ networkId: networkId == null ? null : Number(networkId),
122
+ votingProcedures: votes,
123
+ proposalProcedures: setItems(field(20)).length,
124
+ treasuryDonation: uint(22)?.toString() ?? null,
125
+ currentTreasuryValue: uint(21)?.toString() ?? null,
126
+ };
127
+ }
128
+ /** Items of a CBOR set, with or without the Conway set tag 258. */
129
+ function setItems(obj) {
130
+ const inner = obj instanceof cbor_1.CborTag ? obj.data : obj;
131
+ return inner instanceof cbor_1.CborArray ? inner.array : [];
132
+ }
85
133
  /** Inline datum bytes as they stand in the transaction; decoding and re-encoding may change them. */
86
134
  function inlineDatumBytes(out) {
87
135
  if (!out.cborRef)
@@ -5,9 +5,16 @@ export declare function epochOfSlot(network: EpochNetwork, slot: number): number
5
5
  /** First absolute slot of an epoch, from the network's Shelley anchor. */
6
6
  export declare function epochStartSlot(network: EpochNetwork, epoch: number): number;
7
7
  /**
8
- * Absolute POSIX seconds for a slot via the Shelley-anchored genesis infos (exact for Shelley-era
8
+ * Absolute POSIX milliseconds for a slot via the Shelley-anchored genesis infos (exact for Shelley-era
9
9
  * slots). Ogmios' `eraStart.time` is RelativeTime since system start, not a Unix timestamp.
10
10
  */
11
+ export declare function slotToPosixMs(network: EpochNetwork, slot: number): number;
12
+ /** Absolute POSIX seconds for a slot, rounded down. */
11
13
  export declare function slotToPosixSeconds(network: EpochNetwork, slot: number): number;
14
+ /**
15
+ * Slot that contains a POSIX time in milliseconds.
16
+ * @throws RangeError for a time before the Shelley start, where slots were 20 s long.
17
+ */
18
+ export declare function posixToSlot(network: EpochNetwork, posixMs: number): number;
12
19
  export {};
13
20
  //# sourceMappingURL=epoch-slots.d.ts.map