@odatano/core 1.11.0 → 2.0.0-rc.2
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.
- package/@cds-models/CardanoIndexerService/index.d.ts +142 -0
- package/@cds-models/CardanoIndexerService/index.js +23 -0
- package/@cds-models/CardanoODataService/index.d.ts +693 -2172
- package/@cds-models/CardanoODataService/index.js +88 -390
- package/@cds-models/CardanoSignService/index.d.ts +443 -1574
- package/@cds-models/CardanoSignService/index.js +62 -293
- package/@cds-models/CardanoTransactionService/index.d.ts +431 -1488
- package/@cds-models/CardanoTransactionService/index.js +60 -271
- package/@cds-models/CardanoWorkerService/index.d.ts +224 -0
- package/@cds-models/CardanoWorkerService/index.js +32 -0
- package/@cds-models/_/index.d.ts +70 -40
- package/@cds-models/_/index.js +17 -32
- package/@cds-models/cds/outbox/index.d.ts +28 -0
- package/@cds-models/index.d.ts +225 -522
- package/@cds-models/index.js +35 -218
- package/@cds-models/odatano/cardano/index.d.ts +896 -2947
- package/@cds-models/odatano/cardano/index.js +109 -536
- package/@cds-models/sap/common/index.d.ts +196 -600
- package/@cds-models/sap/common/index.js +28 -269
- package/README.md +36 -2
- package/db/schema.cds +283 -1
- package/db/types.cds +48 -0
- package/package.json +173 -164
- package/src/index.d.ts +1 -1
- package/src/index.js +10 -2
- package/src/plugin.js +12 -2
- package/srv/blockchain/backends/blockfrost-backend.d.ts +21 -2
- package/srv/blockchain/backends/blockfrost-backend.js +68 -15
- package/srv/blockchain/backends/cardano-backend.d.ts +69 -0
- package/srv/blockchain/backends/cardano-backend.js +13 -0
- package/srv/blockchain/backends/koios-backend.d.ts +26 -2
- package/srv/blockchain/backends/koios-backend.js +147 -15
- package/srv/blockchain/backends/ogmios-backend.d.ts +37 -6
- package/srv/blockchain/backends/ogmios-backend.js +254 -5
- package/srv/blockchain/cardano-client.d.ts +19 -0
- package/srv/blockchain/cardano-client.js +36 -0
- package/srv/blockchain/cardano-indexer.d.ts +50 -1
- package/srv/blockchain/cardano-indexer.js +191 -0
- package/srv/blockchain/crawler/crawler.d.ts +151 -0
- package/srv/blockchain/crawler/crawler.js +677 -0
- package/srv/blockchain/crawler/hooks.d.ts +43 -0
- package/srv/blockchain/crawler/hooks.js +62 -0
- package/srv/blockchain/crawler/index.d.ts +26 -0
- package/srv/blockchain/crawler/index.js +135 -0
- package/srv/blockchain/crawler/sync-state.d.ts +94 -0
- package/srv/blockchain/crawler/sync-state.js +265 -0
- package/srv/blockchain/signing/hsm-signer.d.ts +45 -0
- package/srv/blockchain/signing/hsm-signer.js +8 -1
- package/srv/blockchain/wallet-worker/build-request.d.ts +26 -0
- package/srv/blockchain/wallet-worker/build-request.js +341 -0
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +86 -0
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +228 -0
- package/srv/blockchain/wallet-worker/index.d.ts +14 -0
- package/srv/blockchain/wallet-worker/index.js +80 -0
- package/srv/blockchain/wallet-worker/job-store.d.ts +261 -0
- package/srv/blockchain/wallet-worker/job-store.js +564 -0
- package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +43 -0
- package/srv/blockchain/wallet-worker/lease-heartbeat.js +99 -0
- package/srv/blockchain/wallet-worker/signers.d.ts +57 -0
- package/srv/blockchain/wallet-worker/signers.js +131 -0
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +145 -0
- package/srv/blockchain/wallet-worker/wallet-worker.js +542 -0
- package/srv/cardano-indexer-service.cds +73 -0
- package/srv/cardano-indexer-service.d.ts +2 -0
- package/srv/cardano-indexer-service.js +76 -0
- package/srv/cardano-service.js +76 -5
- package/srv/cardano-tx-service.d.ts +1 -11
- package/srv/cardano-tx-service.js +11 -162
- package/srv/cardano-worker-service.cds +125 -0
- package/srv/cardano-worker-service.d.ts +2 -0
- package/srv/cardano-worker-service.js +199 -0
- package/srv/server.d.ts +32 -1
- package/srv/server.js +229 -36
- package/srv/utils/collections.d.ts +13 -0
- package/srv/utils/collections.js +24 -0
- package/srv/utils/crypto.d.ts +16 -0
- package/srv/utils/crypto.js +75 -0
- package/srv/utils/error-codes.d.ts +6 -0
- package/srv/utils/error-codes.js +6 -0
- package/srv/utils/errors.d.ts +12 -0
- package/srv/utils/errors.js +45 -0
- package/srv/utils/mappers.js +13 -3
- package/srv/utils/service-events.d.ts +26 -0
- package/srv/utils/service-events.js +46 -0
- package/srv/utils/tx-request-parsers.d.ts +58 -0
- package/srv/utils/tx-request-parsers.js +170 -0
- package/srv/utils/tx-utils.d.ts +2 -1
- package/srv/utils/tx-utils.js +3 -2
- package/srv/utils/types.d.ts +2 -1
- package/@cds-models/CardanoODataService/index.d.ts.map +0 -1
- package/@cds-models/CardanoODataService/index.js.map +0 -1
- package/@cds-models/CardanoODataService/index.ts +0 -776
- package/@cds-models/CardanoSignService/index.d.ts.map +0 -1
- package/@cds-models/CardanoSignService/index.js.map +0 -1
- package/@cds-models/CardanoSignService/index.ts +0 -569
- package/@cds-models/CardanoTransactionService/index.d.ts.map +0 -1
- package/@cds-models/CardanoTransactionService/index.js.map +0 -1
- package/@cds-models/CardanoTransactionService/index.ts +0 -526
- package/@cds-models/_/index.d.ts.map +0 -1
- package/@cds-models/_/index.js.map +0 -1
- package/@cds-models/_/index.ts +0 -96
- package/@cds-models/cds/outbox/index.ts +0 -27
- package/@cds-models/index.d.ts.map +0 -1
- package/@cds-models/index.js.map +0 -1
- package/@cds-models/index.ts +0 -245
- package/@cds-models/odatano/cardano/index.d.ts.map +0 -1
- package/@cds-models/odatano/cardano/index.js.map +0 -1
- package/@cds-models/odatano/cardano/index.ts +0 -789
- package/@cds-models/sap/common/index.d.ts.map +0 -1
- package/@cds-models/sap/common/index.js.map +0 -1
- package/@cds-models/sap/common/index.ts +0 -249
|
@@ -0,0 +1,228 @@
|
|
|
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.ConfirmationTracker = void 0;
|
|
7
|
+
const cds_1 = __importDefault(require("@sap/cds"));
|
|
8
|
+
const errors_1 = require("../../utils/errors");
|
|
9
|
+
const hooks_1 = require("../crawler/hooks");
|
|
10
|
+
const job_store_1 = require("./job-store");
|
|
11
|
+
const logger = cds_1.default.log('CardanoWalletWorker');
|
|
12
|
+
class ConfirmationTracker {
|
|
13
|
+
deps;
|
|
14
|
+
pending = new Map();
|
|
15
|
+
blockListener = (event) => this.onBlockIndexed(event);
|
|
16
|
+
reorgListener = (event) => { void this.onReorg(event); };
|
|
17
|
+
pollTimer = null;
|
|
18
|
+
running = false;
|
|
19
|
+
polling = false;
|
|
20
|
+
lastKnownTipHeight = null;
|
|
21
|
+
constructor(deps) {
|
|
22
|
+
this.deps = deps;
|
|
23
|
+
}
|
|
24
|
+
start() {
|
|
25
|
+
if (this.running)
|
|
26
|
+
return;
|
|
27
|
+
this.running = true;
|
|
28
|
+
(0, hooks_1.registerBlockIndexedListener)(this.blockListener);
|
|
29
|
+
(0, hooks_1.registerReorgListener)(this.reorgListener);
|
|
30
|
+
this.pollTimer = setInterval(() => { void this.pollOnce(); }, this.deps.options.pollIntervalMs);
|
|
31
|
+
this.pollTimer.unref?.();
|
|
32
|
+
}
|
|
33
|
+
stop() {
|
|
34
|
+
this.running = false;
|
|
35
|
+
(0, hooks_1.unregisterBlockIndexedListener)(this.blockListener);
|
|
36
|
+
(0, hooks_1.unregisterReorgListener)(this.reorgListener);
|
|
37
|
+
if (this.pollTimer) {
|
|
38
|
+
clearInterval(this.pollTimer);
|
|
39
|
+
this.pollTimer = null;
|
|
40
|
+
}
|
|
41
|
+
this.pending.clear();
|
|
42
|
+
}
|
|
43
|
+
/** Number of jobs currently awaiting confirmation. */
|
|
44
|
+
size() {
|
|
45
|
+
return this.pending.size;
|
|
46
|
+
}
|
|
47
|
+
/** Register a submitted job for confirmation watching. Idempotent per jobId. */
|
|
48
|
+
track(job) {
|
|
49
|
+
if (this.pending.has(job.jobId))
|
|
50
|
+
return;
|
|
51
|
+
this.pending.set(job.jobId, {
|
|
52
|
+
jobId: job.jobId,
|
|
53
|
+
walletId: job.walletId,
|
|
54
|
+
kind: job.kind ?? null,
|
|
55
|
+
txHash: job.txHash,
|
|
56
|
+
signedTxCbor: job.signedTxCbor,
|
|
57
|
+
submittedAt: job.submittedAt ?? new Date().toISOString(),
|
|
58
|
+
foundSlot: job.confirmedSlot ?? null,
|
|
59
|
+
foundHeight: job.confirmedHeight ?? null,
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
// ---- Crawler hook path -----------------------------------------------------
|
|
63
|
+
onBlockIndexed(event) {
|
|
64
|
+
if (!this.running || this.pending.size === 0)
|
|
65
|
+
return;
|
|
66
|
+
const tipHeight = event.tipHeight ?? event.height;
|
|
67
|
+
if (tipHeight != null) {
|
|
68
|
+
this.lastKnownTipHeight = Math.max(this.lastKnownTipHeight ?? 0, tipHeight);
|
|
69
|
+
}
|
|
70
|
+
const txHashes = new Set(event.txHashes);
|
|
71
|
+
const found = [...this.pending.values()].filter(j => j.foundHeight == null && txHashes.has(j.txHash));
|
|
72
|
+
// Persist + depth-check detached: hook callers (the crawler) must not await us.
|
|
73
|
+
void (async () => {
|
|
74
|
+
for (const job of found) {
|
|
75
|
+
job.foundSlot = event.slot;
|
|
76
|
+
job.foundHeight = event.height;
|
|
77
|
+
try {
|
|
78
|
+
await cds_1.default.tx((tx) => (0, job_store_1.recordConfirmationPoint)(tx, job.jobId, { slot: event.slot, height: event.height }));
|
|
79
|
+
logger.info(`Job ${job.jobId}: tx ${job.txHash} included in block ${event.hash} (height ${event.height})`);
|
|
80
|
+
}
|
|
81
|
+
catch (err) {
|
|
82
|
+
logger.warn(`Job ${job.jobId}: failed to persist confirmation point (will retry via polling):`, err);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
await this.confirmMature();
|
|
86
|
+
})();
|
|
87
|
+
}
|
|
88
|
+
async onReorg(event) {
|
|
89
|
+
if (!this.running)
|
|
90
|
+
return;
|
|
91
|
+
// The pre-fork tip no longer exists — clamp (or drop) lastKnownTipHeight so
|
|
92
|
+
// confirmations are never counted against it. Without this, a tx re-included
|
|
93
|
+
// on the new chain would reach "depth" instantly via the stale tip height,
|
|
94
|
+
// defeating the confirmation-depth guarantee exactly in the rollback case.
|
|
95
|
+
if (event.forkHeight != null) {
|
|
96
|
+
if (this.lastKnownTipHeight != null && this.lastKnownTipHeight > event.forkHeight) {
|
|
97
|
+
this.lastKnownTipHeight = event.forkHeight;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
this.lastKnownTipHeight = null; // unknown fork height → re-learn from the next block/poll
|
|
102
|
+
}
|
|
103
|
+
for (const job of this.pending.values()) {
|
|
104
|
+
if (job.foundSlot != null && job.foundSlot > event.forkSlot) {
|
|
105
|
+
logger.warn(`Job ${job.jobId}: confirmation point (slot ${job.foundSlot}) rolled back past fork ${event.forkSlot} — re-watching`);
|
|
106
|
+
job.foundSlot = null;
|
|
107
|
+
job.foundHeight = null;
|
|
108
|
+
try {
|
|
109
|
+
await cds_1.default.tx((tx) => (0, job_store_1.clearConfirmationPoint)(tx, job.jobId));
|
|
110
|
+
}
|
|
111
|
+
catch (err) {
|
|
112
|
+
logger.warn(`Job ${job.jobId}: failed to clear confirmation point:`, err);
|
|
113
|
+
}
|
|
114
|
+
if (this.deps.options.resubmitOnRollback && job.signedTxCbor) {
|
|
115
|
+
// SAME signed CBOR only — never a rebuild. "Already known" means the tx
|
|
116
|
+
// survived into the new chain's mempool; that is success, not an error.
|
|
117
|
+
try {
|
|
118
|
+
await this.deps.client.submitTransaction(job.signedTxCbor);
|
|
119
|
+
logger.info(`Job ${job.jobId}: re-submitted original signed tx after rollback`);
|
|
120
|
+
}
|
|
121
|
+
catch (err) {
|
|
122
|
+
if (err instanceof errors_1.TransactionAlreadySubmittedError) {
|
|
123
|
+
logger.debug(`Job ${job.jobId}: tx already known after rollback — nothing to do`);
|
|
124
|
+
}
|
|
125
|
+
else {
|
|
126
|
+
logger.warn(`Job ${job.jobId}: rollback re-submit failed (polling continues to watch):`, err);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
// ---- Polling path ------------------------------------------------------------
|
|
134
|
+
/** One polling round. Public for tests; guarded against overlapping rounds. */
|
|
135
|
+
async pollOnce() {
|
|
136
|
+
if (!this.running || this.polling || this.pending.size === 0)
|
|
137
|
+
return;
|
|
138
|
+
this.polling = true;
|
|
139
|
+
try {
|
|
140
|
+
// Tip first — also serves the depth check for hook-found entries when the
|
|
141
|
+
// crawler is off.
|
|
142
|
+
try {
|
|
143
|
+
const tip = await this.deps.client.getLatestBlock();
|
|
144
|
+
if (tip.height != null) {
|
|
145
|
+
this.lastKnownTipHeight = Math.max(this.lastKnownTipHeight ?? 0, tip.height);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
catch (err) {
|
|
149
|
+
logger.debug('Confirmation polling: tip lookup failed (skipping round):', err);
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
for (const job of [...this.pending.values()]) {
|
|
153
|
+
if (job.foundHeight != null)
|
|
154
|
+
continue;
|
|
155
|
+
try {
|
|
156
|
+
const tx = await this.deps.client.getTransaction(job.txHash);
|
|
157
|
+
job.foundSlot = tx.slot ?? null;
|
|
158
|
+
job.foundHeight = tx.blockHeight ?? null;
|
|
159
|
+
await cds_1.default.tx((t) => (0, job_store_1.recordConfirmationPoint)(t, job.jobId, { slot: job.foundSlot, height: job.foundHeight }));
|
|
160
|
+
logger.info(`Job ${job.jobId}: tx ${job.txHash} found on-chain at height ${job.foundHeight} (polling)`);
|
|
161
|
+
}
|
|
162
|
+
catch (err) {
|
|
163
|
+
// The client's failover wraps per-backend 404s into AllBackendsFailedError,
|
|
164
|
+
// so a plain `instanceof NotFoundError` check never fires — the helper also
|
|
165
|
+
// accepts "every consulted backend said 404" as proof of absence.
|
|
166
|
+
if ((0, errors_1.isNotFoundOnAllBackends)(err)) {
|
|
167
|
+
// Not on-chain yet — check the mempool-TTL timeout.
|
|
168
|
+
const age = Date.now() - Date.parse(job.submittedAt);
|
|
169
|
+
if (age > this.deps.options.confirmationTimeoutMs) {
|
|
170
|
+
await this.finalize(job, 'failed', job_store_1.JOB_ERROR_CODES.TX_DROPPED, new Error(`Transaction ${job.txHash} not seen on-chain within ${this.deps.options.confirmationTimeoutMs}ms of submission`));
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
else {
|
|
174
|
+
logger.debug(`Job ${job.jobId}: confirmation lookup failed (transient, next round retries):`, err);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
await this.confirmMature();
|
|
179
|
+
}
|
|
180
|
+
finally {
|
|
181
|
+
this.polling = false;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
// ---- Shared -----------------------------------------------------------------
|
|
185
|
+
/** Confirm every found job whose depth requirement is met by the known tip. */
|
|
186
|
+
async confirmMature() {
|
|
187
|
+
const tip = this.lastKnownTipHeight;
|
|
188
|
+
if (tip == null)
|
|
189
|
+
return;
|
|
190
|
+
for (const job of [...this.pending.values()]) {
|
|
191
|
+
if (job.foundHeight == null)
|
|
192
|
+
continue;
|
|
193
|
+
const confirmations = tip - job.foundHeight + 1;
|
|
194
|
+
if (confirmations >= this.deps.options.confirmationDepth) {
|
|
195
|
+
await this.finalize(job, 'confirmed');
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
async finalize(job, outcome, errorCode, err) {
|
|
200
|
+
try {
|
|
201
|
+
await cds_1.default.tx(async (tx) => {
|
|
202
|
+
const transitioned = outcome === 'confirmed'
|
|
203
|
+
? await (0, job_store_1.markConfirmed)(tx, job.jobId)
|
|
204
|
+
: await (0, job_store_1.markFailed)(tx, job.jobId, errorCode ?? 'FAILED', err ?? new Error('unknown'));
|
|
205
|
+
if (transitioned) {
|
|
206
|
+
await (0, job_store_1.bumpWalletStats)(tx, job.walletId, outcome);
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
catch (persistErr) {
|
|
211
|
+
logger.error(`Job ${job.jobId}: failed to persist terminal state ${outcome} (next round retries):`, persistErr);
|
|
212
|
+
return; // keep tracking — the next poll round retries the transition
|
|
213
|
+
}
|
|
214
|
+
this.pending.delete(job.jobId);
|
|
215
|
+
logger.info(`Job ${job.jobId}: ${outcome}${outcome === 'failed' ? ` (${errorCode})` : ''}`);
|
|
216
|
+
this.deps.onFinal?.({
|
|
217
|
+
jobId: job.jobId,
|
|
218
|
+
walletId: job.walletId,
|
|
219
|
+
outcome,
|
|
220
|
+
kind: job.kind,
|
|
221
|
+
txHash: job.txHash,
|
|
222
|
+
errorCode,
|
|
223
|
+
errorMessage: err instanceof Error ? err.message : err != null ? String(err) : undefined,
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
exports.ConfirmationTracker = ConfirmationTracker;
|
|
228
|
+
//# sourceMappingURL=confirmation-tracker.js.map
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { CardanoWalletWorker, type WalletWorkerConfig, type WalletWorkerDeps } from './wallet-worker';
|
|
2
|
+
export type StartWalletWorkerDeps = Omit<WalletWorkerDeps, 'instanceId'> & {
|
|
3
|
+
instanceId?: string;
|
|
4
|
+
};
|
|
5
|
+
export type { WalletWorkerConfig };
|
|
6
|
+
/** Start the worker (idempotent — a no-op when one is already running). */
|
|
7
|
+
export declare function startWalletWorker(deps: StartWalletWorkerDeps): Promise<void>;
|
|
8
|
+
/** Stop the local worker (in-flight execution steps are awaited). */
|
|
9
|
+
export declare function stopWalletWorker(): Promise<void>;
|
|
10
|
+
/** Whether a worker is currently running in this process. */
|
|
11
|
+
export declare function isWalletWorkerRunning(): boolean;
|
|
12
|
+
/** The active worker instance, or null. */
|
|
13
|
+
export declare function getWalletWorker(): CardanoWalletWorker | null;
|
|
14
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,80 @@
|
|
|
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.startWalletWorker = startWalletWorker;
|
|
7
|
+
exports.stopWalletWorker = stopWalletWorker;
|
|
8
|
+
exports.isWalletWorkerRunning = isWalletWorkerRunning;
|
|
9
|
+
exports.getWalletWorker = getWalletWorker;
|
|
10
|
+
const cds_1 = __importDefault(require("@sap/cds"));
|
|
11
|
+
const node_crypto_1 = require("node:crypto");
|
|
12
|
+
const wallet_worker_1 = require("./wallet-worker");
|
|
13
|
+
const logger = cds_1.default.log('CardanoWalletWorker');
|
|
14
|
+
/**
|
|
15
|
+
* Module-level singleton lifecycle for the wallet worker. Mirrors the crawler's
|
|
16
|
+
* srv/blockchain/crawler/index.ts: one active worker per process, started
|
|
17
|
+
* fire-and-forget from the server's `served` hook and controlled (pause/resume/
|
|
18
|
+
* status) via the worker control service.
|
|
19
|
+
*
|
|
20
|
+
* Unlike the crawler there is no standby machinery: every instance may run a
|
|
21
|
+
* dispatch loop — the per-WALLET DB leases decide which instance executes a
|
|
22
|
+
* given wallet's jobs, so failover is inherent.
|
|
23
|
+
*/
|
|
24
|
+
let active = null;
|
|
25
|
+
let lifecycleQueue = Promise.resolve();
|
|
26
|
+
/** Start the worker (idempotent — a no-op when one is already running). */
|
|
27
|
+
async function startWalletWorker(deps) {
|
|
28
|
+
return serializeLifecycle(async () => {
|
|
29
|
+
if (active?.isRunning()) {
|
|
30
|
+
logger.debug('startWalletWorker: already running');
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
if (active) {
|
|
34
|
+
const previous = active;
|
|
35
|
+
await previous.stop();
|
|
36
|
+
if (active === previous)
|
|
37
|
+
active = null;
|
|
38
|
+
}
|
|
39
|
+
const candidate = new wallet_worker_1.CardanoWalletWorker({
|
|
40
|
+
...deps,
|
|
41
|
+
instanceId: deps.instanceId ?? `${process.pid}:${(0, node_crypto_1.randomUUID)()}`,
|
|
42
|
+
});
|
|
43
|
+
active = candidate;
|
|
44
|
+
try {
|
|
45
|
+
await candidate.start();
|
|
46
|
+
}
|
|
47
|
+
catch (err) {
|
|
48
|
+
if (active === candidate)
|
|
49
|
+
active = null;
|
|
50
|
+
throw err;
|
|
51
|
+
}
|
|
52
|
+
if (!candidate.isRunning() && active === candidate)
|
|
53
|
+
active = null;
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
/** Stop the local worker (in-flight execution steps are awaited). */
|
|
57
|
+
async function stopWalletWorker() {
|
|
58
|
+
return serializeLifecycle(async () => {
|
|
59
|
+
const worker = active;
|
|
60
|
+
if (!worker)
|
|
61
|
+
return;
|
|
62
|
+
await worker.stop();
|
|
63
|
+
if (active === worker)
|
|
64
|
+
active = null;
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
/** Whether a worker is currently running in this process. */
|
|
68
|
+
function isWalletWorkerRunning() {
|
|
69
|
+
return active?.isRunning() ?? false;
|
|
70
|
+
}
|
|
71
|
+
/** The active worker instance, or null. */
|
|
72
|
+
function getWalletWorker() {
|
|
73
|
+
return active;
|
|
74
|
+
}
|
|
75
|
+
function serializeLifecycle(operation) {
|
|
76
|
+
const result = lifecycleQueue.then(operation, operation);
|
|
77
|
+
lifecycleQueue = result.catch(() => undefined);
|
|
78
|
+
return result;
|
|
79
|
+
}
|
|
80
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,261 @@
|
|
|
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. */
|
|
36
|
+
export declare const WORKER_LEASE_TTL_MS = 15000;
|
|
37
|
+
export declare const JOB_ERROR_CODES: {
|
|
38
|
+
readonly PROCESS_RESTART: "PROCESS_RESTART";
|
|
39
|
+
readonly TX_DROPPED: "TX_DROPPED";
|
|
40
|
+
readonly RETRIES_EXHAUSTED: "RETRIES_EXHAUSTED";
|
|
41
|
+
readonly CANCELLED: "CANCELLED";
|
|
42
|
+
/** Reconciliation proved the tx is not on-chain and the node rejects it for good. */
|
|
43
|
+
readonly SUBMIT_REJECTED: "SUBMIT_REJECTED";
|
|
44
|
+
};
|
|
45
|
+
export type WalletJobStatusValue = 'pending' | 'building' | 'submitting' | 'submitted' | 'confirmed' | 'failed' | 'cancelled';
|
|
46
|
+
export type WalletJobKindValue = 'simpleAda' | 'metadata' | 'multiAsset' | 'mint' | 'plutusSpend' | 'submitSigned';
|
|
47
|
+
export type WorkerSignerTypeValue = 'hsm' | 'software';
|
|
48
|
+
export declare const WALLET_JOB_KINDS: readonly WalletJobKindValue[];
|
|
49
|
+
/** Normalized, number-typed view of a job row. */
|
|
50
|
+
export interface WalletJobRow {
|
|
51
|
+
ID: string;
|
|
52
|
+
walletId: string;
|
|
53
|
+
kind: WalletJobKindValue;
|
|
54
|
+
status: WalletJobStatusValue;
|
|
55
|
+
idempotencyKey: string | null;
|
|
56
|
+
request: string | null;
|
|
57
|
+
priority: number;
|
|
58
|
+
notBefore: string | null;
|
|
59
|
+
attempt: number;
|
|
60
|
+
maxAttempts: number;
|
|
61
|
+
txHash: string | null;
|
|
62
|
+
unsignedTxCbor: string | null;
|
|
63
|
+
signedTxCbor: string | null;
|
|
64
|
+
fee: number | null;
|
|
65
|
+
submittedAt: string | null;
|
|
66
|
+
confirmedAt: string | null;
|
|
67
|
+
confirmedSlot: number | null;
|
|
68
|
+
confirmedHeight: number | null;
|
|
69
|
+
errorCode: string | null;
|
|
70
|
+
errorMessage: string | null;
|
|
71
|
+
createdAt: string | null;
|
|
72
|
+
createdBy: string | null;
|
|
73
|
+
finishedAt: string | null;
|
|
74
|
+
}
|
|
75
|
+
/** Normalized view of a worker-wallet row. */
|
|
76
|
+
export interface WorkerWalletRow {
|
|
77
|
+
walletId: string;
|
|
78
|
+
signerType: WorkerSignerTypeValue;
|
|
79
|
+
address: string | null;
|
|
80
|
+
publicKeyHash: string | null;
|
|
81
|
+
enabled: boolean;
|
|
82
|
+
leaseOwner: string | null;
|
|
83
|
+
leaseUntil: string | null;
|
|
84
|
+
lastJobAt: string | null;
|
|
85
|
+
jobsConfirmed: number;
|
|
86
|
+
jobsFailed: number;
|
|
87
|
+
}
|
|
88
|
+
export { runWithoutAmbientTx } from '../../utils/tx-utils';
|
|
89
|
+
export interface InsertJobArgs {
|
|
90
|
+
walletId: string;
|
|
91
|
+
kind: WalletJobKindValue;
|
|
92
|
+
/** Build-action payload as a JSON string (already validated + size-limited). */
|
|
93
|
+
request: string;
|
|
94
|
+
idempotencyKey?: string | null;
|
|
95
|
+
priority?: number;
|
|
96
|
+
notBefore?: string | null;
|
|
97
|
+
maxAttempts?: number;
|
|
98
|
+
createdBy?: string | null;
|
|
99
|
+
}
|
|
100
|
+
export interface InsertJobResult {
|
|
101
|
+
jobId: string;
|
|
102
|
+
status: WalletJobStatusValue;
|
|
103
|
+
/** True when an idempotent retry matched an existing non-failed job. */
|
|
104
|
+
deduplicated: boolean;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Insert a job row ON THE CALLER'S transaction (NIGHTGATE lesson 1 — see module
|
|
108
|
+
* docs). Idempotency: an active-or-successful row with the same (walletId, kind,
|
|
109
|
+
* idempotencyKey) is returned instead of creating a duplicate. `failed` AND
|
|
110
|
+
* `cancelled` rows do NOT block a retry — both are terminal states in which the
|
|
111
|
+
* intended work never reached the chain, so re-using the key must be able to
|
|
112
|
+
* actually execute it (a cancelled job would otherwise burn its key forever).
|
|
113
|
+
*
|
|
114
|
+
* The deduplication is enforced by the `dedup` UNIQUE constraint on
|
|
115
|
+
* (walletId, kind, dedupKey), NOT by the read below: two concurrent retries — two
|
|
116
|
+
* app instances, or two HANA sessions — can both read "no such job" before either
|
|
117
|
+
* commits, and would both insert. The read is only a fast path; the constraint is
|
|
118
|
+
* what makes it correct, and the loser of the race returns the winner's job.
|
|
119
|
+
*
|
|
120
|
+
* `dedupKey` holds the caller's key while the job owns it and the job's own ID
|
|
121
|
+
* otherwise, so keyless jobs never collide and terminated jobs free their key
|
|
122
|
+
* (see releaseDedupClaim) — without depending on how a database treats NULLs
|
|
123
|
+
* inside a unique index.
|
|
124
|
+
*/
|
|
125
|
+
export declare function insertJob(db: CapTransaction, args: InsertJobArgs): Promise<InsertJobResult>;
|
|
126
|
+
export declare function getJobById(db: CapTransaction, jobId: string): Promise<WalletJobRow | null>;
|
|
127
|
+
/**
|
|
128
|
+
* All dispatchable jobs: status pending, ordered by (priority, createdAt).
|
|
129
|
+
* `notBefore` gating happens in JS — queue depths are small and the JS filter
|
|
130
|
+
* avoids adapter-specific NULL/OR predicate quirks.
|
|
131
|
+
*/
|
|
132
|
+
export declare function findDueJobs(db: CapTransaction, now?: Date): Promise<WalletJobRow[]>;
|
|
133
|
+
/** All jobs awaiting confirmation (used by the tracker on start/recovery). */
|
|
134
|
+
export declare function findSubmittedJobs(db: CapTransaction): Promise<WalletJobRow[]>;
|
|
135
|
+
/** Whether the wallet has a job currently in flight (building, submitting or submitted). */
|
|
136
|
+
export declare function walletHasActiveJob(db: CapTransaction, walletId: string): Promise<boolean>;
|
|
137
|
+
/**
|
|
138
|
+
* The oldest `submitting` row of a wallet whose lease no longer belongs to a live
|
|
139
|
+
* executor — its submit outcome is unknown (crash, or a submit call that failed
|
|
140
|
+
* ambiguously), so it needs chain reconciliation rather than a rebuild. Rows whose
|
|
141
|
+
* wallet lease is still held are being worked on right now and are left alone.
|
|
142
|
+
*/
|
|
143
|
+
export declare function findOrphanedSubmittingJob(db: CapTransaction, walletId: string, now?: Date): Promise<WalletJobRow | null>;
|
|
144
|
+
/**
|
|
145
|
+
* Give up a job's idempotency key by pointing `dedupKey` at the job's own ID
|
|
146
|
+
* (unique by construction). Called on every terminal-but-unsuccessful transition,
|
|
147
|
+
* which is what lets a caller re-use the key for a fresh attempt while the row
|
|
148
|
+
* itself — including its `idempotencyKey` — stays intact for the audit trail.
|
|
149
|
+
*
|
|
150
|
+
* Not called for `confirmed`: a completed job keeps its key so a late duplicate
|
|
151
|
+
* request resolves to it instead of paying again.
|
|
152
|
+
*/
|
|
153
|
+
export declare function releaseDedupClaim(db: CapTransaction, jobId: string): Promise<void>;
|
|
154
|
+
/** pending → building. Increments the attempt counter. Returns false when lost. */
|
|
155
|
+
export declare function markBuilding(db: CapTransaction, jobId: string, attempt: number): Promise<boolean>;
|
|
156
|
+
/**
|
|
157
|
+
* building → submitting. Commits the signed transaction, its hash, the unsigned
|
|
158
|
+
* CBOR and the fee BEFORE the tx is handed to a backend — the whole point of the
|
|
159
|
+
* state: whatever happens to the process during `submitTransaction`, the exact
|
|
160
|
+
* bytes that may be on-chain survive, and the job keeps holding its idempotency
|
|
161
|
+
* key so a caller retry can never turn into a second, differently-built payment.
|
|
162
|
+
* `submittedAt` is the attempt time (timeout base), not proof of acceptance.
|
|
163
|
+
*/
|
|
164
|
+
export declare function markSubmitting(db: CapTransaction, jobId: string, artifacts: {
|
|
165
|
+
txHash: string;
|
|
166
|
+
unsignedTxCbor: string | null;
|
|
167
|
+
signedTxCbor: string;
|
|
168
|
+
fee: string | number | null;
|
|
169
|
+
}): Promise<boolean>;
|
|
170
|
+
/**
|
|
171
|
+
* submitting → submitted: a backend accepted the tx (or reconciliation found it
|
|
172
|
+
* on-chain). The artifacts are already durable from markSubmitting; only the hash
|
|
173
|
+
* is re-asserted, in case the backend canonicalized it.
|
|
174
|
+
*/
|
|
175
|
+
export declare function markSubmitted(db: CapTransaction, jobId: string, txHash: string): Promise<boolean>;
|
|
176
|
+
/**
|
|
177
|
+
* building → pending (transient failure, attempts left). Keeps the error visible
|
|
178
|
+
* and defers the next attempt via `notBefore` (exponential backoff).
|
|
179
|
+
*
|
|
180
|
+
* Guarded on `building` ON PURPOSE: once a job is `submitting` its tx may be in a
|
|
181
|
+
* mempool, and re-queueing it would rebuild a different transaction from the same
|
|
182
|
+
* request — the duplicate-payment path. Those rows go to reconciliation instead.
|
|
183
|
+
*/
|
|
184
|
+
export declare function requeueForRetry(db: CapTransaction, jobId: string, err: unknown, notBefore?: string): Promise<boolean>;
|
|
185
|
+
/** Record where the submitted tx was seen on-chain (not yet at depth). */
|
|
186
|
+
export declare function recordConfirmationPoint(db: CapTransaction, jobId: string, point: {
|
|
187
|
+
slot: number | null;
|
|
188
|
+
height: number | null;
|
|
189
|
+
}): Promise<void>;
|
|
190
|
+
/** A rollback invalidated the recorded confirmation point — back to watching. */
|
|
191
|
+
export declare function clearConfirmationPoint(db: CapTransaction, jobId: string): Promise<void>;
|
|
192
|
+
/** submitted → confirmed (depth reached). */
|
|
193
|
+
export declare function markConfirmed(db: CapTransaction, jobId: string): Promise<boolean>;
|
|
194
|
+
/**
|
|
195
|
+
* Any active state → failed (terminal). Failing a `submitting`/`submitted` row is
|
|
196
|
+
* only safe once the chain has been consulted — a failed row releases the
|
|
197
|
+
* idempotency key, so a premature failure invites the caller's retry to pay twice.
|
|
198
|
+
*/
|
|
199
|
+
export declare function markFailed(db: CapTransaction, jobId: string, code: string, err: unknown): Promise<boolean>;
|
|
200
|
+
/** pending → cancelled. Only pending jobs are cancellable (the tx may otherwise reach the chain). */
|
|
201
|
+
export declare function markCancelled(db: CapTransaction, jobId: string): Promise<boolean>;
|
|
202
|
+
export interface RecoveryResult {
|
|
203
|
+
/** `building` rows flipped to failed (never signed+stored, so never submitted). */
|
|
204
|
+
failedBuilding: number;
|
|
205
|
+
/** `submitted` rows to re-enqueue into the confirmation tracker — the chain decides. */
|
|
206
|
+
submittedToReconcile: WalletJobRow[];
|
|
207
|
+
/** `submitting` rows with an unknown submit outcome — reconciled by the dispatch loop. */
|
|
208
|
+
submittingToReconcile: WalletJobRow[];
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Fail one wallet's orphaned `building` row(s) — but ONLY when the wallet's lease
|
|
212
|
+
* is expired/unowned, i.e. no live instance is executing them. Rows whose wallet
|
|
213
|
+
* lease is held belong to a running executor (possibly on another instance) and
|
|
214
|
+
* must not be touched.
|
|
215
|
+
*
|
|
216
|
+
* Safe by construction: a `building` row is pre-submit by definition — the worker
|
|
217
|
+
* transitions to `submitting` (with the signed CBOR) before anything can reach a
|
|
218
|
+
* backend, so nothing that is still `building` has ever been sent. Rows that made
|
|
219
|
+
* it past that point are `submitting` and are reconciled, never failed here.
|
|
220
|
+
*/
|
|
221
|
+
export declare function failOrphanedBuildingJobs(db: CapTransaction, walletId: string, now?: Date): Promise<number>;
|
|
222
|
+
/**
|
|
223
|
+
* Boot-time recovery (design §8), by state:
|
|
224
|
+
* - `building` — nothing was signed and stored yet, so nothing was submitted:
|
|
225
|
+
* fail with PROCESS_RESTART (caller retries via idempotencyKey).
|
|
226
|
+
* - `submitting` — the signed tx is durable but its fate is unknown: NOT failed
|
|
227
|
+
* and NOT rebuilt. Returned so the dispatch loop reconciles it against the
|
|
228
|
+
* chain and re-submits those exact bytes if needed.
|
|
229
|
+
* - `submitted` — NOT failed: handed to the confirmation tracker; the chain
|
|
230
|
+
* decides (found → confirm; absent past the timeout → TX_DROPPED).
|
|
231
|
+
*
|
|
232
|
+
* Multi-instance safety: a `building` row is only failed when its wallet's lease
|
|
233
|
+
* is expired/unowned. A held lease means ANOTHER live instance is executing that
|
|
234
|
+
* job right now (rolling deploy) — failing it here while its submit succeeds
|
|
235
|
+
* would leave a failed row for an on-chain tx, and since failed rows don't block
|
|
236
|
+
* idempotency dedup, the caller's documented retry would pay twice. Rows skipped
|
|
237
|
+
* here are cleaned up later by failOrphanedBuildingJobs once the lease expires.
|
|
238
|
+
*/
|
|
239
|
+
export declare function recoverInterruptedJobs(db: CapTransaction, now?: Date): Promise<RecoveryResult>;
|
|
240
|
+
/** Idempotently register/refresh a configured wallet row (no key material). */
|
|
241
|
+
export declare function upsertWalletRegistration(db: CapTransaction, wallet: {
|
|
242
|
+
walletId: string;
|
|
243
|
+
signerType: WorkerSignerTypeValue;
|
|
244
|
+
address: string;
|
|
245
|
+
publicKeyHash: string;
|
|
246
|
+
}): Promise<void>;
|
|
247
|
+
export declare function readWallet(db: CapTransaction, walletId: string): Promise<WorkerWalletRow | null>;
|
|
248
|
+
export declare function listWallets(db: CapTransaction): Promise<WorkerWalletRow[]>;
|
|
249
|
+
/**
|
|
250
|
+
* Atomically acquire an expired/unowned per-wallet lease (compare-and-swap +
|
|
251
|
+
* read-back verification, same shape as the crawler lease). At most one worker
|
|
252
|
+
* instance may execute jobs for a wallet at any time.
|
|
253
|
+
*/
|
|
254
|
+
export declare function tryAcquireWalletLease(db: CapTransaction, walletId: string, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
|
|
255
|
+
/** Renew/fence the caller's lease. Call before every job-advancing write. */
|
|
256
|
+
export declare function renewWalletLease(db: CapTransaction, walletId: string, owner: string, now?: Date, ttlMs?: number): Promise<boolean>;
|
|
257
|
+
/** Release only the caller's lease; a stale process can never clear a successor. */
|
|
258
|
+
export declare function releaseWalletLease(db: CapTransaction, walletId: string, owner: string): Promise<void>;
|
|
259
|
+
/** Bump rolling per-wallet stats on a terminal job state. */
|
|
260
|
+
export declare function bumpWalletStats(db: CapTransaction, walletId: string, outcome: 'confirmed' | 'failed'): Promise<void>;
|
|
261
|
+
//# sourceMappingURL=job-store.d.ts.map
|