@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.
- package/@cds-models/CardanoAgentService/index.d.ts +99 -51
- package/@cds-models/CardanoAgentService/index.js +15 -0
- package/@cds-models/CardanoBackendService/index.d.ts +358 -0
- package/@cds-models/CardanoBackendService/index.js +41 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +594 -11
- package/@cds-models/CardanoIndexerService/index.js +74 -0
- package/@cds-models/CardanoODataService/index.d.ts +417 -57
- package/@cds-models/CardanoODataService/index.js +42 -0
- package/@cds-models/CardanoSignService/index.d.ts +45 -19
- package/@cds-models/CardanoSignService/index.js +4 -0
- package/@cds-models/CardanoTransactionService/index.d.ts +70 -44
- package/@cds-models/CardanoTransactionService/index.js +5 -0
- package/@cds-models/CardanoWorkerService/index.d.ts +35 -22
- package/@cds-models/CardanoWorkerService/index.js +2 -0
- package/@cds-models/index.d.ts +114 -4
- package/@cds-models/index.js +20 -4
- package/@cds-models/odatano/cardano/index.d.ts +451 -32
- package/@cds-models/odatano/cardano/index.js +48 -0
- package/README.md +103 -167
- package/db/schema.cds +2455 -1705
- package/db/types.cds +456 -295
- package/package.json +41 -53
- package/scripts/deploy-schema.mjs +113 -0
- package/scripts/migrate-schema.mjs +528 -0
- package/scripts/migrate-slot-leader.mjs +96 -0
- package/src/index.d.ts +20 -21
- package/src/index.js +45 -31
- package/src/plugin.js +17 -35
- package/srv/blockchain/asset-decimals.d.ts +7 -0
- package/srv/blockchain/asset-decimals.js +91 -0
- package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -137
- package/srv/blockchain/backends/blockfrost-backend.js +125 -215
- package/srv/blockchain/backends/call-signal.d.ts +7 -0
- package/srv/blockchain/backends/call-signal.js +22 -0
- package/srv/blockchain/backends/cardano-backend.d.ts +100 -189
- package/srv/blockchain/backends/cardano-backend.js +29 -5
- package/srv/blockchain/backends/koios-backend.d.ts +108 -170
- package/srv/blockchain/backends/koios-backend.js +488 -482
- package/srv/blockchain/backends/odatano-backend.d.ts +55 -0
- package/srv/blockchain/backends/odatano-backend.js +211 -0
- package/srv/blockchain/backends/ogmios-backend.d.ts +122 -190
- package/srv/blockchain/backends/ogmios-backend.js +683 -327
- package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
- package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
- package/srv/blockchain/cardano-client.d.ts +71 -241
- package/srv/blockchain/cardano-client.js +354 -322
- package/srv/blockchain/cardano-indexer.d.ts +295 -283
- package/srv/blockchain/cardano-indexer.js +1690 -502
- package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
- package/srv/blockchain/cardano-tx-builder.js +164 -140
- package/srv/blockchain/circuit-breaker.d.ts +2 -13
- package/srv/blockchain/circuit-breaker.js +11 -15
- package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
- package/srv/blockchain/crawler/account-snapshots.js +173 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +17 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
- package/srv/blockchain/crawler/asset-registry-backfill.d.ts +46 -0
- package/srv/blockchain/crawler/asset-registry-backfill.js +157 -0
- package/srv/blockchain/crawler/asset-slice-backfill.d.ts +35 -0
- package/srv/blockchain/crawler/asset-slice-backfill.js +149 -0
- package/srv/blockchain/crawler/certificate-backfill.d.ts +56 -0
- package/srv/blockchain/crawler/certificate-backfill.js +174 -0
- package/srv/blockchain/crawler/crawler.d.ts +125 -81
- package/srv/blockchain/crawler/crawler.js +738 -167
- package/srv/blockchain/crawler/credential-backfill.d.ts +30 -0
- package/srv/blockchain/crawler/credential-backfill.js +101 -0
- package/srv/blockchain/crawler/hooks.d.ts +2 -17
- package/srv/blockchain/crawler/index.d.ts +1 -8
- package/srv/blockchain/crawler/index.js +31 -17
- package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
- package/srv/blockchain/crawler/input-asset-copies.js +161 -0
- package/srv/blockchain/crawler/key-pages.d.ts +12 -0
- package/srv/blockchain/crawler/key-pages.js +48 -0
- package/srv/blockchain/crawler/metadata-position-backfill.d.ts +22 -0
- package/srv/blockchain/crawler/metadata-position-backfill.js +59 -0
- package/srv/blockchain/crawler/output-datum-backfill.d.ts +41 -0
- package/srv/blockchain/crawler/output-datum-backfill.js +100 -0
- package/srv/blockchain/crawler/sync-state.d.ts +31 -47
- package/srv/blockchain/crawler/sync-state.js +135 -128
- package/srv/blockchain/crawler/transaction-backfill.d.ts +46 -0
- package/srv/blockchain/crawler/transaction-backfill.js +271 -0
- package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
- package/srv/blockchain/crawler/utxo-set-import.js +399 -0
- package/srv/blockchain/crawler/window-plan.d.ts +31 -0
- package/srv/blockchain/crawler/window-plan.js +59 -0
- package/srv/blockchain/ledger-state.d.ts +62 -0
- package/srv/blockchain/ledger-state.js +521 -0
- package/srv/blockchain/pending-spends.d.ts +16 -0
- package/srv/blockchain/pending-spends.js +81 -0
- package/srv/blockchain/pool-metadata.d.ts +15 -0
- package/srv/blockchain/pool-metadata.js +132 -0
- package/srv/blockchain/request-coalescer.d.ts +2 -16
- package/srv/blockchain/request-coalescer.js +2 -16
- package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
- package/srv/blockchain/signing/cose-verifier.js +146 -70
- package/srv/blockchain/signing/external-signer.d.ts +15 -115
- package/srv/blockchain/signing/external-signer.js +22 -131
- package/srv/blockchain/signing/failed-recheck.d.ts +17 -0
- package/srv/blockchain/signing/failed-recheck.js +135 -0
- package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
- package/srv/blockchain/signing/hsm-signer.js +28 -79
- package/srv/blockchain/signing/landing-proof.d.ts +60 -0
- package/srv/blockchain/signing/landing-proof.js +224 -0
- package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
- package/srv/blockchain/signing/signature-verifier.js +71 -87
- package/srv/blockchain/signing/submission-finalizer.d.ts +37 -45
- package/srv/blockchain/signing/submission-finalizer.js +280 -86
- package/srv/blockchain/stored-chain.d.ts +19 -0
- package/srv/blockchain/stored-chain.js +258 -0
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
- package/srv/blockchain/transaction-building/buildooor-tx.js +663 -421
- package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
- package/srv/blockchain/transaction-presence.d.ts +12 -0
- package/srv/blockchain/transaction-presence.js +29 -0
- package/srv/blockchain/transaction-rows.d.ts +12 -0
- package/srv/blockchain/transaction-rows.js +44 -0
- package/srv/blockchain/wallet-worker/build-request.d.ts +8 -23
- package/srv/blockchain/wallet-worker/build-request.js +40 -353
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +27 -47
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +158 -61
- package/srv/blockchain/wallet-worker/index.d.ts +1 -1
- package/srv/blockchain/wallet-worker/index.js +3 -11
- package/srv/blockchain/wallet-worker/invalidation.d.ts +35 -0
- package/srv/blockchain/wallet-worker/invalidation.js +128 -0
- package/srv/blockchain/wallet-worker/job-store.d.ts +58 -150
- package/srv/blockchain/wallet-worker/job-store.js +200 -273
- package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
- package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
- package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
- package/srv/blockchain/wallet-worker/signers.js +4 -12
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +29 -82
- package/srv/blockchain/wallet-worker/wallet-worker.js +334 -198
- package/srv/cardano-agent-service.cds +122 -84
- package/srv/cardano-agent-service.js +12 -9
- package/srv/cardano-backend-service.cds +81 -0
- package/srv/cardano-backend-service.d.ts +2 -0
- package/srv/cardano-backend-service.js +259 -0
- package/srv/cardano-indexer-service.cds +393 -18
- package/srv/cardano-indexer-service.d.ts +5 -1
- package/srv/cardano-indexer-service.js +477 -16
- package/srv/cardano-service.cds +426 -269
- package/srv/cardano-service.js +640 -217
- package/srv/cardano-sign-service.cds +211 -180
- package/srv/cardano-sign-service.js +210 -287
- package/srv/cardano-tx-service.cds +462 -370
- package/srv/cardano-tx-service.js +283 -800
- package/srv/cardano-ui.cds +16 -16
- package/srv/cardano-worker-service.cds +141 -125
- package/srv/cardano-worker-service.js +104 -61
- package/srv/cbor/cip68.d.ts +13 -0
- package/srv/cbor/cip68.js +56 -0
- package/srv/cbor/index.d.ts +3 -1
- package/srv/cbor/index.js +9 -1
- package/srv/cbor/parse.d.ts +30 -18
- package/srv/cbor/parse.js +44 -9
- package/srv/cbor/plutus-data-json.d.ts +20 -0
- package/srv/cbor/plutus-data-json.js +32 -0
- package/srv/config.d.ts +117 -0
- package/srv/config.js +419 -0
- package/srv/server.d.ts +15 -110
- package/srv/server.js +83 -405
- package/srv/utils/agent-access.d.ts +11 -0
- package/srv/utils/agent-access.js +86 -0
- package/srv/utils/agent-grants-config.d.ts +0 -46
- package/srv/utils/agent-grants-config.js +17 -85
- package/srv/utils/agent-grants.d.ts +106 -122
- package/srv/utils/agent-grants.js +538 -237
- package/srv/utils/agent-token-auth.d.ts +4 -99
- package/srv/utils/agent-token-auth.js +62 -186
- package/srv/utils/backend-request-handler.d.ts +3 -17
- package/srv/utils/backend-request-handler.js +3 -18
- package/srv/utils/build-request.d.ts +52 -0
- package/srv/utils/build-request.js +487 -0
- package/srv/utils/collections.d.ts +4 -10
- package/srv/utils/collections.js +14 -10
- package/srv/utils/const.d.ts +32 -75
- package/srv/utils/const.js +40 -80
- package/srv/utils/crypto.d.ts +3 -12
- package/srv/utils/crypto.js +11 -25
- package/srv/utils/db-indexes.d.ts +31 -0
- package/srv/utils/db-indexes.js +185 -0
- package/srv/utils/db-kind.d.ts +23 -0
- package/srv/utils/db-kind.js +42 -0
- package/srv/utils/db-sanitize.d.ts +20 -0
- package/srv/utils/db-sanitize.js +80 -0
- package/srv/utils/deep-json.d.ts +6 -0
- package/srv/utils/deep-json.js +240 -0
- package/srv/utils/detached-run.d.ts +41 -0
- package/srv/utils/detached-run.js +101 -0
- package/srv/utils/epoch-slots.d.ts +14 -0
- package/srv/utils/epoch-slots.js +45 -0
- package/srv/utils/error-codes.d.ts +26 -75
- package/srv/utils/error-codes.js +27 -72
- package/srv/utils/errors.d.ts +55 -187
- package/srv/utils/errors.js +161 -235
- package/srv/utils/lease.d.ts +20 -0
- package/srv/utils/lease.js +62 -0
- package/srv/utils/liveness.d.ts +12 -0
- package/srv/utils/liveness.js +35 -0
- package/srv/utils/mappers.d.ts +111 -223
- package/srv/utils/mappers.js +432 -371
- package/srv/utils/navigation.d.ts +17 -0
- package/srv/utils/navigation.js +52 -0
- package/srv/utils/network-context.d.ts +0 -1
- package/srv/utils/network-context.js +9 -15
- package/srv/utils/paging.d.ts +31 -0
- package/srv/utils/paging.js +43 -0
- package/srv/utils/pg-inline-json.d.ts +8 -0
- package/srv/utils/pg-inline-json.js +58 -0
- package/srv/utils/pg-order-nulls.d.ts +14 -0
- package/srv/utils/pg-order-nulls.js +54 -0
- package/srv/utils/plutus-placeholders.d.ts +16 -22
- package/srv/utils/plutus-placeholders.js +62 -33
- package/srv/utils/rate-limiter.d.ts +2 -21
- package/srv/utils/rate-limiter.js +5 -17
- package/srv/utils/readiness.d.ts +12 -0
- package/srv/utils/readiness.js +29 -0
- package/srv/utils/reference-script.d.ts +19 -0
- package/srv/utils/reference-script.js +84 -0
- package/srv/utils/resolution.d.ts +13 -0
- package/srv/utils/resolution.js +47 -0
- package/srv/utils/result-numbers.d.ts +15 -0
- package/srv/utils/result-numbers.js +61 -0
- package/srv/utils/row-values.d.ts +7 -0
- package/srv/utils/row-values.js +27 -0
- package/srv/utils/service-events.d.ts +0 -24
- package/srv/utils/service-events.js +3 -25
- package/srv/utils/signing-helper.d.ts +3 -20
- package/srv/utils/signing-helper.js +35 -64
- package/srv/utils/tx-build-helper.d.ts +25 -105
- package/srv/utils/tx-build-helper.js +108 -156
- package/srv/utils/tx-request-parsers.d.ts +82 -33
- package/srv/utils/tx-request-parsers.js +401 -49
- package/srv/utils/tx-utils.d.ts +3 -27
- package/srv/utils/tx-utils.js +32 -50
- package/srv/utils/types.d.ts +294 -232
- package/srv/utils/types.js +2 -22
- package/srv/utils/validators.d.ts +22 -92
- package/srv/utils/validators.js +60 -170
|
@@ -10,21 +10,25 @@ 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 submission_finalizer_1 = require("../signing/submission-finalizer");
|
|
14
|
+
const external_signer_1 = require("../signing/external-signer");
|
|
15
|
+
const cbor_1 = require("../../cbor");
|
|
16
|
+
const cardano_1 = require("#cds-models/odatano/cardano");
|
|
13
17
|
const confirmation_tracker_1 = require("./confirmation-tracker");
|
|
14
18
|
const lease_heartbeat_1 = require("./lease-heartbeat");
|
|
15
19
|
const build_request_1 = require("./build-request");
|
|
16
20
|
const service_events_1 = require("../../utils/service-events");
|
|
17
21
|
const signers_1 = require("./signers");
|
|
22
|
+
const landing_proof_1 = require("../signing/landing-proof");
|
|
23
|
+
const invalidation_1 = require("./invalidation");
|
|
18
24
|
const job_store_1 = require("./job-store");
|
|
25
|
+
const { SELECT, UPDATE } = cds_1.default.ql;
|
|
19
26
|
const logger = cds_1.default.log('CardanoWalletWorker');
|
|
20
27
|
/** Retry backoff: 5s · 2^(attempt-1), capped at 60s. */
|
|
21
28
|
function retryBackoffMs(attempt) {
|
|
22
29
|
return Math.min(5_000 * 2 ** Math.max(0, attempt - 1), 60_000);
|
|
23
30
|
}
|
|
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
|
-
*/
|
|
31
|
+
/** Transient errors get a bounded retry; everything else fails the job immediately. */
|
|
28
32
|
function isTransientJobError(err) {
|
|
29
33
|
if (err instanceof errors_1.ProviderUnavailableError)
|
|
30
34
|
return true;
|
|
@@ -46,16 +50,26 @@ function terminalErrorCode(err) {
|
|
|
46
50
|
class CardanoWalletWorker {
|
|
47
51
|
deps;
|
|
48
52
|
signers = new Map();
|
|
49
|
-
executing = new Set(); // walletIds
|
|
53
|
+
executing = new Set(); // walletIds executing in THIS process
|
|
50
54
|
executionPromises = new Set();
|
|
51
55
|
tracker;
|
|
52
56
|
dispatchTimer = null;
|
|
57
|
+
/** Earliest next reconcile per job with an open submit, and how often it was tried. */
|
|
58
|
+
reconcileBackoff = new Map();
|
|
59
|
+
/** Jobs whose transaction has no expiry, has not landed and still can: the unspent inputs, by job. */
|
|
60
|
+
staleJobs = new Map();
|
|
61
|
+
/** Earliest next look at a job's invalidation, and the tip height an own output was first seen at. */
|
|
62
|
+
invalidationNotBefore = new Map();
|
|
63
|
+
invalidationSeen = new Map();
|
|
64
|
+
/** Sends of a stored self-transfer not seen on chain yet, and the earliest next one. */
|
|
65
|
+
invalidationResend = new Map();
|
|
53
66
|
running = false;
|
|
54
|
-
|
|
67
|
+
tickInFlight = null;
|
|
55
68
|
constructor(deps) {
|
|
56
69
|
this.deps = deps;
|
|
57
70
|
this.tracker = new confirmation_tracker_1.ConfirmationTracker({
|
|
58
71
|
client: deps.client,
|
|
72
|
+
indexer: deps.indexer,
|
|
59
73
|
options: {
|
|
60
74
|
confirmationDepth: deps.config.confirmationDepth,
|
|
61
75
|
confirmationTimeoutMs: deps.config.confirmationTimeoutMs,
|
|
@@ -63,18 +77,33 @@ class CardanoWalletWorker {
|
|
|
63
77
|
resubmitOnRollback: deps.config.resubmitOnRollback,
|
|
64
78
|
},
|
|
65
79
|
onFinal: ({ jobId, walletId, outcome, kind, txHash, errorCode, errorMessage }) => {
|
|
66
|
-
logger.debug(`Wallet ${walletId} unblocked (job ${outcome})
|
|
67
|
-
//
|
|
68
|
-
|
|
69
|
-
(0, service_events_1.emitServiceEvent)('CardanoWorkerService',
|
|
80
|
+
logger.debug(`Wallet ${walletId} unblocked (job ${outcome}), next tick dispatches`);
|
|
81
|
+
// Terminal outcomes only, after the commit, so subscribers reading the row see the announced state.
|
|
82
|
+
const event = outcome === 'confirmed' ? 'jobConfirmed' : outcome === 'failed' ? 'jobFailed' : 'jobUnresolved';
|
|
83
|
+
(0, service_events_1.emitServiceEvent)('CardanoWorkerService', event, {
|
|
70
84
|
jobId,
|
|
71
85
|
walletId,
|
|
72
86
|
kind,
|
|
73
87
|
txHash,
|
|
74
|
-
...(outcome === 'failed' ? { errorCode: errorCode ?? null
|
|
88
|
+
...(outcome === 'failed' ? { errorCode: errorCode ?? null } : {}),
|
|
89
|
+
...(outcome !== 'confirmed' ? { errorMessage: errorMessage ?? null } : {}),
|
|
75
90
|
});
|
|
76
91
|
void this.tickSafe();
|
|
77
92
|
},
|
|
93
|
+
onStale: ({ jobId, walletId }, unspentInputs) => {
|
|
94
|
+
this.staleJobs.set(jobId, { walletId, unspentInputs });
|
|
95
|
+
},
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
/** A terminal outcome after its commit, so subscribers reading the row see the announced state. */
|
|
99
|
+
announce(job, outcome, errorCode, err) {
|
|
100
|
+
(0, service_events_1.emitServiceEvent)('CardanoWorkerService', outcome === 'failed' ? 'jobFailed' : 'jobUnresolved', {
|
|
101
|
+
jobId: job.ID,
|
|
102
|
+
walletId: job.walletId,
|
|
103
|
+
kind: job.kind,
|
|
104
|
+
txHash: job.txHash,
|
|
105
|
+
...(outcome === 'failed' ? { errorCode } : {}),
|
|
106
|
+
errorMessage: err instanceof Error ? err.message : err != null ? String(err) : null,
|
|
78
107
|
});
|
|
79
108
|
}
|
|
80
109
|
isRunning() {
|
|
@@ -103,7 +132,7 @@ class CardanoWalletWorker {
|
|
|
103
132
|
logger.warn('Wallet worker refused to start: no wallets configured');
|
|
104
133
|
return;
|
|
105
134
|
}
|
|
106
|
-
// 1. Initialize signers
|
|
135
|
+
// 1. Initialize signers. A broken wallet config skips that wallet, not the worker.
|
|
107
136
|
for (const walletCfg of this.deps.config.wallets) {
|
|
108
137
|
try {
|
|
109
138
|
const signer = (0, signers_1.createWorkerSigner)(walletCfg, this.deps.network);
|
|
@@ -113,37 +142,29 @@ class CardanoWalletWorker {
|
|
|
113
142
|
signerType: walletCfg.signerType,
|
|
114
143
|
address: signer.getAddress(),
|
|
115
144
|
publicKeyHash: signer.getPublicKeyHash(),
|
|
145
|
+
requiresRole: walletCfg.requiresRole ?? null,
|
|
116
146
|
}));
|
|
117
147
|
}
|
|
118
148
|
catch (err) {
|
|
119
|
-
logger.error(`Wallet "${walletCfg.walletId}" skipped
|
|
149
|
+
logger.error(`Wallet "${walletCfg.walletId}" skipped, signer initialization failed:`, err);
|
|
120
150
|
}
|
|
121
151
|
}
|
|
122
152
|
if (this.signers.size === 0) {
|
|
123
153
|
logger.error('Wallet worker not started: no wallet signer could be initialized');
|
|
124
154
|
return;
|
|
125
155
|
}
|
|
126
|
-
//
|
|
127
|
-
|
|
128
|
-
|
|
156
|
+
// a confirmation needs a transaction lookup or a ledger read of the transaction's outputs
|
|
157
|
+
if (!this.deps.client.supports('getTransaction') && !this.deps.client.supports('isUtxoUnspent')) {
|
|
158
|
+
logger.error('Wallet worker not started: no backend can confirm a transaction (getTransaction or isUtxoUnspent)');
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
// 2. Crash recovery: fail interrupted builds, re-watch submitted jobs; `submitting`
|
|
162
|
+
// rows are reconciled by the first tick.
|
|
129
163
|
const recovery = await cds_1.default.tx((tx) => (0, job_store_1.recoverInterruptedJobs)(tx));
|
|
130
164
|
if (recovery.submittingToReconcile.length) {
|
|
131
165
|
logger.warn(`${recovery.submittingToReconcile.length} job(s) with an unresolved submit will be reconciled on the next dispatch tick`);
|
|
132
166
|
}
|
|
133
|
-
|
|
134
|
-
if (!job.txHash)
|
|
135
|
-
continue; // defensive: submitted implies txHash
|
|
136
|
-
this.tracker.track({
|
|
137
|
-
jobId: job.ID,
|
|
138
|
-
walletId: job.walletId,
|
|
139
|
-
kind: job.kind,
|
|
140
|
-
txHash: job.txHash,
|
|
141
|
-
signedTxCbor: job.signedTxCbor,
|
|
142
|
-
submittedAt: job.submittedAt,
|
|
143
|
-
confirmedSlot: job.confirmedSlot,
|
|
144
|
-
confirmedHeight: job.confirmedHeight,
|
|
145
|
-
});
|
|
146
|
-
}
|
|
167
|
+
this.trackSubmitted(recovery.submittedToReconcile);
|
|
147
168
|
// 3. Go.
|
|
148
169
|
this.running = true;
|
|
149
170
|
this.tracker.start();
|
|
@@ -161,7 +182,8 @@ class CardanoWalletWorker {
|
|
|
161
182
|
this.dispatchTimer = null;
|
|
162
183
|
}
|
|
163
184
|
this.tracker.stop();
|
|
164
|
-
//
|
|
185
|
+
// A running tick may still spawn work; let it finish, then await every execution.
|
|
186
|
+
await this.tickInFlight;
|
|
165
187
|
await Promise.allSettled([...this.executionPromises]);
|
|
166
188
|
for (const walletId of this.getWalletIds()) {
|
|
167
189
|
try {
|
|
@@ -175,63 +197,82 @@ class CardanoWalletWorker {
|
|
|
175
197
|
}
|
|
176
198
|
/** One dispatch round; serialized (overlapping timers collapse into one run). */
|
|
177
199
|
async tickSafe() {
|
|
178
|
-
if (!this.running || this.
|
|
200
|
+
if (!this.running || this.tickInFlight)
|
|
179
201
|
return;
|
|
180
|
-
this.
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
catch (err) {
|
|
185
|
-
logger.error('Wallet worker dispatch tick failed:', err);
|
|
186
|
-
}
|
|
187
|
-
finally {
|
|
188
|
-
this.ticking = false;
|
|
189
|
-
}
|
|
202
|
+
this.tickInFlight = this.tick()
|
|
203
|
+
.catch((err) => logger.error('Wallet worker dispatch tick failed:', err))
|
|
204
|
+
.finally(() => { this.tickInFlight = null; });
|
|
205
|
+
await this.tickInFlight;
|
|
190
206
|
}
|
|
191
207
|
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).
|
|
208
|
+
// Interrupted submits first: a stuck `submitting` row blocks its wallet queue.
|
|
194
209
|
await this.reconcileOrphanedSubmissions();
|
|
195
|
-
|
|
196
|
-
|
|
210
|
+
// Submitted jobs of a stopped or crashed instance are watched here too. track() is idempotent.
|
|
211
|
+
await this.adoptSubmittedJobs();
|
|
212
|
+
// Transactions without an expiry that can still land get an input spent by a self-transfer.
|
|
213
|
+
await this.invalidateStaleJobs();
|
|
214
|
+
// The next due job of every idle wallet this instance signs for: one row per wallet.
|
|
215
|
+
const idle = this.getWalletIds().filter(walletId => !this.executing.has(walletId));
|
|
216
|
+
if (!idle.length)
|
|
197
217
|
return;
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
218
|
+
const due = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (tx) => {
|
|
219
|
+
const next = [];
|
|
220
|
+
for (const walletId of idle) {
|
|
221
|
+
const ref = await (0, job_store_1.findNextDueJob)(tx, walletId);
|
|
222
|
+
if (ref)
|
|
223
|
+
next.push(ref);
|
|
224
|
+
}
|
|
225
|
+
return next;
|
|
226
|
+
}));
|
|
227
|
+
// dispatch order across wallets: priority, then age
|
|
228
|
+
due.sort((a, b) => a.priority - b.priority || String(a.createdAt ?? '').localeCompare(String(b.createdAt ?? '')));
|
|
229
|
+
for (const { ID, walletId } of due) {
|
|
205
230
|
if (!this.running)
|
|
206
231
|
return;
|
|
207
232
|
if (this.executing.size >= this.deps.config.maxConcurrentWallets)
|
|
208
233
|
return;
|
|
209
|
-
if (this.executing.has(walletId))
|
|
210
|
-
continue;
|
|
211
234
|
const signer = this.signers.get(walletId);
|
|
212
235
|
if (!signer)
|
|
213
|
-
continue;
|
|
214
|
-
const
|
|
215
|
-
//
|
|
216
|
-
//
|
|
217
|
-
// needing a reboot (boot recovery only covers restarts of THIS instance).
|
|
236
|
+
continue;
|
|
237
|
+
const job = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (tx) => {
|
|
238
|
+
// A building row with an expired lease belongs to a dead executor.
|
|
239
|
+
// Failing it unblocks the wallet without a reboot.
|
|
218
240
|
await (0, job_store_1.failOrphanedBuildingJobs)(tx, walletId);
|
|
219
|
-
//
|
|
220
|
-
// job blocks the wallet queue until the tracker finalizes it (design §6).
|
|
241
|
+
// An active job blocks the wallet queue until the tracker finalizes it.
|
|
221
242
|
if (await (0, job_store_1.walletHasActiveJob)(tx, walletId))
|
|
222
|
-
return
|
|
223
|
-
|
|
243
|
+
return null;
|
|
244
|
+
const next = await (0, job_store_1.getJobById)(tx, ID);
|
|
245
|
+
if (next?.status !== 'pending')
|
|
246
|
+
return null;
|
|
247
|
+
return (await (0, job_store_1.tryAcquireWalletLease)(tx, walletId, this.deps.instanceId)) ? next : null;
|
|
224
248
|
}));
|
|
225
|
-
if (!
|
|
249
|
+
if (!job)
|
|
226
250
|
continue;
|
|
227
251
|
this.spawn(walletId, () => this.executeJob(job, signer));
|
|
228
252
|
}
|
|
229
253
|
}
|
|
230
|
-
/**
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
254
|
+
/** Watch every submitted job of the wallets this instance signs for until it confirms or fails. */
|
|
255
|
+
async adoptSubmittedJobs() {
|
|
256
|
+
const rows = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.findSubmittedJobs)(tx)));
|
|
257
|
+
this.trackSubmitted(rows.filter((row) => this.signers.has(row.walletId)));
|
|
258
|
+
}
|
|
259
|
+
trackSubmitted(rows) {
|
|
260
|
+
for (const job of rows) {
|
|
261
|
+
if (!job.txHash)
|
|
262
|
+
continue; // submitted implies txHash
|
|
263
|
+
this.tracker.track({
|
|
264
|
+
jobId: job.ID,
|
|
265
|
+
walletId: job.walletId,
|
|
266
|
+
kind: job.kind,
|
|
267
|
+
txHash: job.txHash,
|
|
268
|
+
signedTxCbor: job.signedTxCbor,
|
|
269
|
+
submittedAt: job.submittedAt,
|
|
270
|
+
confirmedSlot: job.confirmedSlot,
|
|
271
|
+
confirmedHeight: job.confirmedHeight,
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
/** Adopt `submitting` rows left by a dead executor and resolve them against the chain, under the wallet lease. */
|
|
235
276
|
async reconcileOrphanedSubmissions() {
|
|
236
277
|
const { instanceId } = this.deps;
|
|
237
278
|
for (const walletId of this.getWalletIds()) {
|
|
@@ -243,7 +284,7 @@ class CardanoWalletWorker {
|
|
|
243
284
|
continue;
|
|
244
285
|
const orphan = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (tx) => {
|
|
245
286
|
const stuck = await (0, job_store_1.findOrphanedSubmittingJob)(tx, walletId);
|
|
246
|
-
if (!stuck)
|
|
287
|
+
if (!stuck || (this.reconcileBackoff.get(stuck.ID)?.notBefore ?? 0) > Date.now())
|
|
247
288
|
return null;
|
|
248
289
|
return (await (0, job_store_1.tryAcquireWalletLease)(tx, walletId, instanceId)) ? stuck : null;
|
|
249
290
|
}));
|
|
@@ -254,6 +295,9 @@ class CardanoWalletWorker {
|
|
|
254
295
|
}
|
|
255
296
|
/** Run one wallet's work in the background, tracked for concurrency + shutdown. */
|
|
256
297
|
spawn(walletId, work) {
|
|
298
|
+
// stop() began after the lease was taken; stop() releases it
|
|
299
|
+
if (!this.running)
|
|
300
|
+
return;
|
|
257
301
|
this.executing.add(walletId);
|
|
258
302
|
const execution = work()
|
|
259
303
|
.catch((err) => logger.error(`Wallet ${walletId}: unhandled execution error:`, err))
|
|
@@ -270,16 +314,7 @@ class CardanoWalletWorker {
|
|
|
270
314
|
heartbeat.start();
|
|
271
315
|
return heartbeat;
|
|
272
316
|
}
|
|
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
|
-
*/
|
|
317
|
+
/** Builds, signs and submits one job under a renewed wallet lease. After the submitting commit, reconcileSubmitting owns it. */
|
|
283
318
|
async executeJob(job, signer) {
|
|
284
319
|
const { instanceId } = this.deps;
|
|
285
320
|
const attempt = job.attempt + 1;
|
|
@@ -292,57 +327,50 @@ class CardanoWalletWorker {
|
|
|
292
327
|
let signedTxCbor;
|
|
293
328
|
let fee = null;
|
|
294
329
|
let buildId = null;
|
|
330
|
+
const request = (0, build_request_1.parseJobRequest)(job.request);
|
|
331
|
+
if (!request)
|
|
332
|
+
throw new errors_1.BackendError('requestJson must be a JSON object', 400, error_codes_1.ERROR_CODES.INVALID_INPUT, undefined, undefined, 'requestJson');
|
|
295
333
|
if (job.kind === 'submitSigned') {
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
334
|
+
// jobs queued before the expiry rule are refused here, before anything is sent
|
|
335
|
+
const problem = (0, build_request_1.submitSignedProblem)(request, this.deps.network);
|
|
336
|
+
if (problem)
|
|
337
|
+
throw new errors_1.BackendError(problem, 400, error_codes_1.ERROR_CODES.INVALID_INPUT, undefined, undefined, 'requestJson');
|
|
300
338
|
signedTxCbor = request.signedTxCbor;
|
|
301
339
|
}
|
|
302
340
|
else {
|
|
303
|
-
const rawReq =
|
|
304
|
-
// The worker wallet is
|
|
305
|
-
// spend from foreign addresses through a worker wallet.
|
|
341
|
+
const rawReq = request;
|
|
342
|
+
// The worker wallet is always the sender and change target. It never spends from foreign addresses.
|
|
306
343
|
rawReq.network = this.deps.network;
|
|
307
344
|
rawReq.senderAddress = signer.getAddress();
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
//
|
|
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.
|
|
345
|
+
rawReq.changeAddress = signer.getAddress();
|
|
346
|
+
const build = this.buildOf(job, rawReq);
|
|
347
|
+
// Lease lost → abort BEFORE building; orphan cleanup fails the row once the lease is provably dead.
|
|
317
348
|
if (!(await heartbeat.fence())) {
|
|
318
|
-
logger.warn(`Job ${job.ID}: wallet lease for ${job.walletId} lost before build
|
|
349
|
+
logger.warn(`Job ${job.ID}: wallet lease for ${job.walletId} lost before build, aborting execution`);
|
|
319
350
|
return;
|
|
320
351
|
}
|
|
321
|
-
const buildResult = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(
|
|
352
|
+
const buildResult = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(build));
|
|
322
353
|
unsignedTxCbor = buildResult.unsignedTxCbor;
|
|
323
354
|
fee = buildResult.fee ?? null;
|
|
324
355
|
buildId = buildResult.id ?? null;
|
|
325
356
|
signedTxCbor = signer.signTransaction(unsignedTxCbor, buildResult.txBodyHash);
|
|
357
|
+
// a signature that misses a key the body requires is refused by the node: fail before sending
|
|
358
|
+
const requiredSigners = new Set([signer.getPublicKeyHash(), ...((0, cbor_1.parseTransaction)(unsignedTxCbor).requiredSigners ?? [])].map((k) => k.toLowerCase()));
|
|
359
|
+
(0, external_signer_1.getExternalSignerModule)().verifyOrThrow(signedTxCbor, buildResult.txBodyHash, { requiredSigners: [...requiredSigners] });
|
|
326
360
|
}
|
|
327
|
-
//
|
|
328
|
-
// row can name the transaction before anyone has seen it.
|
|
361
|
+
// Hash from the signed bytes, so the row can name the tx before anyone has seen it.
|
|
329
362
|
const txHash = (0, tx_build_helper_1.getTxHashFromCbor)(signedTxCbor);
|
|
330
|
-
// Last fence before the irreversible part
|
|
331
|
-
//
|
|
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.
|
|
363
|
+
// Last fence before the irreversible part: another instance owning the wallet now
|
|
364
|
+
// may spend the same UTxOs. Nothing has been sent, so standing down costs only a rebuild.
|
|
334
365
|
if (!(await heartbeat.fence())) {
|
|
335
|
-
logger.warn(`Job ${job.ID}: wallet lease for ${job.walletId} lost after signing
|
|
366
|
+
logger.warn(`Job ${job.ID}: wallet lease for ${job.walletId} lost after signing, NOT submitting tx ${txHash}`);
|
|
336
367
|
return;
|
|
337
368
|
}
|
|
338
|
-
// Point of no return: commit the signed tx BEFORE it can reach a backend.
|
|
339
|
-
//
|
|
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.
|
|
369
|
+
// Point of no return: commit the signed tx BEFORE it can reach a backend. The guard on
|
|
370
|
+
// `building` is the second half of the fence: a row already failed by a takeover returns false.
|
|
343
371
|
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
372
|
if (!stored) {
|
|
345
|
-
logger.warn(`Job ${job.ID}: submitting transition was fenced
|
|
373
|
+
logger.warn(`Job ${job.ID}: submitting transition was fenced, not submitting (another executor owns this job)`);
|
|
346
374
|
return;
|
|
347
375
|
}
|
|
348
376
|
await this.submitStoredTransaction(job, { txHash, signedTxCbor, buildId, attempt });
|
|
@@ -356,36 +384,32 @@ class CardanoWalletWorker {
|
|
|
356
384
|
.catch(() => undefined);
|
|
357
385
|
}
|
|
358
386
|
}
|
|
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
|
-
*/
|
|
387
|
+
/** Sends the stored tx. A failed submit leaves the row submitting, since one rejection proves nothing. */
|
|
368
388
|
async submitStoredTransaction(job, tx) {
|
|
369
389
|
let submittedHash;
|
|
370
390
|
try {
|
|
371
391
|
submittedHash = await this.submitWithAlreadyKnownTolerance(tx.signedTxCbor);
|
|
372
392
|
}
|
|
373
393
|
catch (err) {
|
|
374
|
-
logger.error(`Job ${job.ID}: submit failed for tx ${tx.txHash}
|
|
394
|
+
logger.error(`Job ${job.ID}: submit failed for tx ${tx.txHash}, job stays submitting for chain reconciliation:`, err);
|
|
375
395
|
return;
|
|
376
396
|
}
|
|
377
|
-
|
|
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);
|
|
397
|
+
await this.adoptSubmitted(job, submittedHash, tx.signedTxCbor, tx.buildId);
|
|
382
398
|
logger.info(`Job ${job.ID} (wallet ${job.walletId}, kind ${job.kind}): submitted as ${submittedHash} (attempt ${tx.attempt})`);
|
|
383
399
|
}
|
|
384
400
|
/** submitting → submitted + hand to the confirmation tracker. */
|
|
385
|
-
async adoptSubmitted(job, txHash, signedTxCbor) {
|
|
401
|
+
async adoptSubmitted(job, txHash, signedTxCbor, buildId = null) {
|
|
402
|
+
if (job.kind !== 'submitSigned') {
|
|
403
|
+
// Record the submission row as the synchronous flow does, once per tx.
|
|
404
|
+
await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (t) => {
|
|
405
|
+
const known = await t.run(SELECT.one.from(cardano_1.TransactionSubmissions).columns('id').where({ txHash }));
|
|
406
|
+
if (!known)
|
|
407
|
+
await this.deps.indexer.persistTransactionSubmission(t, { signedTxCbor, txHash, buildId, status: 'submitted' });
|
|
408
|
+
})).catch((err) => logger.warn(`Job ${job.ID}: submission bookkeeping failed (job continues):`, err));
|
|
409
|
+
}
|
|
386
410
|
const submitted = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.markSubmitted)(tx, job.ID, txHash)));
|
|
387
411
|
if (!submitted) {
|
|
388
|
-
logger.error(`Job ${job.ID}: tx ${txHash} is out there but the submitted transition was fenced
|
|
412
|
+
logger.error(`Job ${job.ID}: tx ${txHash} is out there but the submitted transition was fenced, tracker adopts the tx anyway`);
|
|
389
413
|
}
|
|
390
414
|
this.tracker.track({
|
|
391
415
|
jobId: job.ID,
|
|
@@ -396,90 +420,208 @@ class CardanoWalletWorker {
|
|
|
396
420
|
submittedAt: job.submittedAt ?? new Date().toISOString(),
|
|
397
421
|
});
|
|
398
422
|
}
|
|
399
|
-
|
|
400
|
-
|
|
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
|
-
*/
|
|
423
|
+
// Resolves a submitting job by re-submitting the stored tx, then looking it up on chain.
|
|
424
|
+
// Fails only when the tx is absent and rejected for good or timed out. Otherwise retries next tick.
|
|
417
425
|
async reconcileSubmitting(job) {
|
|
418
426
|
const { instanceId } = this.deps;
|
|
419
427
|
const heartbeat = this.leaseHeartbeat(job.walletId);
|
|
420
428
|
try {
|
|
421
429
|
if (!job.signedTxCbor || !job.txHash) {
|
|
422
|
-
// Cannot happen via markSubmitting; treat as
|
|
423
|
-
|
|
424
|
-
logger.error(`Job ${job.ID}: submitting row without signed transaction — failing as PROCESS_RESTART`);
|
|
430
|
+
// Cannot happen via markSubmitting; treat as never sent rather than blocking the wallet queue forever.
|
|
431
|
+
logger.error(`Job ${job.ID}: submitting row without signed transaction, failing as PROCESS_RESTART`);
|
|
425
432
|
await this.failReconciled(job, job_store_1.JOB_ERROR_CODES.PROCESS_RESTART, new Error('Job was interrupted before its signed transaction was stored.'));
|
|
426
433
|
return;
|
|
427
434
|
}
|
|
428
435
|
logger.warn(`Job ${job.ID}: reconciling interrupted submit of tx ${job.txHash}`);
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
436
|
+
// The same bytes again while young, later the chain alone. 'failed' only with proof that it cannot land.
|
|
437
|
+
const sentAtMs = job.submittedAt ? Date.parse(job.submittedAt) : NaN;
|
|
438
|
+
const ageMs = Number.isFinite(sentAtMs) ? Date.now() - sentAtMs : 0;
|
|
439
|
+
const { outcome, error, finalRefusal, unspentInputs } = await (0, submission_finalizer_1.attemptSubmit)(job.signedTxCbor, job.txHash, !(ageMs > submission_finalizer_1.RESUBMIT_WINDOW_MS), this.deps.indexer, this.deps.client, Number.isFinite(sentAtMs) ? sentAtMs : null);
|
|
440
|
+
if (outcome === 'accepted') {
|
|
441
|
+
this.reconcileBackoff.delete(job.ID);
|
|
442
|
+
await this.adoptSubmitted(job, job.txHash, job.signedTxCbor);
|
|
443
|
+
logger.info(`Job ${job.ID}: tx ${job.txHash} is with the node or on chain, now awaiting confirmation`);
|
|
434
444
|
return;
|
|
435
445
|
}
|
|
436
|
-
|
|
437
|
-
|
|
446
|
+
if (outcome === 'unknown') {
|
|
447
|
+
if (unspentInputs)
|
|
448
|
+
this.staleJobs.set(job.ID, { walletId: job.walletId, unspentInputs });
|
|
449
|
+
const attempts = (this.reconcileBackoff.get(job.ID)?.attempts ?? 0) + 1;
|
|
450
|
+
this.reconcileBackoff.set(job.ID, { attempts, notBefore: Date.now() + retryBackoffMs(attempts) });
|
|
451
|
+
logger.warn(`Job ${job.ID}: tx ${job.txHash} may still land, next check in ${retryBackoffMs(attempts) / 1000}s:`, error);
|
|
452
|
+
return;
|
|
438
453
|
}
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
454
|
+
this.reconcileBackoff.delete(job.ID);
|
|
455
|
+
if (outcome === 'unresolved') {
|
|
456
|
+
logger.error(`Job ${job.ID}: tx ${job.txHash} can no longer land and nothing shows whether it did; unresolved, an operator resolves it:`, error);
|
|
457
|
+
const marked = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.markUnresolved)(tx, job.ID, error ?? new Error('unresolved'))))
|
|
458
|
+
.catch((persistErr) => { logger.error(`Job ${job.ID}: unresolved persist failed:`, persistErr); return false; });
|
|
459
|
+
if (marked)
|
|
460
|
+
this.announce(job, 'unresolved', job_store_1.JOB_ERROR_CODES.OUTCOME_UNRESOLVED, error);
|
|
461
|
+
return;
|
|
462
|
+
}
|
|
463
|
+
// It landed with failing scripts, or it can never land. The job fails and keeps its idempotency key.
|
|
464
|
+
const code = outcome === 'scriptFailed' ? job_store_1.JOB_ERROR_CODES.SCRIPT_FAILED
|
|
465
|
+
: finalRefusal ? job_store_1.JOB_ERROR_CODES.SUBMIT_REJECTED : job_store_1.JOB_ERROR_CODES.TX_DROPPED;
|
|
466
|
+
logger.error(`Job ${job.ID}: tx ${job.txHash} fails as ${code}:`, error);
|
|
467
|
+
await this.failReconciled(job, code, error);
|
|
468
|
+
}
|
|
469
|
+
finally {
|
|
470
|
+
heartbeat.stop();
|
|
471
|
+
await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.releaseWalletLease)(tx, job.walletId, instanceId)))
|
|
472
|
+
.catch(() => undefined);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
async failReconciled(job, code, err) {
|
|
476
|
+
const transitioned = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (tx) => {
|
|
477
|
+
const done = await (0, job_store_1.markFailedAfterSend)(tx, job.ID, code, err ?? new Error(code));
|
|
478
|
+
if (done) {
|
|
479
|
+
await (0, job_store_1.bumpWalletStats)(tx, job.walletId, 'failed');
|
|
480
|
+
if (job.txHash)
|
|
481
|
+
await tx.run(UPDATE.entity(cardano_1.TransactionSubmissions).set({ status: 'failed' }).where({ txHash: job.txHash, status: { in: ['submitted', 'pending'] } }));
|
|
482
|
+
}
|
|
483
|
+
return done;
|
|
484
|
+
})).catch((persistErr) => { logger.error(`Job ${job.ID}: failure persist failed:`, persistErr); return false; });
|
|
485
|
+
if (transitioned)
|
|
486
|
+
this.announce(job, 'failed', code, err);
|
|
487
|
+
}
|
|
488
|
+
/** One invalidation per wallet at a time: the job already being invalidated first, else a stale one. */
|
|
489
|
+
async invalidateStaleJobs() {
|
|
490
|
+
const { instanceId } = this.deps;
|
|
491
|
+
const now = Date.now();
|
|
492
|
+
for (const walletId of this.getWalletIds()) {
|
|
493
|
+
if (!this.running)
|
|
494
|
+
return;
|
|
495
|
+
if (this.executing.size >= this.deps.config.maxConcurrentWallets)
|
|
496
|
+
return;
|
|
497
|
+
if (this.executing.has(walletId))
|
|
498
|
+
continue;
|
|
499
|
+
const signer = this.signers.get(walletId);
|
|
500
|
+
const target = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (tx) => {
|
|
501
|
+
const inProgress = (await (0, job_store_1.findInvalidatingJobs)(tx, walletId))[0];
|
|
502
|
+
const staleId = [...this.staleJobs].find(([, s]) => s.walletId === walletId)?.[0];
|
|
503
|
+
const id = inProgress?.ID ?? staleId;
|
|
504
|
+
if (!id || (this.invalidationNotBefore.get(id) ?? 0) > now)
|
|
505
|
+
return null;
|
|
506
|
+
if (!(await (0, job_store_1.tryAcquireWalletLease)(tx, walletId, instanceId)))
|
|
507
|
+
return null;
|
|
508
|
+
// read under the lease: another instance may have stored a self-transfer meanwhile
|
|
509
|
+
return (0, job_store_1.getJobById)(tx, id);
|
|
510
|
+
}));
|
|
511
|
+
if (!target)
|
|
512
|
+
continue;
|
|
513
|
+
this.invalidationNotBefore.set(target.ID, now + 60_000);
|
|
514
|
+
this.spawn(walletId, () => this.handleInvalidation(target, signer));
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
// The job's own transaction first: landed means the tracker takes it. Then its self-transfer:
|
|
518
|
+
// deep enough fails the job as INVALIDATED, unable to land sends a new one.
|
|
519
|
+
async handleInvalidation(job, signer) {
|
|
520
|
+
const heartbeat = this.leaseHeartbeat(job.walletId);
|
|
521
|
+
try {
|
|
522
|
+
if (!job.signedTxCbor || !job.txHash || (job.status !== 'submitted' && job.status !== 'submitting')) {
|
|
523
|
+
this.staleJobs.delete(job.ID);
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
const sentAtMs = job.submittedAt ? Date.parse(job.submittedAt) : NaN;
|
|
527
|
+
const own = await (0, landing_proof_1.judgeLanding)(job.signedTxCbor, job.txHash, this.deps, Number.isFinite(sentAtMs) ? sentAtMs : null);
|
|
528
|
+
if (own.verdict === 'onChain' || own.verdict === 'scriptFailed') {
|
|
529
|
+
this.staleJobs.delete(job.ID);
|
|
530
|
+
if (job.status === 'submitting')
|
|
531
|
+
await this.adoptSubmitted(job, job.txHash, job.signedTxCbor);
|
|
532
|
+
return;
|
|
445
533
|
}
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
534
|
+
const unspentInputs = own.verdict === 'stale' ? own.unspentInputs : this.staleJobs.get(job.ID)?.unspentInputs ?? [];
|
|
535
|
+
if (job.invalidationTxHash && job.invalidationTxCbor) {
|
|
536
|
+
const state = await (0, invalidation_1.checkInvalidation)(this.deps, job, this.invalidationSeen);
|
|
537
|
+
if (state === 'confirmed')
|
|
538
|
+
return await this.finishInvalidated(job);
|
|
539
|
+
if (state === 'unknown') {
|
|
540
|
+
const err = new Error(`Transaction ${job.txHash} has no expiry; the input its self-transfer ${job.invalidationTxHash} spends is spent and nothing shows by which transaction`);
|
|
541
|
+
const marked = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.markUnresolved)(tx, job.ID, err)));
|
|
542
|
+
if (marked) {
|
|
543
|
+
this.tracker.untrack(job.ID);
|
|
544
|
+
this.announce(job, 'unresolved', job_store_1.JOB_ERROR_CODES.OUTCOME_UNRESOLVED, err);
|
|
545
|
+
}
|
|
449
546
|
return;
|
|
450
547
|
}
|
|
451
|
-
|
|
548
|
+
if (state === 'included')
|
|
549
|
+
return;
|
|
550
|
+
if (state === 'waiting')
|
|
551
|
+
return await this.resendWaitingInvalidation(job, heartbeat);
|
|
552
|
+
this.invalidationResend.delete(job.ID);
|
|
452
553
|
}
|
|
453
|
-
if (
|
|
454
|
-
|
|
455
|
-
|
|
554
|
+
if (own.verdict !== 'stale')
|
|
555
|
+
return; // not stale (any more): nothing to spend
|
|
556
|
+
const { input, held } = await (0, invalidation_1.pickInvalidationInput)(this.deps, signer.getAddress(), unspentInputs);
|
|
557
|
+
if (!input) {
|
|
558
|
+
// every input is unspent and none is the wallet's: it cannot take the wallet funds
|
|
559
|
+
this.staleJobs.delete(job.ID);
|
|
560
|
+
this.invalidationNotBefore.set(job.ID, Date.now() + 60 * 60_000);
|
|
561
|
+
const released = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.markSpendsNoWalletUtxo)(tx, job.ID)));
|
|
562
|
+
if (released)
|
|
563
|
+
logger.warn(`Job ${job.ID}: tx ${job.txHash} has no expiry and can still land, but spends no UTxO of the wallet; it stays open and no longer holds the wallet queue`);
|
|
456
564
|
return;
|
|
457
565
|
}
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
566
|
+
if (!(await heartbeat.fence()))
|
|
567
|
+
return;
|
|
568
|
+
const keep = [...this.staleJobs].filter(([id, s]) => id !== job.ID && s.walletId === job.walletId).flatMap(([, s]) => s.unspentInputs);
|
|
569
|
+
await (0, invalidation_1.sendInvalidation)(this.deps, job, signer, input, { held, keep });
|
|
570
|
+
}
|
|
571
|
+
catch (err) {
|
|
572
|
+
if (err instanceof invalidation_1.InvalidationUnfundedError) {
|
|
573
|
+
this.invalidationNotBefore.set(job.ID, Date.now() + 60 * 60_000);
|
|
574
|
+
logger.warn(`Job ${job.ID}: tx ${job.txHash} has no expiry and can still land; the wallet cannot fund the self-transfer that would end it (${err.message}). Next try in an hour`);
|
|
462
575
|
return;
|
|
463
576
|
}
|
|
464
|
-
|
|
465
|
-
// mempool lifetime): no transaction of this job can reach the chain anymore,
|
|
466
|
-
// so releasing the idempotency key is safe.
|
|
467
|
-
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);
|
|
469
|
-
await this.failReconciled(job, code, submitError);
|
|
577
|
+
logger.warn(`Job ${job.ID}: invalidation step failed (next tick retries):`, err);
|
|
470
578
|
}
|
|
471
579
|
finally {
|
|
472
580
|
heartbeat.stop();
|
|
473
|
-
await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.releaseWalletLease)(tx, job.walletId, instanceId)))
|
|
581
|
+
await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.releaseWalletLease)(tx, job.walletId, this.deps.instanceId)))
|
|
474
582
|
.catch(() => undefined);
|
|
475
583
|
}
|
|
476
584
|
}
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
585
|
+
// The stored self-transfer, not on chain yet and not expired: the same bytes again, waiting 1, 2, 4
|
|
586
|
+
// and up to 30 minutes between sends.
|
|
587
|
+
async resendWaitingInvalidation(job, heartbeat) {
|
|
588
|
+
if ((0, landing_proof_1.isExpired)(job.invalidationTxCbor, this.deps.network))
|
|
589
|
+
return;
|
|
590
|
+
const state = this.invalidationResend.get(job.ID) ?? { attempts: 0, notBefore: 0 };
|
|
591
|
+
if (state.notBefore > Date.now() || !(await heartbeat.fence()))
|
|
592
|
+
return;
|
|
593
|
+
await (0, invalidation_1.resendInvalidation)(this.deps, job);
|
|
594
|
+
const attempts = state.attempts + 1;
|
|
595
|
+
this.invalidationResend.set(job.ID, { attempts, notBefore: Date.now() + Math.min(60_000 * 2 ** (attempts - 1), 30 * 60_000) });
|
|
596
|
+
}
|
|
597
|
+
async finishInvalidated(job) {
|
|
598
|
+
const err = new Error(`Self-transfer ${job.invalidationTxHash} spent an input of transaction ${job.txHash} and is past rollback depth; ${job.txHash} can never land`);
|
|
599
|
+
const transitioned = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx(async (tx) => {
|
|
600
|
+
const done = await (0, job_store_1.markFailedAfterSend)(tx, job.ID, job_store_1.JOB_ERROR_CODES.INVALIDATED, err);
|
|
601
|
+
if (done) {
|
|
481
602
|
await (0, job_store_1.bumpWalletStats)(tx, job.walletId, 'failed');
|
|
482
|
-
|
|
603
|
+
await tx.run(UPDATE.entity(cardano_1.TransactionSubmissions).set({ status: 'failed' }).where({ txHash: job.txHash, status: { in: ['submitted', 'pending'] } }));
|
|
604
|
+
}
|
|
605
|
+
return done;
|
|
606
|
+
}));
|
|
607
|
+
this.staleJobs.delete(job.ID);
|
|
608
|
+
this.invalidationSeen.delete(job.ID);
|
|
609
|
+
this.invalidationNotBefore.delete(job.ID);
|
|
610
|
+
this.invalidationResend.delete(job.ID);
|
|
611
|
+
this.tracker.untrack(job.ID);
|
|
612
|
+
if (transitioned) {
|
|
613
|
+
logger.warn(`Job ${job.ID}: failed as INVALIDATED`);
|
|
614
|
+
this.announce(job, 'failed', job_store_1.JOB_ERROR_CODES.INVALIDATED, err);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
/** The job's build, ready to run in a transaction. A malformed request throws 400 INVALID_INPUT here. */
|
|
618
|
+
buildOf(job, raw) {
|
|
619
|
+
if (job.kind === 'payout') {
|
|
620
|
+
const request = (0, build_request_1.preparePayoutRequest)(raw);
|
|
621
|
+
return (tx) => this.deps.indexer.indexPlutusBuildResult(tx, request);
|
|
622
|
+
}
|
|
623
|
+
const request = (0, build_request_1.prepareWorkerBuildRequest)(job.kind, raw, this.deps.network);
|
|
624
|
+
return (tx) => this.buildForKind(tx, job, request);
|
|
483
625
|
}
|
|
484
626
|
/** Dispatch the job kind to the matching indexer build method. */
|
|
485
627
|
buildForKind(tx, job, buildReq) {
|
|
@@ -494,11 +636,7 @@ class CardanoWalletWorker {
|
|
|
494
636
|
throw new errors_1.BackendError(`Unsupported job kind "${job.kind}"`, 400, error_codes_1.ERROR_CODES.INVALID_INPUT);
|
|
495
637
|
}
|
|
496
638
|
}
|
|
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
|
-
*/
|
|
639
|
+
/** Submit treating "already known" as success: a re-submit of the same CBOR after a crash hits mempool dedup. */
|
|
502
640
|
async submitWithAlreadyKnownTolerance(signedTxCbor) {
|
|
503
641
|
try {
|
|
504
642
|
return await this.deps.client.submitTransaction(signedTxCbor);
|
|
@@ -506,26 +644,24 @@ class CardanoWalletWorker {
|
|
|
506
644
|
catch (err) {
|
|
507
645
|
if (err instanceof errors_1.TransactionAlreadySubmittedError) {
|
|
508
646
|
const txHash = (0, tx_build_helper_1.getTxHashFromCbor)(signedTxCbor);
|
|
509
|
-
logger.info(`Submit reported tx already known
|
|
647
|
+
logger.info(`Submit reported tx already known, treating as success (${txHash})`);
|
|
510
648
|
return txHash;
|
|
511
649
|
}
|
|
512
650
|
throw err;
|
|
513
651
|
}
|
|
514
652
|
}
|
|
515
653
|
async handleExecutionFailure(job, attempt, err) {
|
|
516
|
-
// Only a pre-submit job may be re-queued
|
|
517
|
-
//
|
|
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.
|
|
654
|
+
// Only a pre-submit (`building`) job may be re-queued or failed here; a `submitting` row's
|
|
655
|
+
// tx may be in a mempool, so it goes to reconciliation.
|
|
520
656
|
const current = await (0, job_store_1.runWithoutAmbientTx)(() => cds_1.default.tx((tx) => (0, job_store_1.getJobById)(tx, job.ID)))
|
|
521
657
|
.catch(() => null);
|
|
522
658
|
if (current && current.status !== 'building') {
|
|
523
|
-
logger.error(`Job ${job.ID}: execution error while ${current.status}
|
|
659
|
+
logger.error(`Job ${job.ID}: execution error while ${current.status}, leaving the outcome to reconciliation:`, err);
|
|
524
660
|
return;
|
|
525
661
|
}
|
|
526
662
|
if (isTransientJobError(err) && attempt < job.maxAttempts) {
|
|
527
663
|
const backoff = retryBackoffMs(attempt);
|
|
528
|
-
logger.warn(`Job ${job.ID}: transient failure on attempt ${attempt}/${job.maxAttempts}
|
|
664
|
+
logger.warn(`Job ${job.ID}: transient failure on attempt ${attempt}/${job.maxAttempts}, retrying in ${backoff}ms:`, err);
|
|
529
665
|
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
666
|
return;
|
|
531
667
|
}
|