@odatano/core 2.0.0-rc.24 → 2.0.0-rc.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/@cds-models/CardanoIndexerService/index.d.ts +37 -0
- package/@cds-models/CardanoIndexerService/index.js +4 -0
- package/@cds-models/CardanoODataService/index.d.ts +27 -2
- package/@cds-models/CardanoODataService/index.js +3 -0
- package/@cds-models/CardanoSignService/index.d.ts +23 -1
- package/@cds-models/CardanoSignService/index.js +3 -0
- package/@cds-models/CardanoTransactionService/index.d.ts +34 -1
- package/@cds-models/CardanoTransactionService/index.js +4 -0
- package/@cds-models/index.d.ts +18 -0
- package/@cds-models/index.js +3 -0
- package/@cds-models/odatano/cardano/index.d.ts +49 -2
- package/@cds-models/odatano/cardano/index.js +6 -0
- package/README.md +195 -195
- package/db/schema.cds +74 -3
- package/db/types.cds +27 -0
- package/package.json +182 -182
- package/srv/blockchain/backends/blockfrost-backend.js +4 -2
- package/srv/blockchain/backends/cardano-backend.d.ts +0 -2
- package/srv/blockchain/backends/koios-backend.d.ts +1 -1
- package/srv/blockchain/backends/koios-backend.js +61 -14
- package/srv/blockchain/backends/odatano-backend.d.ts +5 -0
- package/srv/blockchain/backends/odatano-backend.js +12 -0
- package/srv/blockchain/backends/ogmios-backend.d.ts +12 -2
- package/srv/blockchain/backends/ogmios-backend.js +91 -21
- package/srv/blockchain/cardano-client.d.ts +11 -5
- package/srv/blockchain/cardano-client.js +51 -16
- package/srv/blockchain/cardano-indexer.d.ts +43 -15
- package/srv/blockchain/cardano-indexer.js +177 -68
- package/srv/blockchain/cardano-tx-builder.d.ts +11 -1
- package/srv/blockchain/cardano-tx-builder.js +57 -2
- package/srv/blockchain/crawler/certificate-backfill.d.ts +22 -0
- package/srv/blockchain/crawler/certificate-backfill.js +49 -30
- package/srv/blockchain/crawler/crawler.d.ts +3 -1
- package/srv/blockchain/crawler/crawler.js +12 -7
- package/srv/blockchain/crawler/sync-state.d.ts +3 -1
- package/srv/blockchain/crawler/sync-state.js +15 -2
- package/srv/blockchain/crawler/transaction-backfill.d.ts +52 -0
- package/srv/blockchain/crawler/transaction-backfill.js +283 -0
- package/srv/blockchain/crawler/utxo-set-import.d.ts +9 -0
- package/srv/blockchain/crawler/utxo-set-import.js +138 -47
- package/srv/blockchain/ledger-state.d.ts +16 -1
- package/srv/blockchain/ledger-state.js +38 -18
- package/srv/blockchain/pending-spends.d.ts +28 -0
- package/srv/blockchain/pending-spends.js +89 -0
- package/srv/blockchain/stored-chain.d.ts +5 -2
- package/srv/blockchain/stored-chain.js +31 -5
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +12 -3
- package/srv/blockchain/transaction-building/buildooor-tx.js +203 -21
- package/srv/blockchain/transaction-building/cardano-tx.d.ts +2 -1
- package/srv/blockchain/transaction-rows.d.ts +1 -1
- package/srv/blockchain/transaction-rows.js +2 -1
- package/srv/blockchain/wallet-worker/build-request.js +1 -1
- package/srv/cardano-backend-service.js +35 -8
- package/srv/cardano-indexer-service.cds +201 -176
- package/srv/cardano-indexer-service.js +104 -10
- package/srv/cardano-service.cds +5 -0
- package/srv/cardano-service.js +3 -1
- package/srv/cardano-tx-service.cds +39 -0
- package/srv/cardano-tx-service.js +88 -14
- package/srv/server.js +4 -1
- package/srv/utils/agent-grants.js +1 -0
- package/srv/utils/const.d.ts +5 -0
- package/srv/utils/const.js +6 -1
- package/srv/utils/error-codes.d.ts +2 -0
- package/srv/utils/error-codes.js +2 -0
- package/srv/utils/errors.d.ts +7 -0
- package/srv/utils/errors.js +11 -1
- package/srv/utils/mappers.d.ts +24 -2
- package/srv/utils/mappers.js +49 -0
- package/srv/utils/pg-inline-json.d.ts +8 -0
- package/srv/utils/pg-inline-json.js +63 -0
- package/srv/utils/tx-build-helper.d.ts +2 -0
- package/srv/utils/tx-build-helper.js +12 -0
- package/srv/utils/tx-request-parsers.d.ts +46 -5
- package/srv/utils/tx-request-parsers.js +227 -16
- package/srv/utils/types.d.ts +59 -0
- package/srv/utils/validators.d.ts +5 -1
- package/srv/utils/validators.js +19 -9
|
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.OgmiosBackend = void 0;
|
|
7
7
|
exports.ogmiosScriptHash = ogmiosScriptHash;
|
|
8
|
+
exports.ogmiosPlutusScriptCbor = ogmiosPlutusScriptCbor;
|
|
8
9
|
exports.issuerKeyToPoolId = issuerKeyToPoolId;
|
|
9
10
|
exports.mapOgmiosEpochState = mapOgmiosEpochState;
|
|
10
11
|
exports.decodeDrepId = decodeDrepId;
|
|
@@ -46,6 +47,11 @@ function ogmiosScriptHash(script) {
|
|
|
46
47
|
const bytes = Uint8Array.from(Buffer.concat([Buffer.from([tag]), Buffer.from(s.cbor, 'hex')]));
|
|
47
48
|
return Buffer.from((0, crypto_1.blake2b_224)(bytes)).toString('hex');
|
|
48
49
|
}
|
|
50
|
+
/** Full CBOR of a Plutus reference script as Ogmios delivers it; null for native or absent scripts. */
|
|
51
|
+
function ogmiosPlutusScriptCbor(script) {
|
|
52
|
+
const s = script;
|
|
53
|
+
return s?.language?.startsWith('plutus:') && typeof s.cbor === 'string' && s.cbor.length > 0 ? s.cbor : null;
|
|
54
|
+
}
|
|
49
55
|
/** Bech32 pool id of a block issuer: blake2b-224 of its cold verification key. */
|
|
50
56
|
function issuerKeyToPoolId(verificationKeyHex) {
|
|
51
57
|
const keyHash = (0, crypto_1.blake2b_224)(Uint8Array.from(Buffer.from(verificationKeyHex, 'hex')));
|
|
@@ -169,6 +175,28 @@ function resolveOgmiosTip(tip) {
|
|
|
169
175
|
function resolveOgmiosHeight(height) {
|
|
170
176
|
return height === 'origin' ? 0 : height;
|
|
171
177
|
}
|
|
178
|
+
/**
|
|
179
|
+
* Redeemers of a chain-sync tx. A spend index points into the body inputs sorted by
|
|
180
|
+
* (txHash, index), a mint index into the sorted policy ids; both are resolved here.
|
|
181
|
+
*/
|
|
182
|
+
function mapOgmiosRedeemers(tx) {
|
|
183
|
+
const sortedInputs = [...(tx.inputs ?? [])].sort((a, b) => (0, mappers_1.compareOutRef)({ txHash: a.transaction.id, outputIndex: a.index }, { txHash: b.transaction.id, outputIndex: b.index }));
|
|
184
|
+
const sortedPolicies = Object.keys(tx.mint ?? {}).sort();
|
|
185
|
+
return (tx.redeemers ?? []).map((r) => {
|
|
186
|
+
const { purpose, index } = r.validator;
|
|
187
|
+
const spent = purpose === 'spend' ? sortedInputs[index] : undefined;
|
|
188
|
+
return {
|
|
189
|
+
purpose,
|
|
190
|
+
index,
|
|
191
|
+
data: r.redeemer,
|
|
192
|
+
mem: r.executionUnits.memory.toString(),
|
|
193
|
+
steps: r.executionUnits.cpu.toString(),
|
|
194
|
+
txHash: spent?.transaction.id ?? null,
|
|
195
|
+
outputIndex: spent?.index ?? null,
|
|
196
|
+
policyId: purpose === 'mint' ? (sortedPolicies[index] ?? null) : null,
|
|
197
|
+
};
|
|
198
|
+
});
|
|
199
|
+
}
|
|
172
200
|
/** CardanoBackend implementation over an Ogmios WebSocket (local node). */
|
|
173
201
|
class OgmiosBackend {
|
|
174
202
|
name = 'ogmios';
|
|
@@ -190,6 +218,10 @@ class OgmiosBackend {
|
|
|
190
218
|
stateQueryClient = null;
|
|
191
219
|
txSubmissionClient = null;
|
|
192
220
|
context = null;
|
|
221
|
+
/** Second connection for address queries (see scanQueryClient). */
|
|
222
|
+
scanClient = null;
|
|
223
|
+
scanContext = null;
|
|
224
|
+
scanConnecting = null;
|
|
193
225
|
isShutdown = false;
|
|
194
226
|
reconnectPromise = null;
|
|
195
227
|
network;
|
|
@@ -302,6 +334,38 @@ class OgmiosBackend {
|
|
|
302
334
|
this.context = context;
|
|
303
335
|
return true;
|
|
304
336
|
}
|
|
337
|
+
/**
|
|
338
|
+
* Query client for address queries. The node answers them by scanning its whole UTxO set (seconds
|
|
339
|
+
* each), and Ogmios serves the queries of one connection in order; on their own connection they no
|
|
340
|
+
* longer hold up tip, epoch and protocol parameters. Opened on first use, reopened after a close.
|
|
341
|
+
*/
|
|
342
|
+
async scanQueryClient() {
|
|
343
|
+
this.ensureNotShutdown();
|
|
344
|
+
// never initialized (test-injected clients): the shared client
|
|
345
|
+
if (!this.context)
|
|
346
|
+
return this.stateQueryClient;
|
|
347
|
+
const socket = this.scanContext?.socket;
|
|
348
|
+
if (this.scanClient && socket && socket.readyState === (socket.OPEN ?? 1))
|
|
349
|
+
return this.scanClient;
|
|
350
|
+
if (!this.scanConnecting) {
|
|
351
|
+
this.scanConnecting = (async () => {
|
|
352
|
+
const url = new URL(this.ogmiosUrl);
|
|
353
|
+
const connection = { host: url.hostname, port: Number(url.port) || (url.protocol === 'wss:' ? 443 : 80), tls: url.protocol === 'wss:' };
|
|
354
|
+
const context = await this.withInitTimeout((0, client_1.createInteractionContext)((err) => logger.error(`[OgmiosBackend] address-query context error: ${err.message}`), () => { this.scanClient = null; }, { connection }), 'scan/createInteractionContext');
|
|
355
|
+
try {
|
|
356
|
+
const client = await this.withInitTimeout((0, client_1.createLedgerStateQueryClient)(context), 'scan/ledgerStateQueryClient');
|
|
357
|
+
this.scanContext = context;
|
|
358
|
+
this.scanClient = client;
|
|
359
|
+
return client;
|
|
360
|
+
}
|
|
361
|
+
catch (err) {
|
|
362
|
+
this.forceCloseContext(context);
|
|
363
|
+
throw err;
|
|
364
|
+
}
|
|
365
|
+
})().finally(() => { this.scanConnecting = null; });
|
|
366
|
+
}
|
|
367
|
+
return this.scanConnecting;
|
|
368
|
+
}
|
|
305
369
|
/**
|
|
306
370
|
* Reconnect when the WebSocket died since the last init. No-op when never initialized
|
|
307
371
|
* (test-injected clients); concurrent callers share one reconnect attempt.
|
|
@@ -468,7 +532,7 @@ class OgmiosBackend {
|
|
|
468
532
|
return (0, backend_request_handler_1.handleBackendRequest)(async () => {
|
|
469
533
|
await this.ensureConnected();
|
|
470
534
|
const decoded = (0, mappers_1.decodeShelleyAddress)(address);
|
|
471
|
-
const raw = await this.
|
|
535
|
+
const raw = await (await this.scanQueryClient()).utxo({ addresses: [address] });
|
|
472
536
|
const utxos = raw.map((u) => this.mapOgmiosUtxo(u, address));
|
|
473
537
|
return {
|
|
474
538
|
address,
|
|
@@ -487,7 +551,7 @@ class OgmiosBackend {
|
|
|
487
551
|
async getAddressUtxos(address) {
|
|
488
552
|
return (0, backend_request_handler_1.handleBackendRequest)(async () => {
|
|
489
553
|
await this.ensureConnected();
|
|
490
|
-
const utxos = await this.
|
|
554
|
+
const utxos = await (await this.scanQueryClient()).utxo({ addresses: [address] });
|
|
491
555
|
return utxos.map((u) => this.mapOgmiosUtxo(u, address));
|
|
492
556
|
}, this.name);
|
|
493
557
|
}
|
|
@@ -503,6 +567,7 @@ class OgmiosBackend {
|
|
|
503
567
|
// Ogmios delivers the inline datum as CBOR hex in `datum`
|
|
504
568
|
inlineDatum: typeof u.datum === 'string' ? u.datum : null,
|
|
505
569
|
scriptRef: ogmiosScriptHash(u.script) ?? undefined,
|
|
570
|
+
scriptRefCbor: ogmiosPlutusScriptCbor(u.script),
|
|
506
571
|
};
|
|
507
572
|
}
|
|
508
573
|
/**
|
|
@@ -649,8 +714,22 @@ class OgmiosBackend {
|
|
|
649
714
|
async submitTransaction(signedTxCbor) {
|
|
650
715
|
return (0, backend_request_handler_1.handleBackendRequest)(async () => {
|
|
651
716
|
await this.ensureConnected();
|
|
652
|
-
|
|
653
|
-
|
|
717
|
+
try {
|
|
718
|
+
return await this.txSubmissionClient.submitTransaction(signedTxCbor);
|
|
719
|
+
}
|
|
720
|
+
catch (err) {
|
|
721
|
+
// JSON-RPC 3000-3999: the node rejected the transaction. Known kinds keep their class
|
|
722
|
+
// (already submitted = 409, script failure = 400); anything else becomes a 400 with its reason.
|
|
723
|
+
const known = (0, errors_1.normalizeBackendError)(err, this.name);
|
|
724
|
+
if (known.statusCode >= 400 && known.statusCode < 500)
|
|
725
|
+
throw known;
|
|
726
|
+
const e = err;
|
|
727
|
+
if (typeof e?.code === 'number' && e.code >= 3000 && e.code < 4000) {
|
|
728
|
+
const detail = e.data === undefined ? '' : ` ${JSON.stringify(e.data).slice(0, 800)}`;
|
|
729
|
+
throw new errors_1.TransactionValidationError(`node rejected the transaction (${e.code}): ${String(e.message ?? '')}${detail}`, err);
|
|
730
|
+
}
|
|
731
|
+
throw err;
|
|
732
|
+
}
|
|
654
733
|
}, this.name);
|
|
655
734
|
}
|
|
656
735
|
/**
|
|
@@ -804,21 +883,6 @@ class OgmiosBackend {
|
|
|
804
883
|
return Array.isArray(result) && result.length > 0;
|
|
805
884
|
}, this.name);
|
|
806
885
|
}
|
|
807
|
-
/** Unspent outputs of several addresses in the live ledger (one query per 100 addresses). */
|
|
808
|
-
async getUtxosByAddresses(addresses) {
|
|
809
|
-
if (addresses.length === 0)
|
|
810
|
-
return [];
|
|
811
|
-
return (0, backend_request_handler_1.handleBackendRequest)(async () => {
|
|
812
|
-
await this.ensureConnected();
|
|
813
|
-
const out = [];
|
|
814
|
-
for (let i = 0; i < addresses.length; i += 100) {
|
|
815
|
-
const utxos = await this.stateQueryClient.utxo({ addresses: addresses.slice(i, i + 100) });
|
|
816
|
-
for (const u of utxos)
|
|
817
|
-
out.push(this.mapOgmiosUtxo(u));
|
|
818
|
-
}
|
|
819
|
-
return out;
|
|
820
|
-
}, this.name);
|
|
821
|
-
}
|
|
822
886
|
/** Outputs among `refs` that are unspent in the live ledger; spent or unknown references are absent. */
|
|
823
887
|
async getUnspentOutputs(refs) {
|
|
824
888
|
if (refs.length === 0)
|
|
@@ -850,9 +914,13 @@ class OgmiosBackend {
|
|
|
850
914
|
});
|
|
851
915
|
}
|
|
852
916
|
}
|
|
917
|
+
if (this.scanContext)
|
|
918
|
+
this.forceCloseContext(this.scanContext);
|
|
853
919
|
this.stateQueryClient = null;
|
|
854
920
|
this.txSubmissionClient = null;
|
|
855
921
|
this.context = null;
|
|
922
|
+
this.scanClient = null;
|
|
923
|
+
this.scanContext = null;
|
|
856
924
|
}
|
|
857
925
|
isConnected() {
|
|
858
926
|
if (this.isShutdown || !this.context?.socket) {
|
|
@@ -1106,7 +1174,8 @@ class OgmiosBackend {
|
|
|
1106
1174
|
// so the indexer derives the rest from the resolved collateral inputs later.
|
|
1107
1175
|
const declaredFee = (tx.fee?.ada?.lovelace ?? 0).toString();
|
|
1108
1176
|
const totalCollateral = tx.totalCollateral ? tx.totalCollateral.ada.lovelace.toString() : null;
|
|
1109
|
-
|
|
1177
|
+
// the same ledger view the pagination sources produce (ordering; the partition is already applied)
|
|
1178
|
+
return (0, mappers_1.ledgerView)({
|
|
1110
1179
|
hash: tx.id,
|
|
1111
1180
|
blockHash: block.id,
|
|
1112
1181
|
blockHeight: block.height,
|
|
@@ -1133,7 +1202,8 @@ class OgmiosBackend {
|
|
|
1133
1202
|
stakeAddress,
|
|
1134
1203
|
amount: (value?.ada?.lovelace ?? 0).toString(),
|
|
1135
1204
|
})),
|
|
1136
|
-
|
|
1205
|
+
redeemers: mapOgmiosRedeemers(tx),
|
|
1206
|
+
});
|
|
1137
1207
|
}
|
|
1138
1208
|
/**
|
|
1139
1209
|
* Normalize Ogmios certificates onto the shared `CertificateKind` vocabulary. A `stakeDelegation`
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ChainSyncBackend, PaginatingBackend, EnumeratingBackend, LedgerStateBackend, EpochStateBackend } from './backends/cardano-backend';
|
|
2
|
+
import { PendingSpends } from './pending-spends';
|
|
2
3
|
import { type CircuitBreakerConfig } from './circuit-breaker';
|
|
3
4
|
import { Transaction, Address, UTxO, NetworkInformation, BlockData, EpochData, MetadataLabelTx, PoolData, DrepData, AccountData, AssetInfo, AssetHistoryEntry, LedgerProtocolParameters, ScriptEvaluationResult } from '../utils/types';
|
|
4
5
|
export type Network = 'mainnet' | 'preview' | 'preprod';
|
|
@@ -36,8 +37,12 @@ export declare class CardanoClient {
|
|
|
36
37
|
private uninitializedBackends;
|
|
37
38
|
network: Network;
|
|
38
39
|
max_age_ms: number;
|
|
40
|
+
/** Transactions submitted through this client that the ledger view does not show yet. */
|
|
41
|
+
readonly pendingSpends: PendingSpends;
|
|
39
42
|
private protocolParamsCache?;
|
|
40
43
|
private protocolParamsFetchPromise;
|
|
44
|
+
/** Last protocol parameters the live backend (node) answered. */
|
|
45
|
+
private lastLiveProtocolParams?;
|
|
41
46
|
private static readonly PROTOCOL_PARAMS_TTL_MS;
|
|
42
47
|
private txCoalescer;
|
|
43
48
|
private addrCoalescer;
|
|
@@ -74,7 +79,7 @@ export declare class CardanoClient {
|
|
|
74
79
|
private ensureBackendInitialized;
|
|
75
80
|
/** Wrap a promise with a timeout that rejects with ProviderUnavailableError. */
|
|
76
81
|
private withTimeout;
|
|
77
|
-
/** Per-backend timeout: Koios
|
|
82
|
+
/** Per-backend timeout: Koios and a remote ODATANO get the fallback timeout, everything else the primary one. */
|
|
78
83
|
private getTimeoutForBackend;
|
|
79
84
|
/**
|
|
80
85
|
* Single-backend call with the executeWithPriority resilience contract (breaker gate, timeout,
|
|
@@ -132,15 +137,16 @@ export declare class CardanoClient {
|
|
|
132
137
|
/** The first usable backend that can dump the UTxO set at a point (Ogmios) — crawler.utxoSet import. */
|
|
133
138
|
getLedgerStateBackend(): LedgerStateBackend | null;
|
|
134
139
|
/**
|
|
135
|
-
* Outputs among `refs` that are unspent at the tip, read from the node's ledger
|
|
136
|
-
*
|
|
140
|
+
* Outputs among `refs` that are unspent at the tip, read from the node's ledger (Ogmios, or a remote
|
|
141
|
+
* ODATANO that asks its node); null when no backend can (the caller then resolves via the producing
|
|
142
|
+
* transaction, which carries no reference-script bytes).
|
|
137
143
|
*/
|
|
138
144
|
getUnspentOutputs(refs: Array<{
|
|
139
145
|
txHash: string;
|
|
140
146
|
outputIndex: number;
|
|
141
147
|
}>): Promise<UTxO[] | null>;
|
|
142
|
-
/**
|
|
143
|
-
|
|
148
|
+
/** A usable backend answering output-reference lookups without a whole-ledger dump (the odatano backend). */
|
|
149
|
+
private outputLookupBackend;
|
|
144
150
|
/** True when an initialized backend implements `method` and does not declare it unsupported. */
|
|
145
151
|
hasBackendFor(method: string): boolean;
|
|
146
152
|
/** A backend that reads pool/DRep/pot state at a block (Ogmios) — preferred source of epoch snapshots. */
|
|
@@ -7,6 +7,7 @@ exports.CardanoClient = void 0;
|
|
|
7
7
|
const cds_1 = __importDefault(require("@sap/cds"));
|
|
8
8
|
const cardano_backend_1 = require("./backends/cardano-backend");
|
|
9
9
|
const errors_1 = require("../utils/errors");
|
|
10
|
+
const pending_spends_1 = require("./pending-spends");
|
|
10
11
|
const circuit_breaker_1 = require("./circuit-breaker");
|
|
11
12
|
const request_coalescer_1 = require("./request-coalescer");
|
|
12
13
|
const ogmios_backend_1 = require("./backends/ogmios-backend");
|
|
@@ -36,7 +37,8 @@ const METHOD_ROUTING = {
|
|
|
36
37
|
getAccount: { preferLive: true },
|
|
37
38
|
getAssetInfo: { preferLive: false },
|
|
38
39
|
getProtocolParameters: { preferLive: true },
|
|
39
|
-
|
|
40
|
+
// a node's rejection (4xx) is final: another backend submits to the same ledger
|
|
41
|
+
submitTransaction: { preferLive: true, finalOnClientError: true },
|
|
40
42
|
};
|
|
41
43
|
/**
|
|
42
44
|
* Multi-backend Cardano client: live/state queries prefer Ogmios, historical queries prefer
|
|
@@ -53,8 +55,12 @@ class CardanoClient {
|
|
|
53
55
|
uninitializedBackends = new Set();
|
|
54
56
|
network;
|
|
55
57
|
max_age_ms = 60000; // default 1 minute for temporary caching
|
|
58
|
+
/** Transactions submitted through this client that the ledger view does not show yet. */
|
|
59
|
+
pendingSpends = new pending_spends_1.PendingSpends();
|
|
56
60
|
protocolParamsCache;
|
|
57
61
|
protocolParamsFetchPromise = null;
|
|
62
|
+
/** Last protocol parameters the live backend (node) answered. */
|
|
63
|
+
lastLiveProtocolParams;
|
|
58
64
|
static PROTOCOL_PARAMS_TTL_MS = 5 * 60 * 1000; // 5 minutes
|
|
59
65
|
// Request coalescers — deduplicate concurrent fetches for the same resource
|
|
60
66
|
txCoalescer = new request_coalescer_1.RequestCoalescer();
|
|
@@ -74,7 +80,8 @@ class CardanoClient {
|
|
|
74
80
|
this.historicalBackends.push(new koios_backend_1.KoiosBackend(clientConfig.network, clientConfig.primaryTimeoutMs, clientConfig.koiosApiKey));
|
|
75
81
|
}
|
|
76
82
|
if (backends.includes('odatano')) {
|
|
77
|
-
|
|
83
|
+
// A remote ODATANO runs its own failover chain: allow its primary timeout plus the fallback.
|
|
84
|
+
this.historicalBackends.push(new odatano_backend_1.OdatanoBackend(clientConfig.network, clientConfig.fallbackTimeoutMs, clientConfig.odatanoUrl, clientConfig.odatanoApiKey));
|
|
78
85
|
}
|
|
79
86
|
if (!this.liveBackend && this.historicalBackends.length === 0) {
|
|
80
87
|
throw new errors_1.ConfigError('No valid backends configured for CardanoClient');
|
|
@@ -212,9 +219,9 @@ class CardanoClient {
|
|
|
212
219
|
clearTimeout(timeoutId);
|
|
213
220
|
});
|
|
214
221
|
}
|
|
215
|
-
/** Per-backend timeout: Koios
|
|
222
|
+
/** Per-backend timeout: Koios and a remote ODATANO get the fallback timeout, everything else the primary one. */
|
|
216
223
|
getTimeoutForBackend(backend) {
|
|
217
|
-
if (backend.name === 'koios')
|
|
224
|
+
if (backend.name === 'koios' || backend.name === 'odatano')
|
|
218
225
|
return this.config.fallbackTimeoutMs;
|
|
219
226
|
return this.config.primaryTimeoutMs;
|
|
220
227
|
}
|
|
@@ -245,7 +252,7 @@ class CardanoClient {
|
|
|
245
252
|
}
|
|
246
253
|
}
|
|
247
254
|
/** Execute on backends in preference order (live vs historical) with automatic fallback. */
|
|
248
|
-
async executeWithPriority(fn, preferLive, methodName) {
|
|
255
|
+
async executeWithPriority(fn, preferLive, methodName, finalOnClientError = false) {
|
|
249
256
|
await this.ensureInitialized();
|
|
250
257
|
const errors = [];
|
|
251
258
|
const skipped = [];
|
|
@@ -292,6 +299,8 @@ class CardanoClient {
|
|
|
292
299
|
}
|
|
293
300
|
const logLevel = backendError.statusCode === 404 ? 'debug' : 'warn';
|
|
294
301
|
logger[logLevel](`Backend failed${backendError.statusCode === 404 ? ': resource not found' : ''}: ${backend.name} - ${backendError.message}`);
|
|
302
|
+
if (finalOnClientError && isClientError)
|
|
303
|
+
throw backendError;
|
|
295
304
|
}
|
|
296
305
|
}
|
|
297
306
|
throw new errors_1.AllBackendsFailedError(errors, undefined, skipped);
|
|
@@ -299,7 +308,7 @@ class CardanoClient {
|
|
|
299
308
|
/** Route a call by METHOD_ROUTING (default: historical first). */
|
|
300
309
|
route(methodName, fn) {
|
|
301
310
|
const config = METHOD_ROUTING[methodName] ?? { preferLive: false };
|
|
302
|
-
return this.executeWithPriority(fn, config.preferLive, methodName);
|
|
311
|
+
return this.executeWithPriority(fn, config.preferLive, methodName, config.finalOnClientError);
|
|
303
312
|
}
|
|
304
313
|
/** Transaction by hash (coalesced across concurrent callers). */
|
|
305
314
|
getTransaction(txHash) {
|
|
@@ -451,17 +460,24 @@ class CardanoClient {
|
|
|
451
460
|
return null;
|
|
452
461
|
}
|
|
453
462
|
/**
|
|
454
|
-
* Outputs among `refs` that are unspent at the tip, read from the node's ledger
|
|
455
|
-
*
|
|
463
|
+
* Outputs among `refs` that are unspent at the tip, read from the node's ledger (Ogmios, or a remote
|
|
464
|
+
* ODATANO that asks its node); null when no backend can (the caller then resolves via the producing
|
|
465
|
+
* transaction, which carries no reference-script bytes).
|
|
456
466
|
*/
|
|
457
467
|
async getUnspentOutputs(refs) {
|
|
458
|
-
const backend = this.getLedgerStateBackend();
|
|
468
|
+
const backend = this.getLedgerStateBackend() ?? this.outputLookupBackend();
|
|
459
469
|
return backend ? backend.getUnspentOutputs(refs) : null;
|
|
460
470
|
}
|
|
461
|
-
/**
|
|
462
|
-
|
|
463
|
-
const
|
|
464
|
-
|
|
471
|
+
/** A usable backend answering output-reference lookups without a whole-ledger dump (the odatano backend). */
|
|
472
|
+
outputLookupBackend() {
|
|
473
|
+
const candidates = [this.liveBackend, ...this.historicalBackends];
|
|
474
|
+
for (const b of candidates) {
|
|
475
|
+
const lookup = b;
|
|
476
|
+
if (lookup && !this.uninitializedBackends.has(lookup) && typeof lookup.getUnspentOutputs === 'function') {
|
|
477
|
+
return lookup;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
return null;
|
|
465
481
|
}
|
|
466
482
|
/** True when an initialized backend implements `method` and does not declare it unsupported. */
|
|
467
483
|
hasBackendFor(method) {
|
|
@@ -517,7 +533,16 @@ class CardanoClient {
|
|
|
517
533
|
}
|
|
518
534
|
if (!this.protocolParamsFetchPromise) {
|
|
519
535
|
logger.debug('Fetching fresh protocol parameters');
|
|
520
|
-
this.protocolParamsFetchPromise = this.route('getProtocolParameters', b =>
|
|
536
|
+
this.protocolParamsFetchPromise = this.route('getProtocolParameters', async (b) => {
|
|
537
|
+
const params = await b.getProtocolParameters();
|
|
538
|
+
if (b === this.liveBackend) {
|
|
539
|
+
this.lastLiveProtocolParams = params;
|
|
540
|
+
return params;
|
|
541
|
+
}
|
|
542
|
+
// A fallback answering for the epoch the node last reported: keep the node's values
|
|
543
|
+
const live = this.lastLiveProtocolParams;
|
|
544
|
+
return live && Number(live.epoch) === Number(params.epoch) ? live : params;
|
|
545
|
+
})
|
|
521
546
|
.then(params => {
|
|
522
547
|
this.protocolParamsCache = { data: params, fetchedAt: Date.now() };
|
|
523
548
|
this.protocolParamsFetchPromise = null;
|
|
@@ -574,8 +599,18 @@ class CardanoClient {
|
|
|
574
599
|
* Submit a signed transaction (CBOR hex); returns its hash. On failover after a lost response
|
|
575
600
|
* the next backend may answer 409 "already submitted" — callers treat that as success.
|
|
576
601
|
*/
|
|
577
|
-
submitTransaction(signedTxCbor) {
|
|
578
|
-
|
|
602
|
+
async submitTransaction(signedTxCbor) {
|
|
603
|
+
try {
|
|
604
|
+
const hash = await this.route('submitTransaction', b => b.submitTransaction(signedTxCbor));
|
|
605
|
+
this.pendingSpends.record(signedTxCbor);
|
|
606
|
+
return hash;
|
|
607
|
+
}
|
|
608
|
+
catch (err) {
|
|
609
|
+
// already in the mempool or on chain: its inputs are gone all the same
|
|
610
|
+
if (err instanceof errors_1.TransactionAlreadySubmittedError)
|
|
611
|
+
this.pendingSpends.record(signedTxCbor);
|
|
612
|
+
throw err;
|
|
613
|
+
}
|
|
579
614
|
}
|
|
580
615
|
/** True when Ogmios is the live backend. */
|
|
581
616
|
hasOgmiosBackend() {
|
|
@@ -3,8 +3,8 @@ import type { CardanoClient } from './cardano-client';
|
|
|
3
3
|
import type { CardanoTransactionBuilder } from './cardano-tx-builder';
|
|
4
4
|
import { Transaction as CardanoTransaction, AddressUTxOs, TransactionMetadata, NetworkInformation, Block, Epoch, AssetHistory, Account, Drep, Pool, Asset, Address, LedgerProtocolParameter, AddressTransactions } from '#cds-models/CardanoODataService';
|
|
5
5
|
import { TransactionBuild, TransactionSubmission } from '#cds-models/CardanoTransactionService';
|
|
6
|
-
import { TxBuildRequest, AssetInfo, AccountData, PoolData, NetworkInformation as ProviderNetworkInformation, Address as ProviderAddress, Transaction as ProviderTransaction, UTxO as OdatanoUtxo, BlockData, AssetHistoryEntry as AssetHistoryEntryProviderData } from '../utils/types';
|
|
7
|
-
import { type LedgerAnchor } from './ledger-state';
|
|
6
|
+
import { TxBuildRequest, TxBuildPlutusRequest, AssetInfo, AccountData, PoolData, NetworkInformation as ProviderNetworkInformation, Address as ProviderAddress, Transaction as ProviderTransaction, UTxO as OdatanoUtxo, BlockData, AssetHistoryEntry as AssetHistoryEntryProviderData } from '../utils/types';
|
|
7
|
+
import { type LedgerAnchor, type LedgerLookup } from './ledger-state';
|
|
8
8
|
import type { TxCacheTargets } from '../utils/tx-build-helper';
|
|
9
9
|
/**
|
|
10
10
|
* Indexes Cardano data into the OData entities: fetches via CardanoClient, maps provider data
|
|
@@ -18,11 +18,15 @@ export declare class CardanoIndexer {
|
|
|
18
18
|
private static readonly CRAWL_EPOCH_RETRY_MS;
|
|
19
19
|
/**
|
|
20
20
|
* Crawler epoch memo: refreshed periodically while an epoch is live and once more when the
|
|
21
|
-
* next one starts; holds at most the current and previous epoch.
|
|
22
|
-
* block transaction
|
|
21
|
+
* next one starts; holds at most the current and previous epoch. A row is UPSERTed until a
|
|
22
|
+
* block transaction that wrote it has committed (`confirmBlockCommit`).
|
|
23
23
|
*/
|
|
24
24
|
private crawlEpochCache;
|
|
25
25
|
private crawlEpochCurrent;
|
|
26
|
+
/** Epoch rows known to be committed; a refresh creates a new row object and is written again. */
|
|
27
|
+
private crawlEpochWritten;
|
|
28
|
+
/** Memo updates of the running block transaction, applied only after its commit. */
|
|
29
|
+
private pendingCommit;
|
|
26
30
|
private crawlEpochPrevious;
|
|
27
31
|
/** Analytics coverage of the crawl path; defaults mirror the crawler config defaults. */
|
|
28
32
|
private crawlAssetHistory;
|
|
@@ -52,6 +56,8 @@ export declare class CardanoIndexer {
|
|
|
52
56
|
private ledgerInvalidation;
|
|
53
57
|
/** Units known to have an `Assets` row, so a repeat sighting costs no DB round-trip. */
|
|
54
58
|
private static readonly ASSET_MEMO_CAP;
|
|
59
|
+
/** Output references per node lookup when checking crawled UTxOs. */
|
|
60
|
+
private static readonly OUTREF_CHUNK;
|
|
55
61
|
private assetMemo;
|
|
56
62
|
/**
|
|
57
63
|
* Background registry enrichment queue (`assetCatalogue: 'enrich'`), drained at a fixed rate
|
|
@@ -94,7 +100,7 @@ export declare class CardanoIndexer {
|
|
|
94
100
|
private localAssetInfo;
|
|
95
101
|
/** Address from the crawled UTxO set when it answers, else from the backend. */
|
|
96
102
|
resolveAddress(tx: CapTransaction, addr: string): Promise<ProviderAddress>;
|
|
97
|
-
/** UTxOs of an address: the crawled set (
|
|
103
|
+
/** UTxOs of an address: the crawled set (checked unspent at the node) when it answers, else the backend. */
|
|
98
104
|
resolveAddressUtxos(tx: CapTransaction, addr: string): Promise<OdatanoUtxo[]>;
|
|
99
105
|
/** Asset from the crawled chain when it answers, else from the backend. */
|
|
100
106
|
resolveAssetInfo(tx: CapTransaction, unit: string): Promise<AssetInfo>;
|
|
@@ -107,11 +113,13 @@ export declare class CardanoIndexer {
|
|
|
107
113
|
/** True while the crawled UTxO set answers address queries (live crawler at the tip, set active). */
|
|
108
114
|
ledgerCoverageActive(tx: CapTransaction): Promise<boolean>;
|
|
109
115
|
/**
|
|
110
|
-
* Address from the crawled UTxO set:
|
|
111
|
-
*
|
|
116
|
+
* Address from the crawled UTxO set: the unspent `LedgerUTxOs` (see openLedgerUtxos), type and
|
|
117
|
+
* stake address decoded from the address. An address the set has never
|
|
112
118
|
* seen is an empty address, not an error. null = the set cannot answer.
|
|
113
119
|
*/
|
|
114
120
|
private localAddress;
|
|
121
|
+
/** Addresses of a stake key from the crawled UTxO set, with their unspent outputs (one read for all). */
|
|
122
|
+
private localAccountAddresses;
|
|
115
123
|
/**
|
|
116
124
|
* Latest transactions of an address from the crawled UTxO set: the outputs it received
|
|
117
125
|
* (`LedgerUTxOs.txHash`) and spent (`spentTxHash`) since the anchor. `complete` = the address was
|
|
@@ -140,6 +148,8 @@ export declare class CardanoIndexer {
|
|
|
140
148
|
private verifyUtxoAnchor;
|
|
141
149
|
/** Null while the mode is off, nothing is imported, or an invalidation awaits its commit. */
|
|
142
150
|
getUtxoAnchor(): LedgerAnchor | null;
|
|
151
|
+
/** Apply the memo updates of the block transaction that just committed. */
|
|
152
|
+
confirmBlockCommit(): void;
|
|
143
153
|
/** Hand out a pending invalidation (dropping the anchor) exactly once after the block commit, or null. */
|
|
144
154
|
takeLedgerInvalidation(): string | null;
|
|
145
155
|
/**
|
|
@@ -163,6 +173,11 @@ export declare class CardanoIndexer {
|
|
|
163
173
|
/** Epoch row with only the slot-derived bounds, for an epoch the backend cannot describe. */
|
|
164
174
|
private bareEpochRow;
|
|
165
175
|
constructor(client: CardanoClient, txBuilder: CardanoTransactionBuilder);
|
|
176
|
+
/**
|
|
177
|
+
* Unspent outputs of an address from the crawled set for the transaction builder; null = the set
|
|
178
|
+
* cannot answer. Runs on `cds.db`, i.e. inside the caller's request transaction when there is one.
|
|
179
|
+
*/
|
|
180
|
+
private localAddressUtxos;
|
|
166
181
|
/**
|
|
167
182
|
* Index a transaction with inputs/outputs/assets/metadata; all UPSERTs run in the caller's
|
|
168
183
|
* transaction, so either everything persists or nothing does.
|
|
@@ -172,21 +187,27 @@ export declare class CardanoIndexer {
|
|
|
172
187
|
private writeTransactionChildren;
|
|
173
188
|
/**
|
|
174
189
|
* Index address data with assets and UTxOs; transactions are loaded separately via
|
|
175
|
-
* indexAddressTransactions().
|
|
190
|
+
* indexAddressTransactions(). `prefetched` = address data the caller already fetched in a batch.
|
|
176
191
|
*/
|
|
177
|
-
indexAddress(tx: CapTransaction, addr: string): Promise<Address>;
|
|
192
|
+
indexAddress(tx: CapTransaction, addr: string, prefetched?: ProviderAddress): Promise<Address>;
|
|
178
193
|
/**
|
|
179
194
|
* Index UTxOs by 28-byte payment credential (56-char hex), always fresh from Koios. Child
|
|
180
195
|
* rows are UPSERTed without a parent Addresses row (same pattern as TransactionInputs).
|
|
181
196
|
*/
|
|
182
197
|
indexCredentialUtxos(tx: CapTransaction, credHash: string): Promise<AddressUTxOs[]>;
|
|
183
198
|
/**
|
|
184
|
-
* UTxOs of a payment credential without a provider: addresses from the crawled
|
|
185
|
-
*
|
|
199
|
+
* UTxOs of a payment credential without a provider: addresses and unspent outputs from the crawled
|
|
200
|
+
* UTxO set (see openLedgerUtxos).
|
|
186
201
|
* null = the crawled set cannot answer (not synced, no set, credential column still filling).
|
|
187
202
|
* An address first used in the last `confirmationDepth` blocks is not in the set yet.
|
|
188
203
|
*/
|
|
189
204
|
private localCredentialUtxos;
|
|
205
|
+
/**
|
|
206
|
+
* Unspent outputs of addresses from the crawled set, checked against the node by output reference
|
|
207
|
+
* (a keyed lookup; the node's address query scans its whole UTxO set): drops what was spent after
|
|
208
|
+
* the cursor. Without a usable node, or when the check fails, the set as of the cursor.
|
|
209
|
+
*/
|
|
210
|
+
private openLedgerUtxos;
|
|
190
211
|
/** Unspent `LedgerUTxOs` (+ assets) of the given addresses in the provider UTxO shape. */
|
|
191
212
|
private ledgerUtxosOf;
|
|
192
213
|
/**
|
|
@@ -243,10 +264,11 @@ export declare class CardanoIndexer {
|
|
|
243
264
|
*/
|
|
244
265
|
private warnIfCertificatesUnreported;
|
|
245
266
|
/**
|
|
246
|
-
* Backfill address
|
|
247
|
-
* then earlier-indexed outputs from the DB. Inputs that
|
|
267
|
+
* Backfill address, amount and datum/script fields of bare chain-sync inputs: from this block's
|
|
268
|
+
* own outputs first, then the UTxO set, then earlier-indexed outputs from the DB. Inputs that
|
|
269
|
+
* already carry an address are skipped.
|
|
248
270
|
*/
|
|
249
|
-
|
|
271
|
+
resolveInputs(tx: CapTransaction, txs: ProviderTransaction[], ledger?: LedgerLookup): Promise<void>;
|
|
250
272
|
/**
|
|
251
273
|
* Settle the fee of phase-2-invalid transactions (collateral inputs minus collateral return)
|
|
252
274
|
* and the block total. The declared fee is kept when the mapper already set it via
|
|
@@ -328,6 +350,8 @@ export declare class CardanoIndexer {
|
|
|
328
350
|
indexMultiAssetBuildResult(tx: CapTransaction, buildreq: TxBuildRequest): Promise<TransactionBuild>;
|
|
329
351
|
indexMintBuildResult(tx: CapTransaction, buildreq: TxBuildRequest): Promise<TransactionBuild>;
|
|
330
352
|
indexPlutusSpendBuildResult(tx: CapTransaction, buildreq: TxBuildRequest): Promise<TransactionBuild>;
|
|
353
|
+
/** BuildPlutusTransaction: several script inputs; the redeemers are stored with the build. */
|
|
354
|
+
indexPlutusBuildResult(tx: CapTransaction, buildreq: TxBuildPlutusRequest): Promise<TransactionBuild>;
|
|
331
355
|
/** Protocol parameters, served from the DB row within a 5-minute TTL. */
|
|
332
356
|
indexProtocolParameters(tx: CapTransaction): Promise<LedgerProtocolParameter>;
|
|
333
357
|
/** Persist a transaction submission and flag the build as submitted when linked. */
|
|
@@ -424,7 +448,11 @@ export declare class CardanoIndexer {
|
|
|
424
448
|
* @returns provider transactions for the hashes that had to be fetched
|
|
425
449
|
*/
|
|
426
450
|
ensureTransactionsIndexed(tx: CapTransaction, txHashes: string[]): Promise<Map<string, ProviderTransaction>>;
|
|
427
|
-
/**
|
|
451
|
+
/**
|
|
452
|
+
* Index the addresses of an account with bounded concurrency. The address data the account
|
|
453
|
+
* carries (from the backend, or from the crawled set) is used as is, so an account costs no
|
|
454
|
+
* request per address; an entry without UTxOs is fetched.
|
|
455
|
+
*/
|
|
428
456
|
private _ensureAddresses;
|
|
429
457
|
}
|
|
430
458
|
//# sourceMappingURL=cardano-indexer.d.ts.map
|