@odatano/core 2.0.0-rc.19 → 2.0.0-rc.20
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 +1 -5
- package/@cds-models/CardanoIndexerService/index.d.ts +51 -2
- package/@cds-models/CardanoIndexerService/index.js +7 -0
- package/package.json +1 -1
- package/src/index.d.ts +4 -10
- package/src/index.js +6 -16
- package/src/plugin.js +11 -27
- package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
- package/srv/blockchain/backends/blockfrost-backend.js +39 -150
- package/srv/blockchain/backends/cardano-backend.d.ts +53 -171
- package/srv/blockchain/backends/cardano-backend.js +1 -5
- package/srv/blockchain/backends/koios-backend.d.ts +26 -71
- package/srv/blockchain/backends/koios-backend.js +50 -132
- package/srv/blockchain/backends/ogmios-backend.d.ts +43 -124
- package/srv/blockchain/backends/ogmios-backend.js +71 -179
- package/srv/blockchain/backends/ogmios-frame-guard.d.ts +12 -57
- package/srv/blockchain/backends/ogmios-frame-guard.js +27 -66
- package/srv/blockchain/cardano-client.d.ts +43 -216
- package/srv/blockchain/cardano-client.js +49 -234
- package/srv/blockchain/cardano-indexer.d.ts +79 -357
- package/srv/blockchain/cardano-indexer.js +98 -406
- package/srv/blockchain/cardano-tx-builder.d.ts +19 -84
- package/srv/blockchain/cardano-tx-builder.js +21 -107
- package/srv/blockchain/crawler/certificate-backfill.d.ts +45 -0
- package/srv/blockchain/crawler/certificate-backfill.js +150 -0
- package/srv/blockchain/crawler/crawler.d.ts +41 -145
- package/srv/blockchain/crawler/crawler.js +57 -172
- package/srv/blockchain/crawler/hooks.d.ts +3 -14
- package/srv/blockchain/crawler/index.d.ts +2 -6
- package/srv/blockchain/crawler/index.js +4 -9
- package/srv/blockchain/crawler/sync-state.d.ts +17 -39
- package/srv/blockchain/crawler/sync-state.js +23 -55
- package/srv/blockchain/crawler/utxo-set-import.d.ts +5 -22
- package/srv/blockchain/crawler/utxo-set-import.js +8 -28
- package/srv/blockchain/ledger-state.d.ts +3 -12
- package/srv/blockchain/signing/cose-verifier.d.ts +5 -12
- package/srv/blockchain/signing/cose-verifier.js +6 -12
- package/srv/blockchain/signing/external-signer.d.ts +16 -113
- package/srv/blockchain/signing/external-signer.js +19 -122
- package/srv/blockchain/signing/hsm-signer.d.ts +13 -45
- package/srv/blockchain/signing/hsm-signer.js +23 -63
- package/srv/blockchain/signing/signature-verifier.d.ts +8 -44
- package/srv/blockchain/signing/signature-verifier.js +13 -54
- package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
- package/srv/blockchain/signing/submission-finalizer.js +16 -48
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +65 -174
- package/srv/blockchain/transaction-building/buildooor-tx.js +107 -266
- package/srv/blockchain/transaction-building/cardano-tx.d.ts +8 -34
- package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
- package/srv/blockchain/wallet-worker/build-request.js +9 -22
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +12 -35
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +16 -32
- package/srv/blockchain/wallet-worker/index.js +2 -8
- package/srv/blockchain/wallet-worker/job-store.d.ts +33 -111
- package/srv/blockchain/wallet-worker/job-store.js +0 -0
- package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +4 -20
- package/srv/blockchain/wallet-worker/lease-heartbeat.js +4 -20
- package/srv/blockchain/wallet-worker/signers.d.ts +6 -19
- package/srv/blockchain/wallet-worker/signers.js +3 -8
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +15 -71
- package/srv/blockchain/wallet-worker/wallet-worker.js +34 -90
- package/srv/cardano-agent-service.cds +1 -5
- package/srv/cardano-agent-service.js +3 -7
- package/srv/cardano-indexer-service.cds +32 -4
- package/srv/cardano-indexer-service.js +83 -15
- package/srv/cardano-service.js +36 -98
- package/srv/cardano-sign-service.cds +1 -1
- package/srv/cardano-sign-service.js +55 -173
- package/srv/cardano-tx-service.cds +1 -1
- package/srv/cardano-tx-service.js +54 -174
- package/srv/cardano-worker-service.js +7 -15
- package/srv/server.d.ts +27 -86
- package/srv/server.js +52 -148
- package/srv/utils/agent-grants-config.d.ts +11 -50
- package/srv/utils/agent-grants-config.js +12 -45
- package/srv/utils/agent-grants.d.ts +34 -123
- package/srv/utils/agent-grants.js +57 -156
- package/srv/utils/agent-token-auth.d.ts +2 -5
- package/srv/utils/agent-token-auth.js +2 -5
- package/srv/utils/backend-request-handler.d.ts +2 -16
- package/srv/utils/backend-request-handler.js +3 -18
- package/srv/utils/collections.d.ts +4 -8
- package/srv/utils/collections.js +4 -8
- package/srv/utils/const.d.ts +19 -68
- package/srv/utils/const.js +20 -69
- package/srv/utils/crypto.d.ts +3 -12
- package/srv/utils/crypto.js +5 -18
- package/srv/utils/db-indexes.d.ts +2 -7
- package/srv/utils/db-indexes.js +7 -34
- package/srv/utils/db-sanitize.d.ts +5 -18
- package/srv/utils/db-sanitize.js +6 -19
- package/srv/utils/error-codes.d.ts +18 -73
- package/srv/utils/error-codes.js +17 -70
- package/srv/utils/errors.d.ts +29 -191
- package/srv/utils/errors.js +44 -229
- package/srv/utils/liveness.d.ts +2 -9
- package/srv/utils/liveness.js +3 -11
- package/srv/utils/mappers.d.ts +50 -298
- package/srv/utils/mappers.js +80 -386
- package/srv/utils/network-context.js +2 -11
- package/srv/utils/pg-order-nulls.js +4 -23
- package/srv/utils/plutus-placeholders.d.ts +6 -18
- package/srv/utils/plutus-placeholders.js +6 -20
- package/srv/utils/rate-limiter.d.ts +6 -17
- package/srv/utils/rate-limiter.js +5 -15
- package/srv/utils/service-events.d.ts +2 -22
- package/srv/utils/service-events.js +3 -23
- package/srv/utils/signing-helper.d.ts +3 -18
- package/srv/utils/signing-helper.js +10 -32
- package/srv/utils/tx-build-helper.d.ts +18 -92
- package/srv/utils/tx-build-helper.js +32 -123
- package/srv/utils/tx-request-parsers.d.ts +7 -26
- package/srv/utils/tx-request-parsers.js +7 -26
- package/srv/utils/tx-utils.d.ts +4 -23
- package/srv/utils/tx-utils.js +12 -41
- package/srv/utils/types.d.ts +67 -206
- package/srv/utils/types.js +2 -6
- package/srv/utils/validators.d.ts +19 -89
- package/srv/utils/validators.js +31 -138
|
@@ -15,8 +15,7 @@ using {odatano.cardano as db} from '../db/schema';
|
|
|
15
15
|
* on every request BEFORE the operation's own annotation, so an operation-level
|
|
16
16
|
* `@requires: 'any'` can never open a single function on an otherwise
|
|
17
17
|
* authenticated service (anonymous callers get the 401 challenge first). The
|
|
18
|
-
* requirement therefore sits on each element, and getLiveness() alone is 'any'
|
|
19
|
-
* the same layout as NIGHTGATE's indexer service.
|
|
18
|
+
* requirement therefore sits on each element, and getLiveness() alone is 'any'.
|
|
20
19
|
*/
|
|
21
20
|
// Service-level 'any' on purpose: CAP authorizes the service BEFORE the operation and
|
|
22
21
|
// treats a service without a service-level @requires as authenticated-user under
|
|
@@ -53,6 +52,31 @@ service CardanoIndexerService @(impl: './cardano-indexer-service') {
|
|
|
53
52
|
consecutiveErrors : Integer;
|
|
54
53
|
// crawler-fed ledger state (crawler.utxoSet): snapshot anchor + validity
|
|
55
54
|
utxoSet : UtxoSetStatus;
|
|
55
|
+
// one-off certificate/withdrawal backfill over already crawled blocks (this process)
|
|
56
|
+
certificateBackfill : CertificateBackfillStatus;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
@title : 'Certificate Backfill Status'
|
|
60
|
+
@description: 'Progress of the certificate/withdrawal backfill started with backfillCertificates; process-local, none after a restart'
|
|
61
|
+
type CertificateBackfillStatus {
|
|
62
|
+
status : String; // none | running | done | failed
|
|
63
|
+
fromSlot : String;
|
|
64
|
+
toSlot : String;
|
|
65
|
+
atSlot : String; // last slot handled
|
|
66
|
+
blocks : Integer64;
|
|
67
|
+
certificates : Integer64;
|
|
68
|
+
withdrawals : Integer64;
|
|
69
|
+
startedAt : Timestamp;
|
|
70
|
+
finishedAt : Timestamp;
|
|
71
|
+
error : String;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
@title : 'Certificate Backfill Result'
|
|
75
|
+
type CertificateBackfillResult {
|
|
76
|
+
accepted : Boolean;
|
|
77
|
+
fromSlot : String;
|
|
78
|
+
toSlot : String;
|
|
79
|
+
message : String;
|
|
56
80
|
}
|
|
57
81
|
|
|
58
82
|
@title : 'UTxO Set Status'
|
|
@@ -112,8 +136,7 @@ service CardanoIndexerService @(impl: './cardano-indexer-service') {
|
|
|
112
136
|
// Anonymous on purpose: a liveness probe carries no credentials. 200 as long
|
|
113
137
|
// as the process answers — no backend or DB probe, no secrets, no backend
|
|
114
138
|
// names, no API key state. Readiness stays with getStatus and the worker
|
|
115
|
-
// status, which remain authenticated.
|
|
116
|
-
// `/api/v1/indexer/getLiveness()`, so a gateway probes both products the same way.
|
|
139
|
+
// status, which remain authenticated.
|
|
117
140
|
@title : 'Get Liveness'
|
|
118
141
|
@description: 'Unauthenticated liveness probe: 200 while the process answers. Docker HEALTHCHECK and upstream probes use this instead of the service document.'
|
|
119
142
|
@requires : 'any'
|
|
@@ -133,4 +156,9 @@ service CardanoIndexerService @(impl: './cardano-indexer-service') {
|
|
|
133
156
|
@description: 'One-off import of the UTxO set that anchors crawler.utxoSet. Pause the crawler first. source=ogmios acquires the set at the crawler cursor (crawl must be at the tip); source=file loads a cardano-cli query utxo --whole-utxo dump (.json, or .ndjson from jq -c to_entries[]) taken at anchorSlot/anchorHash. Runs in the background; progress via getStatus().utxoSet.'
|
|
134
157
|
@requires : 'Admin'
|
|
135
158
|
action importUtxoSet(source: String, filePath: String, anchorSlot: Integer64, anchorHash: String) returns UtxoSetImportResult;
|
|
159
|
+
|
|
160
|
+
@title : 'Backfill Certificates'
|
|
161
|
+
@description: 'Fill TransactionCertificates and TransactionWithdrawals for blocks the crawl already holds, from a second chain-sync stream (Ogmios). fromSlot defaults to the crawl start, toSlot to the cursor. Writes only those two tables; the crawler may keep running. Runs in the background; progress via getStatus().certificateBackfill.'
|
|
162
|
+
@requires : 'Admin'
|
|
163
|
+
action backfillCertificates(fromSlot: Integer64, toSlot: Integer64) returns CertificateBackfillResult;
|
|
136
164
|
}
|
|
@@ -9,12 +9,19 @@ const errors_1 = require("./utils/errors");
|
|
|
9
9
|
const crawler_1 = require("./blockchain/crawler");
|
|
10
10
|
const sync_state_1 = require("./blockchain/crawler/sync-state");
|
|
11
11
|
const utxo_set_import_1 = require("./blockchain/crawler/utxo-set-import");
|
|
12
|
+
const certificate_backfill_1 = require("./blockchain/crawler/certificate-backfill");
|
|
12
13
|
const validators_1 = require("./utils/validators");
|
|
13
14
|
const server_1 = require("./server");
|
|
14
15
|
const liveness_1 = require("./utils/liveness");
|
|
15
16
|
const logger = cds_1.default.log('CardanoIndexerService');
|
|
16
17
|
/** One import at a time per process; the promise is only used as the busy flag. */
|
|
17
18
|
let utxoSetImportInFlight = null;
|
|
19
|
+
/** Set while a start request is validated, so a second request cannot start a parallel run. */
|
|
20
|
+
let certificateBackfillStarting = false;
|
|
21
|
+
let certificateBackfill = {
|
|
22
|
+
status: 'none', fromSlot: 0, toSlot: 0, atSlot: 0, blocks: 0, transactions: 0, certificates: 0, withdrawals: 0,
|
|
23
|
+
startedAt: null, finishedAt: null, error: null,
|
|
24
|
+
};
|
|
18
25
|
function utxoSetConfigured() {
|
|
19
26
|
try {
|
|
20
27
|
return Boolean((0, server_1.loadCrawlerConfigFromEnv)()?.utxoSet);
|
|
@@ -24,14 +31,13 @@ function utxoSetConfigured() {
|
|
|
24
31
|
}
|
|
25
32
|
}
|
|
26
33
|
/**
|
|
27
|
-
* CardanoIndexerService handlers
|
|
28
|
-
* singleton (srv/blockchain/crawler).
|
|
29
|
-
* cursor and starts/stops the crawler.
|
|
34
|
+
* CardanoIndexerService handlers: control/observability surface over the crawler
|
|
35
|
+
* singleton (srv/blockchain/crawler). Reads the cursor and starts/stops the crawler.
|
|
30
36
|
*/
|
|
31
37
|
module.exports = (srv) => {
|
|
32
38
|
// getLiveness — unauthenticated probe (@requires: 'any'); no handleRequest, no app context.
|
|
33
39
|
srv.on('getLiveness', async () => (0, liveness_1.buildLiveness)());
|
|
34
|
-
// getStatus — live run state + sync progress (numeric fields as strings, CAP
|
|
40
|
+
// getStatus — live run state + sync progress (numeric fields as strings, CAP 10 convention)
|
|
35
41
|
srv.on('getStatus', async (req) => {
|
|
36
42
|
return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
|
|
37
43
|
const cursor = await (0, sync_state_1.readCursor)(db);
|
|
@@ -41,8 +47,7 @@ module.exports = (srv) => {
|
|
|
41
47
|
return {
|
|
42
48
|
running: (0, sync_state_1.isCrawlerLeaseActive)(cursor),
|
|
43
49
|
syncStatus: cursor?.syncStatus ?? 'stopped',
|
|
44
|
-
// Process-local
|
|
45
|
-
// standby that does not hold the lease reports null, as does a stopped crawler.
|
|
50
|
+
// Process-local: a standby without the lease or a stopped crawler reports null.
|
|
46
51
|
source: (0, crawler_1.getCrawler)()?.getActiveSource() ?? null,
|
|
47
52
|
lastSlot: String(cursor?.lastSlot ?? 0),
|
|
48
53
|
lastHeight: String(lastHeight),
|
|
@@ -57,11 +62,77 @@ module.exports = (srv) => {
|
|
|
57
62
|
importedAt: cursor?.utxoSet?.importedAt ?? null,
|
|
58
63
|
error: cursor?.utxoSet?.error ?? null,
|
|
59
64
|
},
|
|
65
|
+
certificateBackfill: {
|
|
66
|
+
status: certificateBackfill.status,
|
|
67
|
+
fromSlot: String(certificateBackfill.fromSlot),
|
|
68
|
+
toSlot: String(certificateBackfill.toSlot),
|
|
69
|
+
atSlot: String(certificateBackfill.atSlot),
|
|
70
|
+
blocks: certificateBackfill.blocks,
|
|
71
|
+
certificates: certificateBackfill.certificates,
|
|
72
|
+
withdrawals: certificateBackfill.withdrawals,
|
|
73
|
+
startedAt: certificateBackfill.startedAt,
|
|
74
|
+
finishedAt: certificateBackfill.finishedAt,
|
|
75
|
+
error: certificateBackfill.error,
|
|
76
|
+
},
|
|
60
77
|
};
|
|
61
78
|
});
|
|
62
79
|
});
|
|
63
|
-
//
|
|
64
|
-
//
|
|
80
|
+
// backfillCertificates — second chain-sync stream over already crawled blocks; writes the
|
|
81
|
+
// certificate and withdrawal tables only. Validates, then runs detached.
|
|
82
|
+
srv.on('backfillCertificates', async (req) => {
|
|
83
|
+
const data = (req.data ?? {});
|
|
84
|
+
if (data.fromSlot != null && !Number.isInteger(Number(data.fromSlot)))
|
|
85
|
+
return (0, errors_1.rejectInvalid)(req, 'backfillCertificates', 'fromSlot must be an integer', 'fromSlot');
|
|
86
|
+
if (data.toSlot != null && !Number.isInteger(Number(data.toSlot)))
|
|
87
|
+
return (0, errors_1.rejectInvalid)(req, 'backfillCertificates', 'toSlot must be an integer', 'toSlot');
|
|
88
|
+
if (certificateBackfill.status === 'running' || certificateBackfillStarting)
|
|
89
|
+
return (0, errors_1.rejectInvalid)(req, 'backfillCertificates', 'A certificate backfill is already running');
|
|
90
|
+
if (!(0, server_1.getCardanoClient)().getChainSyncBackend())
|
|
91
|
+
return (0, errors_1.rejectInvalid)(req, 'backfillCertificates', 'No chain-sync backend available (needs Ogmios)');
|
|
92
|
+
certificateBackfillStarting = true;
|
|
93
|
+
try {
|
|
94
|
+
return await (0, backend_request_handler_1.handleRequest)(req, async (db) => {
|
|
95
|
+
const cursor = await (0, sync_state_1.readCursor)(db);
|
|
96
|
+
if (!cursor)
|
|
97
|
+
throw new errors_1.TransactionValidationError('No crawler cursor yet — the backfill covers crawled blocks only.');
|
|
98
|
+
const fromSlot = data.fromSlot != null ? Number(data.fromSlot) : (cursor.startSlot ?? 0);
|
|
99
|
+
const toSlot = data.toSlot != null ? Number(data.toSlot) : cursor.lastSlot;
|
|
100
|
+
if (toSlot < fromSlot)
|
|
101
|
+
throw new errors_1.TransactionValidationError(`toSlot ${toSlot} lies before fromSlot ${fromSlot}.`);
|
|
102
|
+
if (toSlot > cursor.lastSlot)
|
|
103
|
+
throw new errors_1.TransactionValidationError(`toSlot ${toSlot} is past the crawler cursor (slot ${cursor.lastSlot}) — only crawled blocks can be backfilled.`);
|
|
104
|
+
certificateBackfill = {
|
|
105
|
+
status: 'running', fromSlot, toSlot, atSlot: fromSlot, blocks: 0, transactions: 0, certificates: 0, withdrawals: 0,
|
|
106
|
+
startedAt: new Date().toISOString(), finishedAt: null, error: null,
|
|
107
|
+
};
|
|
108
|
+
void (0, certificate_backfill_1.backfillCertificates)({
|
|
109
|
+
client: (0, server_1.getCardanoClient)(), fromSlot, toSlot,
|
|
110
|
+
onProgress: (p) => {
|
|
111
|
+
Object.assign(certificateBackfill, p);
|
|
112
|
+
if (certificateBackfill.blocks % 20_000 < 200)
|
|
113
|
+
logger.info(`Certificate backfill at slot ${p.atSlot}: ${p.blocks} blocks, ${p.certificates} certificates, ${p.withdrawals} withdrawals`);
|
|
114
|
+
},
|
|
115
|
+
})
|
|
116
|
+
.then((r) => { Object.assign(certificateBackfill, r, { status: 'done', finishedAt: new Date().toISOString() }); })
|
|
117
|
+
.catch((err) => {
|
|
118
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
119
|
+
Object.assign(certificateBackfill, { status: 'failed', finishedAt: new Date().toISOString(), error: message.slice(0, 500) });
|
|
120
|
+
logger.error(`Certificate backfill failed: ${message}`);
|
|
121
|
+
});
|
|
122
|
+
return {
|
|
123
|
+
accepted: true,
|
|
124
|
+
fromSlot: String(fromSlot),
|
|
125
|
+
toSlot: String(toSlot),
|
|
126
|
+
message: `Certificate backfill started for slots ${fromSlot}..${toSlot}; poll getStatus().certificateBackfill.`,
|
|
127
|
+
};
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
finally {
|
|
131
|
+
certificateBackfillStarting = false;
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
// importUtxoSet — one-off snapshot import that anchors crawler.utxoSet. Validates, then
|
|
135
|
+
// runs detached; progress via getStatus().utxoSet.
|
|
65
136
|
srv.on('importUtxoSet', async (req) => {
|
|
66
137
|
const data = (req.data ?? {});
|
|
67
138
|
const source = data.source === 'file' || data.source === 'ogmios' ? data.source : null;
|
|
@@ -119,19 +190,16 @@ module.exports = (srv) => {
|
|
|
119
190
|
return true;
|
|
120
191
|
});
|
|
121
192
|
});
|
|
122
|
-
// resumeCrawler — (re)start from the persisted cursor
|
|
123
|
-
//
|
|
124
|
-
//
|
|
125
|
-
// NOTE: to apply CHANGED config to a running crawler, call pauseCrawler first —
|
|
126
|
-
// resume on a running crawler is a no-op by design.
|
|
193
|
+
// resumeCrawler — (re)start from the persisted cursor. Gated on config.enabled so an
|
|
194
|
+
// unconfigured crawler is never started (it would sync from genesis). Resume on a running
|
|
195
|
+
// crawler is a no-op; pauseCrawler first to apply changed config.
|
|
127
196
|
srv.on('resumeCrawler', async (req) => {
|
|
128
197
|
let config;
|
|
129
198
|
try {
|
|
130
199
|
config = (0, server_1.loadCrawlerConfigFromEnv)();
|
|
131
200
|
}
|
|
132
201
|
catch (err) {
|
|
133
|
-
// e.g.
|
|
134
|
-
// caller's 400, not a raw 500 from an escaping throw
|
|
202
|
+
// A config problem (e.g. enabled without a start block) is the caller's 400.
|
|
135
203
|
return (0, errors_1.rejectInvalid)(req, 'resumeCrawler', err instanceof Error ? err.message : String(err));
|
|
136
204
|
}
|
|
137
205
|
if (!config.enabled) {
|
package/srv/cardano-service.js
CHANGED
|
@@ -11,28 +11,14 @@ const backend_request_handler_1 = require("./utils/backend-request-handler");
|
|
|
11
11
|
const cbor_1 = require("./cbor");
|
|
12
12
|
const { SELECT } = cds_1.default.ql;
|
|
13
13
|
const logger = cds_1.default.log(`CardanoService`);
|
|
14
|
-
/**
|
|
15
|
-
* Upper bound of the temporal window opened by {@link widenTemporalWindow}.
|
|
16
|
-
* Generous on purpose: it only has to outlast the slowest index-on-miss (chained
|
|
17
|
-
* backend timeouts of several calls) within ONE request.
|
|
18
|
-
*/
|
|
14
|
+
/** Upper bound of the temporal window; must outlast the slowest index-on-miss of one request. */
|
|
19
15
|
const TEMPORAL_WINDOW_SLACK_MS = 60 * 60 * 1000;
|
|
20
16
|
/**
|
|
21
|
-
* Let this request see temporal slices
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
* transaction begins (HANA) or on first use (sqlite) and otherwise defaults to
|
|
27
|
-
* `now` / `now + 1ms` — a window that is closed long before the backend fetch
|
|
28
|
-
* returns, so a slice stamped after the fetch would be invisible to the
|
|
29
|
-
* `req.query` re-read that honours `$expand` / `$select` (KNOWN_ISSUES #13).
|
|
30
|
-
*
|
|
31
|
-
* Only the UPPER bound is moved. No slice is ever future-dated (every mapper
|
|
32
|
-
* stamps `validFrom = now`), so the only additional rows this admits are the
|
|
33
|
-
* ones this very request writes; expired rows stay hidden (`validTo >
|
|
34
|
-
* $valid.from` is untouched). Explicit `sap-valid-*` query options are left
|
|
35
|
-
* alone. Must run before the handler's first DB statement.
|
|
17
|
+
* Let this request see the temporal slices it writes during index-on-miss: CAP's temporal
|
|
18
|
+
* filter (`validFrom < $valid.to`) defaults to a `now`..`now+1ms` window fixed at transaction
|
|
19
|
+
* start, so a slice stamped after the backend fetch would be invisible to the `req.query`
|
|
20
|
+
* re-read. Only the upper bound moves; explicit `sap-valid-*` options are left alone.
|
|
21
|
+
* Must run before the handler's first DB statement.
|
|
36
22
|
*/
|
|
37
23
|
function widenTemporalWindow(req) {
|
|
38
24
|
const q = req.http?.req?.query;
|
|
@@ -41,9 +27,7 @@ function widenTemporalWindow(req) {
|
|
|
41
27
|
const now = Date.now();
|
|
42
28
|
const from = new Date(now).toISOString();
|
|
43
29
|
const to = new Date(now + TEMPORAL_WINDOW_SLACK_MS).toISOString();
|
|
44
|
-
// The DB session
|
|
45
|
-
// with — `req` for our `cds.tx(req)`, the root context if a generic handler got
|
|
46
|
-
// there first — so stamp both bags.
|
|
30
|
+
// The DB session reads the bag of whichever context opened the transaction; stamp both.
|
|
47
31
|
const r = req;
|
|
48
32
|
for (const bag of new Set([r._, r.context?._])) {
|
|
49
33
|
if (!bag)
|
|
@@ -53,47 +37,32 @@ function widenTemporalWindow(req) {
|
|
|
53
37
|
}
|
|
54
38
|
}
|
|
55
39
|
/**
|
|
56
|
-
* Factory: READ handler with index-on-miss
|
|
57
|
-
*
|
|
58
|
-
* client's own query so `$expand` / `$select` are honoured on the keyed branch
|
|
59
|
-
* too (KNOWN_ISSUES #13: returning the bare row silently dropped them).
|
|
60
|
-
* If no key, passes through to generic req.query.
|
|
40
|
+
* Factory: READ handler with index-on-miss. With a key, indexes on a cache miss and then
|
|
41
|
+
* runs the client's own query so `$expand` / `$select` apply; without a key, passes through.
|
|
61
42
|
*/
|
|
62
43
|
function indexOnMissRead(entity, reqKeyField, validate, indexFn, options) {
|
|
63
44
|
const dbKey = options?.entityKeyField || reqKeyField;
|
|
64
45
|
const errMsg = options?.errorMessage || `Invalid ${reqKeyField} format`;
|
|
65
46
|
return async (req) => {
|
|
66
47
|
const key = req.data?.[reqKeyField];
|
|
67
|
-
//
|
|
68
|
-
// like epoch=0 or an empty string (the latter then hit the backend unvalidated)
|
|
48
|
+
// Explicit null check: falsy keys such as epoch=0 or '' must still be validated.
|
|
69
49
|
if (key !== undefined && key !== null && validate && !validate(key))
|
|
70
50
|
(0, errors_1.rejectInvalid)(req, dbKey, errMsg, reqKeyField);
|
|
71
51
|
return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
|
|
72
52
|
if (key !== undefined && key !== null) {
|
|
73
|
-
widenTemporalWindow(req); // before the first DB statement
|
|
74
|
-
//
|
|
53
|
+
widenTemporalWindow(req); // before the first DB statement
|
|
54
|
+
// The temporal aspect hides expired rows, so a miss here triggers a re-index.
|
|
75
55
|
const existing = await db.run(SELECT.one.from(entity).where({ [dbKey]: key }));
|
|
76
|
-
// Populate the row (+ compositions) on a miss, then let CAP run the client's
|
|
77
|
-
// query — one extra SELECT per keyed read, but $expand/$select (and the
|
|
78
|
-
// temporal filter of the projection) apply exactly as on the un-keyed path.
|
|
79
56
|
if (!existing)
|
|
80
57
|
await indexFn(db, key);
|
|
81
|
-
// The client's query is the
|
|
82
|
-
//
|
|
83
|
-
// answers a request the client never made — a second key that does not
|
|
84
|
-
// match, or an excluding $filter, would get a sibling row with a 200
|
|
85
|
-
// instead of a 404 (KNOWN_ISSUES #15). Non-temporal entities always see
|
|
86
|
-
// their fresh rows here; temporal ones rely on widenTemporalWindow above,
|
|
87
|
-
// and if that ever stops working the failure is a loud 404 covered by
|
|
88
|
-
// test/integration/keyed-read-expand.test.ts, not silently wrong data.
|
|
58
|
+
// The client's query is the only authority on the result: never fall back to
|
|
59
|
+
// `existing`, or an excluding $filter / second key would yield a sibling row instead of 404.
|
|
89
60
|
}
|
|
90
61
|
return db.run(req.query);
|
|
91
62
|
});
|
|
92
63
|
};
|
|
93
64
|
}
|
|
94
|
-
/**
|
|
95
|
-
* Factory: Action handler with required key validation and index-on-miss.
|
|
96
|
-
*/
|
|
65
|
+
/** Factory: action handler with required-key validation and index-on-miss. */
|
|
97
66
|
function indexOnMissAction(actionName, entity, reqKeyField, validate, indexFn, options) {
|
|
98
67
|
const dbKey = options?.entityKeyField || reqKeyField;
|
|
99
68
|
const errMsg = options?.errorMessage || `Invalid ${reqKeyField} format`;
|
|
@@ -104,7 +73,7 @@ function indexOnMissAction(actionName, entity, reqKeyField, validate, indexFn, o
|
|
|
104
73
|
if (!validate(key))
|
|
105
74
|
(0, errors_1.rejectInvalid)(req, actionName, errMsg, reqKeyField);
|
|
106
75
|
return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
|
|
107
|
-
//
|
|
76
|
+
// The temporal aspect hides expired rows, so a miss here triggers a re-index.
|
|
108
77
|
const existing = await db.run(SELECT.one.from(entity).where({ [dbKey]: key }));
|
|
109
78
|
if (!existing)
|
|
110
79
|
return await indexFn(db, key);
|
|
@@ -115,23 +84,14 @@ function indexOnMissAction(actionName, entity, reqKeyField, validate, indexFn, o
|
|
|
115
84
|
// ---------------------------------------------------------------------------
|
|
116
85
|
// Service Registration
|
|
117
86
|
// ---------------------------------------------------------------------------
|
|
118
|
-
/**
|
|
119
|
-
* Cardano Service Implementation
|
|
120
|
-
* Handles various Cardano blockchain data queries with index-on-miss behavior.
|
|
121
|
-
*/
|
|
87
|
+
/** CardanoODataService handlers: blockchain read queries with index-on-miss. */
|
|
122
88
|
module.exports = (srv) => {
|
|
123
89
|
logger.debug('Module loaded - registering handlers');
|
|
124
|
-
//
|
|
125
|
-
//
|
|
126
|
-
//
|
|
127
|
-
// registration must use the plural class — under cds 10 registering `srv.on('READ',
|
|
128
|
-
// <singular proxy>)` no longer matches incoming OData READs, so the generic CRUD
|
|
129
|
-
// handler silently served those entities (empty results / 404 instead of
|
|
130
|
-
// index-on-miss). All other names below already resolve to plural classes.
|
|
90
|
+
// For plural-shaped names (NetworkInformation, TransactionMetadata, AssetHistory) cds-typer
|
|
91
|
+
// exports the singular class under the plain name and the entity-set class with a trailing
|
|
92
|
+
// underscore. Handlers must register the entity-set class; a singular one never matches under cds 10.
|
|
131
93
|
const { NetworkInformation_: NetworkInformation, Blocks, Epochs, Addresses, AddressAssets, AddressUTxOs, Transactions, TransactionMetadata_: TransactionMetadata, Pools, Accounts, Dreps, Assets, AssetHistory_: AssetHistory, LedgerProtocolParameters, AddressTransactions } = require('#cds-models/CardanoODataService');
|
|
132
|
-
// Fail fast
|
|
133
|
-
// above): a singular registration silently degrades to the generic CRUD handler.
|
|
134
|
-
// Every cds-typer proxy carries an explicit is_singular marker we can assert on.
|
|
94
|
+
// Fail fast on a singular class: it would silently degrade to the generic CRUD handler.
|
|
135
95
|
for (const [name, entity] of Object.entries({
|
|
136
96
|
NetworkInformation, Blocks, Epochs, Addresses, AddressAssets, AddressUTxOs,
|
|
137
97
|
Transactions, TransactionMetadata, Pools, Accounts, Dreps, Assets, AssetHistory,
|
|
@@ -143,7 +103,6 @@ module.exports = (srv) => {
|
|
|
143
103
|
`plural entity-set class instead (e.g. '${name}_ as ${name}').`);
|
|
144
104
|
}
|
|
145
105
|
}
|
|
146
|
-
// Helper: shorthand for indexer access
|
|
147
106
|
const indexer = () => (0, server_1.getCardanoIndexer)();
|
|
148
107
|
// ---------------------------------------------------------------------------
|
|
149
108
|
// Network Information (singleton - no key field)
|
|
@@ -197,18 +156,13 @@ module.exports = (srv) => {
|
|
|
197
156
|
srv.on('READ', Assets, indexOnMissRead(Assets, 'unit', validators_1.isAssetUnit, (db, u) => indexer().indexAsset(db, u), { errorMessage: 'Invalid asset unit format' }));
|
|
198
157
|
srv.on('GetAssetInfo', indexOnMissAction('GetAssetInfo', Assets, 'unit', validators_1.isAssetUnit, (db, u) => indexer().indexAsset(db, u), { errorMessage: 'Invalid asset unit format' }));
|
|
199
158
|
// ---------------------------------------------------------------------------
|
|
200
|
-
// Asset History
|
|
159
|
+
// Asset History
|
|
201
160
|
// ---------------------------------------------------------------------------
|
|
202
|
-
// Generic READ
|
|
203
|
-
// must call GetAssetHistory(unit) first to seed entries for a given asset,
|
|
204
|
-
// then page via $top/$skip on the AssetHistory entity.
|
|
161
|
+
// Generic READ is served from the DB only; GetAssetHistory(unit) seeds the rows.
|
|
205
162
|
srv.on('READ', AssetHistory, async (req) => {
|
|
206
163
|
return (0, backend_request_handler_1.handleRequest)(req, async (db) => db.run(req.query));
|
|
207
164
|
});
|
|
208
|
-
|
|
209
|
-
* Action: GetAssetHistory - Always-fresh fetch of recent mint/burn events.
|
|
210
|
-
* Multi-backend: Koios preferred (block timestamps), Blockfrost fallback.
|
|
211
|
-
*/
|
|
165
|
+
// GetAssetHistory — always-fresh fetch of recent mint/burn events.
|
|
212
166
|
srv.on('GetAssetHistory', async (req) => {
|
|
213
167
|
const { unit, limit } = req.data;
|
|
214
168
|
if (!unit)
|
|
@@ -216,7 +170,7 @@ module.exports = (srv) => {
|
|
|
216
170
|
if (!(0, validators_1.isAssetUnit)(unit)) {
|
|
217
171
|
return (0, errors_1.rejectInvalid)(req, 'GetAssetHistory', 'Invalid asset unit format', 'unit');
|
|
218
172
|
}
|
|
219
|
-
//
|
|
173
|
+
// Clamp: an unbounded limit would page the upstream backend indefinitely.
|
|
220
174
|
const effectiveLimit = Math.min(Math.max(typeof limit === 'number' ? limit : 100, 1), 100);
|
|
221
175
|
return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
|
|
222
176
|
return await indexer().indexAssetHistory(db, unit, effectiveLimit);
|
|
@@ -227,9 +181,7 @@ module.exports = (srv) => {
|
|
|
227
181
|
// ---------------------------------------------------------------------------
|
|
228
182
|
srv.on('READ', Addresses, indexOnMissRead(Addresses, 'address', validators_1.isValidBech32Address, (db, a) => indexer().indexAddress(db, a), { errorMessage: 'Invalid bech32 address format' }));
|
|
229
183
|
srv.on('GetAddressByBech32', indexOnMissAction('GetAddressByBech32', Addresses, 'address', validators_1.isValidBech32Address, (db, a) => indexer().indexAddress(db, a), { errorMessage: 'Invalid bech32 address format' }));
|
|
230
|
-
|
|
231
|
-
* Action: GetAssetsByAddress - indexes parent address if needed, then queries child assets.
|
|
232
|
-
*/
|
|
184
|
+
// GetAssetsByAddress — indexes the parent address if needed, then queries child assets.
|
|
233
185
|
srv.on('GetAssetsByAddress', async (req) => {
|
|
234
186
|
const { address } = req.data;
|
|
235
187
|
if (!address)
|
|
@@ -241,7 +193,7 @@ module.exports = (srv) => {
|
|
|
241
193
|
if (!existing)
|
|
242
194
|
await indexer().indexAddress(db, address);
|
|
243
195
|
const assets = await db.run(SELECT.from(AddressAssets).where({ address_address: address }));
|
|
244
|
-
//
|
|
196
|
+
// Keep the latest temporal slice per unit
|
|
245
197
|
const seen = new Map();
|
|
246
198
|
for (const asset of assets) {
|
|
247
199
|
if (!seen.has(asset.unit) || asset.validFrom > seen.get(asset.unit).validFrom) {
|
|
@@ -251,9 +203,7 @@ module.exports = (srv) => {
|
|
|
251
203
|
return Array.from(seen.values());
|
|
252
204
|
});
|
|
253
205
|
});
|
|
254
|
-
|
|
255
|
-
* Action: GetUTxOsByAddress - indexes parent address if needed, then queries child UTxOs.
|
|
256
|
-
*/
|
|
206
|
+
// GetUTxOsByAddress — indexes the parent address if needed, then queries child UTxOs.
|
|
257
207
|
srv.on('GetUTxOsByAddress', async (req) => {
|
|
258
208
|
const { address } = req.data;
|
|
259
209
|
if (!address)
|
|
@@ -263,14 +213,9 @@ module.exports = (srv) => {
|
|
|
263
213
|
return (0, backend_request_handler_1.handleRequest)(req, async (db) => {
|
|
264
214
|
const existing = await db.run(SELECT.from(AddressUTxOs).where({ address_address: address }));
|
|
265
215
|
if (!existing || existing.length === 0) {
|
|
266
|
-
//
|
|
267
|
-
//
|
|
268
|
-
//
|
|
269
|
-
// only needs the UTxO set, which Ogmios serves via getAddressUtxos even though it
|
|
270
|
-
// doesn't support getAddress — so when NO configured backend can serve getAddress
|
|
271
|
-
// (AllBackendsFailedError with zero collected errors == every backend skipped it),
|
|
272
|
-
// fall back to a UTxO-only index instead of failing. getAddress is indexAddress's
|
|
273
|
-
// first call, so nothing is persisted before this throws — the fallback is clean.
|
|
216
|
+
// Prefer the full address index; when no configured backend supports getAddress
|
|
217
|
+
// (AllBackendsFailedError with zero collected errors, e.g. Ogmios only), fall back to a
|
|
218
|
+
// UTxO-only index. getAddress is indexAddress's first call, so nothing is persisted before.
|
|
274
219
|
try {
|
|
275
220
|
await indexer().indexAddress(db, address);
|
|
276
221
|
}
|
|
@@ -285,7 +230,7 @@ module.exports = (srv) => {
|
|
|
285
230
|
const fresh = await db.run(SELECT.from(AddressUTxOs).where({ address_address: address }));
|
|
286
231
|
return fresh;
|
|
287
232
|
}
|
|
288
|
-
//
|
|
233
|
+
// Keep the latest temporal slice per hash#index
|
|
289
234
|
const seen = new Map();
|
|
290
235
|
for (const utxo of existing) {
|
|
291
236
|
const key = `${utxo.hash}#${utxo.index}`;
|
|
@@ -296,12 +241,8 @@ module.exports = (srv) => {
|
|
|
296
241
|
return Array.from(seen.values());
|
|
297
242
|
});
|
|
298
243
|
});
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
* Always-fresh (no cache check) — credential queries serve dApp state-read use
|
|
302
|
-
* cases (Indigo CDPs, Liqwid positions) that need current blockchain state.
|
|
303
|
-
* Throws ProviderUnavailableError if Koios backend is not configured.
|
|
304
|
-
*/
|
|
244
|
+
// GetUTxOsByCredential — Koios-only, always-fresh credential-keyed UTxO query
|
|
245
|
+
// (dApp state reads need current data). ProviderUnavailableError without Koios.
|
|
305
246
|
srv.on('GetUTxOsByCredential', async (req) => {
|
|
306
247
|
const { credential } = req.data;
|
|
307
248
|
if (!credential)
|
|
@@ -322,10 +263,7 @@ module.exports = (srv) => {
|
|
|
322
263
|
// Transaction Metadata
|
|
323
264
|
// ---------------------------------------------------------------------------
|
|
324
265
|
srv.on('READ', TransactionMetadata, indexOnMissRead(TransactionMetadata, 'tx_hash', validators_1.isTxHash, (db, h) => indexer().indexTransactionMetadata(db, h), { errorMessage: 'Invalid transaction hash format' }));
|
|
325
|
-
|
|
326
|
-
* Action: GetMetadataByTxHash - returns multiple metadata rows (uses SELECT.from, not SELECT.one).
|
|
327
|
-
* Takes camelCase `txHash` like every other action (renamed from `tx_hash` in 1.9.4).
|
|
328
|
-
*/
|
|
266
|
+
// GetMetadataByTxHash — returns all metadata rows of a transaction.
|
|
329
267
|
srv.on('GetMetadataByTxHash', async (req) => {
|
|
330
268
|
const { txHash } = req.data;
|
|
331
269
|
if (!txHash)
|
|
@@ -355,7 +293,7 @@ module.exports = (srv) => {
|
|
|
355
293
|
return (0, backend_request_handler_1.handleRequest)(req, (db) => indexer().indexProtocolParameters(db));
|
|
356
294
|
});
|
|
357
295
|
// ---------------------------------------------------------------------------
|
|
358
|
-
// Transaction CBOR parsing (pure
|
|
296
|
+
// Transaction CBOR parsing (pure; no backend or DB access)
|
|
359
297
|
// ---------------------------------------------------------------------------
|
|
360
298
|
srv.on('ParseTransactionCbor', async (req) => {
|
|
361
299
|
const { cbor } = req.data;
|
|
@@ -97,7 +97,7 @@ service CardanoSignService @(impl: './cardano-sign-service') {
|
|
|
97
97
|
@description: 'Optional sender address for ownership verification. When provided, verifies the signing request belongs to this address.'
|
|
98
98
|
address: Bech32,
|
|
99
99
|
@title: 'Defer Submit'
|
|
100
|
-
@description: 'When true, verify + claim run on the caller''s transaction and the network submit happens detached AFTER the caller''s commit. Returns immediately with the tx hash (= tx body hash) and status ''pending''. Designed for in-process CAP consumers whose request transaction would otherwise deadlock the pooled sqlite connection
|
|
100
|
+
@description: 'When true, verify + claim run on the caller''s transaction and the network submit happens detached AFTER the caller''s commit. Returns immediately with the tx hash (= tx body hash) and status ''pending''. Designed for in-process CAP consumers whose request transaction would otherwise deadlock the pooled sqlite connection. Track the outcome via the signing request / submission status.'
|
|
101
101
|
deferSubmit: Boolean) returns TransactionSubmissions;
|
|
102
102
|
|
|
103
103
|
|