@odatano/core 2.0.0-rc.5 → 2.0.0-rc.50

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 (208) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +99 -51
  2. package/@cds-models/CardanoAgentService/index.js +15 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +347 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +496 -11
  6. package/@cds-models/CardanoIndexerService/index.js +64 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +414 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +32 -19
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +58 -44
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +7 -22
  14. package/@cds-models/index.d.ts +101 -1
  15. package/@cds-models/index.js +16 -1
  16. package/@cds-models/odatano/cardano/index.d.ts +437 -32
  17. package/@cds-models/odatano/cardano/index.js +48 -0
  18. package/README.md +207 -167
  19. package/db/schema.cds +2402 -1705
  20. package/db/types.cds +446 -295
  21. package/package.json +41 -16
  22. package/scripts/migrate-schema.mjs +334 -0
  23. package/scripts/migrate-slot-leader.mjs +96 -0
  24. package/src/index.d.ts +20 -21
  25. package/src/index.js +45 -31
  26. package/src/plugin.js +17 -35
  27. package/srv/blockchain/asset-decimals.d.ts +7 -0
  28. package/srv/blockchain/asset-decimals.js +91 -0
  29. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -135
  30. package/srv/blockchain/backends/blockfrost-backend.js +66 -172
  31. package/srv/blockchain/backends/cardano-backend.d.ts +94 -186
  32. package/srv/blockchain/backends/cardano-backend.js +29 -5
  33. package/srv/blockchain/backends/koios-backend.d.ts +103 -168
  34. package/srv/blockchain/backends/koios-backend.js +428 -360
  35. package/srv/blockchain/backends/odatano-backend.d.ts +54 -0
  36. package/srv/blockchain/backends/odatano-backend.js +169 -0
  37. package/srv/blockchain/backends/ogmios-backend.d.ts +123 -190
  38. package/srv/blockchain/backends/ogmios-backend.js +637 -315
  39. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  40. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  41. package/srv/blockchain/cardano-client.d.ts +61 -241
  42. package/srv/blockchain/cardano-client.js +253 -293
  43. package/srv/blockchain/cardano-indexer.d.ts +282 -281
  44. package/srv/blockchain/cardano-indexer.js +1551 -484
  45. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  46. package/srv/blockchain/cardano-tx-builder.js +164 -140
  47. package/srv/blockchain/circuit-breaker.d.ts +1 -13
  48. package/srv/blockchain/circuit-breaker.js +5 -15
  49. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  50. package/srv/blockchain/crawler/account-snapshots.js +153 -0
  51. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +15 -0
  52. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  53. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +43 -0
  54. package/srv/blockchain/crawler/asset-registry-backfill.js +153 -0
  55. package/srv/blockchain/crawler/certificate-backfill.d.ts +52 -0
  56. package/srv/blockchain/crawler/certificate-backfill.js +162 -0
  57. package/srv/blockchain/crawler/crawler.d.ts +104 -81
  58. package/srv/blockchain/crawler/crawler.js +532 -160
  59. package/srv/blockchain/crawler/credential-backfill.d.ts +28 -0
  60. package/srv/blockchain/crawler/credential-backfill.js +124 -0
  61. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  62. package/srv/blockchain/crawler/index.d.ts +1 -8
  63. package/srv/blockchain/crawler/index.js +31 -17
  64. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  65. package/srv/blockchain/crawler/input-asset-copies.js +171 -0
  66. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
  67. package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
  68. package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
  69. package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
  70. package/srv/blockchain/crawler/sync-state.d.ts +27 -47
  71. package/srv/blockchain/crawler/sync-state.js +113 -63
  72. package/srv/blockchain/crawler/transaction-backfill.d.ts +44 -0
  73. package/srv/blockchain/crawler/transaction-backfill.js +278 -0
  74. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  75. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  76. package/srv/blockchain/ledger-state.d.ts +62 -0
  77. package/srv/blockchain/ledger-state.js +419 -0
  78. package/srv/blockchain/pending-spends.d.ts +16 -0
  79. package/srv/blockchain/pending-spends.js +81 -0
  80. package/srv/blockchain/pool-metadata.d.ts +15 -0
  81. package/srv/blockchain/pool-metadata.js +132 -0
  82. package/srv/blockchain/request-coalescer.d.ts +2 -16
  83. package/srv/blockchain/request-coalescer.js +2 -16
  84. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  85. package/srv/blockchain/signing/cose-verifier.js +146 -70
  86. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  87. package/srv/blockchain/signing/external-signer.js +17 -126
  88. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  89. package/srv/blockchain/signing/hsm-signer.js +28 -79
  90. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  91. package/srv/blockchain/signing/signature-verifier.js +70 -83
  92. package/srv/blockchain/signing/submission-finalizer.d.ts +23 -45
  93. package/srv/blockchain/signing/submission-finalizer.js +219 -86
  94. package/srv/blockchain/stored-chain.d.ts +20 -0
  95. package/srv/blockchain/stored-chain.js +237 -0
  96. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  97. package/srv/blockchain/transaction-building/buildooor-tx.js +652 -416
  98. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  99. package/srv/blockchain/transaction-presence.d.ts +5 -0
  100. package/srv/blockchain/transaction-presence.js +29 -0
  101. package/srv/blockchain/transaction-rows.d.ts +12 -0
  102. package/srv/blockchain/transaction-rows.js +44 -0
  103. package/srv/blockchain/wallet-worker/build-request.d.ts +5 -20
  104. package/srv/blockchain/wallet-worker/build-request.js +47 -30
  105. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -46
  106. package/srv/blockchain/wallet-worker/confirmation-tracker.js +25 -45
  107. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  108. package/srv/blockchain/wallet-worker/index.js +3 -11
  109. package/srv/blockchain/wallet-worker/job-store.d.ts +30 -148
  110. package/srv/blockchain/wallet-worker/job-store.js +101 -201
  111. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  112. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  113. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  114. package/srv/blockchain/wallet-worker/signers.js +4 -12
  115. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +8 -80
  116. package/srv/blockchain/wallet-worker/wallet-worker.js +107 -155
  117. package/srv/cardano-agent-service.cds +122 -84
  118. package/srv/cardano-agent-service.js +4 -9
  119. package/srv/cardano-backend-service.cds +78 -0
  120. package/srv/cardano-backend-service.d.ts +2 -0
  121. package/srv/cardano-backend-service.js +242 -0
  122. package/srv/cardano-indexer-service.cds +387 -73
  123. package/srv/cardano-indexer-service.d.ts +5 -1
  124. package/srv/cardano-indexer-service.js +532 -16
  125. package/srv/cardano-service.cds +424 -269
  126. package/srv/cardano-service.js +289 -201
  127. package/srv/cardano-sign-service.cds +201 -180
  128. package/srv/cardano-sign-service.js +71 -201
  129. package/srv/cardano-tx-service.cds +451 -370
  130. package/srv/cardano-tx-service.js +271 -289
  131. package/srv/cardano-ui.cds +16 -16
  132. package/srv/cardano-worker-service.cds +118 -125
  133. package/srv/cardano-worker-service.js +52 -61
  134. package/srv/cbor/cip68.d.ts +13 -0
  135. package/srv/cbor/cip68.js +56 -0
  136. package/srv/cbor/index.d.ts +3 -1
  137. package/srv/cbor/index.js +9 -1
  138. package/srv/cbor/parse.d.ts +30 -18
  139. package/srv/cbor/parse.js +44 -9
  140. package/srv/cbor/plutus-data-json.d.ts +20 -0
  141. package/srv/cbor/plutus-data-json.js +32 -0
  142. package/srv/config.d.ts +113 -0
  143. package/srv/config.js +409 -0
  144. package/srv/server.d.ts +15 -110
  145. package/srv/server.js +84 -404
  146. package/srv/utils/agent-access.d.ts +9 -0
  147. package/srv/utils/agent-access.js +67 -0
  148. package/srv/utils/agent-grants-config.d.ts +0 -46
  149. package/srv/utils/agent-grants-config.js +17 -85
  150. package/srv/utils/agent-grants.d.ts +106 -122
  151. package/srv/utils/agent-grants.js +538 -236
  152. package/srv/utils/agent-token-auth.d.ts +4 -99
  153. package/srv/utils/agent-token-auth.js +18 -182
  154. package/srv/utils/backend-request-handler.d.ts +3 -17
  155. package/srv/utils/backend-request-handler.js +3 -18
  156. package/srv/utils/collections.d.ts +3 -10
  157. package/srv/utils/collections.js +3 -10
  158. package/srv/utils/const.d.ts +23 -74
  159. package/srv/utils/const.js +32 -79
  160. package/srv/utils/crypto.d.ts +3 -12
  161. package/srv/utils/crypto.js +6 -21
  162. package/srv/utils/db-indexes.d.ts +27 -0
  163. package/srv/utils/db-indexes.js +120 -0
  164. package/srv/utils/db-sanitize.d.ts +20 -0
  165. package/srv/utils/db-sanitize.js +80 -0
  166. package/srv/utils/deep-json.d.ts +6 -0
  167. package/srv/utils/deep-json.js +240 -0
  168. package/srv/utils/epoch-slots.d.ts +13 -0
  169. package/srv/utils/epoch-slots.js +38 -0
  170. package/srv/utils/error-codes.d.ts +22 -75
  171. package/srv/utils/error-codes.js +23 -72
  172. package/srv/utils/errors.d.ts +46 -187
  173. package/srv/utils/errors.js +114 -230
  174. package/srv/utils/liveness.d.ts +12 -0
  175. package/srv/utils/liveness.js +35 -0
  176. package/srv/utils/mappers.d.ts +102 -223
  177. package/srv/utils/mappers.js +387 -316
  178. package/srv/utils/network-context.js +2 -13
  179. package/srv/utils/paging.d.ts +31 -0
  180. package/srv/utils/paging.js +43 -0
  181. package/srv/utils/pg-inline-json.d.ts +8 -0
  182. package/srv/utils/pg-inline-json.js +58 -0
  183. package/srv/utils/pg-order-nulls.d.ts +14 -0
  184. package/srv/utils/pg-order-nulls.js +54 -0
  185. package/srv/utils/plutus-placeholders.d.ts +16 -22
  186. package/srv/utils/plutus-placeholders.js +62 -33
  187. package/srv/utils/rate-limiter.d.ts +2 -21
  188. package/srv/utils/rate-limiter.js +5 -17
  189. package/srv/utils/readiness.d.ts +12 -0
  190. package/srv/utils/readiness.js +29 -0
  191. package/srv/utils/reference-script.d.ts +19 -0
  192. package/srv/utils/reference-script.js +84 -0
  193. package/srv/utils/result-numbers.d.ts +15 -0
  194. package/srv/utils/result-numbers.js +61 -0
  195. package/srv/utils/service-events.d.ts +0 -24
  196. package/srv/utils/service-events.js +3 -25
  197. package/srv/utils/signing-helper.d.ts +3 -20
  198. package/srv/utils/signing-helper.js +35 -64
  199. package/srv/utils/tx-build-helper.d.ts +10 -105
  200. package/srv/utils/tx-build-helper.js +81 -144
  201. package/srv/utils/tx-request-parsers.d.ts +82 -33
  202. package/srv/utils/tx-request-parsers.js +401 -49
  203. package/srv/utils/tx-utils.d.ts +3 -27
  204. package/srv/utils/tx-utils.js +32 -50
  205. package/srv/utils/types.d.ts +261 -191
  206. package/srv/utils/types.js +2 -6
  207. package/srv/utils/validators.d.ts +22 -92
  208. package/srv/utils/validators.js +50 -149
@@ -3,134 +3,233 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.RESUBMIT_WINDOW_MS = void 0;
6
7
  exports.submitAndFinalize = submitAndFinalize;
8
+ exports.submitRecorded = submitRecorded;
7
9
  exports.scheduleDeferredSubmit = scheduleDeferredSubmit;
8
10
  exports.redriveInterruptedSubmissions = redriveInterruptedSubmissions;
11
+ exports.startSubmissionReconciler = startSubmissionReconciler;
12
+ exports.stopSubmissionReconciler = stopSubmissionReconciler;
9
13
  const cds_1 = __importDefault(require("@sap/cds"));
10
14
  const errors_1 = require("../../utils/errors");
11
15
  const tx_utils_1 = require("../../utils/tx-utils");
12
16
  const tx_build_helper_1 = require("../../utils/tx-build-helper");
13
17
  const external_signer_1 = require("./external-signer");
18
+ const transaction_presence_1 = require("../transaction-presence");
19
+ const CardanoTransactionService_1 = require("#cds-models/CardanoTransactionService");
14
20
  const { SELECT, UPDATE } = cds_1.default.ql;
15
21
  const logger = cds_1.default.log('SubmissionFinalizer');
16
- // Lazy require breaks the srv/server.ts <-> this-module import cycle (the
17
- // server calls redriveInterruptedSubmissions at boot; we need its app-context
18
- // getters at runtime only). Same pattern as src/plugin.ts.
22
+ const SIGNING_REQUESTS = 'odatano.cardano.SigningRequests';
23
+ /** An open submit is sent again for this long. After it only the chain is read. */
24
+ exports.RESUBMIT_WINDOW_MS = 10 * 60_000;
25
+ const RECONCILE_INTERVAL_MS = 60_000;
26
+ // Record ids this process is sending right now. The reconciler leaves them alone.
27
+ const inFlight = new Set();
28
+ // Signing requests whose stored transaction no longer verifies. Reported once, then skipped.
29
+ const unverifiable = new Set();
30
+ // Lazy require avoids the srv/server.ts <-> this-module import cycle; the app-context
31
+ // getters are only needed at runtime.
19
32
  function server() {
20
- // eslint-disable-next-line @typescript-eslint/no-var-requires
21
33
  return require('../../server');
22
34
  }
23
- /**
24
- * Submit a verified+claimed signing request to the blockchain and persist the
25
- * outcome — DELIBERATELY outside the caller's request transaction.
26
- *
27
- * The caller must already have durably committed `status:'submitting'` (the
28
- * claim). This function then:
29
- * 1. submits with NO DB write-lock held (the lock was the reason concurrent
30
- * submits serialized and the SQLite busy-timeout could fire mid-network),
31
- * 2. on submit failure: marks the request 'failed' in its own committed tx
32
- * and rethrows (NOT rolled back to a pre-submit status — losing the
33
- * attempt would hide a tx the node may have accepted),
34
- * 3. on success: persists the submission + 'submitted' status in a committed
35
- * transaction.
36
- *
37
- * Crash window: a process death between (1) and (3) leaves the request durably
38
- * at 'submitting'. Deferred-path requests carry their signed CBOR on the row
39
- * and are re-driven at the next boot (redriveInterruptedSubmissions); sync-path
40
- * requests are left for the operator/poller exactly as before.
41
- */
42
- async function submitAndFinalize(SigningRequests, params, afterFinalize) {
43
- // Persist the submission + 'submitted' status in its own committed transaction.
35
+ function liveDeps() {
36
+ return { indexer: server().getCardanoIndexer(), client: server().getCardanoClient() };
37
+ }
38
+ function messageOf(err) {
39
+ return err instanceof Error ? err.message : String(err);
40
+ }
41
+ // Sends the transaction and says what the attempt proves. With send = false only the chain is read,
42
+ // unless no backend can look transactions up: then the node's answer is the only evidence.
43
+ // `error` is the failed submit, also when the transaction turned out to be known.
44
+ async function attemptSubmit(signedTxCbor, txHash, send, indexer, client) {
45
+ const sent = send || !client.supports('getTransaction');
46
+ let error = new Error(`Transaction ${txHash} is not on chain ${exports.RESUBMIT_WINDOW_MS / 60_000} minutes after its submit`);
47
+ if (sent) {
48
+ try {
49
+ await client.submitTransaction(signedTxCbor);
50
+ return { outcome: 'accepted' };
51
+ }
52
+ catch (submitErr) {
53
+ if (submitErr instanceof errors_1.TransactionAlreadySubmittedError)
54
+ return { outcome: 'accepted', error: submitErr };
55
+ error = submitErr;
56
+ }
57
+ }
58
+ // A refusal may mean the transaction is already on chain and its inputs are spent.
59
+ try {
60
+ if (await (0, transaction_presence_1.isTransactionOnChain)(indexer, client, txHash))
61
+ return { outcome: 'accepted', error };
62
+ }
63
+ catch (lookupErr) {
64
+ logger.warn({ txHash, error: messageOf(lookupErr) }, 'Chain lookup after a failed submit was inconclusive');
65
+ return { outcome: 'unknown', error };
66
+ }
67
+ return { outcome: !sent || (0, errors_1.isSubmitRejection)(error) ? 'rejected' : 'unknown', error };
68
+ }
69
+ // Outcomes are written in detached transactions, so no DB lock is held across the network call.
70
+ // A refused transaction is marked 'failed' and the error rethrown. Without a verdict the request
71
+ // stays 'submitting' for the reconciler and the call throws SubmitOutcomeUnknownError.
72
+ async function submitAndFinalize(SigningRequests, params, afterFinalize, send = true, { indexer, client } = liveDeps()) {
44
73
  const finalizeSubmitted = () => (0, tx_utils_1.detachedTx)('finalize transaction submission', async (db) => {
45
- const submission = await server().getCardanoIndexer().indexVerifiedTransactionSubmission(db, params);
74
+ // Only the caller that moves the request to 'submitted' writes the records.
75
+ const won = await db.run(UPDATE.entity(SigningRequests).set({ status: 'submitted', errorMessage: null })
76
+ .where({ id: params.signingRequestId, status: { in: ['submitting', 'failed'] } }));
77
+ if (won === 0) {
78
+ const request = await db.run(SELECT.one.from(SigningRequests).columns('submission_id').where({ id: params.signingRequestId }));
79
+ return db.run(SELECT.one.from(CardanoTransactionService_1.TransactionSubmissions).where({ id: request?.submission_id ?? null }));
80
+ }
81
+ const submission = await indexer.indexVerifiedTransactionSubmission(db, params);
46
82
  if (afterFinalize)
47
83
  await afterFinalize(db);
48
- // Invalidate stale UTxO cache (spent inputs + output addresses) — best-effort,
49
- // must never roll back the durable submission record.
84
+ // Best effort; must never roll back the durable submission record.
50
85
  try {
51
- await server().getCardanoIndexer().invalidateUtxoCacheForTx(db, (0, tx_build_helper_1.extractTxCacheTargets)(params.fullSignedTxCbor));
86
+ await indexer.invalidateUtxoCacheForTx(db, (0, tx_build_helper_1.extractTxCacheTargets)(params.fullSignedTxCbor));
52
87
  }
53
88
  catch (invalidateErr) {
54
- logger.warn(`UTxO cache invalidation failed (submit unaffected): ${invalidateErr instanceof Error ? invalidateErr.message : String(invalidateErr)}`);
89
+ logger.warn(`UTxO cache invalidation failed (submit unaffected): ${messageOf(invalidateErr)}`);
55
90
  }
56
91
  return submission;
57
92
  });
93
+ inFlight.add(params.signingRequestId);
58
94
  try {
59
- await server().getCardanoClient().submitTransaction(params.fullSignedTxCbor);
95
+ const { outcome, error } = await attemptSubmit(params.fullSignedTxCbor, params.txHash, send, indexer, client);
96
+ if (outcome === 'unknown') {
97
+ logger.warn({ signingRequestId: params.signingRequestId, txHash: params.txHash, error: messageOf(error) }, 'Submit got no verdict; the signing request stays submitting');
98
+ throw new errors_1.SubmitOutcomeUnknownError(params.txHash, error);
99
+ }
100
+ if (outcome === 'rejected') {
101
+ try {
102
+ await (0, tx_utils_1.detachedTx)('mark signing request failed', (db) => db.run(UPDATE.entity(SigningRequests).set({ status: 'failed', errorMessage: messageOf(error) })
103
+ .where({ id: params.signingRequestId, status: 'submitting' })));
104
+ }
105
+ catch (markErr) {
106
+ logger.error({ err: markErr, signingRequestId: params.signingRequestId }, 'Could not durably mark signing request failed after submit error');
107
+ }
108
+ throw error;
109
+ }
110
+ if (error) {
111
+ logger.info({ signingRequestId: params.signingRequestId, txHash: params.txHash }, 'Submit failed but the node or the chain has the transaction; finalizing as submitted');
112
+ }
113
+ return await finalizeSubmitted();
60
114
  }
61
- catch (submitErr) {
62
- // Already-submitted means the tx reached the mempool — e.g. the first backend accepted
63
- // it but its response was lost and a fallback observed the duplicate. That is SUCCESS,
64
- // not failure: finalize it as 'submitted' (same as the happy path) instead of durably
65
- // recording a spurious 'failed' for a tx the node already holds.
66
- if (submitErr instanceof errors_1.TransactionAlreadySubmittedError) {
67
- logger.info({ signingRequestId: params.signingRequestId, txHash: params.txHash }, 'Submit reported already-submitted — finalizing as submitted (tx already in mempool)');
68
- return finalizeSubmitted();
115
+ finally {
116
+ inFlight.delete(params.signingRequestId);
117
+ }
118
+ }
119
+ // Commits what one attempt proves for a recorded submission. Returns only when the node accepted
120
+ // the transaction now. A transaction it already had ends as 409, like a resubmit.
121
+ async function settleRecorded(row, send, indexer, client) {
122
+ inFlight.add(row.id);
123
+ try {
124
+ const { outcome, error } = await attemptSubmit(row.signedTxCbor, row.txHash, send, indexer, client);
125
+ if (outcome === 'accepted' && error === undefined) {
126
+ logger.info({ txHash: row.txHash }, 'Transaction submitted to blockchain');
127
+ await (0, tx_utils_1.detachedTx)('record submission outcome', async (db) => {
128
+ await indexer.updateSubmissionStatus(db, row.id, 'submitted');
129
+ // best-effort: a cache failure must not roll back the submitted status
130
+ try {
131
+ const senders = row.buildId
132
+ ? await db.run(SELECT.from(CardanoTransactionService_1.AddressTransactionBuilds).columns('address_address').where({ txBuild_id: row.buildId }))
133
+ : [];
134
+ await indexer.invalidateUtxoCacheForTx(db, (0, tx_build_helper_1.extractTxCacheTargets)(row.signedTxCbor), senders.map(r => r.address_address).filter((a) => !!a));
135
+ }
136
+ catch (invalidateErr) {
137
+ logger.warn(`UTxO cache invalidation failed (submit unaffected): ${messageOf(invalidateErr)}`);
138
+ }
139
+ });
140
+ return;
69
141
  }
142
+ const errMsg = messageOf(error);
70
143
  try {
71
- await (0, tx_utils_1.detachedTx)('mark signing request failed', (db) => db.run(UPDATE.entity(SigningRequests).set({ status: 'failed' }).where({ id: params.signingRequestId })));
144
+ await (0, tx_utils_1.detachedTx)('record submission outcome', async (db) => {
145
+ // the row stays pending with the last error; a refusal ends only a row that is still pending
146
+ if (outcome === 'unknown')
147
+ return indexer.updateSubmissionStatus(db, row.id, 'pending', errMsg);
148
+ if (outcome === 'rejected')
149
+ return indexer.updateSubmissionStatus(db, row.id, 'failed', errMsg, 'pending');
150
+ // A resubmit keeps one row per transaction: its own row goes when an earlier one exists.
151
+ if (await indexer.dropDuplicateSubmission(db, row.id, row.txHash))
152
+ return;
153
+ return indexer.updateSubmissionStatus(db, row.id, 'submitted');
154
+ });
72
155
  }
73
156
  catch (markErr) {
74
- logger.error({ err: markErr, signingRequestId: params.signingRequestId }, 'Could not durably mark signing request failed after submit error');
157
+ logger.error({ err: markErr, submissionId: row.id }, 'Could not record the submission outcome after a submit error');
158
+ }
159
+ if (outcome === 'unknown') {
160
+ logger.warn({ txHash: row.txHash, error: errMsg }, 'Submit got no verdict; the submission stays pending');
161
+ throw new errors_1.SubmitOutcomeUnknownError(row.txHash, error);
162
+ }
163
+ if (outcome === 'rejected') {
164
+ logger.error({ txHash: row.txHash, error: errMsg }, 'Transaction submission failed');
165
+ throw error;
75
166
  }
76
- throw submitErr;
167
+ throw error instanceof errors_1.TransactionAlreadySubmittedError ? error : new errors_1.TransactionAlreadySubmittedError(row.txHash, error);
77
168
  }
78
- return finalizeSubmitted();
169
+ finally {
170
+ inFlight.delete(row.id);
171
+ }
172
+ }
173
+ // 'pending' commits first and the network call runs outside any DB tx.
174
+ // The final status commits on its own and survives a rethrown error.
175
+ async function submitRecorded(params, indexer = server().getCardanoIndexer(), client = server().getCardanoClient()) {
176
+ const record = await (0, tx_utils_1.detachedTx)('record transaction submission', (db) => indexer.persistTransactionSubmission(db, params));
177
+ await settleRecorded({ id: record.id, ...params }, true, indexer, client);
178
+ return { ...record, status: 'submitted' };
79
179
  }
80
- /**
81
- * Deferred-submit scheduler (KNOWN_ISSUES #11, Layer 2).
82
- *
83
- * Called by an action handler AFTER verify + claim ran on the CALLER's
84
- * transaction. Hooks the request's post-commit event: only once the caller's
85
- * root transaction has committed (claim durable, pooled connection released)
86
- * does the network submit + finalize run — detached via setImmediate +
87
- * runWithoutAmbientTx, so no ambient transaction is held across it.
88
- *
89
- * If the caller's transaction rolls back instead, 'succeeded' never fires and
90
- * nothing was claimed — strictly consistent.
91
- */
180
+ // Submits only after the caller's transaction has committed and released its connection.
181
+ // If the caller rolls back, 'succeeded' never fires and nothing was claimed.
92
182
  function scheduleDeferredSubmit(req, SigningRequests, params) {
93
183
  req.on('succeeded', () => {
184
+ // from the commit on the row is visible to the reconciler
185
+ inFlight.add(params.signingRequestId);
94
186
  setImmediate(() => {
95
187
  (0, tx_utils_1.runWithoutAmbientTx)(() => submitAndFinalize(SigningRequests, params))
96
188
  .then(() => {
97
189
  logger.info({ signingRequestId: params.signingRequestId, txHash: params.txHash }, 'Deferred submit finalized');
98
190
  })
99
191
  .catch((err) => {
100
- // submitAndFinalize already durably marked the request 'failed'.
192
+ // submitAndFinalize already recorded the outcome and logged an open one.
193
+ if (err instanceof errors_1.SubmitOutcomeUnknownError)
194
+ return;
101
195
  logger.error({ err, signingRequestId: params.signingRequestId }, 'Deferred submit failed (signing request marked failed)');
102
196
  });
103
197
  });
104
198
  });
105
199
  }
106
- /**
107
- * Boot-time recovery: re-drive submissions that were claimed on the deferred
108
- * path (status 'submitting' WITH persisted signedTxCbor) but never finalized —
109
- * i.e. the process died between the caller's commit and the detached submit.
110
- *
111
- * Safe to repeat: a tx the node already holds finalizes as 'submitted' via the
112
- * TransactionAlreadySubmittedError path in submitAndFinalize. Rows at
113
- * 'submitting' WITHOUT signed CBOR (sync-path crash window) are deliberately
114
- * left untouched for the operator/poller, exactly as before Layer 2.
115
- *
116
- * @returns number of rows re-driven (attempted, not necessarily succeeded)
117
- */
118
- async function redriveInterruptedSubmissions() {
119
- const SigningRequests = 'odatano.cardano.SigningRequests';
120
- const rows = await (0, tx_utils_1.detachedTx)('load interrupted deferred submissions', (db) => db.run(SELECT.from(SigningRequests)
200
+ function olderThanWindow(sinceMs) {
201
+ return Number.isFinite(sinceMs) && Date.now() - sinceMs > exports.RESUBMIT_WINDOW_MS;
202
+ }
203
+ // Resolves signing requests left at 'submitting' and submissions left at 'pending': after a crash
204
+ // or a submit without a verdict. Runs at boot and on a timer. Returns the number of records tried.
205
+ async function redriveInterruptedSubmissions(deps = liveDeps()) {
206
+ const requests = (await (0, tx_utils_1.detachedTx)('load open signing requests', (db) => db.run(SELECT.from(SIGNING_REQUESTS)
207
+ .columns('id', 'build_id', 'txBodyHash', 'signedTxCbor', 'signerType', 'signerInfo', 'signedAt', 'createdAt')
121
208
  .where({ status: 'submitting' })
122
- .and('signedTxCbor is not null')));
123
- if (!rows.length)
209
+ .and('signedTxCbor is not null')))).filter((row) => !inFlight.has(row.id) && !unverifiable.has(row.id));
210
+ const submissions = (await (0, tx_utils_1.detachedTx)('load open submissions', (db) => db.run(SELECT.from(CardanoTransactionService_1.TransactionSubmissions)
211
+ .columns('id', 'build_id', 'txHash', 'signedTxCbor', 'submittedAt')
212
+ .where({ status: 'pending' }))))
213
+ .filter((row) => !inFlight.has(row.id));
214
+ if (!requests.length && !submissions.length)
124
215
  return 0;
125
- logger.info(`Re-driving ${rows.length} interrupted deferred submission(s)`);
216
+ logger.info(`Resolving ${requests.length} open signing request(s) and ${submissions.length} open submission(s)`);
126
217
  let attempted = 0;
127
- for (const row of rows) {
218
+ for (const row of requests) {
219
+ let verificationResult;
220
+ try {
221
+ // Re-verify from the persisted CBOR to recompute the witness metadata the finalize step persists.
222
+ verificationResult = (0, external_signer_1.getExternalSignerModule)().verifyOrThrow(row.signedTxCbor, row.txBodyHash);
223
+ }
224
+ catch (err) {
225
+ unverifiable.add(row.id);
226
+ logger.error({ err, signingRequestId: row.id }, 'Stored signed transaction no longer verifies; the request stays submitting for inspection');
227
+ continue;
228
+ }
229
+ attempted++;
230
+ const send = !olderThanWindow(Date.parse(String(row.signedAt ?? row.createdAt ?? '')));
128
231
  try {
129
- // Re-verify from the persisted CBOR (deterministic — it passed at claim
130
- // time; this recomputes the witness metadata the finalize step persists).
131
- const verificationResult = (0, external_signer_1.getExternalSignerModule)().verifyOrThrow(row.signedTxCbor, row.txBodyHash);
132
- attempted++;
133
- await submitAndFinalize(SigningRequests, {
232
+ await submitAndFinalize(SIGNING_REQUESTS, {
134
233
  signingRequestId: row.id,
135
234
  buildId: row.build_id ?? '',
136
235
  fullSignedTxCbor: row.signedTxCbor,
@@ -138,16 +237,50 @@ async function redriveInterruptedSubmissions() {
138
237
  verificationResult,
139
238
  signerType: row.signerType ?? undefined,
140
239
  signerInfo: row.signerInfo ?? undefined,
141
- });
142
- logger.info({ signingRequestId: row.id, txHash: row.txBodyHash }, 'Interrupted submission re-driven');
240
+ }, undefined, send, deps);
241
+ logger.info({ signingRequestId: row.id, txHash: row.txBodyHash }, 'Open signing request resolved as submitted');
143
242
  }
144
243
  catch (err) {
145
- // submitAndFinalize marked the row 'failed' on submit errors; verification
146
- // errors leave it at 'submitting' for manual inspection (should not happen
147
- // for CBOR that verified once).
148
- logger.error({ err, signingRequestId: row.id }, 'Re-drive of interrupted submission failed');
244
+ if (err instanceof errors_1.SubmitOutcomeUnknownError)
245
+ continue;
246
+ logger.error({ err, signingRequestId: row.id }, 'Open signing request resolved as failed');
247
+ }
248
+ }
249
+ for (const row of submissions) {
250
+ attempted++;
251
+ const send = !olderThanWindow(Number(row.submittedAt) * 1000);
252
+ try {
253
+ await settleRecorded({ id: row.id, signedTxCbor: row.signedTxCbor, txHash: row.txHash, buildId: row.build_id ?? null }, send, deps.indexer, deps.client);
254
+ logger.info({ submissionId: row.id, txHash: row.txHash }, 'Open submission resolved as submitted');
255
+ }
256
+ catch (err) {
257
+ if (err instanceof errors_1.SubmitOutcomeUnknownError)
258
+ continue;
259
+ const level = err instanceof errors_1.TransactionAlreadySubmittedError ? 'info' : 'error';
260
+ logger[level]({ submissionId: row.id, txHash: row.txHash, error: messageOf(err) }, 'Open submission resolved');
149
261
  }
150
262
  }
151
263
  return attempted;
152
264
  }
265
+ let reconcileTimer = null;
266
+ let reconcileRunning = false;
267
+ /** Starts the periodic pass over open signing requests and submissions. Idempotent. */
268
+ function startSubmissionReconciler() {
269
+ if (reconcileTimer)
270
+ return;
271
+ reconcileTimer = setInterval(() => {
272
+ if (reconcileRunning)
273
+ return;
274
+ reconcileRunning = true;
275
+ (0, tx_utils_1.runWithoutAmbientTx)(() => redriveInterruptedSubmissions())
276
+ .catch((err) => logger.error({ err }, 'Submission reconcile pass failed'))
277
+ .finally(() => { reconcileRunning = false; });
278
+ }, RECONCILE_INTERVAL_MS);
279
+ reconcileTimer.unref();
280
+ }
281
+ function stopSubmissionReconciler() {
282
+ if (reconcileTimer)
283
+ clearInterval(reconcileTimer);
284
+ reconcileTimer = null;
285
+ }
153
286
  //# sourceMappingURL=submission-finalizer.js.map
@@ -0,0 +1,20 @@
1
+ import type { Transaction as CapTransaction } from '@sap/cds';
2
+ import type { BlockData, MetadataLabelTx, Transaction as ProviderTransaction } from '../utils/types';
3
+ type Row = Record<string, unknown>;
4
+ /** `Blocks` row -> BlockData. */
5
+ export declare function blockRowToData(row: Row): BlockData;
6
+ /** A stored block by hash; null when not indexed. */
7
+ export declare function readBlock(db: CapTransaction, hash: string): Promise<BlockData | null>;
8
+ /** A stored block by height; null when not indexed. */
9
+ export declare function readBlockByHeight(db: CapTransaction, height: number): Promise<BlockData | null>;
10
+ /** Up to `count` stored blocks after `afterHeight`. Stops at the first gap, so callers never skip one. */
11
+ export declare function readNextBlocks(db: CapTransaction, afterHeight: number, count: number): Promise<BlockData[]>;
12
+ /** True when a stored input lacks its outpoint (row indexed before outpoints were recorded). */
13
+ export declare function lacksOutpoints(t: ProviderTransaction): boolean;
14
+ /** Stored transactions by hash (missing hashes are absent from the map). */
15
+ export declare function readTransactionsByHash(db: CapTransaction, hashes: string[]): Promise<Map<string, ProviderTransaction>>;
16
+ export declare function readBlockTransactions(db: CapTransaction, blockHash: string): Promise<ProviderTransaction[] | null>;
17
+ /** Metadata of a stored transaction; null when the transaction is not stored. */
18
+ export declare function readTransactionMetadata(db: CapTransaction, txHash: string): Promise<MetadataLabelTx[] | null>;
19
+ export {};
20
+ //# sourceMappingURL=stored-chain.d.ts.map
@@ -0,0 +1,237 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.blockRowToData = blockRowToData;
7
+ exports.readBlock = readBlock;
8
+ exports.readBlockByHeight = readBlockByHeight;
9
+ exports.readNextBlocks = readNextBlocks;
10
+ exports.lacksOutpoints = lacksOutpoints;
11
+ exports.readTransactionsByHash = readTransactionsByHash;
12
+ exports.readBlockTransactions = readBlockTransactions;
13
+ exports.readTransactionMetadata = readTransactionMetadata;
14
+ const cds_1 = __importDefault(require("@sap/cds"));
15
+ const deep_json_1 = require("../utils/deep-json");
16
+ const cardano_1 = require("#cds-models/odatano/cardano");
17
+ const collections_1 = require("../utils/collections");
18
+ const { SELECT } = cds_1.default.ql;
19
+ const num = (v) => Number(v ?? 0);
20
+ const numOrNull = (v) => (v == null ? null : Number(v));
21
+ const str = (v) => (v == null ? '' : String(v));
22
+ /** `Blocks` row -> BlockData. */
23
+ function blockRowToData(row) {
24
+ return {
25
+ time: Math.floor(Date.parse(str(row.time)) / 1000),
26
+ height: numOrNull(row.height),
27
+ hash: str(row.hash),
28
+ slot: numOrNull(row.slot),
29
+ slotLeader: str(row.slotLeader),
30
+ epoch: numOrNull(row.epochNumber),
31
+ epochSlot: numOrNull(row.epochSlot),
32
+ size: num(row.size),
33
+ txCount: num(row.txCount),
34
+ fees: row.fees == null ? null : String(row.fees),
35
+ };
36
+ }
37
+ /** A stored block by hash; null when not indexed. */
38
+ async function readBlock(db, hash) {
39
+ const row = await db.run(SELECT.one.from(cardano_1.Blocks).where({ hash }));
40
+ return row ? blockRowToData(row) : null;
41
+ }
42
+ /** A stored block by height; null when not indexed. */
43
+ async function readBlockByHeight(db, height) {
44
+ const row = await db.run(SELECT.one.from(cardano_1.Blocks).where({ height }));
45
+ return row ? blockRowToData(row) : null;
46
+ }
47
+ /** Up to `count` stored blocks after `afterHeight`. Stops at the first gap, so callers never skip one. */
48
+ async function readNextBlocks(db, afterHeight, count) {
49
+ const rows = await db.run(
50
+ // one operator per column object: `{ '>': a, '<=': b }` renders as `height > a <= b`
51
+ SELECT.from(cardano_1.Blocks).where({ height: { between: afterHeight + 1, and: afterHeight + count } }).orderBy('height asc'));
52
+ const out = [];
53
+ let expected = afterHeight + 1;
54
+ for (const row of rows ?? []) {
55
+ if (num(row.height) !== expected)
56
+ break;
57
+ out.push(blockRowToData(row));
58
+ expected++;
59
+ }
60
+ return out;
61
+ }
62
+ /** True when a stored input lacks its outpoint (row indexed before outpoints were recorded). */
63
+ function lacksOutpoints(t) {
64
+ return (t.inputs ?? []).some(i => i.txHash == null);
65
+ }
66
+ /** Stored transactions by hash (missing hashes are absent from the map). */
67
+ async function readTransactionsByHash(db, hashes) {
68
+ const rows = [];
69
+ for (const hashChunk of (0, collections_1.chunk)(hashes, collections_1.IN_CHUNK)) {
70
+ rows.push(...((await db.run(SELECT.from(cardano_1.Transactions).where({ hash: { in: hashChunk } }))) ?? []));
71
+ }
72
+ const txs = await assembleTransactions(db, rows);
73
+ return new Map(txs.map(t => [t.hash, t]));
74
+ }
75
+ // Stored transactions of a block in order. Null unless all are stored, since a lazily indexed
76
+ // block may hold only some.
77
+ async function readBlockTransactions(db, blockHash) {
78
+ const block = await db.run(SELECT.one.from(cardano_1.Blocks).columns('txCount').where({ hash: blockHash }));
79
+ if (!block)
80
+ return null;
81
+ const rows = await db.run(SELECT.from(cardano_1.Transactions).where({ blockHash }).orderBy('txIndex asc'));
82
+ if ((rows ?? []).length !== num(block.txCount))
83
+ return null;
84
+ return assembleTransactions(db, rows ?? []);
85
+ }
86
+ /** Metadata of a stored transaction; null when the transaction is not stored. */
87
+ async function readTransactionMetadata(db, txHash) {
88
+ const known = await db.run(SELECT.one.from(cardano_1.Transactions).columns('hash').where({ hash: txHash }));
89
+ if (!known)
90
+ return null;
91
+ const rows = await db.run(SELECT.from(cardano_1.TransactionMetadata_).where({ tx_hash: txHash }));
92
+ return (rows ?? []).map(metadataRow);
93
+ }
94
+ function metadataRow(r) {
95
+ return {
96
+ txHash: str(r.tx_hash),
97
+ label: str(r.label),
98
+ json: r.payload == null ? undefined : (0, deep_json_1.parseJson)(String(r.payload)),
99
+ };
100
+ }
101
+ /** Amount list with lovelace first, as the providers deliver it. */
102
+ function amounts(assets) {
103
+ const list = assets.map(a => ({ unit: str(a.unit), quantity: str(a.asset_quantity) }));
104
+ return [...list.filter(a => a.unit === 'lovelace'), ...list.filter(a => a.unit !== 'lovelace')];
105
+ }
106
+ function groupBy(rows, key) {
107
+ const out = new Map();
108
+ for (const r of rows) {
109
+ const k = key(r);
110
+ const list = out.get(k);
111
+ if (list)
112
+ list.push(r);
113
+ else
114
+ out.set(k, [r]);
115
+ }
116
+ return out;
117
+ }
118
+ /** Transactions rows + their child tables -> provider transactions, in the order of `rows`. */
119
+ async function assembleTransactions(db, rows) {
120
+ if (rows.length === 0)
121
+ return [];
122
+ const seqs = rows.map(r => r.txSeq);
123
+ const hashes = rows.map(r => str(r.hash));
124
+ const fetchIn = async (entity, column, keys) => {
125
+ const out = [];
126
+ for (const c of (0, collections_1.chunk)(keys, collections_1.IN_CHUNK)) {
127
+ out.push(...((await db.run(SELECT.from(entity).where({ [column]: { in: c } }))) ?? []));
128
+ }
129
+ return out;
130
+ };
131
+ const [inputs, inputAssets, outputs, outputAssets, metadata, certificates, withdrawals, mints, redeemers, datums] = await Promise.all([
132
+ fetchIn(cardano_1.TransactionInputs, 'txSeq', seqs),
133
+ fetchIn(cardano_1.TransactionInputAssets, 'input_txSeq', seqs),
134
+ fetchIn(cardano_1.TransactionOutputs, 'txSeq', seqs),
135
+ fetchIn(cardano_1.TransactionOutputAssets, 'output_txSeq', seqs),
136
+ fetchIn(cardano_1.TransactionMetadata_, 'tx_hash', hashes),
137
+ fetchIn(cardano_1.TransactionCertificates, 'tx_hash', hashes),
138
+ fetchIn(cardano_1.TransactionWithdrawals, 'tx_hash', hashes),
139
+ fetchIn(cardano_1.AssetHistory_, 'txHash', hashes),
140
+ fetchIn(cardano_1.TransactionRedeemers, 'tx_hash', hashes),
141
+ fetchIn(cardano_1.TransactionDatums, 'tx_hash', hashes),
142
+ ]);
143
+ const inputsBySeq = groupBy(inputs, r => str(r.txSeq));
144
+ const inputAssetsByKey = groupBy(inputAssets, r => `${r.input_txSeq}#${r.input_inputIndex}`);
145
+ const outputsBySeq = groupBy(outputs, r => str(r.txSeq));
146
+ const outputAssetsByKey = groupBy(outputAssets, r => `${r.output_txSeq}#${r.output_outputIndex}`);
147
+ const metadataByHash = groupBy(metadata, r => str(r.tx_hash));
148
+ const certsByHash = groupBy(certificates, r => str(r.tx_hash));
149
+ const withdrawalsByHash = groupBy(withdrawals, r => str(r.tx_hash));
150
+ const mintsByHash = groupBy(mints, r => str(r.txHash));
151
+ const redeemersByHash = groupBy(redeemers, r => str(r.tx_hash));
152
+ const datumsByHash = groupBy(datums, r => str(r.tx_hash));
153
+ return rows.map((t) => {
154
+ const seq = str(t.txSeq);
155
+ const hash = str(t.hash);
156
+ const txInputs = (inputsBySeq.get(seq) ?? [])
157
+ .sort((a, b) => num(a.inputIndex) - num(b.inputIndex))
158
+ .map(i => ({
159
+ address: str(i.address_address),
160
+ amount: amounts(inputAssetsByKey.get(`${seq}#${i.inputIndex}`) ?? []),
161
+ // null on rows indexed before the outpoint was recorded, never a made-up reference
162
+ txHash: (i.spentTxHash ?? null),
163
+ outputIndex: numOrNull(i.spentOutputIndex),
164
+ dataHash: i.utxoData_dataHash ?? null,
165
+ inlineDatum: i.utxoData_inlineDatum ?? null,
166
+ referenceScriptHash: i.utxoData_referenceScriptHash ?? null,
167
+ referenceScriptSize: numOrNull(i.utxoData_referenceScriptSize),
168
+ referenceScriptType: i.utxoData_referenceScriptType ?? null,
169
+ isCollateral: Boolean(i.isCollateral),
170
+ isReference: Boolean(i.isReference),
171
+ }));
172
+ // a phase-2 failure keeps only collateral and reference inputs, and its collateral return
173
+ const spendsCollaterals = txInputs.some(i => i.isCollateral) && !txInputs.some(i => !i.isCollateral && !i.isReference);
174
+ const txOutputs = (outputsBySeq.get(seq) ?? [])
175
+ .sort((a, b) => num(a.outputIndex) - num(b.outputIndex))
176
+ .map(o => ({
177
+ address: str(o.address_address),
178
+ amount: amounts(outputAssetsByKey.get(`${seq}#${o.outputIndex}`) ?? []),
179
+ txHash: hash,
180
+ outputIndex: num(o.outputIndex),
181
+ dataHash: o.utxo_dataHash ?? null,
182
+ inlineDatum: o.utxo_inlineDatum ?? null,
183
+ isCollateral: spendsCollaterals,
184
+ referenceScriptHash: o.utxo_referenceScriptHash ?? null,
185
+ referenceScriptSize: numOrNull(o.utxo_referenceScriptSize),
186
+ referenceScriptType: o.utxo_referenceScriptType ?? null,
187
+ }));
188
+ const certs = certsByHash.get(hash);
189
+ const withdrawn = withdrawalsByHash.get(hash);
190
+ const minted = mintsByHash.get(hash);
191
+ const redeemed = redeemersByHash.get(hash);
192
+ const witnessDatums = datumsByHash.get(hash);
193
+ return {
194
+ hash,
195
+ blockHash: str(t.blockHash),
196
+ blockHeight: num(t.blockHeight),
197
+ slot: num(t.slot),
198
+ index: num(t.txIndex),
199
+ fee: str(t.fee ?? '0'),
200
+ deposit: t.deposit == null ? null : str(t.deposit),
201
+ size: numOrNull(t.size),
202
+ blockTime: num(t.blockTime),
203
+ spendsCollaterals,
204
+ mint: minted?.map(m => ({
205
+ unit: str(m.unit),
206
+ quantity: (m.action === 'burn' ? '-' : '') + str(m.quantity),
207
+ })),
208
+ inputs: txInputs,
209
+ outputs: txOutputs,
210
+ metadata: (metadataByHash.get(hash) ?? []).map(metadataRow),
211
+ certificates: certs?.map((c) => ({
212
+ certIndex: num(c.certIndex),
213
+ kind: str(c.kind),
214
+ stakeAddress: c.stakeAddress ?? null,
215
+ poolId: c.poolId ?? null,
216
+ drepId: c.drepId ?? null,
217
+ deposit: c.deposit == null ? null : String(c.deposit),
218
+ epoch: numOrNull(c.epoch),
219
+ })),
220
+ withdrawals: withdrawn?.map((w) => ({ stakeAddress: str(w.stakeAddress), amount: str(w.lovelace) })),
221
+ redeemers: redeemed
222
+ ?.sort((a, b) => str(a.purpose).localeCompare(str(b.purpose)) || num(a.redeemerIndex) - num(b.redeemerIndex))
223
+ .map((r) => ({
224
+ purpose: str(r.purpose),
225
+ index: num(r.redeemerIndex),
226
+ data: str(r.data),
227
+ mem: str(r.mem),
228
+ steps: str(r.steps),
229
+ txHash: r.spentTxHash ?? null,
230
+ outputIndex: numOrNull(r.spentOutputIndex),
231
+ policyId: r.policyId ?? null,
232
+ })),
233
+ datums: witnessDatums?.map((d) => ({ hash: str(d.dataHash), cbor: str(d.datum) })),
234
+ };
235
+ });
236
+ }
237
+ //# sourceMappingURL=stored-chain.js.map