@odatano/core 1.9.2 → 1.9.4

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.
@@ -208,7 +208,7 @@ service CardanoODataService @(impl: './cardano-service') {
208
208
  action GetMetadataByTxHash(
209
209
  @title: 'Transaction Hash'
210
210
  @description: 'The unique identifier of the transaction'
211
- tx_hash: Blake2b256) returns many TransactionMetadata;
211
+ txHash: Blake2b256) returns many TransactionMetadata;
212
212
 
213
213
  @title : 'Get Addresses by Bech32 Address'
214
214
  @description: 'Retrieve address information using the Bech32 Address'
@@ -249,17 +249,18 @@ module.exports = (srv) => {
249
249
  srv.on('READ', TransactionMetadata, indexOnMissRead(TransactionMetadata, 'tx_hash', validators_1.isTxHash, (db, h) => indexer().indexTransactionMetadata(db, h), { errorMessage: 'Invalid transaction hash format' }));
250
250
  /**
251
251
  * Action: GetMetadataByTxHash - returns multiple metadata rows (uses SELECT.from, not SELECT.one).
252
+ * Takes camelCase `txHash` like every other action (renamed from `tx_hash` in 1.9.4).
252
253
  */
253
254
  srv.on('GetMetadataByTxHash', async (req) => {
254
- const { tx_hash } = req.data;
255
- if (!tx_hash)
256
- (0, errors_1.rejectMissing)(req, 'GetMetadataByTxHash', 'tx_hash');
257
- if (!(0, validators_1.isTxHash)(tx_hash))
258
- (0, errors_1.rejectInvalid)(req, 'GetMetadataByTxHash', 'Invalid transaction hash format', 'tx_hash');
255
+ const { txHash } = req.data;
256
+ if (!txHash)
257
+ (0, errors_1.rejectMissing)(req, 'GetMetadataByTxHash', 'txHash');
258
+ if (!(0, validators_1.isTxHash)(txHash))
259
+ (0, errors_1.rejectInvalid)(req, 'GetMetadataByTxHash', 'Invalid transaction hash format', 'txHash');
259
260
  return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
260
- const existing = await db.run(SELECT.from(TransactionMetadata).where({ tx_hash }));
261
+ const existing = await db.run(SELECT.from(TransactionMetadata).where({ tx_hash: txHash }));
261
262
  if (!existing || existing.length === 0) {
262
- return await indexer().indexTransactionMetadata(db, tx_hash);
263
+ return await indexer().indexTransactionMetadata(db, txHash);
263
264
  }
264
265
  return existing;
265
266
  });
@@ -14,6 +14,7 @@ const external_signer_1 = require("./blockchain/signing/external-signer");
14
14
  const hsm_signer_1 = require("./blockchain/signing/hsm-signer");
15
15
  const cose_verifier_1 = require("./blockchain/signing/cose-verifier");
16
16
  const signing_helper_1 = require("./utils/signing-helper");
17
+ const tx_build_helper_1 = require("./utils/tx-build-helper");
17
18
  const { SELECT, UPDATE } = cds_1.default.ql;
18
19
  const logger = cds_1.default.log('CardanoSignService');
19
20
  /**
@@ -106,6 +107,14 @@ async function submitAndFinalize(SigningRequests, params, afterFinalize) {
106
107
  const submission = await (0, server_1.getCardanoIndexer)().indexVerifiedTransactionSubmission(db, params);
107
108
  if (afterFinalize)
108
109
  await afterFinalize(db);
110
+ // Invalidate stale UTxO cache (spent inputs + output addresses) — best-effort,
111
+ // must never roll back the durable submission record.
112
+ try {
113
+ await (0, server_1.getCardanoIndexer)().invalidateUtxoCacheForTx(db, (0, tx_build_helper_1.extractTxCacheTargets)(params.fullSignedTxCbor));
114
+ }
115
+ catch (invalidateErr) {
116
+ logger.warn(`UTxO cache invalidation failed (submit unaffected): ${invalidateErr instanceof Error ? invalidateErr.message : String(invalidateErr)}`);
117
+ }
109
118
  return submission;
110
119
  });
111
120
  try {
@@ -14,7 +14,7 @@ const mappers_1 = require("./utils/mappers");
14
14
  const server_1 = require("./server");
15
15
  const const_1 = require("./utils/const");
16
16
  const VALID_DERIVE_NETWORKS = ['mainnet', 'preview', 'preprod'];
17
- const { SELECT, UPDATE, DELETE: DELETE_FROM } = cds_1.default.ql;
17
+ const { SELECT, UPDATE } = cds_1.default.ql;
18
18
  const logger = cds_1.default.log('CardanoTxService');
19
19
  /**
20
20
  * Parse and validate a JSON array of UTxO refs ({txHash, outputIndex}) — the shared
@@ -175,7 +175,6 @@ function parseExtraOutputs(extraOutputsJson) {
175
175
  module.exports = (srv) => {
176
176
  logger.debug('Module loaded - registering handlers');
177
177
  const { TransactionBuilds, TransactionSubmissions, AddressTransactionBuilds } = require('#cds-models/CardanoTransactionService');
178
- const { Addresses, AddressUTxOs, AddressAssets } = require('#cds-models/CardanoODataService');
179
178
  /**
180
179
  * Build a simple ADA-only transaction
181
180
  * @param req - CDS request object (with senderAddress, recipientAddress, lovelaceAmount, changeAddress)
@@ -832,13 +831,15 @@ module.exports = (srv) => {
832
831
  logger.info({ txHash }, 'Transaction submitted to blockchain');
833
832
  await (0, server_1.getCardanoIndexer)().updateSubmissionStatus(db, submissionRecord.id, 'submitted');
834
833
  submissionRecord.status = 'submitted';
835
- // Invalidate sender address cache so next read fetches fresh data
836
- const addrBuild = await db.run(SELECT.one.from(AddressTransactionBuilds).where({ txBuild_id: buildId }));
837
- if (addrBuild?.address_address) {
838
- await db.run(DELETE_FROM.from(Addresses).where({ address: addrBuild.address_address }));
839
- await db.run(DELETE_FROM.from(AddressUTxOs).where({ address_address: addrBuild.address_address }));
840
- await db.run(DELETE_FROM.from(AddressAssets).where({ address_address: addrBuild.address_address }));
841
- logger.debug(`Invalidated cache for sender address ${addrBuild.address_address.substring(0, 20)}...`);
834
+ // Invalidate stale UTxO cache: spent input refs + output addresses from
835
+ // the signed CBOR, plus the build's sender address. Best-effort — a
836
+ // failure here must not fail the already-successful submit.
837
+ try {
838
+ const addrBuild = await db.run(SELECT.one.from(AddressTransactionBuilds).where({ txBuild_id: buildId }));
839
+ await (0, server_1.getCardanoIndexer)().invalidateUtxoCacheForTx(db, (0, tx_build_helper_1.extractTxCacheTargets)(signedTxCbor), addrBuild?.address_address ? [addrBuild.address_address] : []);
840
+ }
841
+ catch (invalidateErr) {
842
+ logger.warn(`UTxO cache invalidation failed (submit unaffected): ${invalidateErr instanceof Error ? invalidateErr.message : String(invalidateErr)}`);
842
843
  }
843
844
  }
844
845
  catch (err) {
@@ -883,6 +884,13 @@ module.exports = (srv) => {
883
884
  logger.info({ txHash }, 'External transaction submitted');
884
885
  await (0, server_1.getCardanoIndexer)().updateSubmissionStatus(db, submissionRecord.id, 'submitted');
885
886
  submissionRecord.status = 'submitted';
887
+ // Invalidate stale UTxO cache (spent inputs + output addresses) — best-effort
888
+ try {
889
+ await (0, server_1.getCardanoIndexer)().invalidateUtxoCacheForTx(db, (0, tx_build_helper_1.extractTxCacheTargets)(signedTxCbor));
890
+ }
891
+ catch (invalidateErr) {
892
+ logger.warn(`UTxO cache invalidation failed (submit unaffected): ${invalidateErr instanceof Error ? invalidateErr.message : String(invalidateErr)}`);
893
+ }
886
894
  }
887
895
  catch (err) {
888
896
  const errMsg = err instanceof Error ? err.message : String(err);
@@ -88,11 +88,14 @@ export declare class InsufficientFundsError extends BackendError {
88
88
  readonly available: bigint;
89
89
  /** Constructor
90
90
  * @param assetUnit the asset unit that is insufficient (e.g., "lovelace" or "policyId.assetName")
91
- * @param required the required amount
92
- * @param available the available amount
91
+ * @param required the required amount (0n when unknown)
92
+ * @param available the available amount (0n when unknown)
93
93
  * @param originalError original error object
94
+ * @param detail human-readable cause shown INSTEAD of the amounts — use when
95
+ * the amounts are unknown; "required 0, available 0" reads as
96
+ * nonsense from the consumer's perspective
94
97
  */
95
- constructor(assetUnit: string, required: bigint, available: bigint, originalError?: unknown);
98
+ constructor(assetUnit: string, required: bigint, available: bigint, originalError?: unknown, detail?: string);
96
99
  }
97
100
  /**
98
101
  * MixedAssetsError - UTxO contains mixed assets when pure ADA is required (400)
@@ -119,12 +119,17 @@ class InsufficientFundsError extends BackendError {
119
119
  available;
120
120
  /** Constructor
121
121
  * @param assetUnit the asset unit that is insufficient (e.g., "lovelace" or "policyId.assetName")
122
- * @param required the required amount
123
- * @param available the available amount
122
+ * @param required the required amount (0n when unknown)
123
+ * @param available the available amount (0n when unknown)
124
124
  * @param originalError original error object
125
+ * @param detail human-readable cause shown INSTEAD of the amounts — use when
126
+ * the amounts are unknown; "required 0, available 0" reads as
127
+ * nonsense from the consumer's perspective
125
128
  */
126
- constructor(assetUnit, required, available, originalError) {
127
- super(`Insufficient ${assetUnit}: required ${required}, available ${available}`, 400, error_codes_1.ERROR_CODES.INSUFFICIENT_FUNDS, undefined, originalError, assetUnit);
129
+ constructor(assetUnit, required, available, originalError, detail) {
130
+ super(detail
131
+ ? `Insufficient ${assetUnit}: ${detail}`
132
+ : `Insufficient ${assetUnit}: required ${required}, available ${available}`, 400, error_codes_1.ERROR_CODES.INSUFFICIENT_FUNDS, undefined, originalError, assetUnit);
128
133
  this.assetUnit = assetUnit;
129
134
  this.required = required;
130
135
  this.available = available;
@@ -21,6 +21,30 @@ export declare function assertAdaOnly(u: OdatanoUtxo): void;
21
21
  * @throws {Error} if CBOR is invalid or transaction hash cannot be extracted
22
22
  */
23
23
  export declare function getTxHashFromCbor(txCbor: string): string;
24
+ /** Cache-invalidation targets of a submitted transaction (see extractTxCacheTargets). */
25
+ export interface TxCacheTargets {
26
+ /** UTxO refs consumed by the transaction (now spent). */
27
+ inputs: Array<{
28
+ txHash: string;
29
+ outputIndex: number;
30
+ }>;
31
+ /** Distinct bech32 addresses receiving outputs (sender change + recipients). */
32
+ outputAddresses: string[];
33
+ }
34
+ /**
35
+ * Extract the consumed input refs and the output addresses from a transaction
36
+ * CBOR (signed or unsigned) — the rows a successful submit makes stale in the
37
+ * UTxO cache. Works at the raw-CBOR level for the same reason as
38
+ * getTxHashFromCbor (the high-level Tx.fromCbor rejects its own tag-259
39
+ * AuxiliaryData builds).
40
+ *
41
+ * Outputs whose address bytes cannot be decoded (e.g. Byron bootstrap
42
+ * addresses) are skipped — invalidation is best-effort per address.
43
+ *
44
+ * @param txCbor transaction in CBOR hex format
45
+ * @throws {TransactionValidationError} if the CBOR is not a transaction
46
+ */
47
+ export declare function extractTxCacheTargets(txCbor: string): TxCacheTargets;
24
48
  /**
25
49
  * Maps builder errors to typed BackendErrors
26
50
  * Used by the Buildooor transaction builder.
@@ -28,10 +52,13 @@ export declare function getTxHashFromCbor(txCbor: string): string;
28
52
  * (e.g. "not enough <policyId.assetName>"), falling back to 'lovelace'.
29
53
  * @param err Error from builder
30
54
  * @param assetUnit Optional asset unit override (auto-extracted from error message if omitted)
55
+ * @param context Optional build-flow context (e.g. the collateral/funding partition)
56
+ * appended to the consumer-facing message — the builder's own message
57
+ * has no way of knowing it
31
58
  * @throws {InsufficientFundsError} if error is related to insufficient funds
32
59
  * @throws {Error} original error if not mappable
33
60
  */
34
- export declare function mapBuilderError(err: unknown, assetUnit?: string): never;
61
+ export declare function mapBuilderError(err: unknown, assetUnit?: string, context?: string): never;
35
62
  /**
36
63
  * Parse asset unit string into policyId and assetName
37
64
  * Format: policyId (56 hex chars) + assetName (remaining hex)
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getLovelace = getLovelace;
4
4
  exports.assertAdaOnly = assertAdaOnly;
5
5
  exports.getTxHashFromCbor = getTxHashFromCbor;
6
+ exports.extractTxCacheTargets = extractTxCacheTargets;
6
7
  exports.mapBuilderError = mapBuilderError;
7
8
  exports.parseAssetUnit = parseAssetUnit;
8
9
  exports.jsonToPlutusData = jsonToPlutusData;
@@ -16,6 +17,7 @@ const error_codes_1 = require("./error-codes");
16
17
  const plutus_data_1 = require("@harmoniclabs/plutus-data");
17
18
  const uplc_1 = require("@harmoniclabs/uplc");
18
19
  const cbor_1 = require("@harmoniclabs/cbor");
20
+ const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
19
21
  /**
20
22
  * Extract lovelace amount from UTxO
21
23
  * @param u UTxO to extract from
@@ -72,6 +74,66 @@ function getTxHashFromCbor(txCbor) {
72
74
  throw new errors_1.TransactionValidationError('Failed to parse transaction CBOR', err, error_codes_1.ERROR_CODES.TX_PARSE_FAILED);
73
75
  }
74
76
  }
77
+ /**
78
+ * Extract the consumed input refs and the output addresses from a transaction
79
+ * CBOR (signed or unsigned) — the rows a successful submit makes stale in the
80
+ * UTxO cache. Works at the raw-CBOR level for the same reason as
81
+ * getTxHashFromCbor (the high-level Tx.fromCbor rejects its own tag-259
82
+ * AuxiliaryData builds).
83
+ *
84
+ * Outputs whose address bytes cannot be decoded (e.g. Byron bootstrap
85
+ * addresses) are skipped — invalidation is best-effort per address.
86
+ *
87
+ * @param txCbor transaction in CBOR hex format
88
+ * @throws {TransactionValidationError} if the CBOR is not a transaction
89
+ */
90
+ function extractTxCacheTargets(txCbor) {
91
+ let body;
92
+ try {
93
+ const tx = cbor_1.Cbor.parse((0, uint8array_utils_1.fromHex)(txCbor));
94
+ if (!(tx instanceof cbor_1.CborArray) || !(tx.array[0] instanceof cbor_1.CborMap)) {
95
+ throw new Error('not a transaction');
96
+ }
97
+ body = tx.array[0];
98
+ }
99
+ catch (err) {
100
+ throw new errors_1.TransactionValidationError('Failed to parse transaction CBOR', err, error_codes_1.ERROR_CODES.TX_PARSE_FAILED);
101
+ }
102
+ const bodyValue = (key) => body.map.find(e => e.k instanceof cbor_1.CborUInt && e.k.num === BigInt(key))?.v;
103
+ // key 0: inputs — plain array or a CBOR tag-258 set (Conway)
104
+ const inputs = [];
105
+ let inputsObj = bodyValue(0);
106
+ if (inputsObj instanceof cbor_1.CborTag)
107
+ inputsObj = inputsObj.data;
108
+ if (inputsObj instanceof cbor_1.CborArray) {
109
+ for (const entry of inputsObj.array) {
110
+ if (entry instanceof cbor_1.CborArray &&
111
+ entry.array[0] instanceof cbor_1.CborBytes &&
112
+ entry.array[1] instanceof cbor_1.CborUInt) {
113
+ inputs.push({ txHash: (0, uint8array_utils_1.toHex)(entry.array[0].bytes), outputIndex: Number(entry.array[1].num) });
114
+ }
115
+ }
116
+ }
117
+ // key 1: outputs — post-alonzo map form ({0: address, ...}) or legacy array form ([address, amount, ...])
118
+ const outputAddresses = new Set();
119
+ const outputsObj = bodyValue(1);
120
+ if (outputsObj instanceof cbor_1.CborArray) {
121
+ for (const output of outputsObj.array) {
122
+ const addrObj = output instanceof cbor_1.CborMap
123
+ ? output.map.find(e => e.k instanceof cbor_1.CborUInt && e.k.num === 0n)?.v
124
+ : output instanceof cbor_1.CborArray ? output.array[0] : undefined;
125
+ if (!(addrObj instanceof cbor_1.CborBytes))
126
+ continue;
127
+ try {
128
+ outputAddresses.add(cardano_ledger_ts_1.Address.fromBuffer(addrObj.bytes).toString());
129
+ }
130
+ catch {
131
+ // non-Shelley address bytes — nothing cached under a bech32 key for it
132
+ }
133
+ }
134
+ }
135
+ return { inputs, outputAddresses: [...outputAddresses] };
136
+ }
75
137
  /**
76
138
  * Maps builder errors to typed BackendErrors
77
139
  * Used by the Buildooor transaction builder.
@@ -79,10 +141,13 @@ function getTxHashFromCbor(txCbor) {
79
141
  * (e.g. "not enough <policyId.assetName>"), falling back to 'lovelace'.
80
142
  * @param err Error from builder
81
143
  * @param assetUnit Optional asset unit override (auto-extracted from error message if omitted)
144
+ * @param context Optional build-flow context (e.g. the collateral/funding partition)
145
+ * appended to the consumer-facing message — the builder's own message
146
+ * has no way of knowing it
82
147
  * @throws {InsufficientFundsError} if error is related to insufficient funds
83
148
  * @throws {Error} original error if not mappable
84
149
  */
85
- function mapBuilderError(err, assetUnit) {
150
+ function mapBuilderError(err, assetUnit, context) {
86
151
  // Already-typed errors carry their own status + payload (amounts, asset units,
87
152
  // validation details) — re-wrapping them into a generic InsufficientFundsError
88
153
  // because their MESSAGE happens to contain "balance"/"insufficient" destroys that.
@@ -90,7 +155,8 @@ function mapBuilderError(err, assetUnit) {
90
155
  throw err;
91
156
  }
92
157
  const errObj = err;
93
- const msg = (errObj?.message || errObj?.toString?.() || String(err)).toLowerCase();
158
+ const rawMsg = errObj?.message || errObj?.toString?.() || String(err);
159
+ const msg = rawMsg.toLowerCase();
94
160
  if (msg.includes('not enough') ||
95
161
  msg.includes('insufficient') ||
96
162
  msg.includes('balance')) {
@@ -98,7 +164,9 @@ function mapBuilderError(err, assetUnit) {
98
164
  const match = msg.match(/not enough\s+([a-f0-9.]+)/i);
99
165
  return match?.[1] || 'lovelace';
100
166
  })();
101
- throw new errors_1.InsufficientFundsError(effectiveUnit, 0n, 0n, err);
167
+ // The builder knows no amounts here — surface its own message (plus the build
168
+ // context) instead of a meaningless "required 0, available 0".
169
+ throw new errors_1.InsufficientFundsError(effectiveUnit, 0n, 0n, err, context ? `${rawMsg} (${context})` : rawMsg);
102
170
  }
103
171
  throw err;
104
172
  }