@odatano/core 2.0.0-rc.43 → 2.0.0-rc.45

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 (171) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +0 -46
  2. package/@cds-models/CardanoBackendService/index.d.ts +0 -10
  3. package/@cds-models/CardanoIndexerService/index.d.ts +36 -20
  4. package/@cds-models/CardanoIndexerService/index.js +4 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +19 -47
  6. package/@cds-models/CardanoSignService/index.d.ts +3 -18
  7. package/@cds-models/CardanoTransactionService/index.d.ts +9 -31
  8. package/@cds-models/CardanoWorkerService/index.d.ts +3 -19
  9. package/@cds-models/index.d.ts +17 -0
  10. package/@cds-models/index.js +2 -0
  11. package/@cds-models/odatano/cardano/index.d.ts +1 -34
  12. package/README.md +6 -6
  13. package/db/schema.cds +29 -44
  14. package/db/types.cds +22 -5
  15. package/package.json +3 -1
  16. package/scripts/migrate-slot-leader.mjs +3 -11
  17. package/scripts/migrate-txseq.mjs +3 -12
  18. package/src/index.d.ts +0 -4
  19. package/src/index.js +3 -5
  20. package/src/plugin.js +4 -8
  21. package/srv/blockchain/asset-decimals.d.ts +7 -0
  22. package/srv/blockchain/asset-decimals.js +91 -0
  23. package/srv/blockchain/backends/blockfrost-backend.d.ts +2 -10
  24. package/srv/blockchain/backends/blockfrost-backend.js +15 -21
  25. package/srv/blockchain/backends/cardano-backend.d.ts +12 -71
  26. package/srv/blockchain/backends/koios-backend.d.ts +14 -147
  27. package/srv/blockchain/backends/koios-backend.js +40 -164
  28. package/srv/blockchain/backends/odatano-backend.d.ts +1 -11
  29. package/srv/blockchain/backends/odatano-backend.js +11 -12
  30. package/srv/blockchain/backends/ogmios-backend.d.ts +13 -160
  31. package/srv/blockchain/backends/ogmios-backend.js +48 -175
  32. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +2 -18
  33. package/srv/blockchain/backends/ogmios-frame-guard.js +8 -20
  34. package/srv/blockchain/cardano-client.d.ts +12 -80
  35. package/srv/blockchain/cardano-client.js +36 -88
  36. package/srv/blockchain/cardano-indexer.d.ts +12 -192
  37. package/srv/blockchain/cardano-indexer.js +132 -222
  38. package/srv/blockchain/cardano-tx-builder.d.ts +1 -28
  39. package/srv/blockchain/cardano-tx-builder.js +17 -34
  40. package/srv/blockchain/circuit-breaker.d.ts +1 -13
  41. package/srv/blockchain/circuit-breaker.js +5 -15
  42. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +15 -0
  43. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  44. package/srv/blockchain/crawler/certificate-backfill.d.ts +0 -17
  45. package/srv/blockchain/crawler/certificate-backfill.js +8 -22
  46. package/srv/blockchain/crawler/crawler.d.ts +16 -93
  47. package/srv/blockchain/crawler/crawler.js +85 -160
  48. package/srv/blockchain/crawler/credential-backfill.d.ts +0 -9
  49. package/srv/blockchain/crawler/credential-backfill.js +6 -6
  50. package/srv/blockchain/crawler/hooks.d.ts +1 -5
  51. package/srv/blockchain/crawler/index.d.ts +0 -12
  52. package/srv/blockchain/crawler/index.js +6 -20
  53. package/srv/blockchain/crawler/sync-state.d.ts +6 -44
  54. package/srv/blockchain/crawler/sync-state.js +18 -53
  55. package/srv/blockchain/crawler/transaction-backfill.d.ts +0 -11
  56. package/srv/blockchain/crawler/transaction-backfill.js +11 -30
  57. package/srv/blockchain/crawler/utxo-set-import.d.ts +1 -30
  58. package/srv/blockchain/crawler/utxo-set-import.js +27 -53
  59. package/srv/blockchain/ledger-state.d.ts +10 -54
  60. package/srv/blockchain/ledger-state.js +11 -27
  61. package/srv/blockchain/pending-spends.d.ts +0 -12
  62. package/srv/blockchain/pending-spends.js +4 -12
  63. package/srv/blockchain/request-coalescer.d.ts +2 -16
  64. package/srv/blockchain/request-coalescer.js +2 -16
  65. package/srv/blockchain/signing/cose-verifier.d.ts +0 -9
  66. package/srv/blockchain/signing/cose-verifier.js +4 -10
  67. package/srv/blockchain/signing/external-signer.d.ts +1 -4
  68. package/srv/blockchain/signing/external-signer.js +2 -8
  69. package/srv/blockchain/signing/hsm-signer.d.ts +6 -18
  70. package/srv/blockchain/signing/hsm-signer.js +16 -28
  71. package/srv/blockchain/signing/signature-verifier.d.ts +1 -8
  72. package/srv/blockchain/signing/signature-verifier.js +9 -19
  73. package/srv/blockchain/signing/submission-finalizer.d.ts +10 -16
  74. package/srv/blockchain/signing/submission-finalizer.js +48 -19
  75. package/srv/blockchain/stored-chain.d.ts +1 -14
  76. package/srv/blockchain/stored-chain.js +3 -8
  77. package/srv/blockchain/transaction-building/buildooor-fee-patch.d.ts +0 -4
  78. package/srv/blockchain/transaction-building/buildooor-fee-patch.js +4 -9
  79. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +7 -150
  80. package/srv/blockchain/transaction-building/buildooor-tx.js +91 -196
  81. package/srv/blockchain/transaction-building/caller-datums.d.ts +0 -14
  82. package/srv/blockchain/transaction-building/caller-datums.js +3 -9
  83. package/srv/blockchain/transaction-building/cardano-tx.d.ts +1 -4
  84. package/srv/blockchain/wallet-worker/build-request.d.ts +0 -5
  85. package/srv/blockchain/wallet-worker/build-request.js +6 -9
  86. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -23
  87. package/srv/blockchain/wallet-worker/confirmation-tracker.js +16 -20
  88. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  89. package/srv/blockchain/wallet-worker/index.js +3 -5
  90. package/srv/blockchain/wallet-worker/job-store.d.ts +15 -65
  91. package/srv/blockchain/wallet-worker/job-store.js +0 -0
  92. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -10
  93. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -12
  94. package/srv/blockchain/wallet-worker/signers.d.ts +3 -11
  95. package/srv/blockchain/wallet-worker/signers.js +3 -6
  96. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +3 -21
  97. package/srv/blockchain/wallet-worker/wallet-worker.js +47 -54
  98. package/srv/cardano-agent-service.cds +123 -146
  99. package/srv/cardano-agent-service.js +2 -5
  100. package/srv/cardano-backend-service.cds +10 -17
  101. package/srv/cardano-backend-service.js +7 -12
  102. package/srv/cardano-indexer-service.cds +35 -37
  103. package/srv/cardano-indexer-service.d.ts +5 -1
  104. package/srv/cardano-indexer-service.js +64 -33
  105. package/srv/cardano-service.cds +56 -40
  106. package/srv/cardano-service.js +42 -69
  107. package/srv/cardano-sign-service.cds +14 -23
  108. package/srv/cardano-sign-service.js +18 -24
  109. package/srv/cardano-tx-service.cds +27 -29
  110. package/srv/cardano-tx-service.js +60 -122
  111. package/srv/cardano-worker-service.cds +109 -125
  112. package/srv/cardano-worker-service.js +21 -31
  113. package/srv/cbor/cip68.d.ts +13 -0
  114. package/srv/cbor/cip68.js +56 -0
  115. package/srv/cbor/index.d.ts +1 -0
  116. package/srv/cbor/index.js +6 -1
  117. package/srv/cbor/parse.d.ts +3 -18
  118. package/srv/cbor/parse.js +2 -7
  119. package/srv/cbor/plutus-data-json.d.ts +0 -4
  120. package/srv/server.d.ts +5 -36
  121. package/srv/server.js +30 -51
  122. package/srv/utils/agent-grants-config.d.ts +0 -18
  123. package/srv/utils/agent-grants-config.js +6 -13
  124. package/srv/utils/agent-grants.d.ts +14 -68
  125. package/srv/utils/agent-grants.js +42 -60
  126. package/srv/utils/agent-token-auth.d.ts +0 -5
  127. package/srv/utils/agent-token-auth.js +2 -5
  128. package/srv/utils/backend-request-handler.d.ts +1 -1
  129. package/srv/utils/collections.d.ts +1 -4
  130. package/srv/utils/collections.js +1 -4
  131. package/srv/utils/const.d.ts +0 -18
  132. package/srv/utils/const.js +7 -18
  133. package/srv/utils/crypto.js +3 -5
  134. package/srv/utils/db-indexes.d.ts +2 -0
  135. package/srv/utils/db-indexes.js +22 -9
  136. package/srv/utils/db-sanitize.d.ts +1 -8
  137. package/srv/utils/db-sanitize.js +3 -8
  138. package/srv/utils/epoch-slots.d.ts +1 -8
  139. package/srv/utils/epoch-slots.js +3 -8
  140. package/srv/utils/error-codes.d.ts +0 -4
  141. package/srv/utils/error-codes.js +2 -4
  142. package/srv/utils/errors.d.ts +2 -22
  143. package/srv/utils/errors.js +13 -27
  144. package/srv/utils/liveness.d.ts +0 -4
  145. package/srv/utils/liveness.js +2 -4
  146. package/srv/utils/mappers.d.ts +0 -37
  147. package/srv/utils/mappers.js +22 -39
  148. package/srv/utils/network-context.js +2 -4
  149. package/srv/utils/paging.d.ts +31 -0
  150. package/srv/utils/paging.js +43 -0
  151. package/srv/utils/pg-inline-json.js +3 -7
  152. package/srv/utils/pg-order-nulls.js +2 -5
  153. package/srv/utils/plutus-placeholders.d.ts +0 -13
  154. package/srv/utils/plutus-placeholders.js +6 -13
  155. package/srv/utils/rate-limiter.d.ts +0 -8
  156. package/srv/utils/rate-limiter.js +2 -4
  157. package/srv/utils/reference-script.d.ts +0 -18
  158. package/srv/utils/reference-script.js +8 -19
  159. package/srv/utils/service-events.d.ts +0 -4
  160. package/srv/utils/service-events.js +2 -4
  161. package/srv/utils/signing-helper.d.ts +1 -8
  162. package/srv/utils/signing-helper.js +3 -8
  163. package/srv/utils/tx-build-helper.d.ts +2 -32
  164. package/srv/utils/tx-build-helper.js +26 -40
  165. package/srv/utils/tx-request-parsers.d.ts +1 -25
  166. package/srv/utils/tx-request-parsers.js +10 -25
  167. package/srv/utils/tx-utils.d.ts +0 -8
  168. package/srv/utils/tx-utils.js +10 -13
  169. package/srv/utils/types.d.ts +2 -37
  170. package/srv/utils/validators.d.ts +0 -4
  171. package/srv/utils/validators.js +2 -4
@@ -12,6 +12,8 @@ const errors_1 = require("../../utils/errors");
12
12
  const error_codes_1 = require("../../utils/error-codes");
13
13
  const cbor_1 = require("@harmoniclabs/cbor");
14
14
  const uint8array_utils_1 = require("@harmoniclabs/uint8array-utils");
15
+ const blake2b_1 = __importDefault(require("blake2b"));
16
+ const bech32_1 = require("bech32");
15
17
  const logger = cds_1.default.log('HsmSigner');
16
18
  /** CKM_EDDSA mechanism ID (PKCS#11 v3.0) for Ed25519 signing. */
17
19
  const CKM_EDDSA = 0x00001057;
@@ -21,10 +23,7 @@ let pkcs11Loader = defaultPkcs11Loader;
21
23
  function setPkcs11Loader(loader) {
22
24
  pkcs11Loader = loader ?? defaultPkcs11Loader;
23
25
  }
24
- /**
25
- * Ed25519 transaction signing through a PKCS#11 HSM (YubiHSM 2, CloudHSM, Luna, …); private
26
- * keys never leave the device. Lifecycle: init(network) → sign()/signTransaction() → shutdown().
27
- */
26
+ /** Ed25519 signing through a PKCS#11 HSM. Private keys never leave the device. */
28
27
  class HsmSigner {
29
28
  pkcs11;
30
29
  session;
@@ -37,10 +36,7 @@ class HsmSigner {
37
36
  constructor(config) {
38
37
  this.config = config;
39
38
  }
40
- /**
41
- * Open the PKCS#11 session, locate the key, export the public key and derive the
42
- * enterprise address for `network`. Called once at startup.
43
- */
39
+ /** Opens the session, exports the public key and derives the enterprise address. */
44
40
  async init(network) {
45
41
  // pkcs11js is only loaded when HSM is configured
46
42
  let pkcs11js;
@@ -67,8 +63,8 @@ class HsmSigner {
67
63
  this.pkcs11.C_Login(this.session, pkcs11js.CKU_USER, this.config.pin);
68
64
  }
69
65
  finally {
70
- // Zero the PIN wherever it could linger (config object shared with the server
71
- // singleton — mutate in place —, HSM_PIN env, CAP config), whatever the login outcome.
66
+ // Clear the PIN everywhere it could linger, whatever the login outcome.
67
+ // The config object is shared with the server singleton, so it is changed in place.
72
68
  this.config.pin = '';
73
69
  if (process.env.HSM_PIN)
74
70
  delete process.env.HSM_PIN;
@@ -84,19 +80,17 @@ class HsmSigner {
84
80
  this.publicKeyBytes = this._exportPublicKey(pkcs11js);
85
81
  logger.debug({ publicKeyLength: this.publicKeyBytes.length }, 'Ed25519 public key exported');
86
82
  // Key hash = blake2b-224 of the public key
87
- const blake2b = require('blake2b');
88
83
  const hashOut = Buffer.alloc(28);
89
- blake2b(28).update(this.publicKeyBytes).digest(hashOut);
84
+ (0, blake2b_1.default)(28).update(this.publicKeyBytes).digest(hashOut);
90
85
  this.publicKeyHashHex = hashOut.toString('hex');
91
86
  // Enterprise key-hash address: header 0x61 (mainnet) or 0x60 (testnet)
92
- const { bech32 } = require('bech32');
93
87
  const headerByte = network === 'mainnet' ? 0x61 : 0x60;
94
88
  const payload = Buffer.alloc(29);
95
89
  payload[0] = headerByte;
96
90
  hashOut.copy(payload, 1);
97
- const words = bech32.toWords(payload);
91
+ const words = bech32_1.bech32.toWords(payload);
98
92
  const hrp = network === 'mainnet' ? 'addr' : 'addr_test';
99
- this.cardanoAddress = bech32.encode(hrp, words, 120);
93
+ this.cardanoAddress = bech32_1.bech32.encode(hrp, words, 120);
100
94
  this.connected = true;
101
95
  logger.info({
102
96
  keyLabel: this.config.keyLabel,
@@ -132,10 +126,7 @@ class HsmSigner {
132
126
  throw new errors_1.HsmError(`HSM signing failed: ${msg}`, 500, error_codes_1.ERROR_CODES.HSM_SIGNING_FAILED, err);
133
127
  }
134
128
  }
135
- /**
136
- * Sign the body hash (hex) in the HSM, build the VKey witness [publicKey, signature] and
137
- * splice it into the witness set at the raw CBOR level. Returns the signed tx CBOR (hex).
138
- */
129
+ /** Signs the body hash and splices the VKey witness in at the raw CBOR level. */
139
130
  signTransaction(unsignedTxCbor, txBodyHash) {
140
131
  const hashBytes = Buffer.from(txBodyHash, 'hex');
141
132
  const result = this.sign(hashBytes);
@@ -149,8 +140,8 @@ class HsmSigner {
149
140
  new cbor_1.CborBytes(Buffer.from(result.publicKeyHex, 'hex')),
150
141
  new cbor_1.CborBytes(Buffer.from(result.signatureHex, 'hex')),
151
142
  ]);
152
- // Witness set (txObj.array[1]): vkey witnesses (key 0) become the HSM witness only — single
153
- // signer; multi-sig goes through combineTransactionWithWitnesses(). Other keys are preserved.
143
+ // The HSM witness replaces all vkey witnesses, since it signs alone. Other keys are kept.
144
+ // Multi-sig goes through combineTransactionWithWitnesses().
154
145
  const origWs = txObj.array[1];
155
146
  if (origWs instanceof cbor_1.CborMap) {
156
147
  const entries = origWs.map.filter((e) => !(e.k instanceof cbor_1.CborUInt && Number(e.k.num) === 0));
@@ -201,7 +192,7 @@ class HsmSigner {
201
192
  address: this.connected ? this.cardanoAddress : undefined,
202
193
  };
203
194
  }
204
- /** Graceful shutdown — close PKCS#11 session */
195
+ /** Closes the PKCS#11 session. */
205
196
  shutdown() {
206
197
  if (this.session) {
207
198
  try {
@@ -220,12 +211,12 @@ class HsmSigner {
220
211
  // ---------------------------------------------------------------------------
221
212
  // Private helpers
222
213
  // ---------------------------------------------------------------------------
223
- /** Find an Ed25519 key object (private or public) in the HSM by label and/or ID. */
214
+ /** Finds an Ed25519 key object in the HSM by label or ID. */
224
215
  _findKey(pkcs11js, objectClass) {
225
216
  const template = [
226
217
  { type: pkcs11js.CKA_CLASS, value: objectClass },
227
218
  ];
228
- // CKK_EC_EDWARDS (0x40) — PKCS#11 v3.0, may not be defined in older pkcs11js versions
219
+ // CKK_EC_EDWARDS is PKCS#11 v3.0 and may be missing in older pkcs11js versions.
229
220
  const CKK_EC_EDWARDS = pkcs11js.CKK_EC_EDWARDS ?? 0x00000040;
230
221
  template.push({ type: pkcs11js.CKA_KEY_TYPE, value: CKK_EC_EDWARDS });
231
222
  if (this.config.keyLabel) {
@@ -243,10 +234,7 @@ class HsmSigner {
243
234
  }
244
235
  return handles[0];
245
236
  }
246
- /**
247
- * Export the Ed25519 public key from the HSM.
248
- * Handles both DER-wrapped (04 20 <32 bytes>) and raw 32-byte formats.
249
- */
237
+ /** Accepts a DER-wrapped and a raw 32-byte Ed25519 public key. */
250
238
  _exportPublicKey(pkcs11js) {
251
239
  const pubKeyHandle = this._findKey(pkcs11js, pkcs11js.CKO_PUBLIC_KEY);
252
240
  const attrs = this.pkcs11.C_GetAttributeValue(this.session, pubKeyHandle, [
@@ -1,13 +1,6 @@
1
1
  import { SignatureVerificationResult, TxWitnessVerification, VerificationOptions } from '../../utils/types';
2
- /**
3
- * Check every vkey witness of a signed tx against its body hash. Pure, needs no initialize().
4
- * A tx without vkey witnesses is valid here; which keys had to sign is the caller's check.
5
- */
6
2
  export declare function verifyTxWitnesses(signedTxCbor: string): TxWitnessVerification;
7
- /**
8
- * Verifies externally signed transactions without private keys: CBOR parse, body-hash
9
- * integrity against the build, required signers present, Ed25519 check per witness.
10
- */
3
+ /** Verifies externally signed transactions without private keys. */
11
4
  export declare class SignatureVerifier {
12
5
  /** Verify a signed tx (hex CBOR); all failures are reported in the result, never thrown. */
13
6
  verify(signedTxCbor: string, options?: VerificationOptions): SignatureVerificationResult;
@@ -13,10 +13,8 @@ const crypto_1 = require("@harmoniclabs/crypto");
13
13
  const errors_1 = require("../../utils/errors");
14
14
  const error_codes_1 = require("../../utils/error-codes");
15
15
  const logger = cds_1.default.log('SignatureVerifier');
16
- /**
17
- * blake2b-256 over the ORIGINAL transaction-body bytes (CBOR array index 0). subCborRef
18
- * preserves the exact received bytes, so the hash matches what was signed.
19
- */
16
+ // blake2b-256 over the original body bytes. subCborRef keeps the received bytes,
17
+ // so the hash matches what was signed.
20
18
  function computeBodyHash(txBytes) {
21
19
  const tx = cbor_1.Cbor.parse(txBytes);
22
20
  if (!(tx instanceof cbor_1.CborArray) || tx.array.length < 1 || !tx.array[0].subCborRef) {
@@ -24,11 +22,8 @@ function computeBodyHash(txBytes) {
24
22
  }
25
23
  return (0, uint8array_utils_1.toHex)((0, crypto_1.blake2b_256)(tx.array[0].subCborRef.toBuffer()));
26
24
  }
27
- /**
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.
31
- */
25
+ // Conway wraps the vkey witness array in CBOR tag 258, which is unwrapped here.
26
+ // `malformed` counts entries that are not a [vkey, signature] byte pair.
32
27
  function readVkeyWitnesses(txBytes) {
33
28
  const tx = cbor_1.Cbor.parse(txBytes);
34
29
  if (!(tx instanceof cbor_1.CborArray) || !(tx.array[1] instanceof cbor_1.CborMap))
@@ -61,7 +56,7 @@ function readVkeyWitnesses(txBytes) {
61
56
  function extractVkeyWitnesses(txBytes) {
62
57
  const { witnesses, malformed } = readVkeyWitnesses(txBytes);
63
58
  if (malformed > 0) {
64
- // not fatal, but a malformed witness in a signed tx is suspicious — surface it
59
+ // Not fatal, but a malformed witness in a signed tx is suspicious.
65
60
  logger.warn(`Skipped ${malformed} malformed vkey witness entr${malformed === 1 ? 'y' : 'ies'} while verifying (expected [vkey, signature] byte pairs)`);
66
61
  }
67
62
  return witnesses;
@@ -75,10 +70,8 @@ function signatureValid(w, bodyHashBytes) {
75
70
  return false;
76
71
  }
77
72
  }
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
- */
73
+ // Checks every vkey witness against the body hash. Needs no initialize().
74
+ // A tx without vkey witnesses is valid here; required signers are the caller's check.
82
75
  function verifyTxWitnesses(signedTxCbor) {
83
76
  const errors = [];
84
77
  const signerKeyHashes = [];
@@ -102,10 +95,7 @@ function verifyTxWitnesses(signedTxCbor) {
102
95
  }
103
96
  return { valid: errors.length === 0, txBodyHash, signerKeyHashes, errors };
104
97
  }
105
- /**
106
- * Verifies externally signed transactions without private keys: CBOR parse, body-hash
107
- * integrity against the build, required signers present, Ed25519 check per witness.
108
- */
98
+ /** Verifies externally signed transactions without private keys. */
109
99
  class SignatureVerifier {
110
100
  /** Verify a signed tx (hex CBOR); all failures are reported in the result, never thrown. */
111
101
  verify(signedTxCbor, options = {}) {
@@ -117,7 +107,7 @@ class SignatureVerifier {
117
107
  warnings: [],
118
108
  };
119
109
  try {
120
- // Body hash over the original body bytes — exactly what was signed.
110
+ // Body hash over the original body bytes, exactly what was signed.
121
111
  const txBytes = (0, uint8array_utils_1.fromHex)(signedTxCbor);
122
112
  const computedHash = computeBodyHash(txBytes);
123
113
  result.txBodyHash = computedHash;
@@ -1,4 +1,7 @@
1
1
  import cds, { Request } from '@sap/cds';
2
+ import type { CardanoIndexer } from '../cardano-indexer';
3
+ import type { CardanoClient } from '../cardano-client';
4
+ import { type TransactionSubmission } from '#cds-models/CardanoTransactionService';
2
5
  /** Shape persisted by indexVerifiedTransactionSubmission. */
3
6
  export interface FinalizeParams {
4
7
  signingRequestId: string;
@@ -14,23 +17,14 @@ export interface FinalizeParams {
14
17
  signerType?: string;
15
18
  signerInfo?: string;
16
19
  }
17
- /**
18
- * Submit a claimed signing request (status 'submitting' already committed by the caller) and
19
- * persist the outcome in detached transactions, so no DB lock is held across the network call.
20
- * Submit failure → 'failed' in its own tx, then rethrow. A crash before finalize leaves 'submitting'.
21
- */
20
+ type SubmissionIndexer = Pick<CardanoIndexer, 'persistTransactionSubmission' | 'updateSubmissionStatus' | 'invalidateUtxoCacheForTx'>;
22
21
  export declare function submitAndFinalize(SigningRequests: unknown, params: FinalizeParams, afterFinalize?: (db: cds.Transaction) => Promise<void>): Promise<unknown>;
23
- /**
24
- * Deferred submit: runs submitAndFinalize only after the caller's root transaction has committed
25
- * (claim durable, connection released), detached via setImmediate + runWithoutAmbientTx.
26
- * If the caller rolls back, 'succeeded' never fires and nothing was claimed.
27
- */
22
+ export declare function submitRecorded(params: {
23
+ signedTxCbor: string;
24
+ txHash: string;
25
+ buildId: string | null;
26
+ }, indexer?: SubmissionIndexer, client?: Pick<CardanoClient, 'submitTransaction'>): Promise<TransactionSubmission>;
28
27
  export declare function scheduleDeferredSubmit(req: Request, SigningRequests: unknown, params: FinalizeParams): void;
29
- /**
30
- * Boot-time recovery: re-drive rows at 'submitting' WITH persisted signedTxCbor (process died between
31
- * the caller's commit and the detached submit). Idempotent: a tx the node already holds finalizes as
32
- * 'submitted'. Rows without signed CBOR are left for the operator/poller.
33
- * @returns number of rows re-driven (attempted, not necessarily succeeded)
34
- */
35
28
  export declare function redriveInterruptedSubmissions(): Promise<number>;
29
+ export {};
36
30
  //# sourceMappingURL=submission-finalizer.d.ts.map
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.submitAndFinalize = submitAndFinalize;
7
+ exports.submitRecorded = submitRecorded;
7
8
  exports.scheduleDeferredSubmit = scheduleDeferredSubmit;
8
9
  exports.redriveInterruptedSubmissions = redriveInterruptedSubmissions;
9
10
  const cds_1 = __importDefault(require("@sap/cds"));
@@ -11,6 +12,7 @@ const errors_1 = require("../../utils/errors");
11
12
  const tx_utils_1 = require("../../utils/tx-utils");
12
13
  const tx_build_helper_1 = require("../../utils/tx-build-helper");
13
14
  const external_signer_1 = require("./external-signer");
15
+ const CardanoTransactionService_1 = require("#cds-models/CardanoTransactionService");
14
16
  const { SELECT, UPDATE } = cds_1.default.ql;
15
17
  const logger = cds_1.default.log('SubmissionFinalizer');
16
18
  // Lazy require avoids the srv/server.ts <-> this-module import cycle; the app-context
@@ -18,19 +20,15 @@ const logger = cds_1.default.log('SubmissionFinalizer');
18
20
  function server() {
19
21
  return require('../../server');
20
22
  }
21
- /**
22
- * Submit a claimed signing request (status 'submitting' already committed by the caller) and
23
- * persist the outcome in detached transactions, so no DB lock is held across the network call.
24
- * Submit failure → 'failed' in its own tx, then rethrow. A crash before finalize leaves 'submitting'.
25
- */
23
+ // Outcomes are written in detached transactions, so no DB lock is held across the network call.
24
+ // A failure is marked 'failed' and rethrown. A crash before finalize leaves 'submitting'.
26
25
  async function submitAndFinalize(SigningRequests, params, afterFinalize) {
27
26
  // Persist the submission + 'submitted' status in its own committed transaction.
28
27
  const finalizeSubmitted = () => (0, tx_utils_1.detachedTx)('finalize transaction submission', async (db) => {
29
28
  const submission = await server().getCardanoIndexer().indexVerifiedTransactionSubmission(db, params);
30
29
  if (afterFinalize)
31
30
  await afterFinalize(db);
32
- // Invalidate stale UTxO cache (spent inputs + output addresses) — best-effort,
33
- // must never roll back the durable submission record.
31
+ // Best effort; must never roll back the durable submission record.
34
32
  try {
35
33
  await server().getCardanoIndexer().invalidateUtxoCacheForTx(db, (0, tx_build_helper_1.extractTxCacheTargets)(params.fullSignedTxCbor));
36
34
  }
@@ -46,7 +44,7 @@ async function submitAndFinalize(SigningRequests, params, afterFinalize) {
46
44
  // Already-submitted means the tx reached the mempool (e.g. first backend accepted it, response
47
45
  // lost, fallback saw the duplicate): finalize as 'submitted' rather than recording a spurious 'failed'.
48
46
  if (submitErr instanceof errors_1.TransactionAlreadySubmittedError) {
49
- logger.info({ signingRequestId: params.signingRequestId, txHash: params.txHash }, 'Submit reported already-submitted — finalizing as submitted (tx already in mempool)');
47
+ logger.info({ signingRequestId: params.signingRequestId, txHash: params.txHash }, 'Submit reported already-submitted; finalizing as submitted (tx already in mempool)');
50
48
  return finalizeSubmitted();
51
49
  }
52
50
  try {
@@ -59,11 +57,46 @@ async function submitAndFinalize(SigningRequests, params, afterFinalize) {
59
57
  }
60
58
  return finalizeSubmitted();
61
59
  }
62
- /**
63
- * Deferred submit: runs submitAndFinalize only after the caller's root transaction has committed
64
- * (claim durable, connection released), detached via setImmediate + runWithoutAmbientTx.
65
- * If the caller rolls back, 'succeeded' never fires and nothing was claimed.
66
- */
60
+ // 'pending' commits first and the network call runs outside any DB tx.
61
+ // The final status commits on its own and survives a rethrown error.
62
+ async function submitRecorded(params, indexer = server().getCardanoIndexer(), client = server().getCardanoClient()) {
63
+ const record = await (0, tx_utils_1.detachedTx)('record transaction submission', (db) => indexer.persistTransactionSubmission(db, params));
64
+ try {
65
+ await client.submitTransaction(params.signedTxCbor);
66
+ logger.info({ txHash: params.txHash }, 'Transaction submitted to blockchain');
67
+ }
68
+ catch (submitErr) {
69
+ const alreadySubmitted = submitErr instanceof errors_1.TransactionAlreadySubmittedError;
70
+ const errMsg = submitErr instanceof Error ? submitErr.message : String(submitErr);
71
+ try {
72
+ await (0, tx_utils_1.detachedTx)('record submission outcome', (db) => alreadySubmitted
73
+ ? indexer.updateSubmissionStatus(db, record.id, 'submitted')
74
+ : indexer.updateSubmissionStatus(db, record.id, 'failed', errMsg));
75
+ }
76
+ catch (markErr) {
77
+ logger.error({ err: markErr, submissionId: record.id }, 'Could not record the submission outcome after a submit error');
78
+ }
79
+ if (!alreadySubmitted)
80
+ logger.error({ txHash: params.txHash, error: errMsg }, 'Transaction submission failed');
81
+ throw submitErr;
82
+ }
83
+ await (0, tx_utils_1.detachedTx)('record submission outcome', async (db) => {
84
+ await indexer.updateSubmissionStatus(db, record.id, 'submitted');
85
+ // best-effort: a cache failure must not roll back the submitted status
86
+ try {
87
+ const senders = params.buildId
88
+ ? await db.run(SELECT.from(CardanoTransactionService_1.AddressTransactionBuilds).columns('address_address').where({ txBuild_id: params.buildId }))
89
+ : [];
90
+ await indexer.invalidateUtxoCacheForTx(db, (0, tx_build_helper_1.extractTxCacheTargets)(params.signedTxCbor), senders.map(r => r.address_address).filter((a) => !!a));
91
+ }
92
+ catch (invalidateErr) {
93
+ logger.warn(`UTxO cache invalidation failed (submit unaffected): ${invalidateErr instanceof Error ? invalidateErr.message : String(invalidateErr)}`);
94
+ }
95
+ });
96
+ return { ...record, status: 'submitted' };
97
+ }
98
+ // Submits only after the caller's transaction has committed and released its connection.
99
+ // If the caller rolls back, 'succeeded' never fires and nothing was claimed.
67
100
  function scheduleDeferredSubmit(req, SigningRequests, params) {
68
101
  req.on('succeeded', () => {
69
102
  setImmediate(() => {
@@ -78,12 +111,8 @@ function scheduleDeferredSubmit(req, SigningRequests, params) {
78
111
  });
79
112
  });
80
113
  }
81
- /**
82
- * Boot-time recovery: re-drive rows at 'submitting' WITH persisted signedTxCbor (process died between
83
- * the caller's commit and the detached submit). Idempotent: a tx the node already holds finalizes as
84
- * 'submitted'. Rows without signed CBOR are left for the operator/poller.
85
- * @returns number of rows re-driven (attempted, not necessarily succeeded)
86
- */
114
+ // Boot recovery for rows stuck at 'submitting' that have signed CBOR. Idempotent, since a tx
115
+ // the node already holds finalizes as 'submitted'. Returns the number of rows attempted.
87
116
  async function redriveInterruptedSubmissions() {
88
117
  const SigningRequests = 'odatano.cardano.SigningRequests';
89
118
  const rows = await (0, tx_utils_1.detachedTx)('load interrupted deferred submissions', (db) => db.run(SELECT.from(SigningRequests)
@@ -1,11 +1,5 @@
1
1
  import type { Transaction as CapTransaction } from '@sap/cds';
2
2
  import type { BlockData, MetadataLabelTx, Transaction as ProviderTransaction } from '../utils/types';
3
- /**
4
- * Stored blocks and transactions back in the provider shape (`BlockData`, `Transaction`), for
5
- * serving other ODATANO instances from what this one has indexed. The rows hold the ledger view
6
- * (see ledgerView), so the phase-2 flag follows from them: a valid transaction always spends a
7
- * regular input. Not stored, so absent: `totalCollateral` and `outputAmount`.
8
- */
9
3
  type Row = Record<string, unknown>;
10
4
  /** `Blocks` row -> BlockData. */
11
5
  export declare function blockRowToData(row: Row): BlockData;
@@ -13,19 +7,12 @@ export declare function blockRowToData(row: Row): BlockData;
13
7
  export declare function readBlock(db: CapTransaction, hash: string): Promise<BlockData | null>;
14
8
  /** A stored block by height; null when not indexed. */
15
9
  export declare function readBlockByHeight(db: CapTransaction, height: number): Promise<BlockData | null>;
16
- /**
17
- * Up to `count` stored blocks following height `afterHeight`, contiguous only: the run stops at
18
- * the first missing height, so a caller never walks over a gap.
19
- */
10
+ /** Up to `count` stored blocks after `afterHeight`. Stops at the first gap, so callers never skip one. */
20
11
  export declare function readNextBlocks(db: CapTransaction, afterHeight: number, count: number): Promise<BlockData[]>;
21
12
  /** True when a stored input lacks its outpoint (row indexed before outpoints were recorded). */
22
13
  export declare function lacksOutpoints(t: ProviderTransaction): boolean;
23
14
  /** Stored transactions by hash (missing hashes are absent from the map). */
24
15
  export declare function readTransactionsByHash(db: CapTransaction, hashes: string[]): Promise<Map<string, ProviderTransaction>>;
25
- /**
26
- * Stored transactions of a block in block order; null when the block is not stored with all of its
27
- * transactions (a lazily indexed block may hold only the ones somebody asked for).
28
- */
29
16
  export declare function readBlockTransactions(db: CapTransaction, blockHash: string): Promise<ProviderTransaction[] | null>;
30
17
  /** Metadata of a stored transaction; null when the transaction is not stored. */
31
18
  export declare function readTransactionMetadata(db: CapTransaction, txHash: string): Promise<MetadataLabelTx[] | null>;
@@ -44,10 +44,7 @@ async function readBlockByHeight(db, height) {
44
44
  const row = await db.run(SELECT.one.from(cardano_1.Blocks).where({ height }));
45
45
  return row ? blockRowToData(row) : null;
46
46
  }
47
- /**
48
- * Up to `count` stored blocks following height `afterHeight`, contiguous only: the run stops at
49
- * the first missing height, so a caller never walks over a gap.
50
- */
47
+ /** Up to `count` stored blocks after `afterHeight`. Stops at the first gap, so callers never skip one. */
51
48
  async function readNextBlocks(db, afterHeight, count) {
52
49
  const rows = await db.run(
53
50
  // one operator per column object: `{ '>': a, '<=': b }` renders as `height > a <= b`
@@ -75,10 +72,8 @@ async function readTransactionsByHash(db, hashes) {
75
72
  const txs = await assembleTransactions(db, rows);
76
73
  return new Map(txs.map(t => [t.hash, t]));
77
74
  }
78
- /**
79
- * Stored transactions of a block in block order; null when the block is not stored with all of its
80
- * transactions (a lazily indexed block may hold only the ones somebody asked for).
81
- */
75
+ // Stored transactions of a block in order. Null unless all are stored, since a lazily indexed
76
+ // block may hold only some.
82
77
  async function readBlockTransactions(db, blockHash) {
83
78
  const block = await db.run(SELECT.one.from(cardano_1.Blocks).columns('txCount').where({ hash: blockHash }));
84
79
  if (!block)
@@ -5,10 +5,6 @@ export interface Rational {
5
5
  num: bigint;
6
6
  den: bigint;
7
7
  }
8
- /**
9
- * Reference-script fee as the ledger computes it: `totalBytes` priced tier by tier, each tier
10
- * 1.2 times the previous, exact rationals, floored once at the end.
11
- */
12
8
  export declare function tierRefScriptFee(totalBytes: bigint, pricePerByte: Rational): bigint;
13
9
  /** Reference-script bytes of the inputs and reference inputs, not deduplicated, as the ledger counts them. */
14
10
  export declare function refScriptBytesOf(tx: Tx): bigint;
@@ -10,10 +10,8 @@ const cardano_ledger_ts_1 = require("@harmoniclabs/cardano-ledger-ts");
10
10
  const reference_script_1 = require("../../utils/reference-script");
11
11
  /** Conway reference-script fee: the price per byte rises by 1.2 for every tier of this many bytes. */
12
12
  exports.REF_SCRIPT_TIER_BYTES = 25600n;
13
- /**
14
- * Reference-script fee as the ledger computes it: `totalBytes` priced tier by tier, each tier
15
- * 1.2 times the previous, exact rationals, floored once at the end.
16
- */
13
+ // Ledger reference-script fee: priced tier by tier, each tier 1.2 times the previous.
14
+ // Exact rationals, floored once at the end.
17
15
  function tierRefScriptFee(totalBytes, pricePerByte) {
18
16
  let remaining = totalBytes;
19
17
  let priceNum = pricePerByte.num;
@@ -42,11 +40,8 @@ function refScriptPrice(pp) {
42
40
  const r = (0, cardano_ledger_ts_1.cborFromRational)(pp.minfeeRefScriptCostPerByte ?? cardano_ledger_ts_1.defaultProtocolParameters.minfeeRefScriptCostPerByte);
43
41
  return { num: BigInt(r.num), den: BigInt(r.den) };
44
42
  }
45
- /**
46
- * `TxBuilder.calcMinFee` with the ledger's reference-script rule. Buildooor 0.2.9 prices only the
47
- * reference inputs, linearly; the ledger also counts scripts on spent inputs and prices in tiers.
48
- * The rest (linear fee, estimated key witnesses) is Buildooor's own arithmetic.
49
- */
43
+ // `TxBuilder.calcMinFee` with the ledger's reference-script rule. Buildooor prices only reference
44
+ // inputs, linearly. The ledger also counts scripts on spent inputs and prices them in tiers.
50
45
  function calcMinFeeWithRefScripts(tx, minimum) {
51
46
  const self = this;
52
47
  const pp = self.protocolParamters;