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

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 (239) 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 +358 -0
  4. package/@cds-models/CardanoBackendService/index.js +41 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +594 -11
  6. package/@cds-models/CardanoIndexerService/index.js +74 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +417 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +45 -19
  10. package/@cds-models/CardanoSignService/index.js +4 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +70 -44
  12. package/@cds-models/CardanoTransactionService/index.js +5 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +35 -22
  14. package/@cds-models/CardanoWorkerService/index.js +2 -0
  15. package/@cds-models/index.d.ts +114 -4
  16. package/@cds-models/index.js +20 -4
  17. package/@cds-models/odatano/cardano/index.d.ts +451 -32
  18. package/@cds-models/odatano/cardano/index.js +48 -0
  19. package/README.md +103 -167
  20. package/db/schema.cds +2455 -1705
  21. package/db/types.cds +456 -295
  22. package/package.json +41 -53
  23. package/scripts/deploy-schema.mjs +113 -0
  24. package/scripts/migrate-schema.mjs +528 -0
  25. package/scripts/migrate-slot-leader.mjs +96 -0
  26. package/src/index.d.ts +20 -21
  27. package/src/index.js +45 -31
  28. package/src/plugin.js +17 -35
  29. package/srv/blockchain/asset-decimals.d.ts +7 -0
  30. package/srv/blockchain/asset-decimals.js +91 -0
  31. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -137
  32. package/srv/blockchain/backends/blockfrost-backend.js +125 -215
  33. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  34. package/srv/blockchain/backends/call-signal.js +22 -0
  35. package/srv/blockchain/backends/cardano-backend.d.ts +100 -189
  36. package/srv/blockchain/backends/cardano-backend.js +29 -5
  37. package/srv/blockchain/backends/koios-backend.d.ts +108 -170
  38. package/srv/blockchain/backends/koios-backend.js +488 -482
  39. package/srv/blockchain/backends/odatano-backend.d.ts +55 -0
  40. package/srv/blockchain/backends/odatano-backend.js +211 -0
  41. package/srv/blockchain/backends/ogmios-backend.d.ts +122 -190
  42. package/srv/blockchain/backends/ogmios-backend.js +683 -327
  43. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  44. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  45. package/srv/blockchain/cardano-client.d.ts +71 -241
  46. package/srv/blockchain/cardano-client.js +354 -322
  47. package/srv/blockchain/cardano-indexer.d.ts +295 -283
  48. package/srv/blockchain/cardano-indexer.js +1690 -502
  49. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  50. package/srv/blockchain/cardano-tx-builder.js +164 -140
  51. package/srv/blockchain/circuit-breaker.d.ts +2 -13
  52. package/srv/blockchain/circuit-breaker.js +11 -15
  53. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  54. package/srv/blockchain/crawler/account-snapshots.js +173 -0
  55. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +17 -0
  56. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  57. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +46 -0
  58. package/srv/blockchain/crawler/asset-registry-backfill.js +157 -0
  59. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  60. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  61. package/srv/blockchain/crawler/certificate-backfill.d.ts +56 -0
  62. package/srv/blockchain/crawler/certificate-backfill.js +174 -0
  63. package/srv/blockchain/crawler/crawler.d.ts +125 -81
  64. package/srv/blockchain/crawler/crawler.js +738 -167
  65. package/srv/blockchain/crawler/credential-backfill.d.ts +30 -0
  66. package/srv/blockchain/crawler/credential-backfill.js +101 -0
  67. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  68. package/srv/blockchain/crawler/index.d.ts +1 -8
  69. package/srv/blockchain/crawler/index.js +31 -17
  70. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  71. package/srv/blockchain/crawler/input-asset-copies.js +161 -0
  72. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  73. package/srv/blockchain/crawler/key-pages.js +48 -0
  74. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +22 -0
  75. package/srv/blockchain/crawler/metadata-position-backfill.js +59 -0
  76. package/srv/blockchain/crawler/output-datum-backfill.d.ts +41 -0
  77. package/srv/blockchain/crawler/output-datum-backfill.js +100 -0
  78. package/srv/blockchain/crawler/sync-state.d.ts +31 -47
  79. package/srv/blockchain/crawler/sync-state.js +135 -128
  80. package/srv/blockchain/crawler/transaction-backfill.d.ts +46 -0
  81. package/srv/blockchain/crawler/transaction-backfill.js +271 -0
  82. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  83. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  84. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  85. package/srv/blockchain/crawler/window-plan.js +59 -0
  86. package/srv/blockchain/ledger-state.d.ts +62 -0
  87. package/srv/blockchain/ledger-state.js +521 -0
  88. package/srv/blockchain/pending-spends.d.ts +16 -0
  89. package/srv/blockchain/pending-spends.js +81 -0
  90. package/srv/blockchain/pool-metadata.d.ts +15 -0
  91. package/srv/blockchain/pool-metadata.js +132 -0
  92. package/srv/blockchain/request-coalescer.d.ts +2 -16
  93. package/srv/blockchain/request-coalescer.js +2 -16
  94. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  95. package/srv/blockchain/signing/cose-verifier.js +146 -70
  96. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  97. package/srv/blockchain/signing/external-signer.js +22 -131
  98. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  99. package/srv/blockchain/signing/failed-recheck.js +135 -0
  100. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  101. package/srv/blockchain/signing/hsm-signer.js +28 -79
  102. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  103. package/srv/blockchain/signing/landing-proof.js +224 -0
  104. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  105. package/srv/blockchain/signing/signature-verifier.js +71 -87
  106. package/srv/blockchain/signing/submission-finalizer.d.ts +37 -45
  107. package/srv/blockchain/signing/submission-finalizer.js +280 -86
  108. package/srv/blockchain/stored-chain.d.ts +19 -0
  109. package/srv/blockchain/stored-chain.js +258 -0
  110. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  111. package/srv/blockchain/transaction-building/buildooor-tx.js +663 -421
  112. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  113. package/srv/blockchain/transaction-presence.d.ts +12 -0
  114. package/srv/blockchain/transaction-presence.js +29 -0
  115. package/srv/blockchain/transaction-rows.d.ts +12 -0
  116. package/srv/blockchain/transaction-rows.js +44 -0
  117. package/srv/blockchain/wallet-worker/build-request.d.ts +8 -23
  118. package/srv/blockchain/wallet-worker/build-request.js +40 -353
  119. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +27 -47
  120. package/srv/blockchain/wallet-worker/confirmation-tracker.js +158 -61
  121. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  122. package/srv/blockchain/wallet-worker/index.js +3 -11
  123. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  124. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  125. package/srv/blockchain/wallet-worker/job-store.d.ts +58 -150
  126. package/srv/blockchain/wallet-worker/job-store.js +200 -273
  127. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  128. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  129. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  130. package/srv/blockchain/wallet-worker/signers.js +4 -12
  131. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +29 -82
  132. package/srv/blockchain/wallet-worker/wallet-worker.js +334 -198
  133. package/srv/cardano-agent-service.cds +122 -84
  134. package/srv/cardano-agent-service.js +12 -9
  135. package/srv/cardano-backend-service.cds +81 -0
  136. package/srv/cardano-backend-service.d.ts +2 -0
  137. package/srv/cardano-backend-service.js +259 -0
  138. package/srv/cardano-indexer-service.cds +393 -18
  139. package/srv/cardano-indexer-service.d.ts +5 -1
  140. package/srv/cardano-indexer-service.js +477 -16
  141. package/srv/cardano-service.cds +426 -269
  142. package/srv/cardano-service.js +640 -217
  143. package/srv/cardano-sign-service.cds +211 -180
  144. package/srv/cardano-sign-service.js +210 -287
  145. package/srv/cardano-tx-service.cds +462 -370
  146. package/srv/cardano-tx-service.js +283 -800
  147. package/srv/cardano-ui.cds +16 -16
  148. package/srv/cardano-worker-service.cds +141 -125
  149. package/srv/cardano-worker-service.js +104 -61
  150. package/srv/cbor/cip68.d.ts +13 -0
  151. package/srv/cbor/cip68.js +56 -0
  152. package/srv/cbor/index.d.ts +3 -1
  153. package/srv/cbor/index.js +9 -1
  154. package/srv/cbor/parse.d.ts +30 -18
  155. package/srv/cbor/parse.js +44 -9
  156. package/srv/cbor/plutus-data-json.d.ts +20 -0
  157. package/srv/cbor/plutus-data-json.js +32 -0
  158. package/srv/config.d.ts +117 -0
  159. package/srv/config.js +419 -0
  160. package/srv/server.d.ts +15 -110
  161. package/srv/server.js +83 -405
  162. package/srv/utils/agent-access.d.ts +11 -0
  163. package/srv/utils/agent-access.js +86 -0
  164. package/srv/utils/agent-grants-config.d.ts +0 -46
  165. package/srv/utils/agent-grants-config.js +17 -85
  166. package/srv/utils/agent-grants.d.ts +106 -122
  167. package/srv/utils/agent-grants.js +538 -237
  168. package/srv/utils/agent-token-auth.d.ts +4 -99
  169. package/srv/utils/agent-token-auth.js +62 -186
  170. package/srv/utils/backend-request-handler.d.ts +3 -17
  171. package/srv/utils/backend-request-handler.js +3 -18
  172. package/srv/utils/build-request.d.ts +52 -0
  173. package/srv/utils/build-request.js +487 -0
  174. package/srv/utils/collections.d.ts +4 -10
  175. package/srv/utils/collections.js +14 -10
  176. package/srv/utils/const.d.ts +32 -75
  177. package/srv/utils/const.js +40 -80
  178. package/srv/utils/crypto.d.ts +3 -12
  179. package/srv/utils/crypto.js +11 -25
  180. package/srv/utils/db-indexes.d.ts +31 -0
  181. package/srv/utils/db-indexes.js +185 -0
  182. package/srv/utils/db-kind.d.ts +23 -0
  183. package/srv/utils/db-kind.js +42 -0
  184. package/srv/utils/db-sanitize.d.ts +20 -0
  185. package/srv/utils/db-sanitize.js +80 -0
  186. package/srv/utils/deep-json.d.ts +6 -0
  187. package/srv/utils/deep-json.js +240 -0
  188. package/srv/utils/detached-run.d.ts +41 -0
  189. package/srv/utils/detached-run.js +101 -0
  190. package/srv/utils/epoch-slots.d.ts +14 -0
  191. package/srv/utils/epoch-slots.js +45 -0
  192. package/srv/utils/error-codes.d.ts +26 -75
  193. package/srv/utils/error-codes.js +27 -72
  194. package/srv/utils/errors.d.ts +55 -187
  195. package/srv/utils/errors.js +161 -235
  196. package/srv/utils/lease.d.ts +20 -0
  197. package/srv/utils/lease.js +62 -0
  198. package/srv/utils/liveness.d.ts +12 -0
  199. package/srv/utils/liveness.js +35 -0
  200. package/srv/utils/mappers.d.ts +111 -223
  201. package/srv/utils/mappers.js +432 -371
  202. package/srv/utils/navigation.d.ts +17 -0
  203. package/srv/utils/navigation.js +52 -0
  204. package/srv/utils/network-context.d.ts +0 -1
  205. package/srv/utils/network-context.js +9 -15
  206. package/srv/utils/paging.d.ts +31 -0
  207. package/srv/utils/paging.js +43 -0
  208. package/srv/utils/pg-inline-json.d.ts +8 -0
  209. package/srv/utils/pg-inline-json.js +58 -0
  210. package/srv/utils/pg-order-nulls.d.ts +14 -0
  211. package/srv/utils/pg-order-nulls.js +54 -0
  212. package/srv/utils/plutus-placeholders.d.ts +16 -22
  213. package/srv/utils/plutus-placeholders.js +62 -33
  214. package/srv/utils/rate-limiter.d.ts +2 -21
  215. package/srv/utils/rate-limiter.js +5 -17
  216. package/srv/utils/readiness.d.ts +12 -0
  217. package/srv/utils/readiness.js +29 -0
  218. package/srv/utils/reference-script.d.ts +19 -0
  219. package/srv/utils/reference-script.js +84 -0
  220. package/srv/utils/resolution.d.ts +13 -0
  221. package/srv/utils/resolution.js +47 -0
  222. package/srv/utils/result-numbers.d.ts +15 -0
  223. package/srv/utils/result-numbers.js +61 -0
  224. package/srv/utils/row-values.d.ts +7 -0
  225. package/srv/utils/row-values.js +27 -0
  226. package/srv/utils/service-events.d.ts +0 -24
  227. package/srv/utils/service-events.js +3 -25
  228. package/srv/utils/signing-helper.d.ts +3 -20
  229. package/srv/utils/signing-helper.js +35 -64
  230. package/srv/utils/tx-build-helper.d.ts +25 -105
  231. package/srv/utils/tx-build-helper.js +108 -156
  232. package/srv/utils/tx-request-parsers.d.ts +82 -33
  233. package/srv/utils/tx-request-parsers.js +401 -49
  234. package/srv/utils/tx-utils.d.ts +3 -27
  235. package/srv/utils/tx-utils.js +32 -50
  236. package/srv/utils/types.d.ts +294 -232
  237. package/srv/utils/types.js +2 -22
  238. package/srv/utils/validators.d.ts +22 -92
  239. package/srv/utils/validators.js +60 -170
@@ -3,134 +3,292 @@ 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;
7
+ exports.staleRecordIds = staleRecordIds;
8
+ exports.attemptSubmit = attemptSubmit;
6
9
  exports.submitAndFinalize = submitAndFinalize;
10
+ exports.submitRecorded = submitRecorded;
7
11
  exports.scheduleDeferredSubmit = scheduleDeferredSubmit;
8
12
  exports.redriveInterruptedSubmissions = redriveInterruptedSubmissions;
13
+ exports.startSubmissionReconciler = startSubmissionReconciler;
14
+ exports.stopSubmissionReconciler = stopSubmissionReconciler;
9
15
  const cds_1 = __importDefault(require("@sap/cds"));
10
16
  const errors_1 = require("../../utils/errors");
11
17
  const tx_utils_1 = require("../../utils/tx-utils");
12
18
  const tx_build_helper_1 = require("../../utils/tx-build-helper");
13
19
  const external_signer_1 = require("./external-signer");
20
+ const landing_proof_1 = require("./landing-proof");
21
+ const CardanoTransactionService_1 = require("#cds-models/CardanoTransactionService");
14
22
  const { SELECT, UPDATE } = cds_1.default.ql;
15
23
  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.
24
+ const SIGNING_REQUESTS = 'odatano.cardano.SigningRequests';
25
+ /** An open submit is sent again for this long. After it only the chain is read. */
26
+ exports.RESUBMIT_WINDOW_MS = 10 * 60_000;
27
+ const RECONCILE_INTERVAL_MS = 60_000;
28
+ // Record ids this process is sending right now. The reconciler leaves them alone.
29
+ const inFlight = new Set();
30
+ // Stale records (no expiry, can still land, key not held here) and when the reconciler reads them next.
31
+ const STALE_RECHECK_MS = 60 * 60_000;
32
+ const staleUntil = new Map();
33
+ function noteStale(id, txHash, unspentInputs) {
34
+ staleUntil.set(id, Date.now() + STALE_RECHECK_MS);
35
+ logger.warn({ id, txHash, unspentInputs: unspentInputs.map((r) => `${r.txHash}#${r.outputIndex}`) }, 'Transaction without an expiry has not landed and still can; only spending one of its inputs ends it. Read again in an hour');
36
+ }
37
+ /** Records the reconciler reads only once an hour: no expiry, not landed, an input still unspent. */
38
+ function staleRecordIds() {
39
+ return [...staleUntil.keys()];
40
+ }
41
+ // Signing requests whose stored transaction no longer verifies. Reported once, then skipped.
42
+ const unverifiable = new Set();
43
+ // Lazy require avoids the srv/server.ts <-> this-module import cycle; the app-context
44
+ // getters are only needed at runtime.
19
45
  function server() {
20
- // eslint-disable-next-line @typescript-eslint/no-var-requires
21
46
  return require('../../server');
22
47
  }
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.
48
+ function liveDeps() {
49
+ return { indexer: server().getCardanoIndexer(), client: server().getCardanoClient() };
50
+ }
51
+ function messageOf(err) {
52
+ return err instanceof Error ? err.message : String(err);
53
+ }
54
+ // Sends the transaction and says what the attempt proves. With send = false only the chain is read,
55
+ // unless no backend can look transactions up: then it is sent again, but never past its expiry. A
56
+ // refusal ends the record only where it holds for these bytes; `error` is the failed submit.
57
+ async function attemptSubmit(signedTxCbor, txHash, send, indexer, client, sentAtMs = null) {
58
+ const sent = (send || !client.supports('getTransaction')) && !(0, landing_proof_1.isExpired)(signedTxCbor, client.network);
59
+ let error;
60
+ if (sent) {
61
+ try {
62
+ await client.submitTransaction(signedTxCbor);
63
+ return { outcome: 'accepted' };
64
+ }
65
+ catch (submitErr) {
66
+ if (submitErr instanceof errors_1.TransactionAlreadySubmittedError)
67
+ return { outcome: 'accepted', error: submitErr };
68
+ error = submitErr;
69
+ }
70
+ }
71
+ const landing = await (0, landing_proof_1.judgeLanding)(signedTxCbor, txHash, { indexer, client }, sentAtMs);
72
+ if (landing.verdict === 'onChain')
73
+ return { outcome: 'accepted', error };
74
+ if (landing.verdict === 'scriptFailed')
75
+ return { outcome: 'scriptFailed', error: new errors_1.TransactionValidationError(landing.reason, error) };
76
+ if (sent && (0, landing_proof_1.isFinalRefusal)(error))
77
+ return { outcome: 'rejected', error, finalRefusal: true };
78
+ if (landing.verdict === 'neverLands')
79
+ return { outcome: 'rejected', error: new errors_1.TransactionValidationError(landing.reason, error) };
80
+ if (landing.verdict === 'unresolved')
81
+ return { outcome: 'unresolved', error: new Error(landing.reason) };
82
+ // without an expiry it can still land: open, and the inputs that would let it are named
83
+ if (landing.verdict === 'stale')
84
+ return { outcome: 'unknown', error: new Error(landing.reason), unspentInputs: landing.unspentInputs };
85
+ return { outcome: 'unknown', error: error ?? new Error(`Transaction ${txHash} is not on chain yet and may still land`) };
86
+ }
87
+ // Outcomes are written in detached transactions, so no DB lock is held across the network call.
88
+ // A refused transaction is marked 'failed' and the error rethrown. Without a verdict the request
89
+ // stays 'submitting' for the reconciler and the call throws SubmitOutcomeUnknownError.
90
+ async function submitAndFinalize(SigningRequests, params, afterFinalize, send = true, { indexer, client } = liveDeps()) {
44
91
  const finalizeSubmitted = () => (0, tx_utils_1.detachedTx)('finalize transaction submission', async (db) => {
45
- const submission = await server().getCardanoIndexer().indexVerifiedTransactionSubmission(db, params);
92
+ // Only the caller that moves the request to 'submitted' writes the records.
93
+ const won = await db.run(UPDATE.entity(SigningRequests).set({ status: 'submitted', errorMessage: null })
94
+ .where({ id: params.signingRequestId, status: { in: ['submitting', 'failed'] } }));
95
+ if (won === 0) {
96
+ const request = await db.run(SELECT.one.from(SigningRequests).columns('submission_id').where({ id: params.signingRequestId }));
97
+ return db.run(SELECT.one.from(CardanoTransactionService_1.TransactionSubmissions).where({ id: request?.submission_id ?? null }));
98
+ }
99
+ const submission = await indexer.indexVerifiedTransactionSubmission(db, params);
46
100
  if (afterFinalize)
47
101
  await afterFinalize(db);
48
- // Invalidate stale UTxO cache (spent inputs + output addresses) — best-effort,
49
- // must never roll back the durable submission record.
102
+ // Best effort; must never roll back the durable submission record.
50
103
  try {
51
- await server().getCardanoIndexer().invalidateUtxoCacheForTx(db, (0, tx_build_helper_1.extractTxCacheTargets)(params.fullSignedTxCbor));
104
+ await indexer.invalidateUtxoCacheForTx(db, (0, tx_build_helper_1.extractTxCacheTargets)(params.fullSignedTxCbor));
52
105
  }
53
106
  catch (invalidateErr) {
54
- logger.warn(`UTxO cache invalidation failed (submit unaffected): ${invalidateErr instanceof Error ? invalidateErr.message : String(invalidateErr)}`);
107
+ logger.warn(`UTxO cache invalidation failed (submit unaffected): ${messageOf(invalidateErr)}`);
55
108
  }
56
109
  return submission;
57
110
  });
111
+ inFlight.add(params.signingRequestId);
58
112
  try {
59
- await server().getCardanoClient().submitTransaction(params.fullSignedTxCbor);
113
+ const { outcome, error, unspentInputs } = await attemptSubmit(params.fullSignedTxCbor, params.txHash, send, indexer, client, params.sentAtMs ?? null);
114
+ if (unspentInputs)
115
+ noteStale(params.signingRequestId, params.txHash, unspentInputs);
116
+ else
117
+ staleUntil.delete(params.signingRequestId);
118
+ if (outcome === 'unknown') {
119
+ logger.warn({ signingRequestId: params.signingRequestId, txHash: params.txHash, error: messageOf(error) }, 'Submit got no verdict; the signing request stays submitting');
120
+ throw new errors_1.SubmitOutcomeUnknownError(params.txHash, error);
121
+ }
122
+ if (outcome === 'unresolved') {
123
+ try {
124
+ await (0, tx_utils_1.detachedTx)('mark signing request unresolved', (db) => db.run(UPDATE.entity(SigningRequests).set({ status: 'unresolved', errorMessage: messageOf(error) })
125
+ .where({ id: params.signingRequestId, status: 'submitting' })));
126
+ }
127
+ catch (markErr) {
128
+ logger.error({ err: markErr, signingRequestId: params.signingRequestId }, 'Could not mark signing request unresolved');
129
+ }
130
+ logger.error({ signingRequestId: params.signingRequestId, txHash: params.txHash, error: messageOf(error) }, 'Submit outcome cannot be decided any more; the signing request is unresolved and needs an operator');
131
+ throw new errors_1.SubmitOutcomeUnknownError(params.txHash, error);
132
+ }
133
+ if (outcome === 'rejected' || outcome === 'scriptFailed') {
134
+ try {
135
+ await (0, tx_utils_1.detachedTx)('mark signing request failed', async (db) => {
136
+ const marked = await db.run(UPDATE.entity(SigningRequests).set({ status: 'failed', errorMessage: messageOf(error) })
137
+ .where({ id: params.signingRequestId, status: 'submitting' }));
138
+ // it landed and spent the collateral: the submission record keeps that on file
139
+ if (outcome !== 'scriptFailed' || Number(marked) === 0)
140
+ return;
141
+ const row = await indexer.persistTransactionSubmission(db, {
142
+ signedTxCbor: params.fullSignedTxCbor, txHash: params.txHash, buildId: params.buildId || null,
143
+ });
144
+ await indexer.updateSubmissionStatus(db, row.id, 'failed', messageOf(error));
145
+ await db.run(UPDATE.entity(SigningRequests).set({ submission_id: row.id }).where({ id: params.signingRequestId }));
146
+ });
147
+ }
148
+ catch (markErr) {
149
+ logger.error({ err: markErr, signingRequestId: params.signingRequestId }, 'Could not durably mark signing request failed after submit error');
150
+ }
151
+ throw error;
152
+ }
153
+ if (error) {
154
+ logger.info({ signingRequestId: params.signingRequestId, txHash: params.txHash }, 'Submit failed but the node or the chain has the transaction; finalizing as submitted');
155
+ }
156
+ return await finalizeSubmitted();
157
+ }
158
+ finally {
159
+ inFlight.delete(params.signingRequestId);
60
160
  }
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();
161
+ }
162
+ // Commits what one attempt proves for a recorded submission. Returns only when the node accepted
163
+ // the transaction now. A transaction it already had ends as 409, like a resubmit.
164
+ async function settleRecorded(row, send, indexer, client) {
165
+ inFlight.add(row.id);
166
+ try {
167
+ const { outcome, error, unspentInputs } = await attemptSubmit(row.signedTxCbor, row.txHash, send, indexer, client, row.sentAtMs);
168
+ if (unspentInputs)
169
+ noteStale(row.id, row.txHash, unspentInputs);
170
+ else
171
+ staleUntil.delete(row.id);
172
+ // every write changes only a row still pending: another instance may have settled it meanwhile
173
+ if (outcome === 'accepted' && error === undefined) {
174
+ logger.info({ txHash: row.txHash }, 'Transaction submitted to blockchain');
175
+ await (0, tx_utils_1.detachedTx)('record submission outcome', async (db) => {
176
+ await indexer.updateSubmissionStatus(db, row.id, 'submitted', undefined, 'pending');
177
+ // best-effort: a cache failure must not roll back the submitted status
178
+ try {
179
+ const senders = row.buildId
180
+ ? await db.run(SELECT.from(CardanoTransactionService_1.AddressTransactionBuilds).columns('address_address').where({ txBuild_id: row.buildId }))
181
+ : [];
182
+ await indexer.invalidateUtxoCacheForTx(db, (0, tx_build_helper_1.extractTxCacheTargets)(row.signedTxCbor), senders.map(r => r.address_address).filter((a) => !!a));
183
+ }
184
+ catch (invalidateErr) {
185
+ logger.warn(`UTxO cache invalidation failed (submit unaffected): ${messageOf(invalidateErr)}`);
186
+ }
187
+ });
188
+ return;
69
189
  }
190
+ const errMsg = messageOf(error);
70
191
  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 })));
192
+ await (0, tx_utils_1.detachedTx)('record submission outcome', async (db) => {
193
+ // the row stays pending with the last error; a refusal ends only a row that is still pending
194
+ if (outcome === 'unknown')
195
+ return indexer.updateSubmissionStatus(db, row.id, 'pending', errMsg, 'pending');
196
+ if (outcome === 'unresolved')
197
+ return indexer.updateSubmissionStatus(db, row.id, 'unresolved', errMsg, 'pending');
198
+ if (outcome === 'rejected' || outcome === 'scriptFailed')
199
+ return indexer.updateSubmissionStatus(db, row.id, 'failed', errMsg, 'pending');
200
+ // A resubmit keeps one row per transaction: its own row goes when an earlier one exists.
201
+ if (await indexer.dropDuplicateSubmission(db, row.id, row.txHash))
202
+ return;
203
+ return indexer.updateSubmissionStatus(db, row.id, 'submitted', undefined, 'pending');
204
+ });
72
205
  }
73
206
  catch (markErr) {
74
- logger.error({ err: markErr, signingRequestId: params.signingRequestId }, 'Could not durably mark signing request failed after submit error');
207
+ logger.error({ err: markErr, submissionId: row.id }, 'Could not record the submission outcome after a submit error');
75
208
  }
76
- throw submitErr;
209
+ if (outcome === 'unknown') {
210
+ logger.warn({ txHash: row.txHash, error: errMsg }, 'Submit got no verdict; the submission stays pending');
211
+ throw new errors_1.SubmitOutcomeUnknownError(row.txHash, error);
212
+ }
213
+ if (outcome === 'unresolved') {
214
+ logger.error({ txHash: row.txHash, error: errMsg }, 'Submission outcome cannot be decided any more; it is unresolved and needs an operator');
215
+ throw new errors_1.SubmitOutcomeUnknownError(row.txHash, error);
216
+ }
217
+ if (outcome === 'rejected' || outcome === 'scriptFailed') {
218
+ logger.error({ txHash: row.txHash, error: errMsg }, 'Transaction submission failed');
219
+ throw error;
220
+ }
221
+ throw error instanceof errors_1.TransactionAlreadySubmittedError ? error : new errors_1.TransactionAlreadySubmittedError(row.txHash, error);
77
222
  }
78
- return finalizeSubmitted();
223
+ finally {
224
+ inFlight.delete(row.id);
225
+ }
226
+ }
227
+ // 'pending' commits first and the network call runs outside any DB tx.
228
+ // The final status commits on its own and survives a rethrown error.
229
+ async function submitRecorded(params, indexer = server().getCardanoIndexer(), client = server().getCardanoClient()) {
230
+ const record = await (0, tx_utils_1.detachedTx)('record transaction submission', (db) => indexer.persistTransactionSubmission(db, params));
231
+ await settleRecorded({ id: record.id, ...params, sentAtMs: Date.now() }, true, indexer, client);
232
+ return { ...record, status: 'submitted' };
79
233
  }
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
- */
234
+ // Submits only after the caller's transaction has committed and released its connection.
235
+ // If the caller rolls back, 'succeeded' never fires and nothing was claimed.
92
236
  function scheduleDeferredSubmit(req, SigningRequests, params) {
93
237
  req.on('succeeded', () => {
238
+ // from the commit on the row is visible to the reconciler
239
+ inFlight.add(params.signingRequestId);
94
240
  setImmediate(() => {
95
241
  (0, tx_utils_1.runWithoutAmbientTx)(() => submitAndFinalize(SigningRequests, params))
96
242
  .then(() => {
97
243
  logger.info({ signingRequestId: params.signingRequestId, txHash: params.txHash }, 'Deferred submit finalized');
98
244
  })
99
245
  .catch((err) => {
100
- // submitAndFinalize already durably marked the request 'failed'.
246
+ // submitAndFinalize already recorded the outcome and logged an open one.
247
+ if (err instanceof errors_1.SubmitOutcomeUnknownError)
248
+ return;
101
249
  logger.error({ err, signingRequestId: params.signingRequestId }, 'Deferred submit failed (signing request marked failed)');
102
250
  });
103
251
  });
104
252
  });
105
253
  }
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)
254
+ /** Milliseconds of a stored timestamp, or null when there is none. */
255
+ function msOrNull(value) {
256
+ const ms = value ? Date.parse(value) : NaN;
257
+ return Number.isFinite(ms) ? ms : null;
258
+ }
259
+ function olderThanWindow(sinceMs) {
260
+ return Number.isFinite(sinceMs) && Date.now() - sinceMs > exports.RESUBMIT_WINDOW_MS;
261
+ }
262
+ // Resolves signing requests left at 'submitting' and submissions left at 'pending': after a crash
263
+ // or a submit without a verdict. Runs at boot and on a timer. Returns the number of records tried.
264
+ async function redriveInterruptedSubmissions(deps = liveDeps()) {
265
+ const requests = (await (0, tx_utils_1.detachedTx)('load open signing requests', (db) => db.run(SELECT.from(SIGNING_REQUESTS)
266
+ .columns('id', 'build_id', 'txBodyHash', 'signedTxCbor', 'signerType', 'signerInfo', 'signedAt', 'createdAt')
121
267
  .where({ status: 'submitting' })
122
- .and('signedTxCbor is not null')));
123
- if (!rows.length)
268
+ .and('signedTxCbor is not null')))).filter((row) => !inFlight.has(row.id) && !unverifiable.has(row.id) && (staleUntil.get(row.id) ?? 0) <= Date.now());
269
+ const submissions = (await (0, tx_utils_1.detachedTx)('load open submissions', (db) => db.run(SELECT.from(CardanoTransactionService_1.TransactionSubmissions)
270
+ .columns('id', 'build_id', 'txHash', 'signedTxCbor', 'submittedAt')
271
+ .where({ status: 'pending' }))))
272
+ .filter((row) => !inFlight.has(row.id) && (staleUntil.get(row.id) ?? 0) <= Date.now());
273
+ if (!requests.length && !submissions.length)
124
274
  return 0;
125
- logger.info(`Re-driving ${rows.length} interrupted deferred submission(s)`);
275
+ logger.info(`Resolving ${requests.length} open signing request(s) and ${submissions.length} open submission(s)`);
126
276
  let attempted = 0;
127
- for (const row of rows) {
277
+ for (const row of requests) {
278
+ let verificationResult;
128
279
  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, {
280
+ // Re-verify from the persisted CBOR to recompute the witness metadata the finalize step persists.
281
+ verificationResult = (0, external_signer_1.getExternalSignerModule)().verifyOrThrow(row.signedTxCbor, row.txBodyHash);
282
+ }
283
+ catch (err) {
284
+ unverifiable.add(row.id);
285
+ logger.error({ err, signingRequestId: row.id }, 'Stored signed transaction no longer verifies; the request stays submitting for inspection');
286
+ continue;
287
+ }
288
+ attempted++;
289
+ const send = !olderThanWindow(Date.parse(String(row.signedAt ?? row.createdAt ?? '')));
290
+ try {
291
+ await submitAndFinalize(SIGNING_REQUESTS, {
134
292
  signingRequestId: row.id,
135
293
  buildId: row.build_id ?? '',
136
294
  fullSignedTxCbor: row.signedTxCbor,
@@ -138,16 +296,52 @@ async function redriveInterruptedSubmissions() {
138
296
  verificationResult,
139
297
  signerType: row.signerType ?? undefined,
140
298
  signerInfo: row.signerInfo ?? undefined,
141
- });
142
- logger.info({ signingRequestId: row.id, txHash: row.txBodyHash }, 'Interrupted submission re-driven');
299
+ sentAtMs: msOrNull(row.signedAt ?? row.createdAt),
300
+ }, undefined, send, deps);
301
+ logger.info({ signingRequestId: row.id, txHash: row.txBodyHash }, 'Open signing request resolved as submitted');
143
302
  }
144
303
  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');
304
+ if (err instanceof errors_1.SubmitOutcomeUnknownError)
305
+ continue;
306
+ logger.error({ err, signingRequestId: row.id }, 'Open signing request resolved as failed');
307
+ }
308
+ }
309
+ for (const row of submissions) {
310
+ attempted++;
311
+ const send = !olderThanWindow(Number(row.submittedAt) * 1000);
312
+ try {
313
+ const sentAtMs = row.submittedAt == null ? null : Number(row.submittedAt) * 1000;
314
+ await settleRecorded({ id: row.id, signedTxCbor: row.signedTxCbor, txHash: row.txHash, buildId: row.build_id ?? null, sentAtMs }, send, deps.indexer, deps.client);
315
+ logger.info({ submissionId: row.id, txHash: row.txHash }, 'Open submission resolved as submitted');
316
+ }
317
+ catch (err) {
318
+ if (err instanceof errors_1.SubmitOutcomeUnknownError)
319
+ continue;
320
+ const level = err instanceof errors_1.TransactionAlreadySubmittedError ? 'info' : 'error';
321
+ logger[level]({ submissionId: row.id, txHash: row.txHash, error: messageOf(err) }, 'Open submission resolved');
149
322
  }
150
323
  }
151
324
  return attempted;
152
325
  }
326
+ let reconcileTimer = null;
327
+ let reconcileRunning = false;
328
+ /** Starts the periodic pass over open signing requests and submissions. Idempotent. */
329
+ function startSubmissionReconciler() {
330
+ if (reconcileTimer)
331
+ return;
332
+ reconcileTimer = setInterval(() => {
333
+ if (reconcileRunning)
334
+ return;
335
+ reconcileRunning = true;
336
+ (0, tx_utils_1.runWithoutAmbientTx)(() => redriveInterruptedSubmissions())
337
+ .catch((err) => logger.error({ err }, 'Submission reconcile pass failed'))
338
+ .finally(() => { reconcileRunning = false; });
339
+ }, RECONCILE_INTERVAL_MS);
340
+ reconcileTimer.unref();
341
+ }
342
+ function stopSubmissionReconciler() {
343
+ if (reconcileTimer)
344
+ clearInterval(reconcileTimer);
345
+ reconcileTimer = null;
346
+ }
153
347
  //# sourceMappingURL=submission-finalizer.js.map
@@ -0,0 +1,19 @@
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
+ export declare function readNextBlocks(db: CapTransaction, afterHeight: number, count: number, afterHash?: string | null): Promise<BlockData[]>;
11
+ /** True when a stored input lacks its outpoint (row indexed before outpoints were recorded). */
12
+ export declare function lacksOutpoints(t: ProviderTransaction): boolean;
13
+ /** Stored transactions by hash (missing hashes are absent from the map). */
14
+ export declare function readTransactionsByHash(db: CapTransaction, hashes: string[]): Promise<Map<string, ProviderTransaction>>;
15
+ export declare function readBlockTransactions(db: CapTransaction, blockHash: string): Promise<ProviderTransaction[] | null>;
16
+ /** Metadata of a stored transaction; null when the transaction is not stored. */
17
+ export declare function readTransactionMetadata(db: CapTransaction, txHash: string): Promise<MetadataLabelTx[] | null>;
18
+ export {};
19
+ //# sourceMappingURL=stored-chain.d.ts.map