@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
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.InvalidationUnfundedError = void 0;
7
+ exports.resendInvalidation = resendInvalidation;
8
+ exports.invalidationDepth = invalidationDepth;
9
+ exports.pickInvalidationInput = pickInvalidationInput;
10
+ exports.sendInvalidation = sendInvalidation;
11
+ exports.checkInvalidation = checkInvalidation;
12
+ const cds_1 = __importDefault(require("@sap/cds"));
13
+ const const_1 = require("../../utils/const");
14
+ const errors_1 = require("../../utils/errors");
15
+ const tx_build_helper_1 = require("../../utils/tx-build-helper");
16
+ const tx_utils_1 = require("../../utils/tx-utils");
17
+ const external_signer_1 = require("../signing/external-signer");
18
+ const landing_proof_1 = require("../signing/landing-proof");
19
+ const transaction_presence_1 = require("../transaction-presence");
20
+ const job_store_1 = require("./job-store");
21
+ const logger = cds_1.default.log('CardanoWalletWorker');
22
+ // A job transaction without an expiry can land as long as one of its inputs is unspent. A
23
+ // self-transfer that spends such an input ends that: once it is deeper than the node can roll back,
24
+ // the job's transaction can never land.
25
+ /** Lovelace the self-transfer sends back to the wallet; the change carries the rest. */
26
+ const INVALIDATION_LOVELACE = '1000000';
27
+ /** Sends stored self-transfer bytes again; a refusal proves nothing, the next check reads the chain. */
28
+ async function resendInvalidation(deps, job) {
29
+ try {
30
+ await deps.client.submitTransaction(job.invalidationTxCbor);
31
+ }
32
+ catch (err) {
33
+ if (!(err instanceof errors_1.TransactionAlreadySubmittedError))
34
+ logger.debug(`Job ${job.ID}: self-transfer ${job.invalidationTxHash} resend refused:`, err);
35
+ }
36
+ }
37
+ /** Blocks the self-transfer must be deep before it counts: the depth no rollback reaches. */
38
+ function invalidationDepth(network) {
39
+ return const_1.EPOCH_CONFIG_BY_NETWORK[network].securityParam;
40
+ }
41
+ const keyOf = (r) => `${r.txHash}#${r.outputIndex}`;
42
+ /** An unspent input of the job's transaction that the wallet holds, or null, and the UTxOs the wallet holds. */
43
+ async function pickInvalidationInput(deps, address, unspentInputs) {
44
+ const held = (await (0, tx_utils_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => deps.indexer.resolveAddressUtxos(tx, address))))
45
+ .map((u) => ({ txHash: u.txHash, outputIndex: u.outputIndex }));
46
+ const keys = new Set(held.map(keyOf));
47
+ return { input: unspentInputs.find((r) => keys.has(keyOf(r))) ?? null, held };
48
+ }
49
+ /** The self-transfer cannot be funded: the wallet has too little besides inputs it must not spend. */
50
+ class InvalidationUnfundedError extends Error {
51
+ }
52
+ exports.InvalidationUnfundedError = InvalidationUnfundedError;
53
+ // Builds, signs, stores and sends the self-transfer. It spends the input alone where that pays for it,
54
+ // else with other wallet UTxOs, never with an input another stale job waits on (`keep`). The bytes are
55
+ // stored before the send, as for a job. Returns its hash, or null when the job changed meanwhile.
56
+ async function sendInvalidation(deps, job, signer, input, around = {}) {
57
+ const address = signer.getAddress();
58
+ const keep = (around.keep ?? []).filter((r) => keyOf(r) !== keyOf(input));
59
+ const alone = [...(around.held ?? []).filter((r) => keyOf(r) !== keyOf(input)), ...keep];
60
+ const buildWith = (protectInputs) => (0, tx_utils_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => deps.indexer.indexSimpleBuildResult(tx, {
61
+ network: deps.network,
62
+ senderAddress: address,
63
+ changeAddress: address,
64
+ recipientAddress: address,
65
+ lovelaceAmount: INVALIDATION_LOVELACE,
66
+ forceInputs: [input],
67
+ ...(protectInputs.length ? { protectInputs } : {}),
68
+ })));
69
+ let build;
70
+ try {
71
+ build = await buildWith(alone);
72
+ }
73
+ catch (err) {
74
+ if (!(err instanceof errors_1.InsufficientFundsError))
75
+ throw err;
76
+ try {
77
+ build = await buildWith(keep);
78
+ }
79
+ catch (again) {
80
+ if (again instanceof errors_1.InsufficientFundsError)
81
+ throw new InvalidationUnfundedError(again.message);
82
+ throw again;
83
+ }
84
+ }
85
+ const signedTxCbor = signer.signTransaction(build.unsignedTxCbor, build.txBodyHash);
86
+ (0, external_signer_1.getExternalSignerModule)().verifyOrThrow(signedTxCbor, build.txBodyHash, { requiredSigners: [signer.getPublicKeyHash().toLowerCase()] });
87
+ const txHash = (0, tx_build_helper_1.getTxHashFromCbor)(signedTxCbor);
88
+ const stored = await (0, tx_utils_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.recordInvalidation)(tx, job.ID, { txHash, signedTxCbor }, job.invalidationTxHash)));
89
+ if (!stored)
90
+ return null;
91
+ try {
92
+ await deps.client.submitTransaction(signedTxCbor);
93
+ }
94
+ catch (err) {
95
+ // a refusal proves nothing here: the next check reads the chain
96
+ if (!(err instanceof errors_1.TransactionAlreadySubmittedError))
97
+ logger.warn(`Job ${job.ID}: invalidating tx ${txHash} was refused on send:`, err);
98
+ }
99
+ logger.warn(`Job ${job.ID}: tx ${job.txHash} has no expiry and has not landed; sent self-transfer ${txHash} spending ${input.txHash}#${input.outputIndex}`);
100
+ return txHash;
101
+ }
102
+ // Where the self-transfer stands. seen holds the tip height at which an own output was first seen,
103
+ // for backends that cannot look transactions up.
104
+ async function checkInvalidation(deps, job, seen) {
105
+ const txHash = job.invalidationTxHash;
106
+ const signedTxCbor = job.invalidationTxCbor;
107
+ const tipHeight = (await deps.client.getLatestBlock()).height ?? null;
108
+ const presence = await (0, transaction_presence_1.findOnChain)(deps.indexer, deps.client, txHash);
109
+ let height = presence?.height ?? null;
110
+ if (presence === undefined && tipHeight != null && await (0, landing_proof_1.hasUnspentOutput)(signedTxCbor, txHash, deps.client)) {
111
+ // a tip below the height seen means a rollback: count again from here
112
+ const first = seen.get(job.ID);
113
+ height = first != null && first <= tipHeight ? first : tipHeight;
114
+ seen.set(job.ID, height);
115
+ }
116
+ if (height != null && tipHeight != null) {
117
+ return tipHeight - height + 1 >= invalidationDepth(deps.network) ? 'confirmed' : 'included';
118
+ }
119
+ seen.delete(job.ID);
120
+ const sentAtMs = job.invalidationSentAt ? Date.parse(job.invalidationSentAt) : null;
121
+ const landing = await (0, landing_proof_1.judgeLanding)(signedTxCbor, txHash, deps, Number.isFinite(sentAtMs) ? sentAtMs : null);
122
+ if (landing.verdict === 'neverLands')
123
+ return 'retry';
124
+ if (landing.verdict === 'unresolved')
125
+ return 'unknown';
126
+ return 'waiting';
127
+ }
128
+ //# sourceMappingURL=invalidation.js.map
@@ -1,38 +1,5 @@
1
1
  import type { Transaction as CapTransaction } from '@sap/cds';
2
- /**
3
- * Wallet-worker job store (v2.0).
4
- *
5
- * Persistence layer for `CardanoWalletJobs` + `CardanoWorkerWallets`. Ports the two
6
- * hard-won CAP lessons from NIGHTGATE's background-job runner:
7
- *
8
- * 1. `insertJob` runs on the CALLER's ambient transaction. CAP wraps every action
9
- * handler in its own root tx which may already hold the SQLite write lock; a
10
- * detached insert would deadlock against it. The row simply commits together
11
- * with the handler, and the worker's dispatch loop only sees it once visible.
12
- * 2. Every transition helper runs in its own short `db.tx()` (callers pass a fresh
13
- * tx or use `runWithoutAmbientTx`), so the single pooled SQLite connection is
14
- * never held across the seconds-to-minutes job execution.
15
- *
16
- * State machine (see WALLET_WORKER_DESIGN.md §5):
17
- * pending → building → submitting → submitted → confirmed
18
- * │ │ │ └────→ failed
19
- * │ │ └→ submitted (reconciled) | failed (proven absent)
20
- * │ └→ pending (transient retry) | failed
21
- * └→ cancelled
22
- *
23
- * `submitting` is the durable pre-submit state: the signed CBOR, its hash and the
24
- * fee are committed BEFORE the transaction can reach the network, so a process
25
- * death anywhere around `submitTransaction` leaves a row that can be reconciled
26
- * against the chain (or re-submitted verbatim) instead of a `building` row that
27
- * looks un-submitted. It is a NON-terminal state, so it keeps holding the
28
- * idempotency key — a caller retry gets the same job back rather than a rebuild.
29
- *
30
- * Transitions use guarded UPDATEs (WHERE includes the expected source status) with
31
- * a read-back verification — the wallet lease already fences concurrent workers,
32
- * this is defense in depth. NOTE (CAP 10): numeric columns read back as STRINGS;
33
- * all reads coerce via `num()` so callers get clean numbers.
34
- */
35
- /** Per-wallet DB lease TTL — same rationale as the crawler lease. */
2
+ /** Per-wallet DB lease TTL. */
36
3
  export declare const WORKER_LEASE_TTL_MS = 15000;
37
4
  export declare const JOB_ERROR_CODES: {
38
5
  readonly PROCESS_RESTART: "PROCESS_RESTART";
@@ -41,9 +8,17 @@ export declare const JOB_ERROR_CODES: {
41
8
  readonly CANCELLED: "CANCELLED";
42
9
  /** Reconciliation proved the tx is not on-chain and the node rejects it for good. */
43
10
  readonly SUBMIT_REJECTED: "SUBMIT_REJECTED";
11
+ /** The tx is on chain with failing scripts: only its collateral was spent, the payment did not happen. */
12
+ readonly SCRIPT_FAILED: "SCRIPT_FAILED";
13
+ /** The tx can no longer land and nothing shows whether it did; an operator resolves the job. */
14
+ readonly OUTCOME_UNRESOLVED: "OUTCOME_UNRESOLVED";
15
+ /** An operator resolved an unresolved job as failed after reading the chain. */
16
+ readonly RESOLVED_FAILED: "RESOLVED_FAILED";
17
+ /** A confirmed self-transfer spent an input of the job's transaction, which had no expiry; it can never land. */
18
+ readonly INVALIDATED: "INVALIDATED";
44
19
  };
45
- export type WalletJobStatusValue = 'pending' | 'building' | 'submitting' | 'submitted' | 'confirmed' | 'failed' | 'cancelled';
46
- export type WalletJobKindValue = 'simpleAda' | 'metadata' | 'multiAsset' | 'mint' | 'plutusSpend' | 'submitSigned';
20
+ export type WalletJobStatusValue = 'pending' | 'building' | 'submitting' | 'submitted' | 'confirmed' | 'failed' | 'cancelled' | 'unresolved';
21
+ export type WalletJobKindValue = 'simpleAda' | 'metadata' | 'multiAsset' | 'mint' | 'plutusSpend' | 'payout' | 'submitSigned';
47
22
  export type WorkerSignerTypeValue = 'hsm' | 'software';
48
23
  export declare const WALLET_JOB_KINDS: readonly WalletJobKindValue[];
49
24
  /** Normalized, number-typed view of a job row. */
@@ -71,6 +46,11 @@ export interface WalletJobRow {
71
46
  createdAt: string | null;
72
47
  createdBy: string | null;
73
48
  finishedAt: string | null;
49
+ resolution: string | null;
50
+ invalidationTxHash: string | null;
51
+ invalidationTxCbor: string | null;
52
+ invalidationSentAt: string | null;
53
+ spendsNoWalletUtxo: boolean;
74
54
  }
75
55
  /** Normalized view of a worker-wallet row. */
76
56
  export interface WorkerWalletRow {
@@ -78,6 +58,7 @@ export interface WorkerWalletRow {
78
58
  signerType: WorkerSignerTypeValue;
79
59
  address: string | null;
80
60
  publicKeyHash: string | null;
61
+ requiresRole: string | null;
81
62
  enabled: boolean;
82
63
  leaseOwner: string | null;
83
64
  leaseUntil: string | null;
@@ -100,153 +81,83 @@ export interface InsertJobArgs {
100
81
  export interface InsertJobResult {
101
82
  jobId: string;
102
83
  status: WalletJobStatusValue;
103
- /** True when an idempotent retry matched an existing non-failed job. */
84
+ /** True when an idempotent retry matched the job that holds the key. */
104
85
  deduplicated: boolean;
105
86
  }
106
- /** The job that currently owns an idempotency key, or null when it is free. */
107
- /**
108
- * The stored claim for a caller's idempotency key, SCOPED TO THE PRINCIPAL that
109
- * submits. Two agents (two grants, two users) may both use `order-1` on the
110
- * same wallet: each must get its own job, never a "deduplicated" answer that
111
- * hands one the other's job id. A key from an owner-less caller (privileged
112
- * test context) stays as-is; an owned key becomes a hash of owner + key, which
113
- * fits the String(100) column whatever the owner id's length and never collides
114
- * with a plain key. The caller-visible `idempotencyKey` column keeps the raw key.
115
- */
87
+ /** Dedup key scoped to the submitting user. An owned key is hashed with an `o:` prefix, an owner-less key stays raw. */
116
88
  export declare function dedupKeyFor(owner: string | null | undefined, idempotencyKey: string): string;
117
- /**
118
- * Insert a job row ON THE CALLER'S transaction (NIGHTGATE lesson 1 — see module
119
- * docs). Idempotency: an active-or-successful row with the same (walletId, kind,
120
- * idempotencyKey) is returned instead of creating a duplicate. `failed` AND
121
- * `cancelled` rows do NOT block a retry — both are terminal states in which the
122
- * intended work never reached the chain, so re-using the key must be able to
123
- * actually execute it (a cancelled job would otherwise burn its key forever).
124
- *
125
- * The deduplication is enforced by the `dedup` UNIQUE constraint on
126
- * (walletId, kind, dedupKey), NOT by the read below: two concurrent retries — two
127
- * app instances, or two HANA sessions — can both read "no such job" before either
128
- * commits, and would both insert. The read is only a fast path; the constraint is
129
- * what makes it correct, and the loser of the race returns the winner's job.
130
- *
131
- * `dedupKey` holds the caller's key while the job owns it and the job's own ID
132
- * otherwise, so keyless jobs never collide and terminated jobs free their key
133
- * (see releaseDedupClaim) — without depending on how a database treats NULLs
134
- * inside a unique index.
135
- */
89
+ /** Inserts a job, or returns the job that holds the dedup key. The UNIQUE constraint settles races. */
136
90
  export declare function insertJob(db: CapTransaction, args: InsertJobArgs): Promise<InsertJobResult>;
137
91
  export declare function getJobById(db: CapTransaction, jobId: string): Promise<WalletJobRow | null>;
138
- /**
139
- * All dispatchable jobs: status pending, ordered by (priority, createdAt).
140
- * `notBefore` gating happens in JS — queue depths are small and the JS filter
141
- * avoids adapter-specific NULL/OR predicate quirks.
142
- */
143
- export declare function findDueJobs(db: CapTransaction, now?: Date): Promise<WalletJobRow[]>;
92
+ /** A due job's place in the dispatch order, without its payload. */
93
+ export interface DueJobRef {
94
+ ID: string;
95
+ walletId: string;
96
+ priority: number;
97
+ createdAt: string | null;
98
+ }
99
+ /** The next due pending job of a wallet by priority and age, or null. One row per call, whatever the queue holds. */
100
+ export declare function findNextDueJob(db: CapTransaction, walletId: string, now?: Date): Promise<DueJobRef | null>;
101
+ /** Number of jobs in a status. */
102
+ export declare function countJobs(db: CapTransaction, status: WalletJobStatusValue): Promise<number>;
103
+ /** Number of pending jobs, due or not. */
104
+ export declare function countPendingJobs(db: CapTransaction): Promise<number>;
144
105
  /** All jobs awaiting confirmation (used by the tracker on start/recovery). */
145
106
  export declare function findSubmittedJobs(db: CapTransaction): Promise<WalletJobRow[]>;
146
- /** Whether the wallet has a job currently in flight (building, submitting or submitted). */
107
+ /** Jobs of a wallet whose transaction an invalidating self-transfer is spending around. */
108
+ export declare function findInvalidatingJobs(db: CapTransaction, walletId: string): Promise<WalletJobRow[]>;
147
109
  export declare function walletHasActiveJob(db: CapTransaction, walletId: string): Promise<boolean>;
148
- /**
149
- * The oldest `submitting` row of a wallet whose lease no longer belongs to a live
150
- * executor — its submit outcome is unknown (crash, or a submit call that failed
151
- * ambiguously), so it needs chain reconciliation rather than a rebuild. Rows whose
152
- * wallet lease is still held are being worked on right now and are left alone.
153
- */
110
+ /** Marks a job whose transaction spends no UTxO the wallet holds, so it no longer holds the wallet queue. */
111
+ export declare function markSpendsNoWalletUtxo(db: CapTransaction, jobId: string): Promise<boolean>;
112
+ /** Oldest submitting row of a wallet without a live lease. Its submit outcome is unknown and needs a chain check. */
154
113
  export declare function findOrphanedSubmittingJob(db: CapTransaction, walletId: string, now?: Date): Promise<WalletJobRow | null>;
155
- /**
156
- * Give up a job's idempotency key by pointing `dedupKey` at the job's own ID
157
- * (unique by construction). Called on every terminal-but-unsuccessful transition,
158
- * which is what lets a caller re-use the key for a fresh attempt while the row
159
- * itself — including its `idempotencyKey` — stays intact for the audit trail.
160
- *
161
- * Not called for `confirmed`: a completed job keeps its key so a late duplicate
162
- * request resolves to it instead of paying again.
163
- */
114
+ /** Frees the idempotency key by pointing dedupKey at the job ID. */
164
115
  export declare function releaseDedupClaim(db: CapTransaction, jobId: string): Promise<void>;
165
116
  /** pending → building. Increments the attempt counter. Returns false when lost. */
166
117
  export declare function markBuilding(db: CapTransaction, jobId: string, attempt: number): Promise<boolean>;
167
- /**
168
- * building → submitting. Commits the signed transaction, its hash, the unsigned
169
- * CBOR and the fee BEFORE the tx is handed to a backend — the whole point of the
170
- * state: whatever happens to the process during `submitTransaction`, the exact
171
- * bytes that may be on-chain survive, and the job keeps holding its idempotency
172
- * key so a caller retry can never turn into a second, differently-built payment.
173
- * `submittedAt` is the attempt time (timeout base), not proof of acceptance.
174
- */
118
+ /** Stores the signed tx before the network call, so the exact bytes survive a crash. submittedAt is the attempt time. */
175
119
  export declare function markSubmitting(db: CapTransaction, jobId: string, artifacts: {
176
120
  txHash: string;
177
121
  unsignedTxCbor: string | null;
178
122
  signedTxCbor: string;
179
123
  fee: string | number | null;
180
124
  }): Promise<boolean>;
181
- /**
182
- * submitting → submitted: a backend accepted the tx (or reconciliation found it
183
- * on-chain). The artifacts are already durable from markSubmitting; only the hash
184
- * is re-asserted, in case the backend canonicalized it.
185
- */
125
+ /** submitting → submitted (accepted by a backend or found on-chain). Re-asserts only the hash. */
186
126
  export declare function markSubmitted(db: CapTransaction, jobId: string, txHash: string): Promise<boolean>;
187
- /**
188
- * building → pending (transient failure, attempts left). Keeps the error visible
189
- * and defers the next attempt via `notBefore` (exponential backoff).
190
- *
191
- * Guarded on `building` ON PURPOSE: once a job is `submitting` its tx may be in a
192
- * mempool, and re-queueing it would rebuild a different transaction from the same
193
- * request — the duplicate-payment path. Those rows go to reconciliation instead.
194
- */
127
+ /** Requeues a building job after a transient error. Never a submitting job, since a rebuild could pay twice. */
195
128
  export declare function requeueForRetry(db: CapTransaction, jobId: string, err: unknown, notBefore?: string): Promise<boolean>;
196
129
  /** Record where the submitted tx was seen on-chain (not yet at depth). */
197
130
  export declare function recordConfirmationPoint(db: CapTransaction, jobId: string, point: {
198
131
  slot: number | null;
199
132
  height: number | null;
200
133
  }): Promise<void>;
201
- /** A rollback invalidated the recorded confirmation point — back to watching. */
134
+ /** A rollback invalidated the recorded confirmation point. */
202
135
  export declare function clearConfirmationPoint(db: CapTransaction, jobId: string): Promise<void>;
203
136
  /** submitted → confirmed (depth reached). */
204
137
  export declare function markConfirmed(db: CapTransaction, jobId: string): Promise<boolean>;
205
- /**
206
- * Any active state → failed (terminal). Failing a `submitting`/`submitted` row is
207
- * only safe once the chain has been consulted — a failed row releases the
208
- * idempotency key, so a premature failure invites the caller's retry to pay twice.
209
- */
138
+ /** Fails a job that never sent a transaction and frees its key for the caller's retry. */
210
139
  export declare function markFailed(db: CapTransaction, jobId: string, code: string, err: unknown): Promise<boolean>;
140
+ export declare function markFailedAfterSend(db: CapTransaction, jobId: string, code: string, err: unknown): Promise<boolean>;
141
+ export declare function markUnresolved(db: CapTransaction, jobId: string, err: unknown): Promise<boolean>;
142
+ export declare function recordInvalidation(db: CapTransaction, jobId: string, invalidation: {
143
+ txHash: string;
144
+ signedTxCbor: string;
145
+ }, previous?: string | null): Promise<boolean>;
146
+ export declare function reopenFailedJob(db: CapTransaction, jobId: string, resolution: string): Promise<boolean>;
147
+ /** unresolved → confirmed or failed, as an operator read it on the chain. The key stays either way. */
148
+ export declare function resolveUnresolvedJob(db: CapTransaction, jobId: string, outcome: 'confirmed' | 'failed', resolution: string): Promise<boolean>;
211
149
  /** pending → cancelled. Only pending jobs are cancellable (the tx may otherwise reach the chain). */
212
150
  export declare function markCancelled(db: CapTransaction, jobId: string): Promise<boolean>;
213
151
  export interface RecoveryResult {
214
152
  /** `building` rows flipped to failed (never signed+stored, so never submitted). */
215
153
  failedBuilding: number;
216
- /** `submitted` rows to re-enqueue into the confirmation tracker — the chain decides. */
154
+ /** `submitted` rows for the confirmation tracker. The chain decides. */
217
155
  submittedToReconcile: WalletJobRow[];
218
- /** `submitting` rows with an unknown submit outcome — reconciled by the dispatch loop. */
156
+ /** `submitting` rows with an unknown outcome. The dispatch loop reconciles them. */
219
157
  submittingToReconcile: WalletJobRow[];
220
158
  }
221
- /**
222
- * Fail one wallet's orphaned `building` row(s) — but ONLY when the wallet's lease
223
- * is expired/unowned, i.e. no live instance is executing them. Rows whose wallet
224
- * lease is held belong to a running executor (possibly on another instance) and
225
- * must not be touched.
226
- *
227
- * Safe by construction: a `building` row is pre-submit by definition — the worker
228
- * transitions to `submitting` (with the signed CBOR) before anything can reach a
229
- * backend, so nothing that is still `building` has ever been sent. Rows that made
230
- * it past that point are `submitting` and are reconciled, never failed here.
231
- */
159
+ /** Fails orphaned building rows of a wallet without a live lease. Such rows were never sent. */
232
160
  export declare function failOrphanedBuildingJobs(db: CapTransaction, walletId: string, now?: Date): Promise<number>;
233
- /**
234
- * Boot-time recovery (design §8), by state:
235
- * - `building` — nothing was signed and stored yet, so nothing was submitted:
236
- * fail with PROCESS_RESTART (caller retries via idempotencyKey).
237
- * - `submitting` — the signed tx is durable but its fate is unknown: NOT failed
238
- * and NOT rebuilt. Returned so the dispatch loop reconciles it against the
239
- * chain and re-submits those exact bytes if needed.
240
- * - `submitted` — NOT failed: handed to the confirmation tracker; the chain
241
- * decides (found → confirm; absent past the timeout → TX_DROPPED).
242
- *
243
- * Multi-instance safety: a `building` row is only failed when its wallet's lease
244
- * is expired/unowned. A held lease means ANOTHER live instance is executing that
245
- * job right now (rolling deploy) — failing it here while its submit succeeds
246
- * would leave a failed row for an on-chain tx, and since failed rows don't block
247
- * idempotency dedup, the caller's documented retry would pay twice. Rows skipped
248
- * here are cleaned up later by failOrphanedBuildingJobs once the lease expires.
249
- */
250
161
  export declare function recoverInterruptedJobs(db: CapTransaction, now?: Date): Promise<RecoveryResult>;
251
162
  /** Idempotently register/refresh a configured wallet row (no key material). */
252
163
  export declare function upsertWalletRegistration(db: CapTransaction, wallet: {
@@ -254,14 +165,11 @@ export declare function upsertWalletRegistration(db: CapTransaction, wallet: {
254
165
  signerType: WorkerSignerTypeValue;
255
166
  address: string;
256
167
  publicKeyHash: string;
168
+ requiresRole?: string | null;
257
169
  }): Promise<void>;
258
170
  export declare function readWallet(db: CapTransaction, walletId: string): Promise<WorkerWalletRow | null>;
259
171
  export declare function listWallets(db: CapTransaction): Promise<WorkerWalletRow[]>;
260
- /**
261
- * Atomically acquire an expired/unowned per-wallet lease (compare-and-swap +
262
- * read-back verification, same shape as the crawler lease). At most one worker
263
- * instance may execute jobs for a wallet at any time.
264
- */
172
+ /** Takes a free wallet lease by compare-and-swap with read-back. One instance runs a wallet's jobs at a time. */
265
173
  export declare function tryAcquireWalletLease(db: CapTransaction, walletId: string, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
266
174
  /** Renew/fence the caller's lease. Call before every job-advancing write. */
267
175
  export declare function renewWalletLease(db: CapTransaction, walletId: string, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;