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

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.
@@ -0,0 +1,217 @@
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)
65
+ return stored;
66
+ await indexer().refuseOutsideCrawl(db, 'getTransaction', `Transaction ${hash}`);
67
+ return client().getTransaction(String(hash));
68
+ }, need(validators_1.isTxHash, 'hash', 'transaction hash'));
69
+ op('GetTransactionsBatch', async ({ hashes }, db) => {
70
+ const wanted = hashes;
71
+ const found = await (0, stored_chain_1.readTransactionsByHash)(db, wanted);
72
+ const missing = wanted.filter(h => !found.has(h));
73
+ if (missing.length && client().hasBackendFor('getTransactionsBatch')) {
74
+ for (const [h, t] of await client().getTransactionsBatch(missing))
75
+ found.set(h, t);
76
+ }
77
+ return found;
78
+ }, jsonList('hashes', validators_1.isTxHash, 'transaction hashes'));
79
+ op('GetTransactionMetadata', async ({ hash }, db) => {
80
+ const stored = await (0, stored_chain_1.readTransactionMetadata)(db, String(hash));
81
+ if (stored)
82
+ return stored;
83
+ await indexer().refuseOutsideCrawl(db, 'getTransactionMetadata', `Transaction ${hash}`);
84
+ return client().getTransactionMetadata(String(hash));
85
+ }, need(validators_1.isTxHash, 'hash', 'transaction hash'));
86
+ op('GetBlock', async ({ hash }, db) => {
87
+ const stored = await (0, stored_chain_1.readBlock)(db, String(hash));
88
+ if (stored)
89
+ return stored;
90
+ await indexer().refuseOutsideCrawl(db, 'getBlock', `Block ${hash}`);
91
+ return client().getBlock(String(hash));
92
+ }, need(validators_1.isBlockHash, 'hash', 'block hash'));
93
+ op('GetBlockByHeight', async ({ height }, db) => {
94
+ const stored = await (0, stored_chain_1.readBlockByHeight)(db, Number(height));
95
+ if (stored)
96
+ return stored;
97
+ const paging = client().getPaginatingBackend();
98
+ if (!paging)
99
+ throw new errors_1.ProviderUnavailableError(`Block at height ${height} is not indexed here`, 'odatano');
100
+ return paging.getBlockByHeight(Number(height));
101
+ }, need(v => Number.isInteger(Number(v)) && Number(v) >= 0, 'height', 'height'));
102
+ op('GetNextBlocks', async ({ afterHash, count, afterHeight }, db) => {
103
+ const n = Math.min(Math.max(Number(count) || 1, 1), MAX_LIST);
104
+ const anchor = await (0, stored_chain_1.readBlock)(db, String(afterHash));
105
+ if (anchor?.height != null) {
106
+ const next = await (0, stored_chain_1.readNextBlocks)(db, anchor.height, n);
107
+ if (next.length)
108
+ return next;
109
+ }
110
+ // Unknown cursor block where this chain has another block at that height: the caller's
111
+ // cursor was orphaned. The crawler recognises this prefix and enters reorg recovery.
112
+ if (!anchor && afterHeight != null) {
113
+ const canonical = await (0, stored_chain_1.readBlockByHeight)(db, Number(afterHeight));
114
+ if (canonical) {
115
+ throw new errors_1.ProviderUnavailableError(`CHAIN_POINT_MISMATCH: cursor block ${afterHash} at height ${afterHeight} is no longer canonical (canonical block: ${canonical.hash})`, 'odatano');
116
+ }
117
+ }
118
+ const paging = client().getPaginatingBackend();
119
+ if (paging)
120
+ return paging.getNextBlocks(String(afterHash), n, afterHeight == null ? undefined : Number(afterHeight));
121
+ // Nothing indexed past the cursor yet: the caller is at this instance's tip.
122
+ if (anchor)
123
+ return [];
124
+ throw new errors_1.ProviderUnavailableError(`CHAIN_POINT_MISMATCH: cursor block ${afterHash} is unknown to this instance`, 'odatano');
125
+ }, need(validators_1.isBlockHash, 'afterHash', 'block hash'));
126
+ op('GetBlockTransactions', async ({ blockHash }, db) => {
127
+ const stored = await (0, stored_chain_1.readBlockTransactions)(db, String(blockHash));
128
+ if (stored)
129
+ return stored;
130
+ const paging = client().getPaginatingBackend();
131
+ if (!paging)
132
+ throw new errors_1.ProviderUnavailableError(`Transactions of block ${blockHash} are not indexed here`, 'odatano');
133
+ return paging.getBlockTransactions(String(blockHash));
134
+ }, need(validators_1.isBlockHash, 'blockHash', 'block hash'));
135
+ op('GetLatestBlock', async () => client().getLatestBlock());
136
+ op('GetCurrentSlot', async () => client().getCurrentSlot());
137
+ op('GetEpoch', async ({ epoch }) => client().getEpoch(Number(epoch)), need(validators_1.isEpochNumber, 'epoch', 'epoch number'));
138
+ op('GetLatestEpoch', async () => client().getLatestEpoch());
139
+ // --- addresses and UTxOs -------------------------------------------------------------------------
140
+ const address = need(validators_1.isValidBech32Address, 'address', 'bech32 address');
141
+ op('GetAddress', async ({ address: a }, db) => indexer().resolveAddress(db, String(a)), address);
142
+ op('GetAddressUtxos', async ({ address: a }, db) => indexer().resolveAddressUtxos(db, String(a)), address);
143
+ op('GetAddressTransactionHashes', async (data, db) => indexer().resolveAddressTransactionHashes(db, String(data.address), limitOf(data, 10)), address);
144
+ op('GetAddressTransactions', async (data, db) => {
145
+ const hashes = await indexer().resolveAddressTransactionHashes(db, String(data.address), limitOf(data, 10));
146
+ const found = await (0, stored_chain_1.readTransactionsByHash)(db, hashes);
147
+ const missing = hashes.filter(h => !found.has(h));
148
+ if (missing.length)
149
+ for (const [h, t] of await client().getTransactionsBatch(missing))
150
+ found.set(h, t);
151
+ return hashes.map(h => found.get(h)).filter(Boolean);
152
+ }, address);
153
+ op('GetCredentialUtxos', async ({ credential }, db) => indexer().resolveCredentialUtxos(db, String(credential)), need(validators_1.isValidCredential, 'credential', 'payment credential'));
154
+ 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')));
155
+ op('GetUnspentOutputs', async ({ refs }) => {
156
+ const found = await client().getUnspentOutputs(refs);
157
+ if (found == null)
158
+ throw new errors_1.ProviderUnavailableError('Output lookup needs a ledger-state backend (Ogmios)', 'odatano');
159
+ return found;
160
+ }, jsonList('refs', isRef, 'output references'));
161
+ // --- stake, governance, assets, network ------------------------------------------------------
162
+ op('GetAccount', async ({ stakeAddress }, db) => indexer().resolveAccount(db, String(stakeAddress)), need(validators_1.isValidBech32StakeAddress, 'stakeAddress', 'stake address'));
163
+ op('GetPool', async ({ poolId }, db) => indexer().resolvePool(db, String(poolId)), need(validators_1.isValidPoolId, 'poolId', 'pool id'));
164
+ op('GetDrep', async ({ drepId }) => client().getDrep(String(drepId)), need(validators_1.isValidDrepId, 'drepId', 'DRep id'));
165
+ op('GetPoolIds', async () => (await enumeration()).pools.map(p => p.poolId));
166
+ op('GetPools', async ({ ids }) => {
167
+ const wanted = new Set(ids);
168
+ return (await enumeration()).pools.filter(p => wanted.has(p.poolId));
169
+ }, jsonList('ids', validators_1.isValidPoolId, 'pool ids'));
170
+ op('GetDrepIds', async () => (await enumeration()).dreps.map(d => d.drepId));
171
+ op('GetDreps', async ({ ids }) => {
172
+ const wanted = new Set(ids);
173
+ return (await enumeration()).dreps.filter(d => wanted.has(d.drepId));
174
+ }, jsonList('ids', validators_1.isValidDrepId, 'DRep ids'));
175
+ op('GetAssetInfo', async ({ unit }, db) => indexer().resolveAssetInfo(db, String(unit)), need(validators_1.isAssetUnit, 'unit', 'asset unit'));
176
+ op('GetAssetHistory', async (data, db) => indexer().resolveAssetHistory(db, String(data.unit), limitOf(data, 100)), need(validators_1.isAssetUnit, 'unit', 'asset unit'));
177
+ op('GetNetworkInformation', async (_data, db) => indexer().resolveNetworkInformation(db));
178
+ op('GetProtocolParameters', async () => client().getProtocolParameters());
179
+ // --- transactions in flight ------------------------------------------------------------------
180
+ const cbor = need(validators_1.isValidCbor, 'cbor', 'CBOR hex');
181
+ op('EvaluateTransaction', async ({ cbor: c }) => client().evaluateTransaction(String(c)), cbor);
182
+ op('SubmitTransaction', async ({ cbor: c }) => {
183
+ const hash = await client().submitTransaction(String(c));
184
+ logger.info(`submitted ${hash} for a remote instance`);
185
+ return hash;
186
+ }, cbor);
187
+ /**
188
+ * The full pool and DRep set: an enumerating backend (Koios) when configured, else the node's
189
+ * ledger at the latest block (Ogmios). Cached for a minute; callers page through it by id.
190
+ */
191
+ let enumerated = null;
192
+ async function enumeration() {
193
+ if (enumerated && Date.now() - enumerated.at < 60_000)
194
+ return enumerated;
195
+ const koios = client().getEnumeratingBackend();
196
+ if (koios) {
197
+ const [pools, dreps] = await Promise.all([
198
+ koios.getPoolIds().then(ids => koios.getPools(ids)),
199
+ koios.getDrepIds().then(ids => koios.getDreps(ids)),
200
+ ]);
201
+ enumerated = { at: Date.now(), pools, dreps };
202
+ return enumerated;
203
+ }
204
+ const ledger = client().getEpochStateBackend();
205
+ if (!ledger)
206
+ throw new errors_1.ProviderUnavailableError('Pool/DRep enumeration needs Ogmios or Koios', 'odatano');
207
+ const tip = await client().getLatestBlock();
208
+ const state = await ledger.epochStateAt({ slot: tip.slot ?? 0, hash: tip.hash });
209
+ enumerated = { at: Date.now(), pools: state.pools, dreps: state.dreps };
210
+ return enumerated;
211
+ }
212
+ };
213
+ /** Maps become objects, so a batch answer survives JSON. */
214
+ function toPlain(value) {
215
+ return value instanceof Map ? Object.fromEntries(value) : value;
216
+ }
217
+ //# sourceMappingURL=cardano-backend-service.js.map
package/srv/server.js CHANGED
@@ -36,7 +36,7 @@ const agent_grants_config_1 = require("./utils/agent-grants-config");
36
36
  const process_1 = require("process");
37
37
  const logger = cds_1.default.log('ODATANO');
38
38
  const VALID_NETWORKS = ['mainnet', 'preview', 'preprod'];
39
- const VALID_BACKENDS = ['blockfrost', 'koios', 'ogmios'];
39
+ const VALID_BACKENDS = ['blockfrost', 'koios', 'ogmios', 'odatano'];
40
40
  const CRAWLER_LIMITS = {
41
41
  batchSize: { min: 1, max: 100 },
42
42
  confirmationDepth: { min: 0, max: 2160 },
@@ -192,6 +192,8 @@ async function createTestContext(backends, _txBuilderName = 'buildooor', protoco
192
192
  blockfrostCustomBackend: process_1.env.BLOCKFROST_CUSTOM_BACKEND || undefined,
193
193
  koiosApiKey: process_1.env.KOIOS_API_KEY || '',
194
194
  ogmiosUrl: process_1.env.OGMIOS_URL || '',
195
+ odatanoUrl: process_1.env.ODATANO_URL || undefined,
196
+ odatanoApiKey: process_1.env.ODATANO_API_KEY || undefined,
195
197
  transactionBuilders: ['buildooor'],
196
198
  primaryTimeoutMs: Number(process_1.env.PRIMARY_TIMEOUT_MS) || 30000, // || intentional: NaN (missing env var) falls back to default
197
199
  fallbackTimeoutMs: Number(process_1.env.FALLBACK_TIMEOUT_MS) || 60000,
@@ -270,6 +272,17 @@ function loadConfigFromEnv() {
270
272
  }
271
273
  const koiosApiKey = cdsConfig.koiosApiKey || process_1.env.KOIOS_API_KEY || '';
272
274
  const ogmiosUrl = cdsConfig.ogmiosUrl || process_1.env.OGMIOS_URL || '';
275
+ const odatanoUrl = cdsConfig.odatanoUrl || process_1.env.ODATANO_URL || '';
276
+ const odatanoApiKey = cdsConfig.odatanoApiKey || process_1.env.ODATANO_API_KEY || '';
277
+ if (odatanoUrl && !/^https?:\/\//i.test(odatanoUrl)) {
278
+ throw new errors_1.ConfigError(`Invalid ODATANO_URL "${odatanoUrl}". Must be an http(s) URL (e.g. https://api.preprod.odatano.dev).`);
279
+ }
280
+ if (backends.includes('odatano') && !odatanoUrl && network === 'mainnet') {
281
+ throw new errors_1.ConfigError('ODATANO_URL is required for the odatano backend on mainnet.');
282
+ }
283
+ if (backends.includes('odatano') && !odatanoApiKey) {
284
+ logger.warn('ODATANO_API_KEY is not set but odatano is listed in BACKENDS; the public API refuses calls without a key');
285
+ }
273
286
  if (backends.includes('blockfrost') && !blockfrostApiKey && !blockfrostCustomBackend) {
274
287
  logger.warn('Neither BLOCKFROST_API_KEY nor BLOCKFROST_CUSTOM_BACKEND is set but blockfrost is listed in BACKENDS');
275
288
  }
@@ -286,6 +299,8 @@ function loadConfigFromEnv() {
286
299
  blockfrostCustomBackend: blockfrostCustomBackend || undefined,
287
300
  koiosApiKey,
288
301
  ogmiosUrl,
302
+ odatanoUrl: odatanoUrl || undefined,
303
+ odatanoApiKey: odatanoApiKey || undefined,
289
304
  transactionBuilders: txBuilders,
290
305
  primaryTimeoutMs: Number(primaryTimeout) || 30000, // || intentional: NaN (missing config) falls back to default
291
306
  fallbackTimeoutMs: Number(fallbackTimeout) || 60000,
@@ -66,6 +66,7 @@ exports.AGENT_SERVICE_NAMES = [
66
66
  'CardanoWorkerService',
67
67
  'CardanoIndexerService',
68
68
  'CardanoAgentService',
69
+ 'CardanoBackendService',
69
70
  ];
70
71
  /**
71
72
  * Actions an operator may put on a grant's allow list; each call costs one budget unit. Anything else
@@ -112,6 +113,12 @@ exports.AGENT_ALWAYS_ALLOWED_EVENTS = new Set([
112
113
  'GetJobStatus', 'GetWorkerStatus', 'getStatus', 'getLiveness',
113
114
  // CardanoAgentService: the token's own grant (GetGrantUsage is narrowed to it in enforceAgentGrant)
114
115
  'GetGrantStatus', 'GetGrantUsage',
116
+ // CardanoBackendService: reads and evaluation for another ODATANO instance (submit is allow-listed)
117
+ 'GetTransaction', 'GetTransactionsBatch', 'GetTransactionMetadata', 'GetBlock', 'GetBlockByHeight',
118
+ 'GetNextBlocks', 'GetBlockTransactions', 'GetCurrentSlot', 'GetEpoch', 'GetAddress', 'GetAddressUtxos',
119
+ 'GetAddressTransactions', 'GetAddressTransactionHashes', 'GetCredentialUtxos', 'IsUtxoUnspent',
120
+ 'GetUnspentOutputs', 'GetAccount', 'GetPool', 'GetPoolIds', 'GetPools', 'GetDrep', 'GetDrepIds', 'GetDreps',
121
+ 'GetProtocolParameters', 'EvaluateTransaction',
115
122
  ]);
116
123
  /** Mirrors WalletJobKind in db/types.cds; kept literal so this module stays free of cds-models. */
117
124
  exports.AGENT_JOB_KINDS = ['simpleAda', 'metadata', 'multiAsset', 'mint', 'plutusSpend', 'submitSigned'];