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

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 +23 -12
  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 +36 -44
  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
@@ -8,9 +8,12 @@ exports.dedupKeyFor = dedupKeyFor;
8
8
  exports.insertJob = insertJob;
9
9
  exports.getJobById = getJobById;
10
10
  exports.findNextDueJob = findNextDueJob;
11
+ exports.countJobs = countJobs;
11
12
  exports.countPendingJobs = countPendingJobs;
12
13
  exports.findSubmittedJobs = findSubmittedJobs;
14
+ exports.findInvalidatingJobs = findInvalidatingJobs;
13
15
  exports.walletHasActiveJob = walletHasActiveJob;
16
+ exports.markSpendsNoWalletUtxo = markSpendsNoWalletUtxo;
14
17
  exports.findOrphanedSubmittingJob = findOrphanedSubmittingJob;
15
18
  exports.releaseDedupClaim = releaseDedupClaim;
16
19
  exports.markBuilding = markBuilding;
@@ -22,6 +25,10 @@ exports.clearConfirmationPoint = clearConfirmationPoint;
22
25
  exports.markConfirmed = markConfirmed;
23
26
  exports.markFailed = markFailed;
24
27
  exports.markFailedAfterSend = markFailedAfterSend;
28
+ exports.markUnresolved = markUnresolved;
29
+ exports.recordInvalidation = recordInvalidation;
30
+ exports.reopenFailedJob = reopenFailedJob;
31
+ exports.resolveUnresolvedJob = resolveUnresolvedJob;
25
32
  exports.markCancelled = markCancelled;
26
33
  exports.failOrphanedBuildingJobs = failOrphanedBuildingJobs;
27
34
  exports.recoverInterruptedJobs = recoverInterruptedJobs;
@@ -38,6 +45,8 @@ const cardano_1 = require("#cds-models/odatano/cardano");
38
45
  const deep_json_1 = require("../../utils/deep-json");
39
46
  const errors_1 = require("../../utils/errors");
40
47
  const error_codes_1 = require("../../utils/error-codes");
48
+ const row_values_1 = require("../../utils/row-values");
49
+ const lease_1 = require("../../utils/lease");
41
50
  const { SELECT, INSERT, UPDATE } = cds_1.default.ql;
42
51
  const logger = cds_1.default.log('CardanoWalletWorker');
43
52
  // Job flow: pending, building, submitting, submitted, confirmed. Each state can also end in failed.
@@ -52,24 +61,16 @@ exports.JOB_ERROR_CODES = {
52
61
  CANCELLED: 'CANCELLED',
53
62
  /** Reconciliation proved the tx is not on-chain and the node rejects it for good. */
54
63
  SUBMIT_REJECTED: 'SUBMIT_REJECTED',
64
+ /** The tx is on chain with failing scripts: only its collateral was spent, the payment did not happen. */
65
+ SCRIPT_FAILED: 'SCRIPT_FAILED',
66
+ /** The tx can no longer land and nothing shows whether it did; an operator resolves the job. */
67
+ OUTCOME_UNRESOLVED: 'OUTCOME_UNRESOLVED',
68
+ /** An operator resolved an unresolved job as failed after reading the chain. */
69
+ RESOLVED_FAILED: 'RESOLVED_FAILED',
70
+ /** A confirmed self-transfer spent an input of the job's transaction, which had no expiry; it can never land. */
71
+ INVALIDATED: 'INVALIDATED',
55
72
  };
56
73
  exports.WALLET_JOB_KINDS = ['simpleAda', 'metadata', 'multiAsset', 'mint', 'plutusSpend', 'payout', 'submitSigned'];
57
- function optionalNum(v) {
58
- if (v === null || v === undefined || v === '')
59
- return null;
60
- const n = Number(v);
61
- return Number.isNaN(n) ? null : n;
62
- }
63
- function requiredNum(v, fallback = 0) {
64
- return optionalNum(v) ?? fallback;
65
- }
66
- function timestamp(v) {
67
- if (v === null || v === undefined || v === '')
68
- return null;
69
- if (v instanceof Date)
70
- return v.toISOString();
71
- return String(v);
72
- }
73
74
  function toJobRow(row) {
74
75
  return {
75
76
  ID: String(row.ID),
@@ -78,23 +79,28 @@ function toJobRow(row) {
78
79
  status: row.status,
79
80
  idempotencyKey: row.idempotencyKey ?? null,
80
81
  request: row.request ?? null,
81
- priority: requiredNum(row.priority, 100),
82
- notBefore: timestamp(row.notBefore),
83
- attempt: requiredNum(row.attempt),
84
- maxAttempts: requiredNum(row.maxAttempts, 3),
82
+ priority: (0, row_values_1.requiredNum)(row.priority, 100),
83
+ notBefore: (0, row_values_1.timestamp)(row.notBefore),
84
+ attempt: (0, row_values_1.requiredNum)(row.attempt),
85
+ maxAttempts: (0, row_values_1.requiredNum)(row.maxAttempts, 3),
85
86
  txHash: row.txHash ?? null,
86
87
  unsignedTxCbor: row.unsignedTxCbor ?? null,
87
88
  signedTxCbor: row.signedTxCbor ?? null,
88
- fee: optionalNum(row.fee),
89
- submittedAt: timestamp(row.submittedAt),
90
- confirmedAt: timestamp(row.confirmedAt),
91
- confirmedSlot: optionalNum(row.confirmedSlot),
92
- confirmedHeight: optionalNum(row.confirmedHeight),
89
+ fee: (0, row_values_1.optionalNum)(row.fee),
90
+ submittedAt: (0, row_values_1.timestamp)(row.submittedAt),
91
+ confirmedAt: (0, row_values_1.timestamp)(row.confirmedAt),
92
+ confirmedSlot: (0, row_values_1.optionalNum)(row.confirmedSlot),
93
+ confirmedHeight: (0, row_values_1.optionalNum)(row.confirmedHeight),
93
94
  errorCode: row.errorCode ?? null,
94
95
  errorMessage: row.errorMessage ?? null,
95
- createdAt: timestamp(row.createdAt),
96
+ createdAt: (0, row_values_1.timestamp)(row.createdAt),
96
97
  createdBy: row.createdBy ?? null,
97
- finishedAt: timestamp(row.finishedAt),
98
+ finishedAt: (0, row_values_1.timestamp)(row.finishedAt),
99
+ resolution: row.resolution ?? null,
100
+ invalidationTxHash: row.invalidationTxHash ?? null,
101
+ invalidationTxCbor: row.invalidationTxCbor ?? null,
102
+ invalidationSentAt: (0, row_values_1.timestamp)(row.invalidationSentAt),
103
+ spendsNoWalletUtxo: row.spendsNoWalletUtxo === true,
98
104
  };
99
105
  }
100
106
  function toWalletRow(row) {
@@ -106,10 +112,10 @@ function toWalletRow(row) {
106
112
  requiresRole: row.requiresRole ?? null,
107
113
  enabled: row.enabled !== false,
108
114
  leaseOwner: row.leaseOwner ?? null,
109
- leaseUntil: timestamp(row.leaseUntil),
110
- lastJobAt: timestamp(row.lastJobAt),
111
- jobsConfirmed: requiredNum(row.jobsConfirmed),
112
- jobsFailed: requiredNum(row.jobsFailed),
115
+ leaseUntil: (0, row_values_1.timestamp)(row.leaseUntil),
116
+ lastJobAt: (0, row_values_1.timestamp)(row.lastJobAt),
117
+ jobsConfirmed: (0, row_values_1.requiredNum)(row.jobsConfirmed),
118
+ jobsFailed: (0, row_values_1.requiredNum)(row.jobsFailed),
113
119
  };
114
120
  }
115
121
  // Re-exported from the shared tx-utils so existing imports keep working.
@@ -153,15 +159,17 @@ function canonicalRequest(json) {
153
159
  return json;
154
160
  }
155
161
  }
156
- /** The holder of the key answers a retry of the same request. Another request under the key is a 409. */
162
+ /** The holder of the key answers a retry of the same request. Another request, wallet or kind under the key is a 409. */
157
163
  function answerFromHolder(holder, args) {
158
- if (canonicalRequest(holder.request) !== canonicalRequest(args.request)) {
164
+ const same = holder.walletId === args.walletId && holder.kind === args.kind
165
+ && canonicalRequest(holder.request) === canonicalRequest(args.request);
166
+ if (!same) {
159
167
  throw new errors_1.BackendError(`idempotencyKey "${args.idempotencyKey}" belongs to job ${holder.ID} with a different request`, 409, error_codes_1.ERROR_CODES.IDEMPOTENCY_KEY_CONFLICT, undefined, undefined, 'idempotencyKey');
160
168
  }
161
169
  return { jobId: holder.ID, status: holder.status, deduplicated: true };
162
170
  }
163
- async function readDedupHolder(db, walletId, kind, dedupKey) {
164
- const row = await db.run(SELECT.one.from(cardano_1.CardanoWalletJobs).where({ walletId, kind, dedupKey }));
171
+ async function readDedupHolder(db, dedupKey) {
172
+ const row = await db.run(SELECT.one.from(cardano_1.CardanoWalletJobs).where({ dedupKey }));
165
173
  return row ? toJobRow(row) : null;
166
174
  }
167
175
  /** Inserts a job, or returns the job that holds the dedup key. The UNIQUE constraint settles races. */
@@ -171,7 +179,7 @@ async function insertJob(db, args) {
171
179
  const claim = idempotencyKey ? dedupKeyFor(args.createdBy, idempotencyKey) : null;
172
180
  if (claim) {
173
181
  // A failed holder kept its key because its transaction may have been sent.
174
- const holder = await readDedupHolder(db, args.walletId, args.kind, claim);
182
+ const holder = await readDedupHolder(db, claim);
175
183
  if (holder) {
176
184
  if (holder.status !== 'cancelled')
177
185
  return answerFromHolder(holder, args);
@@ -204,7 +212,7 @@ async function insertJob(db, args) {
204
212
  // Lost the race to another transaction with the same key. Return its job.
205
213
  if (!claim || !isUniqueViolation(err))
206
214
  throw err;
207
- const winner = await readDedupHolder(db, args.walletId, args.kind, claim);
215
+ const winner = await readDedupHolder(db, claim);
208
216
  if (!winner)
209
217
  throw err; // constraint fired for another reason, do not mask it
210
218
  logger.info(`Concurrent submission for idempotency key "${idempotencyKey}", returning job ${winner.ID}`);
@@ -225,22 +233,39 @@ async function findNextDueJob(db, walletId, now = new Date()) {
225
233
  .orderBy('priority', 'createdAt'));
226
234
  if (!row)
227
235
  return null;
228
- return { ID: String(row.ID), walletId: String(row.walletId), priority: requiredNum(row.priority, 100), createdAt: timestamp(row.createdAt) };
236
+ return { ID: String(row.ID), walletId: String(row.walletId), priority: (0, row_values_1.requiredNum)(row.priority, 100), createdAt: (0, row_values_1.timestamp)(row.createdAt) };
229
237
  }
230
- /** Number of pending jobs, due or not. */
231
- async function countPendingJobs(db) {
232
- const row = await db.run(SELECT.one.from(cardano_1.CardanoWalletJobs).columns('count(*) as n').where({ status: 'pending' }));
238
+ /** Number of jobs in a status. */
239
+ async function countJobs(db, status) {
240
+ const row = await db.run(SELECT.one.from(cardano_1.CardanoWalletJobs).columns('count(*) as n').where({ status }));
233
241
  return Number(row?.n ?? 0);
234
242
  }
243
+ /** Number of pending jobs, due or not. */
244
+ function countPendingJobs(db) {
245
+ return countJobs(db, 'pending');
246
+ }
235
247
  /** All jobs awaiting confirmation (used by the tracker on start/recovery). */
236
248
  async function findSubmittedJobs(db) {
237
249
  const rows = await db.run(SELECT.from(cardano_1.CardanoWalletJobs).where({ status: 'submitted' }));
238
250
  return (rows ?? []).map(toJobRow);
239
251
  }
240
- /** Whether the wallet has a job currently in flight (building, submitting or submitted). */
252
+ /** Jobs of a wallet whose transaction an invalidating self-transfer is spending around. */
253
+ async function findInvalidatingJobs(db, walletId) {
254
+ const rows = await db.run(SELECT.from(cardano_1.CardanoWalletJobs)
255
+ .where({ walletId, status: { in: ['submitting', 'submitted'] }, invalidationTxHash: { '!=': null } }));
256
+ return (rows ?? []).map(toJobRow);
257
+ }
258
+ // Whether the wallet has a job in flight (building, submitting or submitted). A job whose transaction
259
+ // spends no UTxO the wallet holds cannot take the wallet funds, so it does not hold the queue.
241
260
  async function walletHasActiveJob(db, walletId) {
242
- const row = await db.run(SELECT.one.from(cardano_1.CardanoWalletJobs).where({ walletId, status: { in: ['building', 'submitting', 'submitted'] } }));
243
- return !!row;
261
+ // a wallet has at most a few jobs in flight, so they are filtered here
262
+ const rows = await db.run(SELECT.from(cardano_1.CardanoWalletJobs).columns('ID', 'spendsNoWalletUtxo').where({ walletId, status: { in: ['building', 'submitting', 'submitted'] } }));
263
+ return (rows ?? []).some((r) => r.spendsNoWalletUtxo !== true);
264
+ }
265
+ /** Marks a job whose transaction spends no UTxO the wallet holds, so it no longer holds the wallet queue. */
266
+ async function markSpendsNoWalletUtxo(db, jobId) {
267
+ const affected = await db.run(UPDATE.entity(cardano_1.CardanoWalletJobs).set({ spendsNoWalletUtxo: true }).where({ ID: jobId, status: { in: ['submitting', 'submitted'] } }));
268
+ return Number(affected) > 0;
244
269
  }
245
270
  /** Oldest submitting row of a wallet without a live lease. Its submit outcome is unknown and needs a chain check. */
246
271
  async function findOrphanedSubmittingJob(db, walletId, now = new Date()) {
@@ -339,6 +364,40 @@ async function markFailedAfterSend(db, jobId, code, err) {
339
364
  finishedAt: new Date().toISOString(),
340
365
  });
341
366
  }
367
+ // Past the last moment its transaction could land, with nothing showing whether it did. The key
368
+ // stays, polling stops and the wallet queue goes on; an operator resolves the job.
369
+ async function markUnresolved(db, jobId, err) {
370
+ const message = err instanceof Error ? err.message : String(err);
371
+ return guardedTransition(db, jobId, ['submitting', 'submitted'], {
372
+ status: 'unresolved',
373
+ errorCode: exports.JOB_ERROR_CODES.OUTCOME_UNRESOLVED,
374
+ errorMessage: message.slice(0, 500),
375
+ finishedAt: new Date().toISOString(),
376
+ });
377
+ }
378
+ // Stores the signed self-transfer before it is sent, so its bytes survive a crash. A later one
379
+ // replaces an earlier one that can no longer land. `previous` is the hash the caller read: when
380
+ // another instance stored one meanwhile, nothing is written.
381
+ async function recordInvalidation(db, jobId, invalidation, previous = null) {
382
+ const affected = await db.run(UPDATE.entity(cardano_1.CardanoWalletJobs)
383
+ .set({ invalidationTxHash: invalidation.txHash, invalidationTxCbor: invalidation.signedTxCbor, invalidationSentAt: new Date().toISOString() })
384
+ .where({ ID: jobId, status: { in: ['submitting', 'submitted'] }, invalidationTxHash: previous }));
385
+ return Number(affected) > 0;
386
+ }
387
+ // A job an earlier version failed on time or a refusal alone, whose transaction is on chain: back to
388
+ // submitted, so the tracker confirms it by depth. The key it kept stays with it.
389
+ async function reopenFailedJob(db, jobId, resolution) {
390
+ return guardedTransition(db, jobId, ['failed'], {
391
+ status: 'submitted', errorCode: null, errorMessage: null, finishedAt: null, resolution: resolution.slice(0, 500),
392
+ });
393
+ }
394
+ /** unresolved → confirmed or failed, as an operator read it on the chain. The key stays either way. */
395
+ async function resolveUnresolvedJob(db, jobId, outcome, resolution) {
396
+ const now = new Date().toISOString();
397
+ return guardedTransition(db, jobId, ['unresolved'], outcome === 'confirmed'
398
+ ? { status: 'confirmed', confirmedAt: now, finishedAt: now, errorCode: null, errorMessage: null, resolution: resolution.slice(0, 500) }
399
+ : { status: 'failed', finishedAt: now, errorCode: exports.JOB_ERROR_CODES.RESOLVED_FAILED, resolution: resolution.slice(0, 500) });
400
+ }
342
401
  /** pending → cancelled. Only pending jobs are cancellable (the tx may otherwise reach the chain). */
343
402
  async function markCancelled(db, jobId) {
344
403
  return guardedTransition(db, jobId, ['pending'], {
@@ -437,50 +496,18 @@ async function listWallets(db) {
437
496
  const rows = await db.run(SELECT.from(cardano_1.CardanoWorkerWallets));
438
497
  return (rows ?? []).map(toWalletRow);
439
498
  }
440
- function leaseDeadlineReached(wallet, owner, expectedMs) {
441
- if (!wallet || wallet.leaseOwner !== owner || !wallet.leaseUntil)
442
- return false;
443
- const actualMs = Date.parse(wallet.leaseUntil);
444
- // One second tolerance for adapter timestamp normalization.
445
- return Number.isFinite(actualMs) && actualMs >= expectedMs - 1_000;
446
- }
499
+ const walletLease = (walletId) => ({ entity: cardano_1.CardanoWorkerWallets, key: { walletId } });
447
500
  /** Takes a free wallet lease by compare-and-swap with read-back. One instance runs a wallet's jobs at a time. */
448
501
  async function tryAcquireWalletLease(db, walletId, owner, now = new Date(), ttlMs = exports.WORKER_LEASE_TTL_MS) {
449
- const raw = await db.run(SELECT.one.from(cardano_1.CardanoWorkerWallets).where({ walletId }));
450
- if (!raw)
451
- return false;
452
- const current = toWalletRow(raw);
453
- if (!current.enabled)
454
- return false;
455
- const deadline = current.leaseUntil ? Date.parse(current.leaseUntil) : Number.NEGATIVE_INFINITY;
456
- if (current.leaseOwner && current.leaseOwner !== owner && deadline > now.getTime())
457
- return false;
458
- const leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
459
- // CAS on the observed owner only: timestamp equality is adapter-fragile and could
460
- // make an expired lease permanently untakeable.
461
- await db.run(UPDATE.entity(cardano_1.CardanoWorkerWallets).set({ leaseOwner: owner, leaseUntil }).where({
462
- walletId,
463
- leaseOwner: raw.leaseOwner ?? null,
464
- }));
465
- const verified = await readWallet(db, walletId);
466
- return leaseDeadlineReached(verified, owner, now.getTime() + ttlMs);
502
+ return (0, lease_1.tryAcquireLease)(db, walletLease(walletId), owner, { now, ttlMs }, (row) => toWalletRow(row).enabled);
467
503
  }
468
504
  /** Renew/fence the caller's lease. Call before every job-advancing write. */
469
505
  async function renewWalletLease(db, walletId, owner, now = new Date(), ttlMs = exports.WORKER_LEASE_TTL_MS) {
470
- const leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
471
- await db.run(UPDATE.entity(cardano_1.CardanoWorkerWallets).set({ leaseUntil }).where({
472
- walletId,
473
- leaseOwner: owner,
474
- }));
475
- const verified = await readWallet(db, walletId);
476
- return leaseDeadlineReached(verified, owner, now.getTime() + ttlMs);
506
+ return (0, lease_1.renewLease)(db, walletLease(walletId), owner, { now, ttlMs });
477
507
  }
478
508
  /** Release only the caller's lease; a stale process can never clear a successor. */
479
509
  async function releaseWalletLease(db, walletId, owner) {
480
- await db.run(UPDATE.entity(cardano_1.CardanoWorkerWallets).set({ leaseOwner: null, leaseUntil: null }).where({
481
- walletId,
482
- leaseOwner: owner,
483
- }));
510
+ await (0, lease_1.releaseLease)(db, walletLease(walletId), owner);
484
511
  }
485
512
  /** Bump rolling per-wallet stats on a terminal job state. */
486
513
  async function bumpWalletStats(db, walletId, outcome) {
@@ -1,4 +1,4 @@
1
- import type { CardanoClient } from '../cardano-client';
1
+ import type { CardanoClient, Network } from '../cardano-client';
2
2
  import type { CardanoIndexer } from '../cardano-indexer';
3
3
  import { type WorkerSigner, type WorkerWalletConfig } from './signers';
4
4
  export interface WalletWorkerConfig {
@@ -14,7 +14,7 @@ export interface WalletWorkerConfig {
14
14
  export interface WalletWorkerDeps {
15
15
  client: CardanoClient;
16
16
  indexer: CardanoIndexer;
17
- network: string;
17
+ network: Network;
18
18
  config: WalletWorkerConfig;
19
19
  instanceId: string;
20
20
  }
@@ -29,9 +29,20 @@ export declare class CardanoWalletWorker {
29
29
  private readonly executionPromises;
30
30
  private readonly tracker;
31
31
  private dispatchTimer;
32
+ /** Earliest next reconcile per job with an open submit, and how often it was tried. */
33
+ private readonly reconcileBackoff;
34
+ /** Jobs whose transaction has no expiry, has not landed and still can: the unspent inputs, by job. */
35
+ private readonly staleJobs;
36
+ /** Earliest next look at a job's invalidation, and the tip height an own output was first seen at. */
37
+ private readonly invalidationNotBefore;
38
+ private readonly invalidationSeen;
39
+ /** Sends of a stored self-transfer not seen on chain yet, and the earliest next one. */
40
+ private readonly invalidationResend;
32
41
  private running;
33
42
  private tickInFlight;
34
43
  constructor(deps: WalletWorkerDeps);
44
+ /** A terminal outcome after its commit, so subscribers reading the row see the announced state. */
45
+ private announce;
35
46
  isRunning(): boolean;
36
47
  /** Wallets this instance can sign for (signer init succeeded). */
37
48
  getWalletIds(): string[];
@@ -48,6 +59,9 @@ export declare class CardanoWalletWorker {
48
59
  /** One dispatch round; serialized (overlapping timers collapse into one run). */
49
60
  private tickSafe;
50
61
  private tick;
62
+ /** Watch every submitted job of the wallets this instance signs for until it confirms or fails. */
63
+ private adoptSubmittedJobs;
64
+ private trackSubmitted;
51
65
  /** Adopt `submitting` rows left by a dead executor and resolve them against the chain, under the wallet lease. */
52
66
  private reconcileOrphanedSubmissions;
53
67
  /** Run one wallet's work in the background, tracked for concurrency + shutdown. */
@@ -62,6 +76,11 @@ export declare class CardanoWalletWorker {
62
76
  private adoptSubmitted;
63
77
  private reconcileSubmitting;
64
78
  private failReconciled;
79
+ /** One invalidation per wallet at a time: the job already being invalidated first, else a stale one. */
80
+ private invalidateStaleJobs;
81
+ private handleInvalidation;
82
+ private resendWaitingInvalidation;
83
+ private finishInvalidated;
65
84
  /** The job's build, ready to run in a transaction. A malformed request throws 400 INVALID_INPUT here. */
66
85
  private buildOf;
67
86
  /** Dispatch the job kind to the matching indexer build method. */