@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
@@ -7,9 +7,13 @@ exports.runWithoutAmbientTx = exports.WALLET_JOB_KINDS = exports.JOB_ERROR_CODES
7
7
  exports.dedupKeyFor = dedupKeyFor;
8
8
  exports.insertJob = insertJob;
9
9
  exports.getJobById = getJobById;
10
- exports.findDueJobs = findDueJobs;
10
+ exports.findNextDueJob = findNextDueJob;
11
+ exports.countJobs = countJobs;
12
+ exports.countPendingJobs = countPendingJobs;
11
13
  exports.findSubmittedJobs = findSubmittedJobs;
14
+ exports.findInvalidatingJobs = findInvalidatingJobs;
12
15
  exports.walletHasActiveJob = walletHasActiveJob;
16
+ exports.markSpendsNoWalletUtxo = markSpendsNoWalletUtxo;
13
17
  exports.findOrphanedSubmittingJob = findOrphanedSubmittingJob;
14
18
  exports.releaseDedupClaim = releaseDedupClaim;
15
19
  exports.markBuilding = markBuilding;
@@ -20,6 +24,11 @@ exports.recordConfirmationPoint = recordConfirmationPoint;
20
24
  exports.clearConfirmationPoint = clearConfirmationPoint;
21
25
  exports.markConfirmed = markConfirmed;
22
26
  exports.markFailed = markFailed;
27
+ exports.markFailedAfterSend = markFailedAfterSend;
28
+ exports.markUnresolved = markUnresolved;
29
+ exports.recordInvalidation = recordInvalidation;
30
+ exports.reopenFailedJob = reopenFailedJob;
31
+ exports.resolveUnresolvedJob = resolveUnresolvedJob;
23
32
  exports.markCancelled = markCancelled;
24
33
  exports.failOrphanedBuildingJobs = failOrphanedBuildingJobs;
25
34
  exports.recoverInterruptedJobs = recoverInterruptedJobs;
@@ -33,42 +42,17 @@ exports.bumpWalletStats = bumpWalletStats;
33
42
  const cds_1 = __importDefault(require("@sap/cds"));
34
43
  const node_crypto_1 = require("node:crypto");
35
44
  const cardano_1 = require("#cds-models/odatano/cardano");
45
+ const deep_json_1 = require("../../utils/deep-json");
46
+ const errors_1 = require("../../utils/errors");
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");
36
50
  const { SELECT, INSERT, UPDATE } = cds_1.default.ql;
37
51
  const logger = cds_1.default.log('CardanoWalletWorker');
38
- /**
39
- * Wallet-worker job store (v2.0).
40
- *
41
- * Persistence layer for `CardanoWalletJobs` + `CardanoWorkerWallets`. Ports the two
42
- * hard-won CAP lessons from NIGHTGATE's background-job runner:
43
- *
44
- * 1. `insertJob` runs on the CALLER's ambient transaction. CAP wraps every action
45
- * handler in its own root tx which may already hold the SQLite write lock; a
46
- * detached insert would deadlock against it. The row simply commits together
47
- * with the handler, and the worker's dispatch loop only sees it once visible.
48
- * 2. Every transition helper runs in its own short `db.tx()` (callers pass a fresh
49
- * tx or use `runWithoutAmbientTx`), so the single pooled SQLite connection is
50
- * never held across the seconds-to-minutes job execution.
51
- *
52
- * State machine (see WALLET_WORKER_DESIGN.md §5):
53
- * pending → building → submitting → submitted → confirmed
54
- * │ │ │ └────→ failed
55
- * │ │ └→ submitted (reconciled) | failed (proven absent)
56
- * │ └→ pending (transient retry) | failed
57
- * └→ cancelled
58
- *
59
- * `submitting` is the durable pre-submit state: the signed CBOR, its hash and the
60
- * fee are committed BEFORE the transaction can reach the network, so a process
61
- * death anywhere around `submitTransaction` leaves a row that can be reconciled
62
- * against the chain (or re-submitted verbatim) instead of a `building` row that
63
- * looks un-submitted. It is a NON-terminal state, so it keeps holding the
64
- * idempotency key — a caller retry gets the same job back rather than a rebuild.
65
- *
66
- * Transitions use guarded UPDATEs (WHERE includes the expected source status) with
67
- * a read-back verification — the wallet lease already fences concurrent workers,
68
- * this is defense in depth. NOTE (CAP 10): numeric columns read back as STRINGS;
69
- * all reads coerce via `num()` so callers get clean numbers.
70
- */
71
- /** Per-wallet DB lease TTL — same rationale as the crawler lease. */
52
+ // Job flow: pending, building, submitting, submitted, confirmed. Each state can also end in failed.
53
+ // submitting stores the signed CBOR before the network call. Transitions are conditional UPDATEs.
54
+ // insertJob uses the caller's tx, since a separate one would deadlock on the SQLite write lock.
55
+ /** Per-wallet DB lease TTL. */
72
56
  exports.WORKER_LEASE_TTL_MS = 15_000;
73
57
  exports.JOB_ERROR_CODES = {
74
58
  PROCESS_RESTART: 'PROCESS_RESTART',
@@ -77,24 +61,16 @@ exports.JOB_ERROR_CODES = {
77
61
  CANCELLED: 'CANCELLED',
78
62
  /** Reconciliation proved the tx is not on-chain and the node rejects it for good. */
79
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',
80
72
  };
81
- exports.WALLET_JOB_KINDS = ['simpleAda', 'metadata', 'multiAsset', 'mint', 'plutusSpend', 'submitSigned'];
82
- function optionalNum(v) {
83
- if (v === null || v === undefined || v === '')
84
- return null;
85
- const n = Number(v);
86
- return Number.isNaN(n) ? null : n;
87
- }
88
- function requiredNum(v, fallback = 0) {
89
- return optionalNum(v) ?? fallback;
90
- }
91
- function timestamp(v) {
92
- if (v === null || v === undefined || v === '')
93
- return null;
94
- if (v instanceof Date)
95
- return v.toISOString();
96
- return String(v);
97
- }
73
+ exports.WALLET_JOB_KINDS = ['simpleAda', 'metadata', 'multiAsset', 'mint', 'plutusSpend', 'payout', 'submitSigned'];
98
74
  function toJobRow(row) {
99
75
  return {
100
76
  ID: String(row.ID),
@@ -103,23 +79,28 @@ function toJobRow(row) {
103
79
  status: row.status,
104
80
  idempotencyKey: row.idempotencyKey ?? null,
105
81
  request: row.request ?? null,
106
- priority: requiredNum(row.priority, 100),
107
- notBefore: timestamp(row.notBefore),
108
- attempt: requiredNum(row.attempt),
109
- 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),
110
86
  txHash: row.txHash ?? null,
111
87
  unsignedTxCbor: row.unsignedTxCbor ?? null,
112
88
  signedTxCbor: row.signedTxCbor ?? null,
113
- fee: optionalNum(row.fee),
114
- submittedAt: timestamp(row.submittedAt),
115
- confirmedAt: timestamp(row.confirmedAt),
116
- confirmedSlot: optionalNum(row.confirmedSlot),
117
- 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),
118
94
  errorCode: row.errorCode ?? null,
119
95
  errorMessage: row.errorMessage ?? null,
120
- createdAt: timestamp(row.createdAt),
96
+ createdAt: (0, row_values_1.timestamp)(row.createdAt),
121
97
  createdBy: row.createdBy ?? null,
122
- 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,
123
104
  };
124
105
  }
125
106
  function toWalletRow(row) {
@@ -128,27 +109,19 @@ function toWalletRow(row) {
128
109
  signerType: row.signerType,
129
110
  address: row.address ?? null,
130
111
  publicKeyHash: row.publicKeyHash ?? null,
112
+ requiresRole: row.requiresRole ?? null,
131
113
  enabled: row.enabled !== false,
132
114
  leaseOwner: row.leaseOwner ?? null,
133
- leaseUntil: timestamp(row.leaseUntil),
134
- lastJobAt: timestamp(row.lastJobAt),
135
- jobsConfirmed: requiredNum(row.jobsConfirmed),
136
- 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),
137
119
  };
138
120
  }
139
- // Moved to srv/utils/tx-utils.ts (shared with the sign-service's deadlock
140
- // guard); re-exported here so existing imports keep working.
121
+ // Re-exported from the shared tx-utils so existing imports keep working.
141
122
  var tx_utils_1 = require("../../utils/tx-utils");
142
123
  Object.defineProperty(exports, "runWithoutAmbientTx", { enumerable: true, get: function () { return tx_utils_1.runWithoutAmbientTx; } });
143
- /**
144
- * Recognize a unique-constraint rejection across the adapters we support —
145
- * SQLite (`SQLITE_CONSTRAINT_UNIQUE`, "UNIQUE constraint failed") and HANA
146
- * (code 301, "unique constraint violated").
147
- *
148
- * Errors it does not recognize are deliberately NOT treated as duplicates: they
149
- * propagate, and the caller's retry dedups through the read path. Swallowing an
150
- * unrelated insert failure as "already exists" would drop the job silently.
151
- */
124
+ /** Unique-constraint error on SQLite or HANA. Unknown errors must propagate, or the job is dropped silently. */
152
125
  function isUniqueViolation(err) {
153
126
  if (!err || typeof err !== 'object')
154
127
  return false;
@@ -160,60 +133,58 @@ function isUniqueViolation(err) {
160
133
  const text = String(message ?? '').toLowerCase();
161
134
  return text.includes('unique constraint') || text.includes('duplicate key');
162
135
  }
163
- /** The job that currently owns an idempotency key, or null when it is free. */
164
- /**
165
- * The stored claim for a caller's idempotency key, SCOPED TO THE PRINCIPAL that
166
- * submits. Two agents (two grants, two users) may both use `order-1` on the
167
- * same wallet: each must get its own job, never a "deduplicated" answer that
168
- * hands one the other's job id. A key from an owner-less caller (privileged
169
- * test context) stays as-is; an owned key becomes a hash of owner + key, which
170
- * fits the String(100) column whatever the owner id's length and never collides
171
- * with a plain key. The caller-visible `idempotencyKey` column keeps the raw key.
172
- */
136
+ /** Dedup key scoped to the submitting user. An owned key is hashed with an `o:` prefix, an owner-less key stays raw. */
173
137
  function dedupKeyFor(owner, idempotencyKey) {
174
138
  const scope = owner?.trim() ?? '';
175
139
  if (!scope)
176
140
  return idempotencyKey;
177
- return `o:${(0, node_crypto_1.createHash)('sha256').update(`${scope}${idempotencyKey}`).digest('hex').slice(0, 48)}`;
141
+ return `o:${(0, node_crypto_1.createHash)('sha256').update(`${scope}\0${idempotencyKey}`).digest('hex').slice(0, 48)}`;
142
+ }
143
+ /** Request JSON with sorted object keys, so two spellings of one request compare equal. */
144
+ function canonicalRequest(json) {
145
+ const sorted = (v) => {
146
+ if (Array.isArray(v))
147
+ return v.map(sorted);
148
+ if (v === null || typeof v !== 'object')
149
+ return v;
150
+ const entries = Object.entries(v).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
151
+ return Object.fromEntries(entries.map(([key, value]) => [key, sorted(value)]));
152
+ };
153
+ if (json == null)
154
+ return '';
155
+ try {
156
+ return (0, deep_json_1.stringifyJson)(sorted((0, deep_json_1.parseJson)(json)));
157
+ }
158
+ catch {
159
+ return json;
160
+ }
161
+ }
162
+ /** The holder of the key answers a retry of the same request. Another request, wallet or kind under the key is a 409. */
163
+ function answerFromHolder(holder, args) {
164
+ const same = holder.walletId === args.walletId && holder.kind === args.kind
165
+ && canonicalRequest(holder.request) === canonicalRequest(args.request);
166
+ if (!same) {
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');
168
+ }
169
+ return { jobId: holder.ID, status: holder.status, deduplicated: true };
178
170
  }
179
- async function readDedupHolder(db, walletId, kind, dedupKey) {
180
- 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 }));
181
173
  return row ? toJobRow(row) : null;
182
174
  }
183
- /**
184
- * Insert a job row ON THE CALLER'S transaction (NIGHTGATE lesson 1 — see module
185
- * docs). Idempotency: an active-or-successful row with the same (walletId, kind,
186
- * idempotencyKey) is returned instead of creating a duplicate. `failed` AND
187
- * `cancelled` rows do NOT block a retry — both are terminal states in which the
188
- * intended work never reached the chain, so re-using the key must be able to
189
- * actually execute it (a cancelled job would otherwise burn its key forever).
190
- *
191
- * The deduplication is enforced by the `dedup` UNIQUE constraint on
192
- * (walletId, kind, dedupKey), NOT by the read below: two concurrent retries — two
193
- * app instances, or two HANA sessions — can both read "no such job" before either
194
- * commits, and would both insert. The read is only a fast path; the constraint is
195
- * what makes it correct, and the loser of the race returns the winner's job.
196
- *
197
- * `dedupKey` holds the caller's key while the job owns it and the job's own ID
198
- * otherwise, so keyless jobs never collide and terminated jobs free their key
199
- * (see releaseDedupClaim) — without depending on how a database treats NULLs
200
- * inside a unique index.
201
- */
175
+ /** Inserts a job, or returns the job that holds the dedup key. The UNIQUE constraint settles races. */
202
176
  async function insertJob(db, args) {
203
177
  const idempotencyKey = args.idempotencyKey ?? null;
204
178
  // The claim is per principal: the same key from another owner is another job.
205
179
  const claim = idempotencyKey ? dedupKeyFor(args.createdBy, idempotencyKey) : null;
206
180
  if (claim) {
207
- // Fast path: an owner exists (by construction it is non-terminal). Terminal
208
- // jobs release their claim, so they never show up here.
209
- const holder = await readDedupHolder(db, args.walletId, args.kind, claim);
181
+ // A failed holder kept its key because its transaction may have been sent.
182
+ const holder = await readDedupHolder(db, claim);
210
183
  if (holder) {
211
- if (holder.status !== 'failed' && holder.status !== 'cancelled') {
212
- return { jobId: holder.ID, status: holder.status, deduplicated: true };
213
- }
214
- // Defensive: a terminal row that still owns the key would block retries
215
- // forever. Free it and continue with a fresh job.
216
- logger.warn(`Job ${holder.ID} is ${holder.status} but still held idempotency key "${idempotencyKey}" — releasing it`);
184
+ if (holder.status !== 'cancelled')
185
+ return answerFromHolder(holder, args);
186
+ // Defensive: a cancelled job frees its key, so this row would block retries forever.
187
+ logger.warn(`Job ${holder.ID} is cancelled but still held idempotency key "${idempotencyKey}", releasing it`);
217
188
  await releaseDedupClaim(db, holder.ID);
218
189
  }
219
190
  }
@@ -224,8 +195,7 @@ async function insertJob(db, args) {
224
195
  kind: args.kind,
225
196
  status: 'pending',
226
197
  idempotencyKey,
227
- // No key → the row's own ID: unique by construction, so keyless jobs never
228
- // contend for the constraint.
198
+ // No key → the row's own ID, so keyless jobs never contend for the constraint.
229
199
  dedupKey: claim ?? jobId,
230
200
  request: args.request,
231
201
  priority: args.priority ?? 100,
@@ -239,15 +209,14 @@ async function insertJob(db, args) {
239
209
  await db.run(INSERT.into(cardano_1.CardanoWalletJobs).entries(entry));
240
210
  }
241
211
  catch (err) {
242
- // Lost the race: another transaction committed the same key first. Its job is
243
- // the one and only job for this key — hand it back instead of paying twice.
212
+ // Lost the race to another transaction with the same key. Return its job.
244
213
  if (!claim || !isUniqueViolation(err))
245
214
  throw err;
246
- const winner = await readDedupHolder(db, args.walletId, args.kind, claim);
215
+ const winner = await readDedupHolder(db, claim);
247
216
  if (!winner)
248
- throw err; // constraint fired for some other reason — do not mask it
249
- logger.info(`Concurrent submission for idempotency key "${idempotencyKey}" — returning job ${winner.ID}`);
250
- return { jobId: winner.ID, status: winner.status, deduplicated: true };
217
+ throw err; // constraint fired for another reason, do not mask it
218
+ logger.info(`Concurrent submission for idempotency key "${idempotencyKey}", returning job ${winner.ID}`);
219
+ return answerFromHolder(winner, args);
251
220
  }
252
221
  return { jobId, status: 'pending', deduplicated: false };
253
222
  }
@@ -256,33 +225,49 @@ async function getJobById(db, jobId) {
256
225
  const row = await db.run(SELECT.one.from(cardano_1.CardanoWalletJobs).where({ ID: jobId }));
257
226
  return row ? toJobRow(row) : null;
258
227
  }
259
- /**
260
- * All dispatchable jobs: status pending, ordered by (priority, createdAt).
261
- * `notBefore` gating happens in JS — queue depths are small and the JS filter
262
- * avoids adapter-specific NULL/OR predicate quirks.
263
- */
264
- async function findDueJobs(db, now = new Date()) {
265
- const rows = await db.run(SELECT.from(cardano_1.CardanoWalletJobs).where({ status: 'pending' }).orderBy('priority', 'createdAt'));
266
- return (rows ?? [])
267
- .map(toJobRow)
268
- .filter(j => !j.notBefore || Date.parse(j.notBefore) <= now.getTime());
228
+ /** The next due pending job of a wallet by priority and age, or null. One row per call, whatever the queue holds. */
229
+ async function findNextDueJob(db, walletId, now = new Date()) {
230
+ const due = { notBefore: null, or: { notBefore: { '<=': now.toISOString() } } };
231
+ const row = await db.run(SELECT.one.from(cardano_1.CardanoWalletJobs).columns('ID', 'walletId', 'priority', 'createdAt')
232
+ .where({ walletId, status: 'pending', and: due })
233
+ .orderBy('priority', 'createdAt'));
234
+ if (!row)
235
+ return null;
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) };
237
+ }
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 }));
241
+ return Number(row?.n ?? 0);
242
+ }
243
+ /** Number of pending jobs, due or not. */
244
+ function countPendingJobs(db) {
245
+ return countJobs(db, 'pending');
269
246
  }
270
247
  /** All jobs awaiting confirmation (used by the tracker on start/recovery). */
271
248
  async function findSubmittedJobs(db) {
272
249
  const rows = await db.run(SELECT.from(cardano_1.CardanoWalletJobs).where({ status: 'submitted' }));
273
250
  return (rows ?? []).map(toJobRow);
274
251
  }
275
- /** 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.
276
260
  async function walletHasActiveJob(db, walletId) {
277
- const row = await db.run(SELECT.one.from(cardano_1.CardanoWalletJobs).where({ walletId, status: { in: ['building', 'submitting', 'submitted'] } }));
278
- return !!row;
279
- }
280
- /**
281
- * The oldest `submitting` row of a wallet whose lease no longer belongs to a live
282
- * executor — its submit outcome is unknown (crash, or a submit call that failed
283
- * ambiguously), so it needs chain reconciliation rather than a rebuild. Rows whose
284
- * wallet lease is still held are being worked on right now and are left alone.
285
- */
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;
269
+ }
270
+ /** Oldest submitting row of a wallet without a live lease. Its submit outcome is unknown and needs a chain check. */
286
271
  async function findOrphanedSubmittingJob(db, walletId, now = new Date()) {
287
272
  const wallet = await readWallet(db, walletId);
288
273
  if (walletLeaseHeld(wallet, now))
@@ -291,30 +276,11 @@ async function findOrphanedSubmittingJob(db, walletId, now = new Date()) {
291
276
  return row ? toJobRow(row) : null;
292
277
  }
293
278
  // ---- Guarded transitions ---------------------------------------------------------
294
- /**
295
- * Give up a job's idempotency key by pointing `dedupKey` at the job's own ID
296
- * (unique by construction). Called on every terminal-but-unsuccessful transition,
297
- * which is what lets a caller re-use the key for a fresh attempt while the row
298
- * itself — including its `idempotencyKey` — stays intact for the audit trail.
299
- *
300
- * Not called for `confirmed`: a completed job keeps its key so a late duplicate
301
- * request resolves to it instead of paying again.
302
- */
279
+ /** Frees the idempotency key by pointing dedupKey at the job ID. */
303
280
  async function releaseDedupClaim(db, jobId) {
304
281
  await db.run(UPDATE.entity(cardano_1.CardanoWalletJobs).set({ dedupKey: jobId }).where({ ID: jobId }));
305
282
  }
306
- /**
307
- * Move a job from one of `fromStatuses` to `set.status` and report whether THIS
308
- * call did it. The guard is the conditional UPDATE; the answer is its affected
309
- * row count (every @cap-js adapter returns a number). A second caller that
310
- * finds the row already in the target state gets `false`: the transition, the
311
- * wallet-stats bump and the terminal event belong to the first one only.
312
- * Two trackers confirming the same job used to count it twice.
313
- *
314
- * Fallback for an adapter that returns something that is not a count: read
315
- * the row back, and accept the target state only if the row was NOT already
316
- * there before this call (checked with a pre-read in that branch).
317
- */
283
+ /** True only when this call made the transition. That caller owns the stats bump and the terminal event. */
318
284
  async function guardedTransition(db, jobId, fromStatuses, set) {
319
285
  const affected = await db.run(UPDATE.entity(cardano_1.CardanoWalletJobs)
320
286
  .set(set)
@@ -322,8 +288,7 @@ async function guardedTransition(db, jobId, fromStatuses, set) {
322
288
  const n = typeof affected === 'number' ? affected : Number(affected);
323
289
  if (Number.isFinite(n))
324
290
  return n > 0;
325
- // Unknown return shape: the row is in the target state AND that state is not
326
- // one it could have been in before (the guard excludes it) means we moved it.
291
+ // Non-numeric return: the row is in the target state and could not have been there before.
327
292
  const row = await getJobById(db, jobId);
328
293
  return row?.status === set.status && !fromStatuses.includes(set.status);
329
294
  }
@@ -331,14 +296,7 @@ async function guardedTransition(db, jobId, fromStatuses, set) {
331
296
  async function markBuilding(db, jobId, attempt) {
332
297
  return guardedTransition(db, jobId, ['pending'], { status: 'building', attempt });
333
298
  }
334
- /**
335
- * building → submitting. Commits the signed transaction, its hash, the unsigned
336
- * CBOR and the fee BEFORE the tx is handed to a backend — the whole point of the
337
- * state: whatever happens to the process during `submitTransaction`, the exact
338
- * bytes that may be on-chain survive, and the job keeps holding its idempotency
339
- * key so a caller retry can never turn into a second, differently-built payment.
340
- * `submittedAt` is the attempt time (timeout base), not proof of acceptance.
341
- */
299
+ /** Stores the signed tx before the network call, so the exact bytes survive a crash. submittedAt is the attempt time. */
342
300
  async function markSubmitting(db, jobId, artifacts) {
343
301
  return guardedTransition(db, jobId, ['building'], {
344
302
  status: 'submitting',
@@ -349,22 +307,11 @@ async function markSubmitting(db, jobId, artifacts) {
349
307
  submittedAt: new Date().toISOString(),
350
308
  });
351
309
  }
352
- /**
353
- * submitting → submitted: a backend accepted the tx (or reconciliation found it
354
- * on-chain). The artifacts are already durable from markSubmitting; only the hash
355
- * is re-asserted, in case the backend canonicalized it.
356
- */
310
+ /** submitting → submitted (accepted by a backend or found on-chain). Re-asserts only the hash. */
357
311
  async function markSubmitted(db, jobId, txHash) {
358
312
  return guardedTransition(db, jobId, ['submitting'], { status: 'submitted', txHash });
359
313
  }
360
- /**
361
- * building → pending (transient failure, attempts left). Keeps the error visible
362
- * and defers the next attempt via `notBefore` (exponential backoff).
363
- *
364
- * Guarded on `building` ON PURPOSE: once a job is `submitting` its tx may be in a
365
- * mempool, and re-queueing it would rebuild a different transaction from the same
366
- * request — the duplicate-payment path. Those rows go to reconciliation instead.
367
- */
314
+ /** Requeues a building job after a transient error. Never a submitting job, since a rebuild could pay twice. */
368
315
  async function requeueForRetry(db, jobId, err, notBefore) {
369
316
  const message = err instanceof Error ? err.message : String(err);
370
317
  return guardedTransition(db, jobId, ['building'], {
@@ -379,7 +326,7 @@ async function recordConfirmationPoint(db, jobId, point) {
379
326
  .set({ confirmedSlot: point.slot, confirmedHeight: point.height })
380
327
  .where({ ID: jobId, status: 'submitted' }));
381
328
  }
382
- /** A rollback invalidated the recorded confirmation point — back to watching. */
329
+ /** A rollback invalidated the recorded confirmation point. */
383
330
  async function clearConfirmationPoint(db, jobId) {
384
331
  await db.run(UPDATE.entity(cardano_1.CardanoWalletJobs)
385
332
  .set({ confirmedSlot: null, confirmedHeight: null })
@@ -396,21 +343,61 @@ async function markConfirmed(db, jobId) {
396
343
  errorMessage: null,
397
344
  });
398
345
  }
399
- /**
400
- * Any active state → failed (terminal). Failing a `submitting`/`submitted` row is
401
- * only safe once the chain has been consulted — a failed row releases the
402
- * idempotency key, so a premature failure invites the caller's retry to pay twice.
403
- */
346
+ /** Fails a job that never sent a transaction and frees its key for the caller's retry. */
404
347
  async function markFailed(db, jobId, code, err) {
405
348
  const message = err instanceof Error ? err.message : String(err);
406
- return guardedTransition(db, jobId, ['pending', 'building', 'submitting', 'submitted'], {
349
+ return guardedTransition(db, jobId, ['pending', 'building'], {
407
350
  status: 'failed',
408
351
  errorCode: code.slice(0, 50),
409
352
  errorMessage: message.slice(0, 500),
410
353
  finishedAt: new Date().toISOString(),
411
- dedupKey: jobId, // free the idempotency key for the caller's retry
354
+ dedupKey: jobId,
412
355
  });
413
356
  }
357
+ // The signed bytes may still reach the chain, so the key stays: a retry gets this job, not a second payment.
358
+ async function markFailedAfterSend(db, jobId, code, err) {
359
+ const message = err instanceof Error ? err.message : String(err);
360
+ return guardedTransition(db, jobId, ['submitting', 'submitted'], {
361
+ status: 'failed',
362
+ errorCode: code.slice(0, 50),
363
+ errorMessage: message.slice(0, 500),
364
+ finishedAt: new Date().toISOString(),
365
+ });
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
+ }
414
401
  /** pending → cancelled. Only pending jobs are cancellable (the tx may otherwise reach the chain). */
415
402
  async function markCancelled(db, jobId) {
416
403
  return guardedTransition(db, jobId, ['pending'], {
@@ -427,17 +414,7 @@ function walletLeaseHeld(wallet, now) {
427
414
  const deadline = Date.parse(wallet.leaseUntil);
428
415
  return Number.isFinite(deadline) && deadline > now.getTime();
429
416
  }
430
- /**
431
- * Fail one wallet's orphaned `building` row(s) — but ONLY when the wallet's lease
432
- * is expired/unowned, i.e. no live instance is executing them. Rows whose wallet
433
- * lease is held belong to a running executor (possibly on another instance) and
434
- * must not be touched.
435
- *
436
- * Safe by construction: a `building` row is pre-submit by definition — the worker
437
- * transitions to `submitting` (with the signed CBOR) before anything can reach a
438
- * backend, so nothing that is still `building` has ever been sent. Rows that made
439
- * it past that point are `submitting` and are reconciled, never failed here.
440
- */
417
+ /** Fails orphaned building rows of a wallet without a live lease. Such rows were never sent. */
441
418
  async function failOrphanedBuildingJobs(db, walletId, now = new Date()) {
442
419
  const wallet = await readWallet(db, walletId);
443
420
  if (walletLeaseHeld(wallet, now))
@@ -445,9 +422,7 @@ async function failOrphanedBuildingJobs(db, walletId, now = new Date()) {
445
422
  const building = await db.run(SELECT.from(cardano_1.CardanoWalletJobs).columns('ID').where({ walletId, status: 'building' }));
446
423
  if (!building?.length)
447
424
  return 0;
448
- // Per row rather than one bulk UPDATE: each row releases its idempotency key to
449
- // its OWN ID (see releaseDedupClaim), which a single statement cannot express
450
- // portably. Orphan sets are one row in practice — a wallet runs one job at a time.
425
+ // Per row: each releases its idempotency key to its OWN ID, which one bulk UPDATE cannot express portably.
451
426
  for (const { ID } of building) {
452
427
  await db.run(UPDATE.entity(cardano_1.CardanoWalletJobs)
453
428
  .set({
@@ -462,23 +437,8 @@ async function failOrphanedBuildingJobs(db, walletId, now = new Date()) {
462
437
  logger.warn(`Wallet ${walletId}: failed ${building.length} orphaned building job(s) as failed:PROCESS_RESTART`);
463
438
  return building.length;
464
439
  }
465
- /**
466
- * Boot-time recovery (design §8), by state:
467
- * - `building` — nothing was signed and stored yet, so nothing was submitted:
468
- * fail with PROCESS_RESTART (caller retries via idempotencyKey).
469
- * - `submitting` — the signed tx is durable but its fate is unknown: NOT failed
470
- * and NOT rebuilt. Returned so the dispatch loop reconciles it against the
471
- * chain and re-submits those exact bytes if needed.
472
- * - `submitted` — NOT failed: handed to the confirmation tracker; the chain
473
- * decides (found → confirm; absent past the timeout → TX_DROPPED).
474
- *
475
- * Multi-instance safety: a `building` row is only failed when its wallet's lease
476
- * is expired/unowned. A held lease means ANOTHER live instance is executing that
477
- * job right now (rolling deploy) — failing it here while its submit succeeds
478
- * would leave a failed row for an on-chain tx, and since failed rows don't block
479
- * idempotency dedup, the caller's documented retry would pay twice. Rows skipped
480
- * here are cleaned up later by failOrphanedBuildingJobs once the lease expires.
481
- */
440
+ // Boot recovery. Building rows without a live lease fail with PROCESS_RESTART.
441
+ // Submitting rows are checked against the chain, never rebuilt. Submitted rows go to the tracker.
482
442
  async function recoverInterruptedJobs(db, now = new Date()) {
483
443
  const building = await db.run(SELECT.from(cardano_1.CardanoWalletJobs).columns('ID', 'walletId').where({ status: 'building' }));
484
444
  let failedBuilding = 0;
@@ -491,7 +451,7 @@ async function recoverInterruptedJobs(db, now = new Date()) {
491
451
  skippedWallets.push(walletId);
492
452
  }
493
453
  if (skippedWallets.length) {
494
- logger.info(`Recovery skipped building job(s) for wallet(s) ${skippedWallets.join(', ')} — lease still held by a live instance`);
454
+ logger.info(`Recovery skipped building job(s) for wallet(s) ${skippedWallets.join(', ')}, lease still held by a live instance`);
495
455
  }
496
456
  const submitted = await findSubmittedJobs(db);
497
457
  if (submitted.length) {
@@ -499,19 +459,21 @@ async function recoverInterruptedJobs(db, now = new Date()) {
499
459
  }
500
460
  const submitting = (await db.run(SELECT.from(cardano_1.CardanoWalletJobs).where({ status: 'submitting' })) ?? []).map(toJobRow);
501
461
  if (submitting.length) {
502
- logger.warn(`${submitting.length} job(s) interrupted around submit — the dispatch loop will reconcile them against the chain (never a rebuild)`);
462
+ logger.warn(`${submitting.length} job(s) interrupted around submit. The dispatch loop will reconcile them against the chain (never a rebuild)`);
503
463
  }
504
464
  return { failedBuilding, submittedToReconcile: submitted, submittingToReconcile: submitting };
505
465
  }
506
466
  // ---- Worker wallets --------------------------------------------------------------
507
467
  /** Idempotently register/refresh a configured wallet row (no key material). */
508
468
  async function upsertWalletRegistration(db, wallet) {
469
+ const requiresRole = wallet.requiresRole ?? null;
509
470
  const existing = await db.run(SELECT.one.from(cardano_1.CardanoWorkerWallets).where({ walletId: wallet.walletId }));
510
471
  if (existing) {
511
472
  await db.run(UPDATE.entity(cardano_1.CardanoWorkerWallets).set({
512
473
  signerType: wallet.signerType,
513
474
  address: wallet.address,
514
475
  publicKeyHash: wallet.publicKeyHash,
476
+ requiresRole,
515
477
  }).where({ walletId: wallet.walletId }));
516
478
  return;
517
479
  }
@@ -520,6 +482,7 @@ async function upsertWalletRegistration(db, wallet) {
520
482
  signerType: wallet.signerType,
521
483
  address: wallet.address,
522
484
  publicKeyHash: wallet.publicKeyHash,
485
+ requiresRole,
523
486
  enabled: true,
524
487
  jobsConfirmed: 0,
525
488
  jobsFailed: 0,
@@ -533,54 +496,18 @@ async function listWallets(db) {
533
496
  const rows = await db.run(SELECT.from(cardano_1.CardanoWorkerWallets));
534
497
  return (rows ?? []).map(toWalletRow);
535
498
  }
536
- function leaseDeadlineReached(wallet, owner, expectedMs) {
537
- if (!wallet || wallet.leaseOwner !== owner || !wallet.leaseUntil)
538
- return false;
539
- const actualMs = Date.parse(wallet.leaseUntil);
540
- // One second tolerance for adapter timestamp normalization (crawler lease pattern).
541
- return Number.isFinite(actualMs) && actualMs >= expectedMs - 1_000;
542
- }
543
- /**
544
- * Atomically acquire an expired/unowned per-wallet lease (compare-and-swap +
545
- * read-back verification, same shape as the crawler lease). At most one worker
546
- * instance may execute jobs for a wallet at any time.
547
- */
499
+ const walletLease = (walletId) => ({ entity: cardano_1.CardanoWorkerWallets, key: { walletId } });
500
+ /** Takes a free wallet lease by compare-and-swap with read-back. One instance runs a wallet's jobs at a time. */
548
501
  async function tryAcquireWalletLease(db, walletId, owner, now = new Date(), ttlMs = exports.WORKER_LEASE_TTL_MS) {
549
- const raw = await db.run(SELECT.one.from(cardano_1.CardanoWorkerWallets).where({ walletId }));
550
- if (!raw)
551
- return false;
552
- const current = toWalletRow(raw);
553
- if (!current.enabled)
554
- return false;
555
- const deadline = current.leaseUntil ? Date.parse(current.leaseUntil) : Number.NEGATIVE_INFINITY;
556
- if (current.leaseOwner && current.leaseOwner !== owner && deadline > now.getTime())
557
- return false;
558
- const leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
559
- // CAS on the observed owner only — timestamp equality is adapter-fragile and
560
- // could make an expired lease permanently untakeable (see tryAcquireCrawlerLease).
561
- await db.run(UPDATE.entity(cardano_1.CardanoWorkerWallets).set({ leaseOwner: owner, leaseUntil }).where({
562
- walletId,
563
- leaseOwner: raw.leaseOwner ?? null,
564
- }));
565
- const verified = await readWallet(db, walletId);
566
- return leaseDeadlineReached(verified, owner, now.getTime() + ttlMs);
502
+ return (0, lease_1.tryAcquireLease)(db, walletLease(walletId), owner, { now, ttlMs }, (row) => toWalletRow(row).enabled);
567
503
  }
568
504
  /** Renew/fence the caller's lease. Call before every job-advancing write. */
569
505
  async function renewWalletLease(db, walletId, owner, now = new Date(), ttlMs = exports.WORKER_LEASE_TTL_MS) {
570
- const leaseUntil = new Date(now.getTime() + ttlMs).toISOString();
571
- await db.run(UPDATE.entity(cardano_1.CardanoWorkerWallets).set({ leaseUntil }).where({
572
- walletId,
573
- leaseOwner: owner,
574
- }));
575
- const verified = await readWallet(db, walletId);
576
- return leaseDeadlineReached(verified, owner, now.getTime() + ttlMs);
506
+ return (0, lease_1.renewLease)(db, walletLease(walletId), owner, { now, ttlMs });
577
507
  }
578
508
  /** Release only the caller's lease; a stale process can never clear a successor. */
579
509
  async function releaseWalletLease(db, walletId, owner) {
580
- await db.run(UPDATE.entity(cardano_1.CardanoWorkerWallets).set({ leaseOwner: null, leaseUntil: null }).where({
581
- walletId,
582
- leaseOwner: owner,
583
- }));
510
+ await (0, lease_1.releaseLease)(db, walletLease(walletId), owner);
584
511
  }
585
512
  /** Bump rolling per-wallet stats on a terminal job state. */
586
513
  async function bumpWalletStats(db, walletId, outcome) {