@odatano/core 2.0.0-rc.23 → 2.0.0-rc.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/@cds-models/CardanoBackendService/index.d.ts +357 -0
  2. package/@cds-models/CardanoBackendService/index.js +40 -0
  3. package/@cds-models/CardanoIndexerService/index.d.ts +37 -0
  4. package/@cds-models/CardanoIndexerService/index.js +4 -0
  5. package/@cds-models/CardanoODataService/index.d.ts +27 -2
  6. package/@cds-models/CardanoODataService/index.js +3 -0
  7. package/@cds-models/CardanoSignService/index.d.ts +23 -1
  8. package/@cds-models/CardanoSignService/index.js +3 -0
  9. package/@cds-models/CardanoTransactionService/index.d.ts +34 -1
  10. package/@cds-models/CardanoTransactionService/index.js +4 -0
  11. package/@cds-models/index.d.ts +18 -0
  12. package/@cds-models/index.js +3 -0
  13. package/@cds-models/odatano/cardano/index.d.ts +49 -2
  14. package/@cds-models/odatano/cardano/index.js +6 -0
  15. package/db/schema.cds +74 -3
  16. package/db/types.cds +27 -0
  17. package/package.json +182 -181
  18. package/srv/blockchain/backends/blockfrost-backend.js +4 -2
  19. package/srv/blockchain/backends/cardano-backend.d.ts +0 -2
  20. package/srv/blockchain/backends/koios-backend.d.ts +1 -1
  21. package/srv/blockchain/backends/koios-backend.js +61 -14
  22. package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
  23. package/srv/blockchain/backends/odatano-backend.js +166 -0
  24. package/srv/blockchain/backends/ogmios-backend.d.ts +12 -2
  25. package/srv/blockchain/backends/ogmios-backend.js +91 -21
  26. package/srv/blockchain/cardano-client.d.ts +23 -9
  27. package/srv/blockchain/cardano-client.js +77 -25
  28. package/srv/blockchain/cardano-indexer.d.ts +61 -15
  29. package/srv/blockchain/cardano-indexer.js +248 -79
  30. package/srv/blockchain/cardano-tx-builder.d.ts +11 -1
  31. package/srv/blockchain/cardano-tx-builder.js +59 -4
  32. package/srv/blockchain/crawler/certificate-backfill.d.ts +22 -0
  33. package/srv/blockchain/crawler/certificate-backfill.js +49 -30
  34. package/srv/blockchain/crawler/crawler.d.ts +3 -1
  35. package/srv/blockchain/crawler/crawler.js +12 -7
  36. package/srv/blockchain/crawler/sync-state.d.ts +3 -1
  37. package/srv/blockchain/crawler/sync-state.js +15 -2
  38. package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
  39. package/srv/blockchain/crawler/transaction-backfill.js +283 -0
  40. package/srv/blockchain/crawler/utxo-set-import.d.ts +9 -0
  41. package/srv/blockchain/crawler/utxo-set-import.js +138 -47
  42. package/srv/blockchain/ledger-state.d.ts +16 -1
  43. package/srv/blockchain/ledger-state.js +38 -18
  44. package/srv/blockchain/pending-spends.d.ts +28 -0
  45. package/srv/blockchain/pending-spends.js +89 -0
  46. package/srv/blockchain/stored-chain.d.ts +33 -0
  47. package/srv/blockchain/stored-chain.js +234 -0
  48. package/srv/blockchain/transaction-building/buildooor-tx.d.ts +12 -3
  49. package/srv/blockchain/transaction-building/buildooor-tx.js +203 -21
  50. package/srv/blockchain/transaction-building/cardano-tx.d.ts +2 -1
  51. package/srv/blockchain/transaction-rows.d.ts +1 -1
  52. package/srv/blockchain/transaction-rows.js +2 -1
  53. package/srv/blockchain/wallet-worker/build-request.js +1 -1
  54. package/srv/cardano-backend-service.cds +52 -0
  55. package/srv/cardano-backend-service.d.ts +2 -0
  56. package/srv/cardano-backend-service.js +244 -0
  57. package/srv/cardano-indexer-service.cds +201 -176
  58. package/srv/cardano-indexer-service.js +104 -10
  59. package/srv/cardano-service.cds +5 -0
  60. package/srv/cardano-tx-service.cds +39 -0
  61. package/srv/cardano-tx-service.js +88 -14
  62. package/srv/server.js +20 -2
  63. package/srv/utils/agent-grants.js +8 -0
  64. package/srv/utils/const.d.ts +5 -0
  65. package/srv/utils/const.js +6 -1
  66. package/srv/utils/error-codes.d.ts +2 -0
  67. package/srv/utils/error-codes.js +2 -0
  68. package/srv/utils/errors.d.ts +7 -0
  69. package/srv/utils/errors.js +11 -1
  70. package/srv/utils/mappers.d.ts +24 -2
  71. package/srv/utils/mappers.js +49 -0
  72. package/srv/utils/pg-inline-json.d.ts +8 -0
  73. package/srv/utils/pg-inline-json.js +63 -0
  74. package/srv/utils/tx-build-helper.d.ts +2 -0
  75. package/srv/utils/tx-build-helper.js +12 -0
  76. package/srv/utils/tx-request-parsers.d.ts +46 -5
  77. package/srv/utils/tx-request-parsers.js +227 -16
  78. package/srv/utils/types.d.ts +59 -0
  79. package/srv/utils/validators.d.ts +5 -1
  80. package/srv/utils/validators.js +19 -9
@@ -0,0 +1,244 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const cds_1 = __importDefault(require("@sap/cds"));
7
+ const client_1 = require("@cardano-ogmios/client");
8
+ const backend_request_handler_1 = require("./utils/backend-request-handler");
9
+ const errors_1 = require("./utils/errors");
10
+ const validators_1 = require("./utils/validators");
11
+ const server_1 = require("./server");
12
+ const stored_chain_1 = require("./blockchain/stored-chain");
13
+ const logger = cds_1.default.log('CardanoBackendService');
14
+ /** Largest list one call may ask for (hashes, refs, ids, blocks). */
15
+ const MAX_LIST = 500;
16
+ const MAX_LIMIT = 1000;
17
+ /**
18
+ * CardanoBackendService: the provider shape for another ODATANO instance. Stored blocks and
19
+ * transactions come from the index; the rest goes through the indexer's resolvers (crawled data
20
+ * first, then this instance's backends). Answers are JSON strings (safeJSON keeps big integers).
21
+ */
22
+ module.exports = (srv) => {
23
+ const client = () => (0, server_1.getCardanoClient)();
24
+ const indexer = () => (0, server_1.getCardanoIndexer)();
25
+ /** Register an operation: validate, run, answer the JSON of the result. */
26
+ const op = (name, run, validate) => {
27
+ srv.on(name, async (req) => {
28
+ const data = (req.data ?? {});
29
+ validate?.(req, data);
30
+ return (0, backend_request_handler_1.handleRequest)(req, async (db) => client_1.safeJSON.stringify(toPlain(await run(data, db))));
31
+ });
32
+ };
33
+ // --- validation helpers ----------------------------------------------------------------------
34
+ const need = (check, field, what) => (req, data) => {
35
+ if (data[field] == null || data[field] === '')
36
+ (0, errors_1.rejectMissing)(req, req.event, field);
37
+ if (!check(data[field]))
38
+ (0, errors_1.rejectInvalid)(req, req.event, `Invalid ${what}`, field);
39
+ };
40
+ const both = (...checks) => (req, data) => checks.forEach(c => c(req, data));
41
+ const limitOf = (data, fallback) => Math.min(Math.max(Number(data.limit) || fallback, 1), MAX_LIMIT);
42
+ const jsonList = (field, check, what) => (req, data) => {
43
+ if (data[field] == null)
44
+ (0, errors_1.rejectMissing)(req, req.event, field);
45
+ let list;
46
+ try {
47
+ list = JSON.parse(String(data[field]));
48
+ }
49
+ catch {
50
+ (0, errors_1.rejectInvalid)(req, req.event, `${field} must be a JSON array`, field);
51
+ }
52
+ if (!Array.isArray(list) || list.length > MAX_LIST || !list.every(check)) {
53
+ (0, errors_1.rejectInvalid)(req, req.event, `${field} must be a JSON array of up to ${MAX_LIST} ${what}`, field);
54
+ }
55
+ data[field] = list;
56
+ };
57
+ const isRef = (r) => {
58
+ const ref = r;
59
+ return (0, validators_1.isTxHash)(ref?.txHash) && Number.isInteger(ref?.outputIndex) && Number(ref.outputIndex) >= 0;
60
+ };
61
+ // --- blocks and transactions -------------------------------------------------------------------
62
+ op('GetTransaction', async ({ hash }, db) => {
63
+ const stored = (await (0, stored_chain_1.readTransactionsByHash)(db, [String(hash)])).get(String(hash));
64
+ if (stored && !(0, stored_chain_1.lacksOutpoints)(stored))
65
+ return stored;
66
+ if (stored) {
67
+ // An old row without input outpoints: the backend's copy when one can serve it
68
+ if (!client().hasBackendFor('getTransaction'))
69
+ return stored;
70
+ return client().getTransaction(String(hash)).catch(() => stored);
71
+ }
72
+ await indexer().refuseOutsideCrawl(db, 'getTransaction', `Transaction ${hash}`);
73
+ return client().getTransaction(String(hash));
74
+ }, need(validators_1.isTxHash, 'hash', 'transaction hash'));
75
+ op('GetTransactionsBatch', async ({ hashes }, db) => {
76
+ const wanted = hashes;
77
+ const found = await (0, stored_chain_1.readTransactionsByHash)(db, wanted);
78
+ const absent = wanted.filter(h => !found.has(h));
79
+ // old rows without input outpoints: the backend's copy replaces them when it has one
80
+ const stale = wanted.filter(h => found.has(h) && (0, stored_chain_1.lacksOutpoints)(found.get(h)));
81
+ if ((absent.length || stale.length) && client().hasBackendFor('getTransactionsBatch')) {
82
+ let fetched;
83
+ try {
84
+ fetched = await client().getTransactionsBatch([...absent, ...stale]);
85
+ }
86
+ catch (err) {
87
+ if (absent.length)
88
+ throw err;
89
+ fetched = new Map();
90
+ }
91
+ for (const [h, t] of fetched)
92
+ found.set(h, t);
93
+ }
94
+ return found;
95
+ }, jsonList('hashes', validators_1.isTxHash, 'transaction hashes'));
96
+ op('GetTransactionMetadata', async ({ hash }, db) => {
97
+ const stored = await (0, stored_chain_1.readTransactionMetadata)(db, String(hash));
98
+ if (stored)
99
+ return stored;
100
+ await indexer().refuseOutsideCrawl(db, 'getTransactionMetadata', `Transaction ${hash}`);
101
+ return client().getTransactionMetadata(String(hash));
102
+ }, need(validators_1.isTxHash, 'hash', 'transaction hash'));
103
+ op('GetBlock', async ({ hash }, db) => {
104
+ const stored = await (0, stored_chain_1.readBlock)(db, String(hash));
105
+ if (stored)
106
+ return stored;
107
+ await indexer().refuseOutsideCrawl(db, 'getBlock', `Block ${hash}`);
108
+ return client().getBlock(String(hash));
109
+ }, need(validators_1.isBlockHash, 'hash', 'block hash'));
110
+ op('GetBlockByHeight', async ({ height }, db) => {
111
+ const stored = await (0, stored_chain_1.readBlockByHeight)(db, Number(height));
112
+ if (stored)
113
+ return stored;
114
+ const paging = client().getPaginatingBackend();
115
+ if (!paging)
116
+ throw new errors_1.ProviderUnavailableError(`Block at height ${height} is not indexed here`, 'odatano');
117
+ return paging.getBlockByHeight(Number(height));
118
+ }, need(v => Number.isInteger(Number(v)) && Number(v) >= 0, 'height', 'height'));
119
+ op('GetNextBlocks', async ({ afterHash, count, afterHeight }, db) => {
120
+ const n = Math.min(Math.max(Number(count) || 1, 1), MAX_LIST);
121
+ const anchor = await (0, stored_chain_1.readBlock)(db, String(afterHash));
122
+ if (anchor?.height != null) {
123
+ const next = await (0, stored_chain_1.readNextBlocks)(db, anchor.height, n);
124
+ if (next.length)
125
+ return next;
126
+ }
127
+ // Unknown cursor block where this chain has another block at that height: the caller's
128
+ // cursor was orphaned. The crawler recognises this prefix and enters reorg recovery.
129
+ if (!anchor && afterHeight != null) {
130
+ const canonical = await (0, stored_chain_1.readBlockByHeight)(db, Number(afterHeight));
131
+ if (canonical) {
132
+ throw new errors_1.ChainPointMismatchError(`CHAIN_POINT_MISMATCH: cursor block ${afterHash} at height ${afterHeight} is no longer canonical (canonical block: ${canonical.hash})`, 'odatano');
133
+ }
134
+ }
135
+ const paging = client().getPaginatingBackend();
136
+ if (paging) {
137
+ try {
138
+ return await paging.getNextBlocks(String(afterHash), n, afterHeight == null ? undefined : Number(afterHeight));
139
+ }
140
+ catch (err) {
141
+ // the provider's reorg marker, as 409 so it survives production error masking
142
+ const message = err instanceof Error ? err.message : '';
143
+ if (message.startsWith('CHAIN_POINT_MISMATCH:'))
144
+ throw new errors_1.ChainPointMismatchError(message, 'odatano');
145
+ throw err;
146
+ }
147
+ }
148
+ // Nothing indexed past the cursor yet: the caller is at this instance's tip.
149
+ if (anchor)
150
+ return [];
151
+ throw new errors_1.ChainPointMismatchError(`CHAIN_POINT_MISMATCH: cursor block ${afterHash} is unknown to this instance`, 'odatano');
152
+ }, need(validators_1.isBlockHash, 'afterHash', 'block hash'));
153
+ op('GetBlockTransactions', async ({ blockHash }, db) => {
154
+ const stored = await (0, stored_chain_1.readBlockTransactions)(db, String(blockHash));
155
+ if (stored)
156
+ return stored;
157
+ const paging = client().getPaginatingBackend();
158
+ if (!paging)
159
+ throw new errors_1.ProviderUnavailableError(`Transactions of block ${blockHash} are not indexed here`, 'odatano');
160
+ return paging.getBlockTransactions(String(blockHash));
161
+ }, need(validators_1.isBlockHash, 'blockHash', 'block hash'));
162
+ op('GetLatestBlock', async () => client().getLatestBlock());
163
+ op('GetCurrentSlot', async () => client().getCurrentSlot());
164
+ op('GetEpoch', async ({ epoch }) => client().getEpoch(Number(epoch)), need(validators_1.isEpochNumber, 'epoch', 'epoch number'));
165
+ op('GetLatestEpoch', async () => client().getLatestEpoch());
166
+ // --- addresses and UTxOs -------------------------------------------------------------------------
167
+ const address = need(validators_1.isValidBech32Address, 'address', 'bech32 address');
168
+ op('GetAddress', async ({ address: a }, db) => indexer().resolveAddress(db, String(a)), address);
169
+ op('GetAddressUtxos', async ({ address: a }, db) => indexer().resolveAddressUtxos(db, String(a)), address);
170
+ op('GetAddressTransactionHashes', async (data, db) => indexer().resolveAddressTransactionHashes(db, String(data.address), limitOf(data, 10)), address);
171
+ op('GetAddressTransactions', async (data, db) => {
172
+ const hashes = await indexer().resolveAddressTransactionHashes(db, String(data.address), limitOf(data, 10));
173
+ const found = await (0, stored_chain_1.readTransactionsByHash)(db, hashes);
174
+ const missing = hashes.filter(h => !found.has(h));
175
+ if (missing.length)
176
+ for (const [h, t] of await client().getTransactionsBatch(missing))
177
+ found.set(h, t);
178
+ return hashes.map(h => found.get(h)).filter(Boolean);
179
+ }, address);
180
+ op('GetCredentialUtxos', async ({ credential }, db) => indexer().resolveCredentialUtxos(db, String(credential)), need(validators_1.isValidCredential, 'credential', 'payment credential'));
181
+ op('IsUtxoUnspent', async ({ txHash, outputIndex }) => client().isUtxoUnspent(String(txHash), Number(outputIndex)), both(need(validators_1.isTxHash, 'txHash', 'transaction hash'), need(v => Number.isInteger(Number(v)) && Number(v) >= 0, 'outputIndex', 'output index')));
182
+ op('GetUnspentOutputs', async ({ refs }) => {
183
+ const found = await client().getUnspentOutputs(refs);
184
+ if (found == null)
185
+ throw new errors_1.ProviderUnavailableError('Output lookup needs a ledger-state backend (Ogmios)', 'odatano');
186
+ return found;
187
+ }, jsonList('refs', isRef, 'output references'));
188
+ // --- stake, governance, assets, network ------------------------------------------------------
189
+ op('GetAccount', async ({ stakeAddress }, db) => indexer().resolveAccount(db, String(stakeAddress)), need(validators_1.isValidBech32StakeAddress, 'stakeAddress', 'stake address'));
190
+ op('GetPool', async ({ poolId }, db) => indexer().resolvePool(db, String(poolId)), need(validators_1.isValidPoolId, 'poolId', 'pool id'));
191
+ op('GetDrep', async ({ drepId }) => client().getDrep(String(drepId)), need(validators_1.isValidDrepId, 'drepId', 'DRep id'));
192
+ op('GetPoolIds', async () => (await enumeration()).pools.map(p => p.poolId));
193
+ op('GetPools', async ({ ids }) => {
194
+ const wanted = new Set(ids);
195
+ return (await enumeration()).pools.filter(p => wanted.has(p.poolId));
196
+ }, jsonList('ids', validators_1.isValidPoolId, 'pool ids'));
197
+ op('GetDrepIds', async () => (await enumeration()).dreps.map(d => d.drepId));
198
+ op('GetDreps', async ({ ids }) => {
199
+ const wanted = new Set(ids);
200
+ return (await enumeration()).dreps.filter(d => wanted.has(d.drepId));
201
+ }, jsonList('ids', validators_1.isValidDrepId, 'DRep ids'));
202
+ op('GetAssetInfo', async ({ unit }, db) => indexer().resolveAssetInfo(db, String(unit)), need(validators_1.isAssetUnit, 'unit', 'asset unit'));
203
+ op('GetAssetHistory', async (data, db) => indexer().resolveAssetHistory(db, String(data.unit), limitOf(data, 100)), need(validators_1.isAssetUnit, 'unit', 'asset unit'));
204
+ op('GetNetworkInformation', async (_data, db) => indexer().resolveNetworkInformation(db));
205
+ op('GetProtocolParameters', async () => client().getProtocolParameters());
206
+ // --- transactions in flight ------------------------------------------------------------------
207
+ const cbor = need(validators_1.isValidCbor, 'cbor', 'CBOR hex');
208
+ op('EvaluateTransaction', async ({ cbor: c }) => client().evaluateTransaction(String(c)), cbor);
209
+ op('SubmitTransaction', async ({ cbor: c }) => {
210
+ const hash = await client().submitTransaction(String(c));
211
+ logger.info(`submitted ${hash} for a remote instance`);
212
+ return hash;
213
+ }, cbor);
214
+ /**
215
+ * The full pool and DRep set: an enumerating backend (Koios) when configured, else the node's
216
+ * ledger at the latest block (Ogmios). Cached for a minute; callers page through it by id.
217
+ */
218
+ let enumerated = null;
219
+ async function enumeration() {
220
+ if (enumerated && Date.now() - enumerated.at < 60_000)
221
+ return enumerated;
222
+ const koios = client().getEnumeratingBackend();
223
+ if (koios) {
224
+ const [pools, dreps] = await Promise.all([
225
+ koios.getPoolIds().then(ids => koios.getPools(ids)),
226
+ koios.getDrepIds().then(ids => koios.getDreps(ids)),
227
+ ]);
228
+ enumerated = { at: Date.now(), pools, dreps };
229
+ return enumerated;
230
+ }
231
+ const ledger = client().getEpochStateBackend();
232
+ if (!ledger)
233
+ throw new errors_1.ProviderUnavailableError('Pool/DRep enumeration needs Ogmios or Koios', 'odatano');
234
+ const tip = await client().getLatestBlock();
235
+ const state = await ledger.epochStateAt({ slot: tip.slot ?? 0, hash: tip.hash });
236
+ enumerated = { at: Date.now(), pools: state.pools, dreps: state.dreps };
237
+ return enumerated;
238
+ }
239
+ };
240
+ /** Maps become objects, so a batch answer survives JSON. */
241
+ function toPlain(value) {
242
+ return value instanceof Map ? Object.fromEntries(value) : value;
243
+ }
244
+ //# sourceMappingURL=cardano-backend-service.js.map
@@ -1,176 +1,201 @@
1
- using {odatano.cardano as db} from '../db/schema';
2
-
3
- /**
4
- * Cardano Indexer Service (v2.0)
5
- *
6
- * Control + observability surface for the chain crawler / pre-sync engine:
7
- * - read-only projections of the sync cursor and reorg audit log
8
- * - status function + pause/resume actions delegating to the crawler singleton
9
- *
10
- * Security note: see CardanoODataService (cardano-service.cds) for the rationale on
11
- * auth. pause/resume are operational actions — gate behind a dedicated Admin scope.
12
- * Read-only status and audit data remain available to authenticated users.
13
- *
14
- * Deliberately NO service-level @requires: CAP checks a service-level requirement
15
- * on every request BEFORE the operation's own annotation, so an operation-level
16
- * `@requires: 'any'` can never open a single function on an otherwise
17
- * authenticated service (anonymous callers get the 401 challenge first). The
18
- * requirement therefore sits on each element, and getLiveness() alone is 'any'.
19
- */
20
- // Service-level 'any' on purpose: CAP authorizes the service BEFORE the operation and
21
- // treats a service without a service-level @requires as authenticated-user under
22
- // NODE_ENV=production, which would 401 the anonymous operation below despite its own
23
- // 'any'. Every element carries its requirement; the service itself refuses nothing.
24
- @requires: 'any'
25
- service CardanoIndexerService @(impl: './cardano-indexer-service') {
26
-
27
- @readonly
28
- @requires : 'authenticated-user'
29
- @title : 'Sync State'
30
- @description: 'Singleton crawl cursor — pre-sync progress, tip lag, status, errors'
31
- entity SyncState as projection on db.CardanoSyncState;
32
-
33
- @readonly
34
- @requires : 'authenticated-user'
35
- @title : 'Reorg Log'
36
- @description: 'Audit trail of chain rollbacks handled by the crawler'
37
- entity ReorgLog as projection on db.CardanoReorgLog;
38
-
39
- @title : 'Crawler Status'
40
- @description: 'Live crawler status summary (numeric fields as strings, CAP-10 aligned)'
41
- type CrawlerStatus {
42
- running : Boolean;
43
- syncStatus : String;
44
- // 'chain-sync' | 'pagination' for the crawler in this process; null when this
45
- // instance is not the one crawling. Pagination is ~50x slower, and a crawl that
46
- // degraded to it still advances the cursor — this is how an operator tells.
47
- source : String;
48
- lastSlot : String;
49
- lastHeight : String;
50
- tipHeight : String;
51
- syncProgress : String;
52
- consecutiveErrors : Integer;
53
- // crawler-fed ledger state (crawler.utxoSet): snapshot anchor + validity
54
- utxoSet : UtxoSetStatus;
55
- // one-off certificate/withdrawal backfill over already crawled blocks (this process)
56
- certificateBackfill : CertificateBackfillStatus;
57
- // per-epoch pool/DRep/pot snapshots (crawler.epochSnapshots)
58
- epochSnapshots : EpochSnapshotStatus;
59
- }
60
-
61
- @title : 'Epoch Snapshot Status'
62
- @description: 'Latest epoch snapshot and the source this process would use for the next one'
63
- type EpochSnapshotStatus {
64
- enabled : Boolean; // crawler.epochSnapshots configured
65
- source : String; // ogmios | koios | null (no usable backend)
66
- lastEpoch : Integer; // newest snapshotted epoch; null before the first
67
- lastSource: String; // source of that snapshot
68
- lastSlot : String; // block it was taken at
69
- }
70
-
71
- @title : 'Certificate Backfill Status'
72
- @description: 'Progress of the certificate/withdrawal backfill started with backfillCertificates; process-local, none after a restart'
73
- type CertificateBackfillStatus {
74
- status : String; // none | running | done | failed
75
- fromSlot : String;
76
- toSlot : String;
77
- atSlot : String; // last slot handled
78
- blocks : Integer64;
79
- certificates : Integer64;
80
- withdrawals : Integer64;
81
- startedAt : Timestamp;
82
- finishedAt : Timestamp;
83
- error : String;
84
- }
85
-
86
- @title : 'Certificate Backfill Result'
87
- type CertificateBackfillResult {
88
- accepted : Boolean;
89
- fromSlot : String;
90
- toSlot : String;
91
- message : String;
92
- }
93
-
94
- @title : 'UTxO Set Status'
95
- @description: 'State of the crawler-maintained UTxO set (crawler.utxoSet)'
96
- type UtxoSetStatus {
97
- enabled : Boolean; // crawler.utxoSet configured
98
- status : String; // none | importing | active | invalid
99
- anchorSlot : String; // null until imported
100
- anchorHash : String;
101
- importedAt : Timestamp;
102
- error : String; // why invalid
103
- }
104
-
105
- @title : 'UTxO Set Import Result'
106
- type UtxoSetImportResult {
107
- accepted : Boolean;
108
- anchorSlot : String;
109
- anchorHash : String;
110
- message : String;
111
- }
112
-
113
- @title : 'Get Crawler Status'
114
- @description: 'Return the current crawler run state and sync progress'
115
- /**
116
- * Emitted AFTER each block is committed. Subscribe instead of polling:
117
- * (await cds.connect.to('CardanoIndexerService')).on('blockIndexed', ({ data }) => …)
118
- * In-process (plugin mode) this needs no messaging service.
119
- */
120
- event blockIndexed {
121
- hash : String(64);
122
- slot : Integer64;
123
- height : Integer64;
124
- txHashes : many String(64);
125
- tipSlot : Integer64;
126
- tipHeight: Integer64;
127
- }
128
-
129
- /** Emitted AFTER a rollback is committed. Everything above `forkSlot` was removed. */
130
- event reorg {
131
- forkSlot : Integer64;
132
- forkHeight : Integer64;
133
- blocksRolledBack : Integer;
134
- }
135
-
136
- @requires : 'authenticated-user'
137
- function getStatus() returns CrawlerStatus;
138
-
139
- @title : 'Liveness'
140
- type Liveness {
141
- status : String; // 'alive'
142
- timestamp : Timestamp;
143
- uptime : Integer; // seconds since process start
144
- version : String; // @odatano/core version
145
- network : String; // configured network
146
- }
147
-
148
- // Anonymous on purpose: a liveness probe carries no credentials. 200 as long
149
- // as the process answers — no backend or DB probe, no secrets, no backend
150
- // names, no API key state. Readiness stays with getStatus and the worker
151
- // status, which remain authenticated.
152
- @title : 'Get Liveness'
153
- @description: 'Unauthenticated liveness probe: 200 while the process answers. Docker HEALTHCHECK and upstream probes use this instead of the service document.'
154
- @requires : 'any'
155
- function getLiveness() returns Liveness;
156
-
157
- @title : 'Pause Crawler'
158
- @description: 'Stop the crawler (closes the chain-sync stream). Resume continues from the cursor.'
159
- @requires : 'Admin'
160
- action pauseCrawler() returns Boolean;
161
-
162
- @title : 'Resume Crawler'
163
- @description: 'Start/restart the crawler from the persisted cursor using the configured source.'
164
- @requires : 'Admin'
165
- action resumeCrawler() returns Boolean;
166
-
167
- @title : 'Import UTxO Set'
168
- @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.'
169
- @requires : 'Admin'
170
- action importUtxoSet(source: String, filePath: String, anchorSlot: Integer64, anchorHash: String) returns UtxoSetImportResult;
171
-
172
- @title : 'Backfill Certificates'
173
- @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.'
174
- @requires : 'Admin'
175
- action backfillCertificates(fromSlot: Integer64, toSlot: Integer64) returns CertificateBackfillResult;
176
- }
1
+ using {odatano.cardano as db} from '../db/schema';
2
+
3
+ /**
4
+ * Cardano Indexer Service (v2.0)
5
+ *
6
+ * Control + observability surface for the chain crawler / pre-sync engine:
7
+ * - read-only projections of the sync cursor and reorg audit log
8
+ * - status function + pause/resume actions delegating to the crawler singleton
9
+ *
10
+ * Security note: see CardanoODataService (cardano-service.cds) for the rationale on
11
+ * auth. pause/resume are operational actions — gate behind a dedicated Admin scope.
12
+ * Read-only status and audit data remain available to authenticated users.
13
+ *
14
+ * Deliberately NO service-level @requires: CAP checks a service-level requirement
15
+ * on every request BEFORE the operation's own annotation, so an operation-level
16
+ * `@requires: 'any'` can never open a single function on an otherwise
17
+ * authenticated service (anonymous callers get the 401 challenge first). The
18
+ * requirement therefore sits on each element, and getLiveness() alone is 'any'.
19
+ */
20
+ // Service-level 'any' on purpose: CAP authorizes the service BEFORE the operation and
21
+ // treats a service without a service-level @requires as authenticated-user under
22
+ // NODE_ENV=production, which would 401 the anonymous operation below despite its own
23
+ // 'any'. Every element carries its requirement; the service itself refuses nothing.
24
+ @requires: 'any'
25
+ service CardanoIndexerService @(impl: './cardano-indexer-service') {
26
+
27
+ @readonly
28
+ @requires : 'authenticated-user'
29
+ @title : 'Sync State'
30
+ @description: 'Singleton crawl cursor — pre-sync progress, tip lag, status, errors'
31
+ entity SyncState as projection on db.CardanoSyncState;
32
+
33
+ @readonly
34
+ @requires : 'authenticated-user'
35
+ @title : 'Reorg Log'
36
+ @description: 'Audit trail of chain rollbacks handled by the crawler'
37
+ entity ReorgLog as projection on db.CardanoReorgLog;
38
+
39
+ @title : 'Crawler Status'
40
+ @description: 'Live crawler status summary (numeric fields as strings, CAP-10 aligned)'
41
+ type CrawlerStatus {
42
+ running : Boolean;
43
+ syncStatus : String;
44
+ // 'chain-sync' | 'pagination' for the crawler in this process; null when this
45
+ // instance is not the one crawling. Pagination is ~50x slower, and a crawl that
46
+ // degraded to it still advances the cursor — this is how an operator tells.
47
+ source : String;
48
+ lastSlot : String;
49
+ lastHeight : String;
50
+ tipHeight : String;
51
+ syncProgress : String;
52
+ consecutiveErrors : Integer;
53
+ // crawler-fed ledger state (crawler.utxoSet): snapshot anchor + validity
54
+ utxoSet : UtxoSetStatus;
55
+ // one-off certificate/withdrawal backfill over already crawled blocks (this process)
56
+ certificateBackfill : CertificateBackfillStatus;
57
+ // one-off input/redeemer backfill over already crawled blocks (this process)
58
+ transactionBackfill : TransactionBackfillStatus;
59
+ // per-epoch pool/DRep/pot snapshots (crawler.epochSnapshots)
60
+ epochSnapshots : EpochSnapshotStatus;
61
+ }
62
+
63
+ @title : 'Epoch Snapshot Status'
64
+ @description: 'Latest epoch snapshot and the source this process would use for the next one'
65
+ type EpochSnapshotStatus {
66
+ enabled : Boolean; // crawler.epochSnapshots configured
67
+ source : String; // ogmios | koios | null (no usable backend)
68
+ lastEpoch : Integer; // newest snapshotted epoch; null before the first
69
+ lastSource: String; // source of that snapshot
70
+ lastSlot : String; // block it was taken at
71
+ }
72
+
73
+ @title : 'Certificate Backfill Status'
74
+ @description: 'Progress of the certificate/withdrawal backfill started with backfillCertificates; process-local, none after a restart'
75
+ type CertificateBackfillStatus {
76
+ status : String; // none | running | done | failed
77
+ fromSlot : String;
78
+ toSlot : String;
79
+ atSlot : String; // last slot handled
80
+ blocks : Integer64;
81
+ certificates : Integer64;
82
+ withdrawals : Integer64;
83
+ startedAt : Timestamp;
84
+ finishedAt : Timestamp;
85
+ error : String;
86
+ }
87
+
88
+ @title : 'Transaction Backfill Status'
89
+ @description: 'Progress of the backfill started with backfillTransactions; process-local, none after a restart'
90
+ type TransactionBackfillStatus {
91
+ status : String; // none | running | done | failed
92
+ fromSlot : String;
93
+ toSlot : String;
94
+ atSlot : String; // last slot handled
95
+ blocks : Integer64;
96
+ transactions : Integer64;
97
+ inputs : Integer64; // input rows that got at least one field
98
+ redeemers : Integer64;
99
+ rewritten : Integer64; // transactions whose stored rows differed in order or extent from the ledger view, now rewritten
100
+ skipped : Integer64; // transactions whose stored inputs differ from the stream
101
+ startedAt : Timestamp;
102
+ finishedAt : Timestamp;
103
+ error : String;
104
+ }
105
+
106
+ @title : 'Certificate Backfill Result'
107
+ type CertificateBackfillResult {
108
+ accepted : Boolean;
109
+ fromSlot : String;
110
+ toSlot : String;
111
+ message : String;
112
+ }
113
+
114
+ @title : 'UTxO Set Status'
115
+ @description: 'State of the crawler-maintained UTxO set (crawler.utxoSet)'
116
+ type UtxoSetStatus {
117
+ enabled : Boolean; // crawler.utxoSet configured
118
+ status : String; // none | importing | active | invalid
119
+ anchorSlot : String; // null until imported
120
+ anchorHash : String;
121
+ importedAt : Timestamp;
122
+ error : String; // why invalid
123
+ }
124
+
125
+ @title : 'UTxO Set Import Result'
126
+ type UtxoSetImportResult {
127
+ accepted : Boolean;
128
+ anchorSlot : String;
129
+ anchorHash : String;
130
+ message : String;
131
+ }
132
+
133
+ @title : 'Get Crawler Status'
134
+ @description: 'Return the current crawler run state and sync progress'
135
+ /**
136
+ * Emitted AFTER each block is committed. Subscribe instead of polling:
137
+ * (await cds.connect.to('CardanoIndexerService')).on('blockIndexed', ({ data }) => …)
138
+ * In-process (plugin mode) this needs no messaging service.
139
+ */
140
+ event blockIndexed {
141
+ hash : String(64);
142
+ slot : Integer64;
143
+ height : Integer64;
144
+ txHashes : many String(64);
145
+ tipSlot : Integer64;
146
+ tipHeight: Integer64;
147
+ }
148
+
149
+ /** Emitted AFTER a rollback is committed. Everything above `forkSlot` was removed. */
150
+ event reorg {
151
+ forkSlot : Integer64;
152
+ forkHeight : Integer64;
153
+ blocksRolledBack : Integer;
154
+ }
155
+
156
+ @requires : 'authenticated-user'
157
+ function getStatus() returns CrawlerStatus;
158
+
159
+ @title : 'Liveness'
160
+ type Liveness {
161
+ status : String; // 'alive'
162
+ timestamp : Timestamp;
163
+ uptime : Integer; // seconds since process start
164
+ version : String; // @odatano/core version
165
+ network : String; // configured network
166
+ }
167
+
168
+ // Anonymous on purpose: a liveness probe carries no credentials. 200 as long
169
+ // as the process answers — no backend or DB probe, no secrets, no backend
170
+ // names, no API key state. Readiness stays with getStatus and the worker
171
+ // status, which remain authenticated.
172
+ @title : 'Get Liveness'
173
+ @description: 'Unauthenticated liveness probe: 200 while the process answers. Docker HEALTHCHECK and upstream probes use this instead of the service document.'
174
+ @requires : 'any'
175
+ function getLiveness() returns Liveness;
176
+
177
+ @title : 'Pause Crawler'
178
+ @description: 'Stop the crawler (closes the chain-sync stream). Resume continues from the cursor.'
179
+ @requires : 'Admin'
180
+ action pauseCrawler() returns Boolean;
181
+
182
+ @title : 'Resume Crawler'
183
+ @description: 'Start/restart the crawler from the persisted cursor using the configured source.'
184
+ @requires : 'Admin'
185
+ action resumeCrawler() returns Boolean;
186
+
187
+ @title : 'Import UTxO Set'
188
+ @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. source=aggregates rebuilds only the sums (LedgerAddresses, LedgerAddressAssets, LedgerAccounts) from the rows an earlier import left, e.g. after its aggregate phase failed; a cursor past the anchor is set back to it. Runs in the background; progress via getStatus().utxoSet.'
189
+ @requires : 'Admin'
190
+ action importUtxoSet(source: String, filePath: String, anchorSlot: Integer64, anchorHash: String) returns UtxoSetImportResult;
191
+
192
+ @title : 'Backfill Certificates'
193
+ @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.'
194
+ @requires : 'Admin'
195
+ action backfillCertificates(fromSlot: Integer64, toSlot: Integer64) returns CertificateBackfillResult;
196
+
197
+ @title : 'Backfill Transactions'
198
+ @description: 'Complete transactions the crawl already holds from a second chain-sync stream (Ogmios): input outpoints, the spent output datum and reference-script hash, missing input addresses, and TransactionRedeemers. Fills empty fields only; a transaction whose stored inputs differ from the stream is skipped. fromSlot defaults to the crawl start, toSlot to the cursor; the crawler may keep running. Runs in the background; progress via getStatus().transactionBackfill.'
199
+ @requires : 'Admin'
200
+ action backfillTransactions(fromSlot: Integer64, toSlot: Integer64) returns CertificateBackfillResult;
201
+ }