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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/@cds-models/CardanoAgentService/index.d.ts +99 -51
  2. package/@cds-models/CardanoAgentService/index.js +15 -0
  3. package/@cds-models/CardanoBackendService/index.d.ts +347 -0
  4. package/@cds-models/CardanoBackendService/index.js +40 -0
  5. package/@cds-models/CardanoIndexerService/index.d.ts +496 -11
  6. package/@cds-models/CardanoIndexerService/index.js +64 -0
  7. package/@cds-models/CardanoODataService/index.d.ts +414 -57
  8. package/@cds-models/CardanoODataService/index.js +42 -0
  9. package/@cds-models/CardanoSignService/index.d.ts +32 -19
  10. package/@cds-models/CardanoSignService/index.js +3 -0
  11. package/@cds-models/CardanoTransactionService/index.d.ts +58 -44
  12. package/@cds-models/CardanoTransactionService/index.js +4 -0
  13. package/@cds-models/CardanoWorkerService/index.d.ts +7 -22
  14. package/@cds-models/index.d.ts +101 -1
  15. package/@cds-models/index.js +16 -1
  16. package/@cds-models/odatano/cardano/index.d.ts +437 -32
  17. package/@cds-models/odatano/cardano/index.js +48 -0
  18. package/README.md +207 -167
  19. package/db/schema.cds +2402 -1705
  20. package/db/types.cds +446 -295
  21. package/package.json +41 -16
  22. package/scripts/migrate-schema.mjs +334 -0
  23. package/scripts/migrate-slot-leader.mjs +96 -0
  24. package/src/index.d.ts +20 -21
  25. package/src/index.js +45 -31
  26. package/src/plugin.js +17 -35
  27. package/srv/blockchain/asset-decimals.d.ts +7 -0
  28. package/srv/blockchain/asset-decimals.js +91 -0
  29. package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -135
  30. package/srv/blockchain/backends/blockfrost-backend.js +66 -172
  31. package/srv/blockchain/backends/cardano-backend.d.ts +94 -186
  32. package/srv/blockchain/backends/cardano-backend.js +29 -5
  33. package/srv/blockchain/backends/koios-backend.d.ts +103 -168
  34. package/srv/blockchain/backends/koios-backend.js +428 -360
  35. package/srv/blockchain/backends/odatano-backend.d.ts +54 -0
  36. package/srv/blockchain/backends/odatano-backend.js +169 -0
  37. package/srv/blockchain/backends/ogmios-backend.d.ts +123 -190
  38. package/srv/blockchain/backends/ogmios-backend.js +637 -315
  39. package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
  40. package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
  41. package/srv/blockchain/cardano-client.d.ts +61 -241
  42. package/srv/blockchain/cardano-client.js +253 -293
  43. package/srv/blockchain/cardano-indexer.d.ts +282 -281
  44. package/srv/blockchain/cardano-indexer.js +1551 -484
  45. package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
  46. package/srv/blockchain/cardano-tx-builder.js +164 -140
  47. package/srv/blockchain/circuit-breaker.d.ts +1 -13
  48. package/srv/blockchain/circuit-breaker.js +5 -15
  49. package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
  50. package/srv/blockchain/crawler/account-snapshots.js +153 -0
  51. package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +15 -0
  52. package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
  53. package/srv/blockchain/crawler/asset-registry-backfill.d.ts +43 -0
  54. package/srv/blockchain/crawler/asset-registry-backfill.js +153 -0
  55. package/srv/blockchain/crawler/certificate-backfill.d.ts +52 -0
  56. package/srv/blockchain/crawler/certificate-backfill.js +162 -0
  57. package/srv/blockchain/crawler/crawler.d.ts +104 -81
  58. package/srv/blockchain/crawler/crawler.js +532 -160
  59. package/srv/blockchain/crawler/credential-backfill.d.ts +28 -0
  60. package/srv/blockchain/crawler/credential-backfill.js +124 -0
  61. package/srv/blockchain/crawler/hooks.d.ts +2 -17
  62. package/srv/blockchain/crawler/index.d.ts +1 -8
  63. package/srv/blockchain/crawler/index.js +31 -17
  64. package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
  65. package/srv/blockchain/crawler/input-asset-copies.js +171 -0
  66. package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
  67. package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
  68. package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
  69. package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
  70. package/srv/blockchain/crawler/sync-state.d.ts +27 -47
  71. package/srv/blockchain/crawler/sync-state.js +113 -63
  72. package/srv/blockchain/crawler/transaction-backfill.d.ts +44 -0
  73. package/srv/blockchain/crawler/transaction-backfill.js +278 -0
  74. package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
  75. package/srv/blockchain/crawler/utxo-set-import.js +399 -0
  76. package/srv/blockchain/ledger-state.d.ts +62 -0
  77. package/srv/blockchain/ledger-state.js +419 -0
  78. package/srv/blockchain/pending-spends.d.ts +16 -0
  79. package/srv/blockchain/pending-spends.js +81 -0
  80. package/srv/blockchain/pool-metadata.d.ts +15 -0
  81. package/srv/blockchain/pool-metadata.js +132 -0
  82. package/srv/blockchain/request-coalescer.d.ts +2 -16
  83. package/srv/blockchain/request-coalescer.js +2 -16
  84. package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
  85. package/srv/blockchain/signing/cose-verifier.js +146 -70
  86. package/srv/blockchain/signing/external-signer.d.ts +15 -115
  87. package/srv/blockchain/signing/external-signer.js +17 -126
  88. package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
  89. package/srv/blockchain/signing/hsm-signer.js +28 -79
  90. package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
  91. package/srv/blockchain/signing/signature-verifier.js +70 -83
  92. package/srv/blockchain/signing/submission-finalizer.d.ts +23 -45
  93. package/srv/blockchain/signing/submission-finalizer.js +219 -86
  94. package/srv/blockchain/stored-chain.d.ts +20 -0
  95. package/srv/blockchain/stored-chain.js +237 -0
  96. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
  97. package/srv/blockchain/transaction-building/buildooor-tx.js +652 -416
  98. package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
  99. package/srv/blockchain/transaction-presence.d.ts +5 -0
  100. package/srv/blockchain/transaction-presence.js +29 -0
  101. package/srv/blockchain/transaction-rows.d.ts +12 -0
  102. package/srv/blockchain/transaction-rows.js +44 -0
  103. package/srv/blockchain/wallet-worker/build-request.d.ts +5 -20
  104. package/srv/blockchain/wallet-worker/build-request.js +47 -30
  105. package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -46
  106. package/srv/blockchain/wallet-worker/confirmation-tracker.js +25 -45
  107. package/srv/blockchain/wallet-worker/index.d.ts +1 -1
  108. package/srv/blockchain/wallet-worker/index.js +3 -11
  109. package/srv/blockchain/wallet-worker/job-store.d.ts +30 -148
  110. package/srv/blockchain/wallet-worker/job-store.js +101 -201
  111. package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
  112. package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
  113. package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
  114. package/srv/blockchain/wallet-worker/signers.js +4 -12
  115. package/srv/blockchain/wallet-worker/wallet-worker.d.ts +8 -80
  116. package/srv/blockchain/wallet-worker/wallet-worker.js +107 -155
  117. package/srv/cardano-agent-service.cds +122 -84
  118. package/srv/cardano-agent-service.js +4 -9
  119. package/srv/cardano-backend-service.cds +78 -0
  120. package/srv/cardano-backend-service.d.ts +2 -0
  121. package/srv/cardano-backend-service.js +242 -0
  122. package/srv/cardano-indexer-service.cds +387 -73
  123. package/srv/cardano-indexer-service.d.ts +5 -1
  124. package/srv/cardano-indexer-service.js +532 -16
  125. package/srv/cardano-service.cds +424 -269
  126. package/srv/cardano-service.js +289 -201
  127. package/srv/cardano-sign-service.cds +201 -180
  128. package/srv/cardano-sign-service.js +71 -201
  129. package/srv/cardano-tx-service.cds +451 -370
  130. package/srv/cardano-tx-service.js +271 -289
  131. package/srv/cardano-ui.cds +16 -16
  132. package/srv/cardano-worker-service.cds +118 -125
  133. package/srv/cardano-worker-service.js +52 -61
  134. package/srv/cbor/cip68.d.ts +13 -0
  135. package/srv/cbor/cip68.js +56 -0
  136. package/srv/cbor/index.d.ts +3 -1
  137. package/srv/cbor/index.js +9 -1
  138. package/srv/cbor/parse.d.ts +30 -18
  139. package/srv/cbor/parse.js +44 -9
  140. package/srv/cbor/plutus-data-json.d.ts +20 -0
  141. package/srv/cbor/plutus-data-json.js +32 -0
  142. package/srv/config.d.ts +113 -0
  143. package/srv/config.js +409 -0
  144. package/srv/server.d.ts +15 -110
  145. package/srv/server.js +84 -404
  146. package/srv/utils/agent-access.d.ts +9 -0
  147. package/srv/utils/agent-access.js +67 -0
  148. package/srv/utils/agent-grants-config.d.ts +0 -46
  149. package/srv/utils/agent-grants-config.js +17 -85
  150. package/srv/utils/agent-grants.d.ts +106 -122
  151. package/srv/utils/agent-grants.js +538 -236
  152. package/srv/utils/agent-token-auth.d.ts +4 -99
  153. package/srv/utils/agent-token-auth.js +18 -182
  154. package/srv/utils/backend-request-handler.d.ts +3 -17
  155. package/srv/utils/backend-request-handler.js +3 -18
  156. package/srv/utils/collections.d.ts +3 -10
  157. package/srv/utils/collections.js +3 -10
  158. package/srv/utils/const.d.ts +23 -74
  159. package/srv/utils/const.js +32 -79
  160. package/srv/utils/crypto.d.ts +3 -12
  161. package/srv/utils/crypto.js +6 -21
  162. package/srv/utils/db-indexes.d.ts +27 -0
  163. package/srv/utils/db-indexes.js +120 -0
  164. package/srv/utils/db-sanitize.d.ts +20 -0
  165. package/srv/utils/db-sanitize.js +80 -0
  166. package/srv/utils/deep-json.d.ts +6 -0
  167. package/srv/utils/deep-json.js +240 -0
  168. package/srv/utils/epoch-slots.d.ts +13 -0
  169. package/srv/utils/epoch-slots.js +38 -0
  170. package/srv/utils/error-codes.d.ts +22 -75
  171. package/srv/utils/error-codes.js +23 -72
  172. package/srv/utils/errors.d.ts +46 -187
  173. package/srv/utils/errors.js +114 -230
  174. package/srv/utils/liveness.d.ts +12 -0
  175. package/srv/utils/liveness.js +35 -0
  176. package/srv/utils/mappers.d.ts +102 -223
  177. package/srv/utils/mappers.js +387 -316
  178. package/srv/utils/network-context.js +2 -13
  179. package/srv/utils/paging.d.ts +31 -0
  180. package/srv/utils/paging.js +43 -0
  181. package/srv/utils/pg-inline-json.d.ts +8 -0
  182. package/srv/utils/pg-inline-json.js +58 -0
  183. package/srv/utils/pg-order-nulls.d.ts +14 -0
  184. package/srv/utils/pg-order-nulls.js +54 -0
  185. package/srv/utils/plutus-placeholders.d.ts +16 -22
  186. package/srv/utils/plutus-placeholders.js +62 -33
  187. package/srv/utils/rate-limiter.d.ts +2 -21
  188. package/srv/utils/rate-limiter.js +5 -17
  189. package/srv/utils/readiness.d.ts +12 -0
  190. package/srv/utils/readiness.js +29 -0
  191. package/srv/utils/reference-script.d.ts +19 -0
  192. package/srv/utils/reference-script.js +84 -0
  193. package/srv/utils/result-numbers.d.ts +15 -0
  194. package/srv/utils/result-numbers.js +61 -0
  195. package/srv/utils/service-events.d.ts +0 -24
  196. package/srv/utils/service-events.js +3 -25
  197. package/srv/utils/signing-helper.d.ts +3 -20
  198. package/srv/utils/signing-helper.js +35 -64
  199. package/srv/utils/tx-build-helper.d.ts +10 -105
  200. package/srv/utils/tx-build-helper.js +81 -144
  201. package/srv/utils/tx-request-parsers.d.ts +82 -33
  202. package/srv/utils/tx-request-parsers.js +401 -49
  203. package/srv/utils/tx-utils.d.ts +3 -27
  204. package/srv/utils/tx-utils.js +32 -50
  205. package/srv/utils/types.d.ts +261 -191
  206. package/srv/utils/types.js +2 -6
  207. package/srv/utils/validators.d.ts +22 -92
  208. package/srv/utils/validators.js +50 -149
@@ -10,21 +10,21 @@ const cds_1 = __importDefault(require("@sap/cds"));
10
10
  const errors_1 = require("../../utils/errors");
11
11
  const error_codes_1 = require("../../utils/error-codes");
12
12
  const tx_build_helper_1 = require("../../utils/tx-build-helper");
13
+ const transaction_presence_1 = require("../transaction-presence");
14
+ const cardano_1 = require("#cds-models/odatano/cardano");
13
15
  const confirmation_tracker_1 = require("./confirmation-tracker");
14
16
  const lease_heartbeat_1 = require("./lease-heartbeat");
15
17
  const build_request_1 = require("./build-request");
16
18
  const service_events_1 = require("../../utils/service-events");
17
19
  const signers_1 = require("./signers");
18
20
  const job_store_1 = require("./job-store");
21
+ const { SELECT } = cds_1.default.ql;
19
22
  const logger = cds_1.default.log('CardanoWalletWorker');
20
23
  /** Retry backoff: 5s · 2^(attempt-1), capped at 60s. */
21
24
  function retryBackoffMs(attempt) {
22
25
  return Math.min(5_000 * 2 ** Math.max(0, attempt - 1), 60_000);
23
26
  }
24
- /**
25
- * Transient errors are worth a bounded retry; everything else is deterministic
26
- * (a retry cannot change the outcome) and fails the job immediately.
27
- */
27
+ /** Transient errors get a bounded retry; everything else fails the job immediately. */
28
28
  function isTransientJobError(err) {
29
29
  if (err instanceof errors_1.ProviderUnavailableError)
30
30
  return true;
@@ -46,12 +46,12 @@ function terminalErrorCode(err) {
46
46
  class CardanoWalletWorker {
47
47
  deps;
48
48
  signers = new Map();
49
- executing = new Set(); // walletIds with an execution in flight in THIS process
49
+ executing = new Set(); // walletIds executing in THIS process
50
50
  executionPromises = new Set();
51
51
  tracker;
52
52
  dispatchTimer = null;
53
53
  running = false;
54
- ticking = false;
54
+ tickInFlight = null;
55
55
  constructor(deps) {
56
56
  this.deps = deps;
57
57
  this.tracker = new confirmation_tracker_1.ConfirmationTracker({
@@ -63,9 +63,8 @@ class CardanoWalletWorker {
63
63
  resubmitOnRollback: deps.config.resubmitOnRollback,
64
64
  },
65
65
  onFinal: ({ jobId, walletId, outcome, kind, txHash, errorCode, errorMessage }) => {
66
- logger.debug(`Wallet ${walletId} unblocked (job ${outcome}) — next tick dispatches`);
67
- // Fired only on a TERMINAL outcome, after the transition is committed, so a
68
- // subscriber that reads the job row sees the state the event announces.
66
+ logger.debug(`Wallet ${walletId} unblocked (job ${outcome}), next tick dispatches`);
67
+ // Terminal outcomes only, after the commit, so subscribers reading the row see the announced state.
69
68
  (0, service_events_1.emitServiceEvent)('CardanoWorkerService', outcome === 'confirmed' ? 'jobConfirmed' : 'jobFailed', {
70
69
  jobId,
71
70
  walletId,
@@ -103,7 +102,7 @@ class CardanoWalletWorker {
103
102
  logger.warn('Wallet worker refused to start: no wallets configured');
104
103
  return;
105
104
  }
106
- // 1. Initialize signers — a broken wallet config skips that wallet, not the worker.
105
+ // 1. Initialize signers. A broken wallet config skips that wallet, not the worker.
107
106
  for (const walletCfg of this.deps.config.wallets) {
108
107
  try {
109
108
  const signer = (0, signers_1.createWorkerSigner)(walletCfg, this.deps.network);
@@ -113,19 +112,19 @@ class CardanoWalletWorker {
113
112
  signerType: walletCfg.signerType,
114
113
  address: signer.getAddress(),
115
114
  publicKeyHash: signer.getPublicKeyHash(),
115
+ requiresRole: walletCfg.requiresRole ?? null,
116
116
  }));
117
117
  }
118
118
  catch (err) {
119
- logger.error(`Wallet "${walletCfg.walletId}" skipped — signer initialization failed:`, err);
119
+ logger.error(`Wallet "${walletCfg.walletId}" skipped, signer initialization failed:`, err);
120
120
  }
121
121
  }
122
122
  if (this.signers.size === 0) {
123
123
  logger.error('Wallet worker not started: no wallet signer could be initialized');
124
124
  return;
125
125
  }
126
- // 2. Crash recovery: fail interrupted builds, re-watch submitted jobs. Rows
127
- // interrupted around the submit call stay `submitting` — the first tick
128
- // reconciles them against the chain (reconcileOrphanedSubmissions).
126
+ // 2. Crash recovery: fail interrupted builds, re-watch submitted jobs; `submitting`
127
+ // rows are reconciled by the first tick.
129
128
  const recovery = await cds_1.default.tx((tx) => (0, job_store_1.recoverInterruptedJobs)(tx));
130
129
  if (recovery.submittingToReconcile.length) {
131
130
  logger.warn(`${recovery.submittingToReconcile.length} job(s) with an unresolved submit will be reconciled on the next dispatch tick`);
@@ -161,7 +160,8 @@ class CardanoWalletWorker {
161
160
  this.dispatchTimer = null;
162
161
  }
163
162
  this.tracker.stop();
164
- // Executions are short (build+sign+submit) — await them so teardown never races a write.
163
+ // A running tick may still spawn work; let it finish, then await every execution.
164
+ await this.tickInFlight;
165
165
  await Promise.allSettled([...this.executionPromises]);
166
166
  for (const walletId of this.getWalletIds()) {
167
167
  try {
@@ -175,63 +175,57 @@ class CardanoWalletWorker {
175
175
  }
176
176
  /** One dispatch round; serialized (overlapping timers collapse into one run). */
177
177
  async tickSafe() {
178
- if (!this.running || this.ticking)
178
+ if (!this.running || this.tickInFlight)
179
179
  return;
180
- this.ticking = true;
181
- try {
182
- await this.tick();
183
- }
184
- catch (err) {
185
- logger.error('Wallet worker dispatch tick failed:', err);
186
- }
187
- finally {
188
- this.ticking = false;
189
- }
180
+ this.tickInFlight = this.tick()
181
+ .catch((err) => logger.error('Wallet worker dispatch tick failed:', err))
182
+ .finally(() => { this.tickInFlight = null; });
183
+ await this.tickInFlight;
190
184
  }
191
185
  async tick() {
192
- // Interrupted submits first: a stuck `submitting` row blocks its wallet queue
193
- // and may be the only work there is (no pending job would ever surface it).
186
+ // Interrupted submits first: a stuck `submitting` row blocks its wallet queue.
194
187
  await this.reconcileOrphanedSubmissions();
195
- const due = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.findDueJobs)(tx)));
196
- if (!due.length)
188
+ // The next due job of every idle wallet this instance signs for: one row per wallet.
189
+ const idle = this.getWalletIds().filter(walletId => !this.executing.has(walletId));
190
+ if (!idle.length)
197
191
  return;
198
- // First runnable job per wallet, dispatch order (priority, createdAt) preserved.
199
- const nextPerWallet = new Map();
200
- for (const job of due) {
201
- if (!nextPerWallet.has(job.walletId))
202
- nextPerWallet.set(job.walletId, job);
203
- }
204
- for (const [walletId, job] of nextPerWallet) {
192
+ const due = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (tx) => {
193
+ const next = [];
194
+ for (const walletId of idle) {
195
+ const ref = await (0, job_store_1.findNextDueJob)(tx, walletId);
196
+ if (ref)
197
+ next.push(ref);
198
+ }
199
+ return next;
200
+ }));
201
+ // dispatch order across wallets: priority, then age
202
+ due.sort((a, b) => a.priority - b.priority || String(a.createdAt ?? '').localeCompare(String(b.createdAt ?? '')));
203
+ for (const { ID, walletId } of due) {
205
204
  if (!this.running)
206
205
  return;
207
206
  if (this.executing.size >= this.deps.config.maxConcurrentWallets)
208
207
  return;
209
- if (this.executing.has(walletId))
210
- continue;
211
208
  const signer = this.signers.get(walletId);
212
209
  if (!signer)
213
- continue; // job for a wallet this instance cannot sign for
214
- const dispatched = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (tx) => {
215
- // Steady-state orphan cleanup: a building row whose wallet lease expired
216
- // belongs to a dead executor — fail it here so the wallet unblocks without
217
- // needing a reboot (boot recovery only covers restarts of THIS instance).
210
+ continue;
211
+ const job = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (tx) => {
212
+ // A building row with an expired lease belongs to a dead executor.
213
+ // Failing it unblocks the wallet without a reboot.
218
214
  await (0, job_store_1.failOrphanedBuildingJobs)(tx, walletId);
219
- // DB truth serializes across restarts and instances: a building OR submitted
220
- // job blocks the wallet queue until the tracker finalizes it (design §6).
215
+ // An active job blocks the wallet queue until the tracker finalizes it.
221
216
  if (await (0, job_store_1.walletHasActiveJob)(tx, walletId))
222
- return false;
223
- return (0, job_store_1.tryAcquireWalletLease)(tx, walletId, this.deps.instanceId);
217
+ return null;
218
+ const next = await (0, job_store_1.getJobById)(tx, ID);
219
+ if (next?.status !== 'pending')
220
+ return null;
221
+ return (await (0, job_store_1.tryAcquireWalletLease)(tx, walletId, this.deps.instanceId)) ? next : null;
224
222
  }));
225
- if (!dispatched)
223
+ if (!job)
226
224
  continue;
227
225
  this.spawn(walletId, () => this.executeJob(job, signer));
228
226
  }
229
227
  }
230
- /**
231
- * Adopt `submitting` rows left behind by a dead executor (this process before a
232
- * restart, or another instance whose lease expired) and resolve them against the
233
- * chain. Runs per wallet under the same lease the executor would hold.
234
- */
228
+ /** Adopt `submitting` rows left by a dead executor and resolve them against the chain, under the wallet lease. */
235
229
  async reconcileOrphanedSubmissions() {
236
230
  const { instanceId } = this.deps;
237
231
  for (const walletId of this.getWalletIds()) {
@@ -254,6 +248,9 @@ class CardanoWalletWorker {
254
248
  }
255
249
  /** Run one wallet's work in the background, tracked for concurrency + shutdown. */
256
250
  spawn(walletId, work) {
251
+ // stop() began after the lease was taken; stop() releases it
252
+ if (!this.running)
253
+ return;
257
254
  this.executing.add(walletId);
258
255
  const execution = work()
259
256
  .catch((err) => logger.error(`Wallet ${walletId}: unhandled execution error:`, err))
@@ -270,16 +267,7 @@ class CardanoWalletWorker {
270
267
  heartbeat.start();
271
268
  return heartbeat;
272
269
  }
273
- /**
274
- * Execute one job: building → (build → sign) → submitting → submit → submitted,
275
- * then hand to the tracker. The wallet lease is held for the duration — renewed by
276
- * a heartbeat, because build+sign can outlast its TTL — and released afterwards
277
- * (queue serialization continues via the job row, not the lease).
278
- *
279
- * Everything up to and including the `submitting` commit may fail freely — nothing
280
- * has been sent, so the job re-queues or fails normally. Past that commit the job
281
- * belongs to `reconcileSubmitting`.
282
- */
270
+ /** Builds, signs and submits one job under a renewed wallet lease. After the submitting commit, reconcileSubmitting owns it. */
283
271
  async executeJob(job, signer) {
284
272
  const { instanceId } = this.deps;
285
273
  const attempt = job.attempt + 1;
@@ -301,48 +289,36 @@ class CardanoWalletWorker {
301
289
  }
302
290
  else {
303
291
  const rawReq = JSON.parse(job.request ?? '{}');
304
- // The worker wallet is ALWAYS the sender/change target — callers cannot
305
- // spend from foreign addresses through a worker wallet.
292
+ // The worker wallet is always the sender and change target. It never spends from foreign addresses.
306
293
  rawReq.network = this.deps.network;
307
294
  rawReq.senderAddress = signer.getAddress();
308
295
  if (!rawReq.changeAddress)
309
296
  rawReq.changeAddress = signer.getAddress();
310
- // The stored request has the documented Build*-action payload shape
311
- // (assetsJson/mintActionsJson/… strings) — transform it into the
312
- // TxBuildRequest shape the indexer build methods expect.
313
- const buildReq = (0, build_request_1.prepareWorkerBuildRequest)(job.kind, rawReq, this.deps.network);
314
- // Fencing: if the lease was lost (instance stalled past the TTL, another
315
- // instance may have taken over the wallet), abort BEFORE building — the
316
- // orphan cleanup will fail the row once the lease is provably dead.
297
+ const build = this.buildOf(job, rawReq);
298
+ // Lease lost → abort BEFORE building; orphan cleanup fails the row once the lease is provably dead.
317
299
  if (!(await heartbeat.fence())) {
318
- logger.warn(`Job ${job.ID}: wallet lease for ${job.walletId} lost before build — aborting execution`);
300
+ logger.warn(`Job ${job.ID}: wallet lease for ${job.walletId} lost before build, aborting execution`);
319
301
  return;
320
302
  }
321
- const buildResult = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => this.buildForKind(tx, job, buildReq)));
303
+ const buildResult = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(build));
322
304
  unsignedTxCbor = buildResult.unsignedTxCbor;
323
305
  fee = buildResult.fee ?? null;
324
306
  buildId = buildResult.id ?? null;
325
307
  signedTxCbor = signer.signTransaction(unsignedTxCbor, buildResult.txBodyHash);
326
308
  }
327
- // The hash comes from the signed bytes, not from the submit response, so the
328
- // row can name the transaction before anyone has seen it.
309
+ // Hash from the signed bytes, so the row can name the tx before anyone has seen it.
329
310
  const txHash = (0, tx_build_helper_1.getTxHashFromCbor)(signedTxCbor);
330
- // Last fence before the irreversible part. Build+sign just consumed real time;
331
- // if the wallet moved to another instance meanwhile, that instance is entitled
332
- // to spend the same UTxOs — submitting now would race it. Nothing has been sent
333
- // yet, so standing down here costs only a rebuild.
311
+ // Last fence before the irreversible part: another instance owning the wallet now
312
+ // may spend the same UTxOs. Nothing has been sent, so standing down costs only a rebuild.
334
313
  if (!(await heartbeat.fence())) {
335
- logger.warn(`Job ${job.ID}: wallet lease for ${job.walletId} lost after signing — NOT submitting tx ${txHash}`);
314
+ logger.warn(`Job ${job.ID}: wallet lease for ${job.walletId} lost after signing, NOT submitting tx ${txHash}`);
336
315
  return;
337
316
  }
338
- // Point of no return: commit the signed tx BEFORE it can reach a backend.
339
- // A crash after this leaves a `submitting` row that reconciliation resolves;
340
- // a crash before it leaves a `building` row that was provably never sent.
341
- // The guard on `building` is also the second half of the fence: if a takeover
342
- // already failed this row, the transition returns false and nothing is sent.
317
+ // Point of no return: commit the signed tx BEFORE it can reach a backend. The guard on
318
+ // `building` is the second half of the fence: a row already failed by a takeover returns false.
343
319
  const stored = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.markSubmitting)(tx, job.ID, { txHash, unsignedTxCbor, signedTxCbor, fee })));
344
320
  if (!stored) {
345
- logger.warn(`Job ${job.ID}: submitting transition was fenced — not submitting (another executor owns this job)`);
321
+ logger.warn(`Job ${job.ID}: submitting transition was fenced, not submitting (another executor owns this job)`);
346
322
  return;
347
323
  }
348
324
  await this.submitStoredTransaction(job, { txHash, signedTxCbor, buildId, attempt });
@@ -356,36 +332,32 @@ class CardanoWalletWorker {
356
332
  .catch(() => undefined);
357
333
  }
358
334
  }
359
- /**
360
- * Send a transaction that is already durable in its `submitting` row and advance
361
- * the job to `submitted`.
362
- *
363
- * A submit failure is NEVER propagated as a job failure here: a rejection from one
364
- * backend does not prove the tx is absent from every mempool (failover, timeouts,
365
- * a node that accepted before the connection dropped). The row simply stays
366
- * `submitting` and the next tick reconciles it against the chain.
367
- */
335
+ /** Sends the stored tx. A failed submit leaves the row submitting, since one rejection proves nothing. */
368
336
  async submitStoredTransaction(job, tx) {
369
337
  let submittedHash;
370
338
  try {
371
339
  submittedHash = await this.submitWithAlreadyKnownTolerance(tx.signedTxCbor);
372
340
  }
373
341
  catch (err) {
374
- logger.error(`Job ${job.ID}: submit failed for tx ${tx.txHash} — job stays submitting for chain reconciliation:`, err);
342
+ logger.error(`Job ${job.ID}: submit failed for tx ${tx.txHash}, job stays submitting for chain reconciliation:`, err);
375
343
  return;
376
344
  }
377
- if (job.kind !== 'submitSigned') {
378
- // Observability parity with the synchronous flow: record the submission row.
379
- await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((t) => this.deps.indexer.persistTransactionSubmission(t, { signedTxCbor: tx.signedTxCbor, txHash: submittedHash, buildId: tx.buildId }))).catch((err) => logger.warn(`Job ${job.ID}: submission bookkeeping failed (job continues):`, err));
380
- }
381
- await this.adoptSubmitted(job, submittedHash, tx.signedTxCbor);
345
+ await this.adoptSubmitted(job, submittedHash, tx.signedTxCbor, tx.buildId);
382
346
  logger.info(`Job ${job.ID} (wallet ${job.walletId}, kind ${job.kind}): submitted as ${submittedHash} (attempt ${tx.attempt})`);
383
347
  }
384
348
  /** submitting → submitted + hand to the confirmation tracker. */
385
- async adoptSubmitted(job, txHash, signedTxCbor) {
349
+ async adoptSubmitted(job, txHash, signedTxCbor, buildId = null) {
350
+ if (job.kind !== 'submitSigned') {
351
+ // Record the submission row as the synchronous flow does, once per tx.
352
+ await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (t) => {
353
+ const known = await t.run(SELECT.one.from(cardano_1.TransactionSubmissions).columns('id').where({ txHash }));
354
+ if (!known)
355
+ await this.deps.indexer.persistTransactionSubmission(t, { signedTxCbor, txHash, buildId, status: 'submitted' });
356
+ })).catch((err) => logger.warn(`Job ${job.ID}: submission bookkeeping failed (job continues):`, err));
357
+ }
386
358
  const submitted = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.markSubmitted)(tx, job.ID, txHash)));
387
359
  if (!submitted) {
388
- logger.error(`Job ${job.ID}: tx ${txHash} is out there but the submitted transition was fenced — tracker adopts the tx anyway`);
360
+ logger.error(`Job ${job.ID}: tx ${txHash} is out there but the submitted transition was fenced, tracker adopts the tx anyway`);
389
361
  }
390
362
  this.tracker.track({
391
363
  jobId: job.ID,
@@ -396,32 +368,15 @@ class CardanoWalletWorker {
396
368
  submittedAt: job.submittedAt ?? new Date().toISOString(),
397
369
  });
398
370
  }
399
- /**
400
- * Resolve a `submitting` job whose submit outcome is unknown (process died around
401
- * the network call, or the call failed ambiguously). The stored transaction is the
402
- * only one this job may ever have — it is re-submitted verbatim, never rebuilt.
403
- *
404
- * 1. Re-submit the same CBOR: mempool/ledger dedup makes this a no-op if it was
405
- * accepted before, so success (or "already known") simply promotes the job.
406
- * 2. If that fails, ask the chain: found → the tx did make it, promote it.
407
- * 3. Only when the chain proves absence AND the node rejects the tx for good (or
408
- * it has been absent past the confirmation timeout) is the job failed —
409
- * failing releases the idempotency key, so it needs that proof.
410
- * Anything else leaves the row as-is; the next tick tries again.
411
- *
412
- * Runs under the same heartbeat-kept wallet lease as an execution: the chain
413
- * lookups here are slow enough to outlive the raw TTL. Losing the lease mid-way
414
- * is not dangerous (the re-submit is the same transaction, and every terminal
415
- * transition is row-guarded), so it only stops further work.
416
- */
371
+ // Resolves a submitting job by re-submitting the stored tx, then looking it up on chain.
372
+ // Fails only when the tx is absent and rejected for good or timed out. Otherwise retries next tick.
417
373
  async reconcileSubmitting(job) {
418
374
  const { instanceId } = this.deps;
419
375
  const heartbeat = this.leaseHeartbeat(job.walletId);
420
376
  try {
421
377
  if (!job.signedTxCbor || !job.txHash) {
422
- // Cannot happen via markSubmitting; treat as a never-sent job rather than
423
- // leaving the wallet queue blocked forever.
424
- logger.error(`Job ${job.ID}: submitting row without signed transaction — failing as PROCESS_RESTART`);
378
+ // Cannot happen via markSubmitting; treat as never sent rather than blocking the wallet queue forever.
379
+ logger.error(`Job ${job.ID}: submitting row without signed transaction, failing as PROCESS_RESTART`);
425
380
  await this.failReconciled(job, job_store_1.JOB_ERROR_CODES.PROCESS_RESTART, new Error('Job was interrupted before its signed transaction was stored.'));
426
381
  return;
427
382
  }
@@ -430,42 +385,36 @@ class CardanoWalletWorker {
430
385
  try {
431
386
  const txHash = await this.submitWithAlreadyKnownTolerance(job.signedTxCbor);
432
387
  await this.adoptSubmitted(job, txHash, job.signedTxCbor);
433
- logger.info(`Job ${job.ID}: re-submitted the original signed tx (${txHash}) — now awaiting confirmation`);
388
+ logger.info(`Job ${job.ID}: re-submitted the original signed tx (${txHash}), now awaiting confirmation`);
434
389
  return;
435
390
  }
436
391
  catch (err) {
437
392
  submitError = err;
438
393
  }
439
- // The tx may have been rejected precisely BECAUSE it is already on-chain
440
- // (its inputs are spent), so the chain — not the rejection — decides.
394
+ // A rejection may mean the tx is already on-chain (inputs spent), so the chain decides.
441
395
  let onChain;
442
396
  try {
443
- await this.deps.client.getTransaction(job.txHash);
444
- onChain = true;
397
+ // null: no backend can look transactions up, so the re-submit above is the only evidence
398
+ onChain = await (0, transaction_presence_1.isTransactionOnChain)(this.deps.indexer, this.deps.client, job.txHash) === true;
445
399
  }
446
400
  catch (lookupErr) {
447
- if (!(0, errors_1.isNotFoundOnAllBackends)(lookupErr)) {
448
- logger.warn(`Job ${job.ID}: chain lookup for ${job.txHash} inconclusive — retrying next tick:`, lookupErr);
449
- return;
450
- }
451
- onChain = false;
401
+ logger.warn(`Job ${job.ID}: chain lookup for ${job.txHash} inconclusive, retrying next tick:`, lookupErr);
402
+ return;
452
403
  }
453
404
  if (onChain) {
454
- logger.info(`Job ${job.ID}: tx ${job.txHash} is on-chain despite the failed submit — awaiting confirmation`);
405
+ logger.info(`Job ${job.ID}: tx ${job.txHash} is on-chain despite the failed submit, awaiting confirmation`);
455
406
  await this.adoptSubmitted(job, job.txHash, job.signedTxCbor);
456
407
  return;
457
408
  }
458
409
  const ageMs = job.submittedAt ? Date.now() - Date.parse(job.submittedAt) : 0;
459
410
  const expired = ageMs > this.deps.config.confirmationTimeoutMs;
460
411
  if (isTransientJobError(submitError) && !expired) {
461
- logger.warn(`Job ${job.ID}: re-submit failed transiently and tx is not on-chain — retrying next tick:`, submitError);
412
+ logger.warn(`Job ${job.ID}: re-submit failed transiently and tx is not on-chain, retrying next tick:`, submitError);
462
413
  return;
463
414
  }
464
- // Proven absent + a rejection that will not change (or a tx that is past its
465
- // mempool lifetime): no transaction of this job can reach the chain anymore,
466
- // so releasing the idempotency key is safe.
415
+ // Not on-chain and not submittable now. The job fails and keeps its idempotency key.
467
416
  const code = expired ? job_store_1.JOB_ERROR_CODES.TX_DROPPED : job_store_1.JOB_ERROR_CODES.SUBMIT_REJECTED;
468
- logger.error(`Job ${job.ID}: tx ${job.txHash} is not on-chain and cannot be submitted (${code}) — failing:`, submitError);
417
+ logger.error(`Job ${job.ID}: tx ${job.txHash} is not on-chain and cannot be submitted (${code}), failing:`, submitError);
469
418
  await this.failReconciled(job, code, submitError);
470
419
  }
471
420
  finally {
@@ -476,11 +425,20 @@ class CardanoWalletWorker {
476
425
  }
477
426
  async failReconciled(job, code, err) {
478
427
  await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (tx) => {
479
- const transitioned = await (0, job_store_1.markFailed)(tx, job.ID, code, err ?? new Error(code));
428
+ const transitioned = await (0, job_store_1.markFailedAfterSend)(tx, job.ID, code, err ?? new Error(code));
480
429
  if (transitioned)
481
430
  await (0, job_store_1.bumpWalletStats)(tx, job.walletId, 'failed');
482
431
  })).catch((persistErr) => logger.error(`Job ${job.ID}: failure persist failed:`, persistErr));
483
432
  }
433
+ /** The job's build, ready to run in a transaction. A malformed request throws 400 INVALID_INPUT here. */
434
+ buildOf(job, raw) {
435
+ if (job.kind === 'payout') {
436
+ const request = (0, build_request_1.preparePayoutRequest)(raw);
437
+ return (tx) => this.deps.indexer.indexPlutusBuildResult(tx, request);
438
+ }
439
+ const request = (0, build_request_1.prepareWorkerBuildRequest)(job.kind, raw, this.deps.network);
440
+ return (tx) => this.buildForKind(tx, job, request);
441
+ }
484
442
  /** Dispatch the job kind to the matching indexer build method. */
485
443
  buildForKind(tx, job, buildReq) {
486
444
  const indexer = this.deps.indexer;
@@ -494,11 +452,7 @@ class CardanoWalletWorker {
494
452
  throw new errors_1.BackendError(`Unsupported job kind "${job.kind}"`, 400, error_codes_1.ERROR_CODES.INVALID_INPUT);
495
453
  }
496
454
  }
497
- /**
498
- * Submit tolerant of "already known": after a crash between submit and the
499
- * `submitted` transition, the retry re-submits the same CBOR — mempool dedup
500
- * answers with an already-submitted error that IS our success case.
501
- */
455
+ /** Submit treating "already known" as success: a re-submit of the same CBOR after a crash hits mempool dedup. */
502
456
  async submitWithAlreadyKnownTolerance(signedTxCbor) {
503
457
  try {
504
458
  return await this.deps.client.submitTransaction(signedTxCbor);
@@ -506,26 +460,24 @@ class CardanoWalletWorker {
506
460
  catch (err) {
507
461
  if (err instanceof errors_1.TransactionAlreadySubmittedError) {
508
462
  const txHash = (0, tx_build_helper_1.getTxHashFromCbor)(signedTxCbor);
509
- logger.info(`Submit reported tx already known — treating as success (${txHash})`);
463
+ logger.info(`Submit reported tx already known, treating as success (${txHash})`);
510
464
  return txHash;
511
465
  }
512
466
  throw err;
513
467
  }
514
468
  }
515
469
  async handleExecutionFailure(job, attempt, err) {
516
- // Only a pre-submit job may be re-queued (rebuild) or failed from here. Once the
517
- // row is `submitting`, a signed tx exists that may be in a mempool: rebuilding it
518
- // would double-pay and failing it would release the idempotency key on a
519
- // transaction the chain has not ruled on. Those rows go to reconciliation.
470
+ // Only a pre-submit (`building`) job may be re-queued or failed here; a `submitting` row's
471
+ // tx may be in a mempool, so it goes to reconciliation.
520
472
  const current = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.getJobById)(tx, job.ID)))
521
473
  .catch(() => null);
522
474
  if (current && current.status !== 'building') {
523
- logger.error(`Job ${job.ID}: execution error while ${current.status} — leaving the outcome to reconciliation:`, err);
475
+ logger.error(`Job ${job.ID}: execution error while ${current.status}, leaving the outcome to reconciliation:`, err);
524
476
  return;
525
477
  }
526
478
  if (isTransientJobError(err) && attempt < job.maxAttempts) {
527
479
  const backoff = retryBackoffMs(attempt);
528
- logger.warn(`Job ${job.ID}: transient failure on attempt ${attempt}/${job.maxAttempts} — retrying in ${backoff}ms:`, err);
480
+ logger.warn(`Job ${job.ID}: transient failure on attempt ${attempt}/${job.maxAttempts}, retrying in ${backoff}ms:`, err);
529
481
  await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.requeueForRetry)(tx, job.ID, err, new Date(Date.now() + backoff).toISOString()))).catch((persistErr) => logger.error(`Job ${job.ID}: retry re-queue failed:`, persistErr));
530
482
  return;
531
483
  }