@odatano/core 2.0.0-rc.50 → 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 (151) hide show
  1. package/@cds-models/CardanoBackendService/index.d.ts +14 -3
  2. package/@cds-models/CardanoBackendService/index.js +1 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +98 -0
  4. package/@cds-models/CardanoIndexerService/index.js +10 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +3 -0
  6. package/@cds-models/CardanoSignService/index.d.ts +13 -0
  7. package/@cds-models/CardanoSignService/index.js +1 -0
  8. package/@cds-models/CardanoTransactionService/index.d.ts +12 -0
  9. package/@cds-models/CardanoTransactionService/index.js +1 -0
  10. package/@cds-models/CardanoWorkerService/index.d.ts +28 -0
  11. package/@cds-models/CardanoWorkerService/index.js +2 -0
  12. package/@cds-models/index.d.ts +13 -3
  13. package/@cds-models/index.js +4 -3
  14. package/@cds-models/odatano/cardano/index.d.ts +14 -0
  15. package/README.md +45 -149
  16. package/db/schema.cds +63 -10
  17. package/db/types.cds +10 -0
  18. package/package.json +7 -44
  19. package/scripts/deploy-schema.mjs +113 -0
  20. package/scripts/migrate-schema.mjs +209 -15
  21. package/srv/blockchain/backends/blockfrost-backend.d.ts +2 -4
  22. package/srv/blockchain/backends/blockfrost-backend.js +61 -45
  23. package/srv/blockchain/backends/call-signal.d.ts +7 -0
  24. package/srv/blockchain/backends/call-signal.js +22 -0
  25. package/srv/blockchain/backends/cardano-backend.d.ts +6 -3
  26. package/srv/blockchain/backends/koios-backend.d.ts +9 -6
  27. package/srv/blockchain/backends/koios-backend.js +145 -207
  28. package/srv/blockchain/backends/odatano-backend.d.ts +2 -1
  29. package/srv/blockchain/backends/odatano-backend.js +51 -9
  30. package/srv/blockchain/backends/ogmios-backend.d.ts +1 -2
  31. package/srv/blockchain/backends/ogmios-backend.js +82 -48
  32. package/srv/blockchain/cardano-client.d.ts +15 -5
  33. package/srv/blockchain/cardano-client.js +143 -71
  34. package/srv/blockchain/cardano-indexer.d.ts +27 -16
  35. package/srv/blockchain/cardano-indexer.js +223 -102
  36. package/srv/blockchain/circuit-breaker.d.ts +1 -0
  37. package/srv/blockchain/circuit-breaker.js +6 -0
  38. package/srv/blockchain/crawler/account-snapshots.js +22 -2
  39. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +2 -0
  40. package/srv/blockchain/crawler/asset-decimals-backfill.js +29 -29
  41. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +3 -0
  42. package/srv/blockchain/crawler/asset-registry-backfill.js +4 -0
  43. package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
  44. package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
  45. package/srv/blockchain/crawler/certificate-backfill.d.ts +4 -0
  46. package/srv/blockchain/crawler/certificate-backfill.js +15 -3
  47. package/srv/blockchain/crawler/crawler.d.ts +22 -1
  48. package/srv/blockchain/crawler/crawler.js +223 -24
  49. package/srv/blockchain/crawler/credential-backfill.d.ts +2 -0
  50. package/srv/blockchain/crawler/credential-backfill.js +43 -66
  51. package/srv/blockchain/crawler/input-asset-copies.d.ts +4 -4
  52. package/srv/blockchain/crawler/input-asset-copies.js +17 -27
  53. package/srv/blockchain/crawler/key-pages.d.ts +12 -0
  54. package/srv/blockchain/crawler/key-pages.js +48 -0
  55. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +6 -0
  56. package/srv/blockchain/crawler/metadata-position-backfill.js +23 -19
  57. package/srv/blockchain/crawler/output-datum-backfill.d.ts +3 -1
  58. package/srv/blockchain/crawler/output-datum-backfill.js +8 -18
  59. package/srv/blockchain/crawler/sync-state.d.ts +5 -1
  60. package/srv/blockchain/crawler/sync-state.js +63 -106
  61. package/srv/blockchain/crawler/transaction-backfill.d.ts +2 -0
  62. package/srv/blockchain/crawler/transaction-backfill.js +6 -13
  63. package/srv/blockchain/crawler/utxo-set-import.js +2 -2
  64. package/srv/blockchain/crawler/window-plan.d.ts +31 -0
  65. package/srv/blockchain/crawler/window-plan.js +59 -0
  66. package/srv/blockchain/ledger-state.d.ts +2 -2
  67. package/srv/blockchain/ledger-state.js +139 -37
  68. package/srv/blockchain/signing/external-signer.js +5 -5
  69. package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
  70. package/srv/blockchain/signing/failed-recheck.js +135 -0
  71. package/srv/blockchain/signing/landing-proof.d.ts +60 -0
  72. package/srv/blockchain/signing/landing-proof.js +224 -0
  73. package/srv/blockchain/signing/signature-verifier.js +10 -13
  74. package/srv/blockchain/signing/submission-finalizer.d.ts +17 -3
  75. package/srv/blockchain/signing/submission-finalizer.js +90 -29
  76. package/srv/blockchain/stored-chain.d.ts +1 -2
  77. package/srv/blockchain/stored-chain.js +36 -15
  78. package/srv/blockchain/transaction-building/buildooor-tx.js +16 -10
  79. package/srv/blockchain/transaction-presence.d.ts +8 -1
  80. package/srv/blockchain/transaction-presence.js +12 -12
  81. package/srv/blockchain/wallet-worker/build-request.d.ts +6 -6
  82. package/srv/blockchain/wallet-worker/build-request.js +35 -365
  83. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +23 -2
  84. package/srv/blockchain/wallet-worker/confirmation-tracker.js +140 -23
  85. package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
  86. package/srv/blockchain/wallet-worker/invalidation.js +128 -0
  87. package/srv/blockchain/wallet-worker/job-store.d.ts +28 -2
  88. package/srv/blockchain/wallet-worker/job-store.js +107 -80
  89. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +21 -2
  90. package/srv/blockchain/wallet-worker/wallet-worker.js +241 -57
  91. package/srv/cardano-agent-service.cds +1 -1
  92. package/srv/cardano-agent-service.js +8 -0
  93. package/srv/cardano-backend-service.cds +4 -1
  94. package/srv/cardano-backend-service.js +26 -9
  95. package/srv/cardano-indexer-service.cds +448 -387
  96. package/srv/cardano-indexer-service.js +226 -281
  97. package/srv/cardano-service.cds +7 -5
  98. package/srv/cardano-service.js +404 -69
  99. package/srv/cardano-sign-service.cds +11 -1
  100. package/srv/cardano-sign-service.js +161 -108
  101. package/srv/cardano-tx-service.cds +15 -4
  102. package/srv/cardano-tx-service.js +105 -604
  103. package/srv/cardano-worker-service.cds +25 -2
  104. package/srv/cardano-worker-service.js +56 -4
  105. package/srv/config.d.ts +4 -0
  106. package/srv/config.js +10 -0
  107. package/srv/server.js +5 -7
  108. package/srv/utils/agent-access.d.ts +4 -2
  109. package/srv/utils/agent-access.js +26 -7
  110. package/srv/utils/agent-grants.d.ts +1 -1
  111. package/srv/utils/agent-grants.js +7 -8
  112. package/srv/utils/agent-token-auth.js +45 -5
  113. package/srv/utils/build-request.d.ts +52 -0
  114. package/srv/utils/build-request.js +487 -0
  115. package/srv/utils/collections.d.ts +1 -0
  116. package/srv/utils/collections.js +11 -0
  117. package/srv/utils/const.d.ts +10 -2
  118. package/srv/utils/const.js +13 -6
  119. package/srv/utils/crypto.js +5 -4
  120. package/srv/utils/db-indexes.d.ts +5 -1
  121. package/srv/utils/db-indexes.js +79 -14
  122. package/srv/utils/db-kind.d.ts +23 -0
  123. package/srv/utils/db-kind.js +42 -0
  124. package/srv/utils/detached-run.d.ts +41 -0
  125. package/srv/utils/detached-run.js +101 -0
  126. package/srv/utils/epoch-slots.d.ts +1 -0
  127. package/srv/utils/epoch-slots.js +7 -0
  128. package/srv/utils/error-codes.d.ts +4 -0
  129. package/srv/utils/error-codes.js +4 -0
  130. package/srv/utils/errors.d.ts +10 -1
  131. package/srv/utils/errors.js +51 -9
  132. package/srv/utils/lease.d.ts +20 -0
  133. package/srv/utils/lease.js +62 -0
  134. package/srv/utils/mappers.d.ts +9 -0
  135. package/srv/utils/mappers.js +57 -67
  136. package/srv/utils/navigation.d.ts +17 -0
  137. package/srv/utils/navigation.js +52 -0
  138. package/srv/utils/network-context.d.ts +0 -1
  139. package/srv/utils/network-context.js +8 -3
  140. package/srv/utils/pg-inline-json.js +3 -3
  141. package/srv/utils/pg-order-nulls.js +3 -3
  142. package/srv/utils/resolution.d.ts +13 -0
  143. package/srv/utils/resolution.js +47 -0
  144. package/srv/utils/row-values.d.ts +7 -0
  145. package/srv/utils/row-values.js +27 -0
  146. package/srv/utils/tx-build-helper.d.ts +15 -0
  147. package/srv/utils/tx-build-helper.js +28 -13
  148. package/srv/utils/types.d.ts +35 -43
  149. package/srv/utils/types.js +1 -17
  150. package/srv/utils/validators.d.ts +2 -2
  151. package/srv/utils/validators.js +14 -25
@@ -7,10 +7,18 @@ exports.ConfirmationTracker = void 0;
7
7
  const cds_1 = __importDefault(require("@sap/cds"));
8
8
  const cardano_1 = require("#cds-models/odatano/cardano");
9
9
  const errors_1 = require("../../utils/errors");
10
+ const tx_utils_1 = require("../../utils/tx-utils");
11
+ const landing_proof_1 = require("../signing/landing-proof");
12
+ const transaction_presence_1 = require("../transaction-presence");
10
13
  const hooks_1 = require("../crawler/hooks");
11
14
  const job_store_1 = require("./job-store");
12
15
  const { UPDATE } = cds_1.default.ql;
13
16
  const logger = cds_1.default.log('CardanoWalletWorker');
17
+ /** A job overdue for confirmation has the chain read for it at most this often. */
18
+ const LANDING_CHECK_INTERVAL_MS = 60_000;
19
+ /** First and longest wait before the stored bytes of an overdue job are sent again. */
20
+ const RESEND_BACKOFF_MIN_MS = 60_000;
21
+ const RESEND_BACKOFF_MAX_MS = 30 * 60_000;
14
22
  class ConfirmationTracker {
15
23
  deps;
16
24
  pending = new Map();
@@ -48,6 +56,10 @@ class ConfirmationTracker {
48
56
  size() {
49
57
  return this.pending.size;
50
58
  }
59
+ /** Stops watching a job another path finalized. */
60
+ untrack(jobId) {
61
+ this.pending.delete(jobId);
62
+ }
51
63
  /** Register a submitted job for confirmation watching. Idempotent per jobId. */
52
64
  track(job) {
53
65
  if (this.pending.has(job.jobId))
@@ -109,8 +121,8 @@ class ConfirmationTracker {
109
121
  }
110
122
  }
111
123
  }
112
- /** Back to watching after a rollback. Re-submits the same signed CBOR, never a rebuild, to avoid a double spend. */
113
- async forgetInclusion(job) {
124
+ /** Back to watching. After a rollback it re-submits the same signed CBOR, never a rebuild, to avoid a double spend. */
125
+ async forgetInclusion(job, resubmit = true) {
114
126
  job.foundSlot = null;
115
127
  job.foundHeight = null;
116
128
  job.seenRound = undefined;
@@ -120,7 +132,7 @@ class ConfirmationTracker {
120
132
  catch (err) {
121
133
  logger.warn(`Job ${job.jobId}: failed to clear confirmation point:`, err);
122
134
  }
123
- if (this.deps.options.resubmitOnRollback && job.signedTxCbor) {
135
+ if (resubmit && this.deps.options.resubmitOnRollback && job.signedTxCbor && !(0, landing_proof_1.isExpired)(job.signedTxCbor, this.deps.client.network)) {
124
136
  try {
125
137
  await this.deps.client.submitTransaction(job.signedTxCbor);
126
138
  logger.info(`Job ${job.jobId}: re-submitted original signed tx after rollback`);
@@ -157,27 +169,28 @@ class ConfirmationTracker {
157
169
  for (const job of [...this.pending.values()]) {
158
170
  if (job.foundHeight != null)
159
171
  continue;
172
+ let found;
160
173
  try {
161
- const tx = await this.deps.client.getTransaction(job.txHash);
162
- job.foundSlot = tx.slot ?? null;
163
- job.foundHeight = tx.blockHeight ?? null;
174
+ found = await this.locate(job);
175
+ }
176
+ catch (err) {
177
+ logger.debug(`Job ${job.jobId}: confirmation lookup failed (transient, next round retries):`, err);
178
+ continue;
179
+ }
180
+ if (found?.scriptFailed) {
181
+ await this.finalize(job, 'failed', job_store_1.JOB_ERROR_CODES.SCRIPT_FAILED, new Error(`Transaction ${job.txHash} is on chain with failing scripts: only its collateral was spent`));
182
+ continue;
183
+ }
184
+ if (found && found.height != null) {
185
+ job.foundSlot = found.slot;
186
+ job.foundHeight = found.height;
164
187
  job.seenRound = this.round;
165
188
  await cds_1.default.tx((t) => (0, job_store_1.recordConfirmationPoint)(t, job.jobId, { slot: job.foundSlot, height: job.foundHeight }));
166
189
  logger.info(`Job ${job.jobId}: tx ${job.txHash} found on-chain at height ${job.foundHeight} (polling)`);
190
+ continue;
167
191
  }
168
- catch (err) {
169
- // Failover wraps per-backend 404s into AllBackendsFailedError; the helper
170
- // treats "every backend said 404" as proof of absence.
171
- if ((0, errors_1.isNotFoundOnAllBackends)(err)) {
172
- // Not on-chain yet. Check the submission timeout.
173
- const age = Date.now() - Date.parse(job.submittedAt);
174
- if (age > this.deps.options.confirmationTimeoutMs) {
175
- await this.finalize(job, 'failed', job_store_1.JOB_ERROR_CODES.TX_DROPPED, new Error(`Transaction ${job.txHash} not seen on-chain within ${this.deps.options.confirmationTimeoutMs}ms of submission`));
176
- }
177
- }
178
- else {
179
- logger.debug(`Job ${job.jobId}: confirmation lookup failed (transient, next round retries):`, err);
180
- }
192
+ if (Date.now() - Date.parse(job.submittedAt) > this.deps.options.confirmationTimeoutMs && job.signedTxCbor) {
193
+ await this.settleOverdue(job, job.signedTxCbor);
181
194
  }
182
195
  }
183
196
  // Polling has no reorg signal: inclusions from an earlier round are re-checked first.
@@ -187,7 +200,74 @@ class ConfirmationTracker {
187
200
  this.polling = false;
188
201
  }
189
202
  }
203
+ // Unseen past the timeout: proof that it can never land fails the job, time alone proves nothing.
204
+ // While it stays open the same bytes go out again: a node may have dropped them from its mempool.
205
+ async settleOverdue(job, signedTxCbor) {
206
+ const now = Date.now();
207
+ if (now < (job.nextLandingCheckAt ?? 0))
208
+ return;
209
+ job.nextLandingCheckAt = now + LANDING_CHECK_INTERVAL_MS;
210
+ const sentAtMs = Date.parse(job.submittedAt);
211
+ const landing = await (0, tx_utils_1.runWithoutAmbientTx)(() => (0, landing_proof_1.judgeLanding)(signedTxCbor, job.txHash, this.deps, Number.isFinite(sentAtMs) ? sentAtMs : null));
212
+ if (landing.verdict === 'neverLands') {
213
+ await this.finalize(job, 'failed', job_store_1.JOB_ERROR_CODES.TX_DROPPED, new Error(landing.reason));
214
+ return;
215
+ }
216
+ if (landing.verdict === 'scriptFailed') {
217
+ await this.finalize(job, 'failed', job_store_1.JOB_ERROR_CODES.SCRIPT_FAILED, new Error(landing.reason));
218
+ return;
219
+ }
220
+ if (landing.verdict === 'unresolved') {
221
+ await this.finalize(job, 'unresolved', job_store_1.JOB_ERROR_CODES.OUTCOME_UNRESOLVED, new Error(landing.reason));
222
+ return;
223
+ }
224
+ // no expiry and still able to land: the worker spends one of its inputs, no resend
225
+ if (landing.verdict === 'stale') {
226
+ this.deps.onStale?.({ jobId: job.jobId, walletId: job.walletId }, landing.unspentInputs);
227
+ return;
228
+ }
229
+ // expired bytes are refused by every node, sending them again only costs requests
230
+ if (landing.verdict !== 'open' || now < (job.nextResendAt ?? 0) || (0, landing_proof_1.isExpired)(signedTxCbor, this.deps.client.network))
231
+ return;
232
+ job.resends = (job.resends ?? 0) + 1;
233
+ job.nextResendAt = now + Math.min(RESEND_BACKOFF_MIN_MS * 2 ** (job.resends - 1), RESEND_BACKOFF_MAX_MS);
234
+ try {
235
+ await this.deps.client.submitTransaction(signedTxCbor);
236
+ logger.info(`Job ${job.jobId}: tx ${job.txHash} still unseen, sent its signed bytes again`);
237
+ }
238
+ catch (err) {
239
+ if (!(err instanceof errors_1.TransactionAlreadySubmittedError)) {
240
+ logger.debug(`Job ${job.jobId}: resend of tx ${job.txHash} was refused (the chain still decides):`, err);
241
+ }
242
+ }
243
+ }
190
244
  // ---- Shared -----------------------------------------------------------------
245
+ // Where the transaction is: the crawled chain first, then a backend lookup. Without a transaction
246
+ // lookup an unspent output shows it on chain; its height is then taken as the tip, never deeper.
247
+ // Null when it is not on chain. Throws when a lookup gives no answer.
248
+ async locate(job) {
249
+ const presence = await (0, transaction_presence_1.findOnChain)(this.deps.indexer, this.deps.client, job.txHash);
250
+ if (presence)
251
+ return presence;
252
+ if (presence === null)
253
+ return null;
254
+ // only an own output seen unspent shows it on chain; spent inputs prove nothing about who spent them
255
+ if (job.signedTxCbor && this.lastKnownTipHeight != null && await (0, landing_proof_1.hasUnspentOutput)(job.signedTxCbor, job.txHash, this.deps.client)) {
256
+ return { slot: null, height: this.lastKnownTipHeight, scriptFailed: false };
257
+ }
258
+ return null;
259
+ }
260
+ // Without a transaction lookup, after an own output was seen. included: an own output is unspent.
261
+ // rolledBack: an input is unspent again. unknown: everything is spent, by whom shows nowhere.
262
+ async stillOnLedger(signedTxCbor, txHash) {
263
+ if (await (0, landing_proof_1.hasUnspentOutput)(signedTxCbor, txHash, this.deps.client))
264
+ return 'included';
265
+ for (const input of (0, landing_proof_1.landingFacts)(signedTxCbor).inputs) {
266
+ if (await this.deps.client.isUtxoUnspent(input.txHash, input.outputIndex))
267
+ return 'rolledBack';
268
+ }
269
+ return 'unknown';
270
+ }
191
271
  /** Confirms found jobs deep enough. With revalidate, an inclusion not seen this round is looked up again. */
192
272
  async confirmMature(revalidate = false) {
193
273
  const tip = this.lastKnownTipHeight;
@@ -205,10 +285,39 @@ class ConfirmationTracker {
205
285
  }
206
286
  /** True if the tx is still on-chain and deep enough. A moved tx takes its new height, a vanished one is watched again. */
207
287
  async stillIncluded(job, tip) {
288
+ if (!this.deps.client.supports('getTransaction')) {
289
+ if (!job.signedTxCbor)
290
+ return true;
291
+ let state;
292
+ try {
293
+ state = await this.stillOnLedger(job.signedTxCbor, job.txHash);
294
+ }
295
+ catch (err) {
296
+ logger.debug(`Job ${job.jobId}: inclusion re-check failed (transient, next round retries):`, err);
297
+ return false;
298
+ }
299
+ job.seenRound = this.round;
300
+ if (state === 'included')
301
+ return true;
302
+ if (state === 'rolledBack') {
303
+ logger.warn(`Job ${job.jobId}: an input of tx ${job.txHash} is unspent again (was at height ${job.foundHeight}). Rollback without a crawler signal, re-watching`);
304
+ this.lastKnownTipHeight = null;
305
+ await this.forgetInclusion(job);
306
+ return false;
307
+ }
308
+ // its outputs and inputs are all spent: no evidence left that this transaction spent them
309
+ logger.warn(`Job ${job.jobId}: every output and input of tx ${job.txHash} is spent before the confirmation depth; nothing shows it is still included, waiting for the chain to decide`);
310
+ await this.forgetInclusion(job, false);
311
+ return false;
312
+ }
208
313
  try {
209
314
  const tx = await this.deps.client.getTransaction(job.txHash);
210
315
  const height = tx.blockHeight ?? null;
211
316
  job.seenRound = this.round;
317
+ if (tx.spendsCollaterals === true) {
318
+ await this.finalize(job, 'failed', job_store_1.JOB_ERROR_CODES.SCRIPT_FAILED, new Error(`Transaction ${job.txHash} is on chain with failing scripts: only its collateral was spent`));
319
+ return false;
320
+ }
212
321
  if (height != null && height !== job.foundHeight) {
213
322
  logger.warn(`Job ${job.jobId}: tx ${job.txHash} moved from height ${job.foundHeight} to ${height}, re-anchoring`);
214
323
  job.foundHeight = height;
@@ -233,14 +342,19 @@ class ConfirmationTracker {
233
342
  let transitioned = false;
234
343
  try {
235
344
  await cds_1.default.tx(async (tx) => {
345
+ if (outcome === 'unresolved') {
346
+ transitioned = await (0, job_store_1.markUnresolved)(tx, job.jobId, err ?? new Error('unresolved'));
347
+ if (transitioned)
348
+ await tx.run(UPDATE.entity(cardano_1.TransactionSubmissions).set({ status: 'unresolved' }).where({ txHash: job.txHash, status: 'submitted' }));
349
+ return;
350
+ }
236
351
  transitioned = outcome === 'confirmed'
237
352
  ? await (0, job_store_1.markConfirmed)(tx, job.jobId)
238
353
  : await (0, job_store_1.markFailedAfterSend)(tx, job.jobId, errorCode ?? 'FAILED', err ?? new Error('unknown'));
239
354
  if (transitioned) {
240
355
  await (0, job_store_1.bumpWalletStats)(tx, job.walletId, outcome);
241
- if (outcome === 'confirmed') {
242
- await tx.run(UPDATE.entity(cardano_1.TransactionSubmissions).set({ status: 'confirmed' }).where({ txHash: job.txHash, status: 'submitted' }));
243
- }
356
+ // the job's submission record follows its outcome
357
+ await tx.run(UPDATE.entity(cardano_1.TransactionSubmissions).set({ status: outcome }).where({ txHash: job.txHash, status: 'submitted' }));
244
358
  }
245
359
  });
246
360
  }
@@ -254,7 +368,10 @@ class ConfirmationTracker {
254
368
  logger.debug(`Job ${job.jobId}: ${outcome} transition already applied elsewhere, no event from this tracker`);
255
369
  return;
256
370
  }
257
- logger.info(`Job ${job.jobId}: ${outcome}${outcome === 'failed' ? ` (${errorCode})` : ''}`);
371
+ if (outcome === 'unresolved')
372
+ logger.error(`Job ${job.jobId}: unresolved, an operator resolves it (${err instanceof Error ? err.message : String(err)})`);
373
+ else
374
+ logger.info(`Job ${job.jobId}: ${outcome}${outcome === 'failed' ? ` (${errorCode})` : ''}`);
258
375
  this.deps.onFinal?.({
259
376
  jobId: job.jobId,
260
377
  walletId: job.walletId,
@@ -0,0 +1,35 @@
1
+ import type { CardanoClient, Network } from '../cardano-client';
2
+ import type { CardanoIndexer } from '../cardano-indexer';
3
+ import { type WalletJobRow } from './job-store';
4
+ import type { WorkerSigner } from './signers';
5
+ /** Sends stored self-transfer bytes again; a refusal proves nothing, the next check reads the chain. */
6
+ export declare function resendInvalidation(deps: InvalidationDeps, job: WalletJobRow): Promise<void>;
7
+ export type OutputRef = {
8
+ txHash: string;
9
+ outputIndex: number;
10
+ };
11
+ /** confirmed: deep enough, the job's transaction can never land. included: on chain, not deep enough yet.
12
+ * retry: it can no longer land itself. unknown: its inputs are spent and nothing shows by whom.
13
+ * waiting: not seen yet and it may still land, so its bytes are sent again. */
14
+ export type InvalidationState = 'confirmed' | 'included' | 'retry' | 'unknown' | 'waiting';
15
+ export interface InvalidationDeps {
16
+ client: CardanoClient;
17
+ indexer: CardanoIndexer;
18
+ network: Network;
19
+ }
20
+ /** Blocks the self-transfer must be deep before it counts: the depth no rollback reaches. */
21
+ export declare function invalidationDepth(network: Network): number;
22
+ /** An unspent input of the job's transaction that the wallet holds, or null, and the UTxOs the wallet holds. */
23
+ export declare function pickInvalidationInput(deps: InvalidationDeps, address: string, unspentInputs: OutputRef[]): Promise<{
24
+ input: OutputRef | null;
25
+ held: OutputRef[];
26
+ }>;
27
+ /** The self-transfer cannot be funded: the wallet has too little besides inputs it must not spend. */
28
+ export declare class InvalidationUnfundedError extends Error {
29
+ }
30
+ export declare function sendInvalidation(deps: InvalidationDeps, job: WalletJobRow, signer: WorkerSigner, input: OutputRef, around?: {
31
+ held?: OutputRef[];
32
+ keep?: OutputRef[];
33
+ }): Promise<string | null>;
34
+ export declare function checkInvalidation(deps: InvalidationDeps, job: WalletJobRow, seen: Map<string, number>): Promise<InvalidationState>;
35
+ //# sourceMappingURL=invalidation.d.ts.map
@@ -0,0 +1,128 @@
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.InvalidationUnfundedError = void 0;
7
+ exports.resendInvalidation = resendInvalidation;
8
+ exports.invalidationDepth = invalidationDepth;
9
+ exports.pickInvalidationInput = pickInvalidationInput;
10
+ exports.sendInvalidation = sendInvalidation;
11
+ exports.checkInvalidation = checkInvalidation;
12
+ const cds_1 = __importDefault(require("@sap/cds"));
13
+ const const_1 = require("../../utils/const");
14
+ const errors_1 = require("../../utils/errors");
15
+ const tx_build_helper_1 = require("../../utils/tx-build-helper");
16
+ const tx_utils_1 = require("../../utils/tx-utils");
17
+ const external_signer_1 = require("../signing/external-signer");
18
+ const landing_proof_1 = require("../signing/landing-proof");
19
+ const transaction_presence_1 = require("../transaction-presence");
20
+ const job_store_1 = require("./job-store");
21
+ const logger = cds_1.default.log('CardanoWalletWorker');
22
+ // A job transaction without an expiry can land as long as one of its inputs is unspent. A
23
+ // self-transfer that spends such an input ends that: once it is deeper than the node can roll back,
24
+ // the job's transaction can never land.
25
+ /** Lovelace the self-transfer sends back to the wallet; the change carries the rest. */
26
+ const INVALIDATION_LOVELACE = '1000000';
27
+ /** Sends stored self-transfer bytes again; a refusal proves nothing, the next check reads the chain. */
28
+ async function resendInvalidation(deps, job) {
29
+ try {
30
+ await deps.client.submitTransaction(job.invalidationTxCbor);
31
+ }
32
+ catch (err) {
33
+ if (!(err instanceof errors_1.TransactionAlreadySubmittedError))
34
+ logger.debug(`Job ${job.ID}: self-transfer ${job.invalidationTxHash} resend refused:`, err);
35
+ }
36
+ }
37
+ /** Blocks the self-transfer must be deep before it counts: the depth no rollback reaches. */
38
+ function invalidationDepth(network) {
39
+ return const_1.EPOCH_CONFIG_BY_NETWORK[network].securityParam;
40
+ }
41
+ const keyOf = (r) => `${r.txHash}#${r.outputIndex}`;
42
+ /** An unspent input of the job's transaction that the wallet holds, or null, and the UTxOs the wallet holds. */
43
+ async function pickInvalidationInput(deps, address, unspentInputs) {
44
+ const held = (await (0, tx_utils_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => deps.indexer.resolveAddressUtxos(tx, address))))
45
+ .map((u) => ({ txHash: u.txHash, outputIndex: u.outputIndex }));
46
+ const keys = new Set(held.map(keyOf));
47
+ return { input: unspentInputs.find((r) => keys.has(keyOf(r))) ?? null, held };
48
+ }
49
+ /** The self-transfer cannot be funded: the wallet has too little besides inputs it must not spend. */
50
+ class InvalidationUnfundedError extends Error {
51
+ }
52
+ exports.InvalidationUnfundedError = InvalidationUnfundedError;
53
+ // Builds, signs, stores and sends the self-transfer. It spends the input alone where that pays for it,
54
+ // else with other wallet UTxOs, never with an input another stale job waits on (`keep`). The bytes are
55
+ // stored before the send, as for a job. Returns its hash, or null when the job changed meanwhile.
56
+ async function sendInvalidation(deps, job, signer, input, around = {}) {
57
+ const address = signer.getAddress();
58
+ const keep = (around.keep ?? []).filter((r) => keyOf(r) !== keyOf(input));
59
+ const alone = [...(around.held ?? []).filter((r) => keyOf(r) !== keyOf(input)), ...keep];
60
+ const buildWith = (protectInputs) => (0, tx_utils_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => deps.indexer.indexSimpleBuildResult(tx, {
61
+ network: deps.network,
62
+ senderAddress: address,
63
+ changeAddress: address,
64
+ recipientAddress: address,
65
+ lovelaceAmount: INVALIDATION_LOVELACE,
66
+ forceInputs: [input],
67
+ ...(protectInputs.length ? { protectInputs } : {}),
68
+ })));
69
+ let build;
70
+ try {
71
+ build = await buildWith(alone);
72
+ }
73
+ catch (err) {
74
+ if (!(err instanceof errors_1.InsufficientFundsError))
75
+ throw err;
76
+ try {
77
+ build = await buildWith(keep);
78
+ }
79
+ catch (again) {
80
+ if (again instanceof errors_1.InsufficientFundsError)
81
+ throw new InvalidationUnfundedError(again.message);
82
+ throw again;
83
+ }
84
+ }
85
+ const signedTxCbor = signer.signTransaction(build.unsignedTxCbor, build.txBodyHash);
86
+ (0, external_signer_1.getExternalSignerModule)().verifyOrThrow(signedTxCbor, build.txBodyHash, { requiredSigners: [signer.getPublicKeyHash().toLowerCase()] });
87
+ const txHash = (0, tx_build_helper_1.getTxHashFromCbor)(signedTxCbor);
88
+ const stored = await (0, tx_utils_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.recordInvalidation)(tx, job.ID, { txHash, signedTxCbor }, job.invalidationTxHash)));
89
+ if (!stored)
90
+ return null;
91
+ try {
92
+ await deps.client.submitTransaction(signedTxCbor);
93
+ }
94
+ catch (err) {
95
+ // a refusal proves nothing here: the next check reads the chain
96
+ if (!(err instanceof errors_1.TransactionAlreadySubmittedError))
97
+ logger.warn(`Job ${job.ID}: invalidating tx ${txHash} was refused on send:`, err);
98
+ }
99
+ logger.warn(`Job ${job.ID}: tx ${job.txHash} has no expiry and has not landed; sent self-transfer ${txHash} spending ${input.txHash}#${input.outputIndex}`);
100
+ return txHash;
101
+ }
102
+ // Where the self-transfer stands. seen holds the tip height at which an own output was first seen,
103
+ // for backends that cannot look transactions up.
104
+ async function checkInvalidation(deps, job, seen) {
105
+ const txHash = job.invalidationTxHash;
106
+ const signedTxCbor = job.invalidationTxCbor;
107
+ const tipHeight = (await deps.client.getLatestBlock()).height ?? null;
108
+ const presence = await (0, transaction_presence_1.findOnChain)(deps.indexer, deps.client, txHash);
109
+ let height = presence?.height ?? null;
110
+ if (presence === undefined && tipHeight != null && await (0, landing_proof_1.hasUnspentOutput)(signedTxCbor, txHash, deps.client)) {
111
+ // a tip below the height seen means a rollback: count again from here
112
+ const first = seen.get(job.ID);
113
+ height = first != null && first <= tipHeight ? first : tipHeight;
114
+ seen.set(job.ID, height);
115
+ }
116
+ if (height != null && tipHeight != null) {
117
+ return tipHeight - height + 1 >= invalidationDepth(deps.network) ? 'confirmed' : 'included';
118
+ }
119
+ seen.delete(job.ID);
120
+ const sentAtMs = job.invalidationSentAt ? Date.parse(job.invalidationSentAt) : null;
121
+ const landing = await (0, landing_proof_1.judgeLanding)(signedTxCbor, txHash, deps, Number.isFinite(sentAtMs) ? sentAtMs : null);
122
+ if (landing.verdict === 'neverLands')
123
+ return 'retry';
124
+ if (landing.verdict === 'unresolved')
125
+ return 'unknown';
126
+ return 'waiting';
127
+ }
128
+ //# sourceMappingURL=invalidation.js.map
@@ -8,8 +8,16 @@ export declare const JOB_ERROR_CODES: {
8
8
  readonly CANCELLED: "CANCELLED";
9
9
  /** Reconciliation proved the tx is not on-chain and the node rejects it for good. */
10
10
  readonly SUBMIT_REJECTED: "SUBMIT_REJECTED";
11
+ /** The tx is on chain with failing scripts: only its collateral was spent, the payment did not happen. */
12
+ readonly SCRIPT_FAILED: "SCRIPT_FAILED";
13
+ /** The tx can no longer land and nothing shows whether it did; an operator resolves the job. */
14
+ readonly OUTCOME_UNRESOLVED: "OUTCOME_UNRESOLVED";
15
+ /** An operator resolved an unresolved job as failed after reading the chain. */
16
+ readonly RESOLVED_FAILED: "RESOLVED_FAILED";
17
+ /** A confirmed self-transfer spent an input of the job's transaction, which had no expiry; it can never land. */
18
+ readonly INVALIDATED: "INVALIDATED";
11
19
  };
12
- export type WalletJobStatusValue = 'pending' | 'building' | 'submitting' | 'submitted' | 'confirmed' | 'failed' | 'cancelled';
20
+ export type WalletJobStatusValue = 'pending' | 'building' | 'submitting' | 'submitted' | 'confirmed' | 'failed' | 'cancelled' | 'unresolved';
13
21
  export type WalletJobKindValue = 'simpleAda' | 'metadata' | 'multiAsset' | 'mint' | 'plutusSpend' | 'payout' | 'submitSigned';
14
22
  export type WorkerSignerTypeValue = 'hsm' | 'software';
15
23
  export declare const WALLET_JOB_KINDS: readonly WalletJobKindValue[];
@@ -38,6 +46,11 @@ export interface WalletJobRow {
38
46
  createdAt: string | null;
39
47
  createdBy: string | null;
40
48
  finishedAt: string | null;
49
+ resolution: string | null;
50
+ invalidationTxHash: string | null;
51
+ invalidationTxCbor: string | null;
52
+ invalidationSentAt: string | null;
53
+ spendsNoWalletUtxo: boolean;
41
54
  }
42
55
  /** Normalized view of a worker-wallet row. */
43
56
  export interface WorkerWalletRow {
@@ -85,12 +98,17 @@ export interface DueJobRef {
85
98
  }
86
99
  /** The next due pending job of a wallet by priority and age, or null. One row per call, whatever the queue holds. */
87
100
  export declare function findNextDueJob(db: CapTransaction, walletId: string, now?: Date): Promise<DueJobRef | null>;
101
+ /** Number of jobs in a status. */
102
+ export declare function countJobs(db: CapTransaction, status: WalletJobStatusValue): Promise<number>;
88
103
  /** Number of pending jobs, due or not. */
89
104
  export declare function countPendingJobs(db: CapTransaction): Promise<number>;
90
105
  /** All jobs awaiting confirmation (used by the tracker on start/recovery). */
91
106
  export declare function findSubmittedJobs(db: CapTransaction): Promise<WalletJobRow[]>;
92
- /** Whether the wallet has a job currently in flight (building, submitting or submitted). */
107
+ /** Jobs of a wallet whose transaction an invalidating self-transfer is spending around. */
108
+ export declare function findInvalidatingJobs(db: CapTransaction, walletId: string): Promise<WalletJobRow[]>;
93
109
  export declare function walletHasActiveJob(db: CapTransaction, walletId: string): Promise<boolean>;
110
+ /** Marks a job whose transaction spends no UTxO the wallet holds, so it no longer holds the wallet queue. */
111
+ export declare function markSpendsNoWalletUtxo(db: CapTransaction, jobId: string): Promise<boolean>;
94
112
  /** Oldest submitting row of a wallet without a live lease. Its submit outcome is unknown and needs a chain check. */
95
113
  export declare function findOrphanedSubmittingJob(db: CapTransaction, walletId: string, now?: Date): Promise<WalletJobRow | null>;
96
114
  /** Frees the idempotency key by pointing dedupKey at the job ID. */
@@ -120,6 +138,14 @@ export declare function markConfirmed(db: CapTransaction, jobId: string): Promis
120
138
  /** Fails a job that never sent a transaction and frees its key for the caller's retry. */
121
139
  export declare function markFailed(db: CapTransaction, jobId: string, code: string, err: unknown): Promise<boolean>;
122
140
  export declare function markFailedAfterSend(db: CapTransaction, jobId: string, code: string, err: unknown): Promise<boolean>;
141
+ export declare function markUnresolved(db: CapTransaction, jobId: string, err: unknown): Promise<boolean>;
142
+ export declare function recordInvalidation(db: CapTransaction, jobId: string, invalidation: {
143
+ txHash: string;
144
+ signedTxCbor: string;
145
+ }, previous?: string | null): Promise<boolean>;
146
+ export declare function reopenFailedJob(db: CapTransaction, jobId: string, resolution: string): Promise<boolean>;
147
+ /** unresolved → confirmed or failed, as an operator read it on the chain. The key stays either way. */
148
+ export declare function resolveUnresolvedJob(db: CapTransaction, jobId: string, outcome: 'confirmed' | 'failed', resolution: string): Promise<boolean>;
123
149
  /** pending → cancelled. Only pending jobs are cancellable (the tx may otherwise reach the chain). */
124
150
  export declare function markCancelled(db: CapTransaction, jobId: string): Promise<boolean>;
125
151
  export interface RecoveryResult {