@odatano/core 2.0.0-rc.4 → 2.0.0-rc.41
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 +251 -0
- package/@cds-models/CardanoAgentService/index.js +36 -0
- package/@cds-models/CardanoBackendService/index.d.ts +357 -0
- package/@cds-models/CardanoBackendService/index.js +40 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +194 -2
- package/@cds-models/CardanoIndexerService/index.js +25 -0
- package/@cds-models/CardanoODataService/index.d.ts +305 -7
- package/@cds-models/CardanoODataService/index.js +34 -0
- package/@cds-models/CardanoSignService/index.d.ts +28 -3
- package/@cds-models/CardanoSignService/index.js +3 -0
- package/@cds-models/CardanoTransactionService/index.d.ts +46 -13
- package/@cds-models/CardanoTransactionService/index.js +4 -0
- package/@cds-models/index.d.ts +72 -0
- package/@cds-models/index.js +12 -0
- package/@cds-models/odatano/cardano/index.d.ts +408 -7
- package/@cds-models/odatano/cardano/index.js +42 -0
- package/README.md +64 -5
- package/db/schema.cds +2297 -1633
- package/db/types.cds +114 -0
- package/package.json +27 -6
- package/scripts/migrate-slot-leader.mjs +104 -0
- package/scripts/migrate-txseq.mjs +147 -0
- package/src/index.d.ts +18 -11
- package/src/index.js +44 -14
- package/src/plugin.js +42 -52
- package/srv/blockchain/backends/blockfrost-backend.d.ts +29 -131
- package/srv/blockchain/backends/blockfrost-backend.js +53 -162
- package/srv/blockchain/backends/cardano-backend.d.ts +104 -158
- package/srv/blockchain/backends/cardano-backend.js +19 -5
- package/srv/blockchain/backends/koios-backend.d.ts +126 -60
- package/srv/blockchain/backends/koios-backend.js +376 -235
- package/srv/blockchain/backends/odatano-backend.d.ts +64 -0
- package/srv/blockchain/backends/odatano-backend.js +170 -0
- package/srv/blockchain/backends/ogmios-backend.d.ts +162 -94
- package/srv/blockchain/backends/ogmios-backend.js +556 -201
- package/srv/blockchain/backends/ogmios-frame-guard.d.ts +32 -0
- package/srv/blockchain/backends/ogmios-frame-guard.js +142 -0
- package/srv/blockchain/cardano-client.d.ts +87 -202
- package/srv/blockchain/cardano-client.js +210 -240
- package/srv/blockchain/cardano-indexer.d.ts +311 -242
- package/srv/blockchain/cardano-indexer.js +1238 -362
- package/srv/blockchain/cardano-tx-builder.d.ts +44 -81
- package/srv/blockchain/cardano-tx-builder.js +173 -132
- package/srv/blockchain/crawler/certificate-backfill.d.ts +67 -0
- package/srv/blockchain/crawler/certificate-backfill.js +169 -0
- package/srv/blockchain/crawler/crawler.d.ts +139 -54
- package/srv/blockchain/crawler/crawler.js +478 -96
- package/srv/blockchain/crawler/hooks.d.ts +3 -14
- package/srv/blockchain/crawler/index.d.ts +5 -0
- package/srv/blockchain/crawler/index.js +35 -7
- package/srv/blockchain/crawler/sync-state.d.ts +46 -28
- package/srv/blockchain/crawler/sync-state.js +128 -43
- 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 +78 -0
- package/srv/blockchain/crawler/utxo-set-import.js +363 -0
- package/srv/blockchain/ledger-state.d.ts +101 -0
- package/srv/blockchain/ledger-state.js +432 -0
- package/srv/blockchain/pending-spends.d.ts +28 -0
- package/srv/blockchain/pending-spends.js +89 -0
- 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 +14 -45
- package/srv/blockchain/signing/signature-verifier.js +73 -76
- package/srv/blockchain/signing/submission-finalizer.d.ts +9 -36
- package/srv/blockchain/signing/submission-finalizer.js +16 -49
- package/srv/blockchain/stored-chain.d.ts +33 -0
- package/srv/blockchain/stored-chain.js +234 -0
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +111 -173
- package/srv/blockchain/transaction-building/buildooor-tx.js +649 -326
- package/srv/blockchain/transaction-building/caller-datums.d.ts +29 -0
- package/srv/blockchain/transaction-building/caller-datums.js +139 -0
- package/srv/blockchain/transaction-building/cardano-tx.d.ts +10 -35
- package/srv/blockchain/transaction-rows.d.ts +12 -0
- package/srv/blockchain/transaction-rows.js +43 -0
- package/srv/blockchain/wallet-worker/build-request.d.ts +4 -17
- package/srv/blockchain/wallet-worker/build-request.js +18 -23
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +25 -17
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +87 -41
- package/srv/blockchain/wallet-worker/index.js +2 -8
- package/srv/blockchain/wallet-worker/job-store.d.ts +36 -103
- 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 +40 -91
- package/srv/cardano-agent-service.cds +146 -0
- package/srv/cardano-agent-service.d.ts +2 -0
- package/srv/cardano-agent-service.js +12 -0
- package/srv/cardano-backend-service.cds +52 -0
- package/srv/cardano-backend-service.d.ts +2 -0
- package/srv/cardano-backend-service.js +244 -0
- package/srv/cardano-indexer-service.cds +201 -73
- package/srv/cardano-indexer-service.js +280 -11
- package/srv/cardano-service.cds +65 -2
- package/srv/cardano-service.js +170 -129
- package/srv/cardano-sign-service.cds +200 -180
- package/srv/cardano-sign-service.js +57 -184
- package/srv/cardano-tx-service.cds +439 -370
- package/srv/cardano-tx-service.js +231 -190
- package/srv/cardano-ui.cds +16 -16
- package/srv/cardano-worker-service.js +7 -15
- package/srv/cbor/index.d.ts +1 -1
- package/srv/cbor/parse.d.ts +27 -0
- package/srv/cbor/parse.js +63 -2
- package/srv/server.d.ts +28 -86
- package/srv/server.js +132 -135
- package/srv/utils/agent-grants-config.d.ts +37 -0
- package/srv/utils/agent-grants-config.js +138 -0
- package/srv/utils/agent-grants.d.ts +262 -0
- package/srv/utils/agent-grants.js +922 -0
- package/srv/utils/agent-token-auth.d.ts +16 -0
- package/srv/utils/agent-token-auth.js +78 -0
- 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 +30 -67
- package/srv/utils/const.js +32 -72
- package/srv/utils/crypto.d.ts +3 -12
- package/srv/utils/crypto.js +5 -18
- package/srv/utils/db-indexes.d.ts +25 -0
- package/srv/utils/db-indexes.js +94 -0
- package/srv/utils/db-sanitize.d.ts +27 -0
- package/srv/utils/db-sanitize.js +85 -0
- package/srv/utils/epoch-slots.d.ts +20 -0
- package/srv/utils/epoch-slots.js +43 -0
- package/srv/utils/error-codes.d.ts +20 -73
- package/srv/utils/error-codes.js +19 -70
- package/srv/utils/errors.d.ts +50 -177
- package/srv/utils/errors.js +94 -218
- package/srv/utils/legacy-service-paths.d.ts +11 -0
- package/srv/utils/legacy-service-paths.js +58 -0
- package/srv/utils/liveness.d.ts +16 -0
- package/srv/utils/liveness.js +40 -0
- package/srv/utils/mappers.d.ts +128 -214
- package/srv/utils/mappers.js +354 -299
- package/srv/utils/network-context.js +2 -11
- package/srv/utils/pg-inline-json.d.ts +8 -0
- package/srv/utils/pg-inline-json.js +62 -0
- package/srv/utils/pg-order-nulls.d.ts +14 -0
- package/srv/utils/pg-order-nulls.js +56 -0
- package/srv/utils/plutus-placeholders.d.ts +23 -16
- package/srv/utils/plutus-placeholders.js +63 -27
- package/srv/utils/rate-limiter.d.ts +46 -0
- package/srv/utils/rate-limiter.js +116 -0
- package/srv/utils/service-events.d.ts +2 -22
- package/srv/utils/service-events.js +3 -23
- package/srv/utils/signing-helper.d.ts +6 -16
- package/srv/utils/signing-helper.js +36 -60
- package/srv/utils/tx-build-helper.d.ts +28 -93
- package/srv/utils/tx-build-helper.js +75 -124
- package/srv/utils/tx-request-parsers.d.ts +101 -28
- package/srv/utils/tx-request-parsers.js +410 -43
- package/srv/utils/tx-utils.d.ts +4 -23
- package/srv/utils/tx-utils.js +12 -41
- package/srv/utils/types.d.ts +252 -179
- package/srv/utils/types.js +2 -6
- package/srv/utils/validators.d.ts +24 -90
- package/srv/utils/validators.js +50 -147
|
@@ -4,39 +4,26 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.OgmiosBackend = void 0;
|
|
7
|
+
exports.ogmiosScriptHash = ogmiosScriptHash;
|
|
8
|
+
exports.ogmiosPlutusScriptCbor = ogmiosPlutusScriptCbor;
|
|
9
|
+
exports.issuerKeyToPoolId = issuerKeyToPoolId;
|
|
10
|
+
exports.mapOgmiosEpochState = mapOgmiosEpochState;
|
|
11
|
+
exports.decodeDrepId = decodeDrepId;
|
|
7
12
|
exports.resolveOgmiosTip = resolveOgmiosTip;
|
|
8
13
|
exports.resolveOgmiosHeight = resolveOgmiosHeight;
|
|
9
14
|
const cds_1 = __importDefault(require("@sap/cds"));
|
|
10
15
|
const node_http_1 = __importDefault(require("node:http"));
|
|
11
16
|
const client_1 = require("@cardano-ogmios/client");
|
|
17
|
+
const bech32_1 = require("bech32");
|
|
18
|
+
const crypto_1 = require("@harmoniclabs/crypto");
|
|
12
19
|
const backend_request_handler_1 = require("../../utils/backend-request-handler");
|
|
13
20
|
const errors_1 = require("../../utils/errors");
|
|
21
|
+
const ogmios_frame_guard_1 = require("./ogmios-frame-guard");
|
|
22
|
+
const epoch_slots_1 = require("../../utils/epoch-slots");
|
|
14
23
|
const mappers_1 = require("../../utils/mappers");
|
|
15
24
|
const const_1 = require("../../utils/const");
|
|
16
25
|
const logger = cds_1.default.log('OgmiosBackend');
|
|
17
|
-
/**
|
|
18
|
-
* First absolute slot of the given epoch, from the network's Shelley anchor.
|
|
19
|
-
* Replaces the old `epoch * 432000` math, which was wrong on preview (86 400
|
|
20
|
-
* slots per epoch) and on mainnet/preprod (Byron offset).
|
|
21
|
-
*/
|
|
22
|
-
function epochStartSlot(network, epoch) {
|
|
23
|
-
const cfg = const_1.EPOCH_CONFIG_BY_NETWORK[network];
|
|
24
|
-
return cfg.shelleyStartSlot + (epoch - cfg.shelleyStartEpoch) * cfg.slotsPerEpoch;
|
|
25
|
-
}
|
|
26
|
-
/**
|
|
27
|
-
* Absolute POSIX seconds for a slot, via the same Shelley-anchored genesis infos
|
|
28
|
-
* the transaction builder uses for validity windows. The previous code treated
|
|
29
|
-
* Ogmios' `eraStart.time` (RelativeTime since SYSTEM start) as a Unix timestamp.
|
|
30
|
-
*/
|
|
31
|
-
function slotToPosixSeconds(network, slot) {
|
|
32
|
-
const genesis = const_1.GENESIS_INFOS_BY_NETWORK[network];
|
|
33
|
-
return Math.floor((genesis.systemStartPosixMs + (slot - genesis.startSlotNo) * genesis.slotLengthMs) / 1000);
|
|
34
|
-
}
|
|
35
|
-
/**
|
|
36
|
-
* Parse an Ogmios `Ratio` ("num/den" string, e.g. "3/1000") into a number.
|
|
37
|
-
* `Number("3/1000")` is NaN — previously every ratio-typed protocol parameter
|
|
38
|
-
* (priceMem, priceStep, a0, rho, tau) came out as NaN.
|
|
39
|
-
*/
|
|
26
|
+
/** Parse an Ogmios `Ratio` ("num/den", e.g. "3/1000") into a number; `Number("3/1000")` is NaN. */
|
|
40
27
|
function parseOgmiosRatio(ratio) {
|
|
41
28
|
if (ratio === null || ratio === undefined)
|
|
42
29
|
return 0;
|
|
@@ -50,11 +37,37 @@ function parseOgmiosRatio(ratio) {
|
|
|
50
37
|
const n = Number(ratio);
|
|
51
38
|
return Number.isFinite(n) ? n : 0;
|
|
52
39
|
}
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
40
|
+
const SCRIPT_LANGUAGE_TAG = { native: 0, 'plutus:v1': 1, 'plutus:v2': 2, 'plutus:v3': 3 };
|
|
41
|
+
/** Hash of an Ogmios `Script`: blake2b-224 over the language tag byte followed by the script CBOR. */
|
|
42
|
+
function ogmiosScriptHash(script) {
|
|
43
|
+
const s = script;
|
|
44
|
+
const tag = s?.language === undefined ? undefined : SCRIPT_LANGUAGE_TAG[s.language];
|
|
45
|
+
if (tag === undefined || typeof s?.cbor !== 'string' || s.cbor.length === 0)
|
|
46
|
+
return null;
|
|
47
|
+
const bytes = Uint8Array.from(Buffer.concat([Buffer.from([tag]), Buffer.from(s.cbor, 'hex')]));
|
|
48
|
+
return Buffer.from((0, crypto_1.blake2b_224)(bytes)).toString('hex');
|
|
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
|
+
}
|
|
55
|
+
/** Bech32 pool id of a block issuer: blake2b-224 of its cold verification key. */
|
|
56
|
+
function issuerKeyToPoolId(verificationKeyHex) {
|
|
57
|
+
const keyHash = (0, crypto_1.blake2b_224)(Uint8Array.from(Buffer.from(verificationKeyHex, 'hex')));
|
|
58
|
+
return bech32_1.bech32.encode('pool', bech32_1.bech32.toWords(keyHash));
|
|
59
|
+
}
|
|
60
|
+
/** CIP-129 DRep id for a registered DRep, the predefined id for abstain / no confidence. */
|
|
61
|
+
function ogmiosDrepToId(d) {
|
|
62
|
+
if (!d)
|
|
63
|
+
return null;
|
|
64
|
+
if (d.type === 'abstain')
|
|
65
|
+
return 'drep_always_abstain';
|
|
66
|
+
if (d.type === 'noConfidence')
|
|
67
|
+
return 'drep_always_no_confidence';
|
|
68
|
+
return d.id ? (0, mappers_1.credentialToDrepId)(d.id, d.from === 'script') : null;
|
|
69
|
+
}
|
|
70
|
+
/** Lovelace amount from Ogmios' value shapes; v6 returns `{ ada: { lovelace } }` objects. */
|
|
58
71
|
function ogmiosValueToLovelaceString(value) {
|
|
59
72
|
if (value === null || value === undefined)
|
|
60
73
|
return '0';
|
|
@@ -63,6 +76,97 @@ function ogmiosValueToLovelaceString(value) {
|
|
|
63
76
|
const lovelace = value.ada?.lovelace;
|
|
64
77
|
return lovelace === undefined ? '0' : String(lovelace);
|
|
65
78
|
}
|
|
79
|
+
/** Fraction a/b of two lovelace amounts; 0 when b is 0. */
|
|
80
|
+
function ratio(a, b) {
|
|
81
|
+
return b === 0n ? 0 : Number((a * 1000000n) / b) / 1_000_000;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Ogmios ledger answers -> EpochLedgerState. Saturation follows the ledger: live stake over
|
|
85
|
+
* (max supply - reserves) / nOpt. Figures the ledger view does not carry stay 0 / null: active
|
|
86
|
+
* stake (the indexer derives it from the previous snapshot), block counts, delegator counts,
|
|
87
|
+
* DRep last activity.
|
|
88
|
+
*/
|
|
89
|
+
function mapOgmiosEpochState(raw) {
|
|
90
|
+
const lovelace = (v) => BigInt(ogmiosValueToLovelaceString(v));
|
|
91
|
+
const reserves = raw.pots?.reserves ? lovelace(raw.pots.reserves) : null;
|
|
92
|
+
const nOpt = raw.performances?.desiredNumberOfStakePools ?? 0;
|
|
93
|
+
const saturationPoint = reserves != null && nOpt > 0
|
|
94
|
+
? (BigInt(const_1.CARDANO_DEFAULTS.MAX_LOVELACE_SUPPLY) - reserves) / BigInt(nOpt)
|
|
95
|
+
: 0n;
|
|
96
|
+
const entries = Object.entries(raw.stakePools);
|
|
97
|
+
const liveTotal = entries.reduce((sum, [, p]) => sum + lovelace(p.stake), 0n);
|
|
98
|
+
const pools = entries.map(([poolId, p]) => {
|
|
99
|
+
const live = lovelace(p.stake);
|
|
100
|
+
return {
|
|
101
|
+
poolId,
|
|
102
|
+
vrfKeyHash: p.vrfVerificationKeyHash || '',
|
|
103
|
+
blocksMinted: 0,
|
|
104
|
+
blocksEpoch: null,
|
|
105
|
+
liveStake: live.toString(),
|
|
106
|
+
liveSize: ratio(live, liveTotal),
|
|
107
|
+
liveSaturation: ratio(live, saturationPoint),
|
|
108
|
+
liveDelegators: null,
|
|
109
|
+
activeStake: '0',
|
|
110
|
+
activeSize: 0,
|
|
111
|
+
pledge: ogmiosValueToLovelaceString(p.pledge),
|
|
112
|
+
margin: parseOgmiosRatio(p.margin),
|
|
113
|
+
fixedCost: ogmiosValueToLovelaceString(p.cost),
|
|
114
|
+
rewardAccount: p.rewardAccount || '',
|
|
115
|
+
};
|
|
116
|
+
});
|
|
117
|
+
let abstain = null;
|
|
118
|
+
let noConfidence = null;
|
|
119
|
+
const dreps = [];
|
|
120
|
+
for (const d of raw.dreps) {
|
|
121
|
+
if (d.type === 'abstain') {
|
|
122
|
+
abstain = (abstain ?? 0n) + lovelace(d.stake);
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
if (d.type === 'noConfidence') {
|
|
126
|
+
noConfidence = (noConfidence ?? 0n) + lovelace(d.stake);
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
if (d.type !== 'registered' || !d.id)
|
|
130
|
+
continue;
|
|
131
|
+
const mandate = d.mandate?.epoch;
|
|
132
|
+
dreps.push({
|
|
133
|
+
drepId: (0, mappers_1.credentialToDrepId)(d.id, d.from === 'script'),
|
|
134
|
+
hex: d.id,
|
|
135
|
+
amount: ogmiosValueToLovelaceString(d.stake),
|
|
136
|
+
hasScript: d.from === 'script',
|
|
137
|
+
lastActiveEpoch: 0,
|
|
138
|
+
expired: typeof mandate === 'number' && mandate < raw.epoch,
|
|
139
|
+
retired: false,
|
|
140
|
+
deposit: d.deposit ? ogmiosValueToLovelaceString(d.deposit) : null,
|
|
141
|
+
expiresEpoch: typeof mandate === 'number' ? mandate : null,
|
|
142
|
+
delegatorCount: Array.isArray(d.delegators) ? d.delegators.length : null,
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
return {
|
|
146
|
+
epoch: raw.epoch,
|
|
147
|
+
pools,
|
|
148
|
+
dreps,
|
|
149
|
+
treasury: raw.pots?.treasury ? ogmiosValueToLovelaceString(raw.pots.treasury) : null,
|
|
150
|
+
reserves: reserves == null ? null : reserves.toString(),
|
|
151
|
+
drepAbstainStake: abstain == null ? null : abstain.toString(),
|
|
152
|
+
drepNoConfidenceStake: noConfidence == null ? null : noConfidence.toString(),
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Decode a CIP-129 DRep ID (`drep1…`, 29 bytes) into credential hash and type. Header byte:
|
|
157
|
+
* high nibble 0x2 = DRep, low nibble 0x2 = key hash / 0x3 = script hash.
|
|
158
|
+
*/
|
|
159
|
+
function decodeDrepId(drepId) {
|
|
160
|
+
const decoded = bech32_1.bech32.decode(drepId, const_1.BECH32_MAX_LENGTH);
|
|
161
|
+
const bytes = Buffer.from(bech32_1.bech32.fromWords(decoded.words));
|
|
162
|
+
if (decoded.prefix !== 'drep' || bytes.length !== 29) {
|
|
163
|
+
throw new errors_1.NotFoundError('Drep', 'ogmios');
|
|
164
|
+
}
|
|
165
|
+
return {
|
|
166
|
+
hashHex: bytes.subarray(1).toString('hex'),
|
|
167
|
+
isScript: (bytes[0] & 0x0f) === 0x03,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
66
170
|
/** Resolve Ogmios ledger tip which may be 'origin' (genesis block) or a point */
|
|
67
171
|
function resolveOgmiosTip(tip) {
|
|
68
172
|
return tip === 'origin' ? { slot: 0, hash: '' } : { slot: tip.slot, hash: tip.id };
|
|
@@ -71,15 +175,34 @@ function resolveOgmiosTip(tip) {
|
|
|
71
175
|
function resolveOgmiosHeight(height) {
|
|
72
176
|
return height === 'origin' ? 0 : height;
|
|
73
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
|
+
}
|
|
200
|
+
/** CardanoBackend implementation over an Ogmios WebSocket (local node). */
|
|
74
201
|
class OgmiosBackend {
|
|
75
202
|
name = 'ogmios';
|
|
76
203
|
/**
|
|
77
|
-
* Capability declaration — the orchestrator skips Ogmios for these without
|
|
78
|
-
*
|
|
79
|
-
* getAddress/getNetworkInformation previously FABRICATED placeholder data
|
|
80
|
-
* (type:'base'/isScript:false/stakeAddress:null resp. maxSupply as
|
|
81
|
-
* total/circulating) which preferLive routing then preferred over correct
|
|
82
|
-
* Blockfrost/Koios data.
|
|
204
|
+
* Capability declaration — the orchestrator skips Ogmios for these without counting
|
|
205
|
+
* circuit failures. Historic queries are out of protocol scope.
|
|
83
206
|
*/
|
|
84
207
|
unsupportedMethods = new Set([
|
|
85
208
|
// getEpoch is NOT listed: Ogmios can serve the CURRENT epoch and only
|
|
@@ -88,22 +211,22 @@ class OgmiosBackend {
|
|
|
88
211
|
'getTransaction',
|
|
89
212
|
'getTransactionMetadata',
|
|
90
213
|
'getAddressTransactions',
|
|
91
|
-
|
|
214
|
+
// getDrep is NOT listed: served from the live ledger state via
|
|
215
|
+
// queryLedgerState/delegateRepresentatives (Ogmios ≥ 6.4).
|
|
92
216
|
'getAssetInfo',
|
|
93
|
-
'getAddress',
|
|
94
|
-
'getNetworkInformation',
|
|
95
217
|
]);
|
|
96
218
|
stateQueryClient = null;
|
|
97
219
|
txSubmissionClient = null;
|
|
98
220
|
context = null;
|
|
221
|
+
/** Second connection for address queries (see scanQueryClient). */
|
|
222
|
+
scanClient = null;
|
|
223
|
+
scanContext = null;
|
|
224
|
+
scanConnecting = null;
|
|
99
225
|
isShutdown = false;
|
|
100
226
|
reconnectPromise = null;
|
|
101
227
|
network;
|
|
102
228
|
timeoutMs;
|
|
103
229
|
ogmiosUrl;
|
|
104
|
-
/**
|
|
105
|
-
* Constructor
|
|
106
|
-
*/
|
|
107
230
|
constructor(network, timeoutMs, ogmiosUrl) {
|
|
108
231
|
if (!ogmiosUrl) {
|
|
109
232
|
throw new errors_1.BackendInitError('ogmios', new Error('ogmiosUrl is not set'));
|
|
@@ -113,21 +236,9 @@ class OgmiosBackend {
|
|
|
113
236
|
this.ogmiosUrl = ogmiosUrl;
|
|
114
237
|
}
|
|
115
238
|
/**
|
|
116
|
-
* Force
|
|
117
|
-
*
|
|
118
|
-
*
|
|
119
|
-
* `GET http://<ogmios>/health` via the library's `cross-fetch` → node-fetch v2
|
|
120
|
-
* → Node-core `http`. Since Node 19, `http.globalAgent` defaults to
|
|
121
|
-
* keepAlive:true, so node-fetch reuses pooled sockets. Against Ogmios' Warp
|
|
122
|
-
* server on Node 22/24 a reused socket the server has already half-closed
|
|
123
|
-
* yields "Invalid response body … Premature close" the instant the body is
|
|
124
|
-
* read — deterministically (Node 20's older http client tolerated it; `curl`
|
|
125
|
-
* does too, so the /health response itself is well-formed and the node is
|
|
126
|
-
* healthy). The lib pins cross-fetch even in 7.0 and exposes no way to inject
|
|
127
|
-
* an agent into that internal fetch, so we neutralise keep-alive process-wide
|
|
128
|
-
* for `http://`. Blast radius is tiny: the only `http://` consumer is the local
|
|
129
|
-
* Ogmios probe — Blockfrost/Koios run over `https` with their own axios agents
|
|
130
|
-
* and are unaffected. Runs once, lazily, only when Ogmios is actually used.
|
|
239
|
+
* Force non-keep-alive HTTP for the Ogmios `/health` probe: node-fetch v2 uses `http.globalAgent`,
|
|
240
|
+
* whose pooled sockets (kept alive since Node 19) fail with "Premature close" once Ogmios' Warp server
|
|
241
|
+
* half-closes them. No agent hook exists, so keep-alive is disabled process-wide for `http://` only.
|
|
131
242
|
*/
|
|
132
243
|
static keepAliveDisabled = false;
|
|
133
244
|
static disableHttpKeepAlive() {
|
|
@@ -155,17 +266,12 @@ class OgmiosBackend {
|
|
|
155
266
|
}
|
|
156
267
|
}
|
|
157
268
|
/**
|
|
158
|
-
* Bound an init step in time
|
|
159
|
-
*
|
|
160
|
-
*
|
|
161
|
-
* app-context bootstrap (seen as a 6h CI job timeout). On timeout we reject
|
|
162
|
-
* with a message containing "timeout" so the orchestrator's transient-error
|
|
163
|
-
* retry picks it up instead of dying.
|
|
269
|
+
* Bound an init step in time: the WebSocket connect/handshake has no built-in timeout and
|
|
270
|
+
* can hang when the node is busy. The rejection message contains "timeout" so the
|
|
271
|
+
* orchestrator's transient-error retry picks it up.
|
|
164
272
|
*/
|
|
165
273
|
withInitTimeout(p, label) {
|
|
166
|
-
//
|
|
167
|
-
// integration suite's 20s cds.test() hook, so each attempt must be brief.
|
|
168
|
-
// Still bounds a genuinely hung connect in production.
|
|
274
|
+
// Short on purpose: the orchestrator retries init several times within a bounded bootstrap window.
|
|
169
275
|
const ms = Math.max(1, Math.min(this.timeoutMs, 4000));
|
|
170
276
|
let timer;
|
|
171
277
|
const timeout = new Promise((_, reject) => {
|
|
@@ -175,10 +281,8 @@ class OgmiosBackend {
|
|
|
175
281
|
return Promise.race([p, timeout]).finally(() => clearTimeout(timer));
|
|
176
282
|
}
|
|
177
283
|
/**
|
|
178
|
-
* Force-release an
|
|
179
|
-
*
|
|
180
|
-
* the close fallback keeps the helper compatible with the public structural
|
|
181
|
-
* InteractionContext type and lightweight test doubles.
|
|
284
|
+
* Force-release an interaction socket after a failed/expired open or close. The runtime
|
|
285
|
+
* socket is `ws` (has `terminate`); the `close` fallback keeps test doubles working.
|
|
182
286
|
*/
|
|
183
287
|
forceCloseContext(context) {
|
|
184
288
|
const socket = context.socket;
|
|
@@ -194,9 +298,7 @@ class OgmiosBackend {
|
|
|
194
298
|
// Best effort only: the socket may already have completed its close event.
|
|
195
299
|
}
|
|
196
300
|
}
|
|
197
|
-
/**
|
|
198
|
-
* Initialize the Ogmios backend connection
|
|
199
|
-
*/
|
|
301
|
+
/** Open the interaction context and the query/submission clients. */
|
|
200
302
|
async init() {
|
|
201
303
|
OgmiosBackend.disableHttpKeepAlive();
|
|
202
304
|
OgmiosBackend.validateOgmiosUrl(this.ogmiosUrl);
|
|
@@ -209,9 +311,7 @@ class OgmiosBackend {
|
|
|
209
311
|
const context = await this.withInitTimeout((0, client_1.createInteractionContext)(
|
|
210
312
|
/* c8 ignore next */
|
|
211
313
|
(err) => logger.error(`[OgmiosBackend] Interaction context error: ${err.message}`), () => {
|
|
212
|
-
// Socket closed: clear the clients so the next request reconnects via
|
|
213
|
-
// ensureConnected — previously this handler only logged and the backend
|
|
214
|
-
// stayed dead until process restart.
|
|
314
|
+
// Socket closed: clear the clients so the next request reconnects via ensureConnected.
|
|
215
315
|
if (this.isShutdown)
|
|
216
316
|
return;
|
|
217
317
|
logger.warn('[OgmiosBackend] WebSocket closed — will reconnect on next request');
|
|
@@ -235,10 +335,40 @@ class OgmiosBackend {
|
|
|
235
335
|
return true;
|
|
236
336
|
}
|
|
237
337
|
/**
|
|
238
|
-
*
|
|
239
|
-
*
|
|
240
|
-
*
|
|
241
|
-
|
|
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
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Reconnect when the WebSocket died since the last init. No-op when never initialized
|
|
371
|
+
* (test-injected clients); concurrent callers share one reconnect attempt.
|
|
242
372
|
*/
|
|
243
373
|
async ensureConnected() {
|
|
244
374
|
this.ensureNotShutdown();
|
|
@@ -274,13 +404,11 @@ class OgmiosBackend {
|
|
|
274
404
|
async getEpoch(epochNumber) {
|
|
275
405
|
return (0, backend_request_handler_1.handleBackendRequest)(async () => {
|
|
276
406
|
await this.ensureConnected();
|
|
277
|
-
// Get current epoch directly via epoch() query
|
|
278
407
|
const currentEpoch = await this.stateQueryClient.epoch();
|
|
279
408
|
// Ogmios only supports current epoch queries
|
|
280
409
|
if (epochNumber !== currentEpoch) {
|
|
281
410
|
throw new errors_1.NotFoundError(`Historic Epoch ${epochNumber} not supported (current: ${currentEpoch})`, this.name);
|
|
282
411
|
}
|
|
283
|
-
// Return current epoch data
|
|
284
412
|
return this.getLatestEpoch();
|
|
285
413
|
}, this.name);
|
|
286
414
|
}
|
|
@@ -305,13 +433,50 @@ class OgmiosBackend {
|
|
|
305
433
|
}, this.name);
|
|
306
434
|
}
|
|
307
435
|
/**
|
|
308
|
-
*
|
|
309
|
-
*
|
|
310
|
-
*
|
|
436
|
+
* DRep data from the live ledger state (`queryLedgerState/delegateRepresentatives`) via the
|
|
437
|
+
* raw `Method()` primitive, since the client ships no wrapper. Ogmios lists only REGISTERED
|
|
438
|
+
* DReps: retired/unknown → NotFoundError; `expired` is derived from the mandate epoch.
|
|
439
|
+
* @param drepId CIP-129 bech32 DRep ID (`drep1…`)
|
|
311
440
|
*/
|
|
312
|
-
async getDrep(
|
|
441
|
+
async getDrep(drepId) {
|
|
313
442
|
return (0, backend_request_handler_1.handleBackendRequest)(async () => {
|
|
314
|
-
|
|
443
|
+
await this.ensureConnected();
|
|
444
|
+
if (!this.context) {
|
|
445
|
+
throw new errors_1.ProviderUnavailableError('Ogmios interaction context not available', this.name);
|
|
446
|
+
}
|
|
447
|
+
const { hashHex, isScript } = decodeDrepId(drepId);
|
|
448
|
+
const [summaries, currentEpoch] = await Promise.all([
|
|
449
|
+
(0, client_1.Method)({
|
|
450
|
+
method: 'queryLedgerState/delegateRepresentatives',
|
|
451
|
+
params: isScript ? { scripts: [hashHex] } : { keys: [hashHex] },
|
|
452
|
+
}, {
|
|
453
|
+
handler: (response, resolve, reject) => {
|
|
454
|
+
if (response.error) {
|
|
455
|
+
reject(new Error(response.error.message ?? `Ogmios error ${response.error.code ?? ''}`.trim()));
|
|
456
|
+
}
|
|
457
|
+
else {
|
|
458
|
+
resolve(Array.isArray(response.result) ? response.result : []);
|
|
459
|
+
}
|
|
460
|
+
},
|
|
461
|
+
}, this.context),
|
|
462
|
+
this.stateQueryClient.epoch(),
|
|
463
|
+
]);
|
|
464
|
+
// Filter by id: the query is already credential-scoped, but never trust a
|
|
465
|
+
// broader answer (abstain/noConfidence rows carry no id and are dropped here).
|
|
466
|
+
const drep = summaries.find((s) => s.type === 'registered' && s.id?.toLowerCase() === hashHex);
|
|
467
|
+
if (!drep)
|
|
468
|
+
throw new errors_1.NotFoundError('Drep', this.name);
|
|
469
|
+
const mandateEpoch = drep.mandate?.epoch;
|
|
470
|
+
return {
|
|
471
|
+
drepId,
|
|
472
|
+
hex: hashHex,
|
|
473
|
+
amount: ogmiosValueToLovelaceString(drep.stake),
|
|
474
|
+
hasScript: isScript || drep.from === 'script',
|
|
475
|
+
// Ogmios reports the mandate (expiry) epoch, not the last activity — keep 0.
|
|
476
|
+
lastActiveEpoch: 0,
|
|
477
|
+
expired: typeof mandateEpoch === 'number' && mandateEpoch < Number(currentEpoch),
|
|
478
|
+
retired: false,
|
|
479
|
+
};
|
|
315
480
|
}, this.name);
|
|
316
481
|
}
|
|
317
482
|
/**
|
|
@@ -325,25 +490,58 @@ class OgmiosBackend {
|
|
|
325
490
|
}, this.name);
|
|
326
491
|
}
|
|
327
492
|
/**
|
|
328
|
-
*
|
|
329
|
-
*
|
|
330
|
-
* maxSupply as total/circulating, which preferLive routing then preferred
|
|
331
|
-
* over correct Blockfrost/Koios data)
|
|
493
|
+
* Supply figures from `queryLedgerState/treasuryAndReserves`: total = max − reserves.
|
|
494
|
+
* Circulating, locked and stake totals are not in the ledger state and stay '0'.
|
|
332
495
|
*/
|
|
333
496
|
async getNetworkInformation() {
|
|
334
497
|
return (0, backend_request_handler_1.handleBackendRequest)(async () => {
|
|
335
|
-
|
|
498
|
+
await this.ensureConnected();
|
|
499
|
+
if (!this.context) {
|
|
500
|
+
throw new errors_1.ProviderUnavailableError('Ogmios interaction context not available', this.name);
|
|
501
|
+
}
|
|
502
|
+
const pots = await (0, client_1.Method)({ method: 'queryLedgerState/treasuryAndReserves' }, {
|
|
503
|
+
handler: (response, resolve, reject) => {
|
|
504
|
+
if (response.error) {
|
|
505
|
+
reject(new Error(response.error.message ?? `Ogmios error ${response.error.code ?? ''}`.trim()));
|
|
506
|
+
}
|
|
507
|
+
else {
|
|
508
|
+
resolve(response.result ?? {});
|
|
509
|
+
}
|
|
510
|
+
},
|
|
511
|
+
}, this.context);
|
|
512
|
+
const max = const_1.CARDANO_DEFAULTS.MAX_LOVELACE_SUPPLY;
|
|
513
|
+
const reserves = ogmiosValueToLovelaceString(pots.reserves);
|
|
514
|
+
return {
|
|
515
|
+
supply: {
|
|
516
|
+
max,
|
|
517
|
+
total: (BigInt(max) - BigInt(reserves)).toString(),
|
|
518
|
+
circulating: '0',
|
|
519
|
+
locked: '0',
|
|
520
|
+
treasury: ogmiosValueToLovelaceString(pots.treasury),
|
|
521
|
+
reserves,
|
|
522
|
+
},
|
|
523
|
+
stake: { live: '0', active: '0' },
|
|
524
|
+
};
|
|
336
525
|
}, this.name);
|
|
337
526
|
}
|
|
338
527
|
/**
|
|
339
|
-
*
|
|
340
|
-
*
|
|
341
|
-
* previous implementation fabricated type:'base'/isScript:false/
|
|
342
|
-
* stakeAddress:null. UTxOs remain available via getAddressUtxos.)
|
|
528
|
+
* Address at the tip: type, script flag and stake address decoded from the address itself,
|
|
529
|
+
* UTxOs from the ledger, balance summed over them. No transaction history (getAddressTransactions).
|
|
343
530
|
*/
|
|
344
|
-
async getAddress(
|
|
531
|
+
async getAddress(address) {
|
|
345
532
|
return (0, backend_request_handler_1.handleBackendRequest)(async () => {
|
|
346
|
-
|
|
533
|
+
await this.ensureConnected();
|
|
534
|
+
const decoded = (0, mappers_1.decodeShelleyAddress)(address);
|
|
535
|
+
const raw = await (await this.scanQueryClient()).utxo({ addresses: [address] });
|
|
536
|
+
const utxos = raw.map((u) => this.mapOgmiosUtxo(u, address));
|
|
537
|
+
return {
|
|
538
|
+
address,
|
|
539
|
+
stakeAddress: decoded.stakeAddress,
|
|
540
|
+
type: decoded.type,
|
|
541
|
+
isScript: decoded.isScript,
|
|
542
|
+
amount: (0, mappers_1.sumUtxoAmounts)(utxos),
|
|
543
|
+
utxos,
|
|
544
|
+
};
|
|
347
545
|
}, this.name);
|
|
348
546
|
}
|
|
349
547
|
/** get current specific Address UTxOs
|
|
@@ -353,31 +551,85 @@ class OgmiosBackend {
|
|
|
353
551
|
async getAddressUtxos(address) {
|
|
354
552
|
return (0, backend_request_handler_1.handleBackendRequest)(async () => {
|
|
355
553
|
await this.ensureConnected();
|
|
356
|
-
const utxos = await this.
|
|
357
|
-
return utxos.map((u) =>
|
|
358
|
-
// convert Ogmios value format to standard amount array
|
|
359
|
-
const amount = this.convertOgmiosValue(u.value);
|
|
360
|
-
return {
|
|
361
|
-
txHash: u.transaction?.id || '',
|
|
362
|
-
outputIndex: u.index || 0,
|
|
363
|
-
address: u.address || address,
|
|
364
|
-
amount: amount,
|
|
365
|
-
blockHash: '',
|
|
366
|
-
datumHash: u.datumHash,
|
|
367
|
-
// Ogmios delivers the inline datum as CBOR hex in `datum` — it was
|
|
368
|
-
// dropped before, breaking inline-datum spends when Ogmios serves UTxOs
|
|
369
|
-
inlineDatum: typeof u.datum === 'string' ? u.datum : null,
|
|
370
|
-
scriptRef: u.script?.hash
|
|
371
|
-
};
|
|
372
|
-
});
|
|
554
|
+
const utxos = await (await this.scanQueryClient()).utxo({ addresses: [address] });
|
|
555
|
+
return utxos.map((u) => this.mapOgmiosUtxo(u, address));
|
|
373
556
|
}, this.name);
|
|
374
557
|
}
|
|
558
|
+
/** Ogmios `Utxo` entry → normalized UTxO line (shared by the address query and the set import). */
|
|
559
|
+
mapOgmiosUtxo(u, fallbackAddress = '') {
|
|
560
|
+
return {
|
|
561
|
+
txHash: u.transaction?.id || '',
|
|
562
|
+
outputIndex: u.index || 0,
|
|
563
|
+
address: u.address || fallbackAddress,
|
|
564
|
+
amount: this.convertOgmiosValue(u.value),
|
|
565
|
+
blockHash: '',
|
|
566
|
+
datumHash: u.datumHash,
|
|
567
|
+
// Ogmios delivers the inline datum as CBOR hex in `datum`
|
|
568
|
+
inlineDatum: typeof u.datum === 'string' ? u.datum : null,
|
|
569
|
+
scriptRef: ogmiosScriptHash(u.script) ?? undefined,
|
|
570
|
+
scriptRefCbor: ogmiosPlutusScriptCbor(u.script),
|
|
571
|
+
};
|
|
572
|
+
}
|
|
375
573
|
/**
|
|
376
|
-
*
|
|
377
|
-
*
|
|
378
|
-
*
|
|
379
|
-
* @returns {Promise<Transaction[]>} always throws - use historical backend instead
|
|
574
|
+
* Run `fn` against the ledger state acquired at `point` on a SEPARATE WebSocket: local-state-query
|
|
575
|
+
* holds one acquired point per connection, so the shared socket would pin live queries to the past.
|
|
576
|
+
* The point must be inside the node's volatile window (k blocks) or acquisition is refused.
|
|
380
577
|
*/
|
|
578
|
+
async withLedgerStateAt(point, label, fn) {
|
|
579
|
+
const url = new URL(this.ogmiosUrl);
|
|
580
|
+
const connection = { host: url.hostname, port: Number(url.port) || (url.protocol === 'wss:' ? 443 : 80), tls: url.protocol === 'wss:' };
|
|
581
|
+
const context = await (0, client_1.createInteractionContext)((err) => logger.error(`[OgmiosBackend] ${label} context error: ${err.message}`), () => { }, { connection });
|
|
582
|
+
let client = null;
|
|
583
|
+
try {
|
|
584
|
+
client = await (0, client_1.createLedgerStateQueryClient)(context, { point: { slot: point.slot, id: point.hash } });
|
|
585
|
+
return await fn(client);
|
|
586
|
+
}
|
|
587
|
+
finally {
|
|
588
|
+
// shutdown() closes THIS connection only; the backend's own socket is untouched
|
|
589
|
+
if (client) {
|
|
590
|
+
try {
|
|
591
|
+
await client.shutdown();
|
|
592
|
+
}
|
|
593
|
+
catch { /* best effort */ }
|
|
594
|
+
}
|
|
595
|
+
else
|
|
596
|
+
this.forceCloseContext(context);
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
/** Whole UTxO set as of `point` (crawler snapshot import). */
|
|
600
|
+
async queryUtxoSetAt(point) {
|
|
601
|
+
return (0, backend_request_handler_1.handleBackendRequest)(() => this.withLedgerStateAt(point, 'snapshot', async (client) => {
|
|
602
|
+
const utxos = await client.utxo();
|
|
603
|
+
return utxos.map((u) => this.mapOgmiosUtxo(u));
|
|
604
|
+
}), this.name);
|
|
605
|
+
}
|
|
606
|
+
/**
|
|
607
|
+
* Pools, DReps and pots as of `point` (crawler epoch snapshot), all read from one acquired
|
|
608
|
+
* ledger state. Performances are optional: without them (no nOpt) saturation stays 0.
|
|
609
|
+
*/
|
|
610
|
+
async epochStateAt(point) {
|
|
611
|
+
return (0, backend_request_handler_1.handleBackendRequest)(() => this.withLedgerStateAt(point, 'epoch snapshot', async (client) => {
|
|
612
|
+
const ctx = client.context;
|
|
613
|
+
const [epoch, stakePools, performances, dreps, pots] = await Promise.all([
|
|
614
|
+
client.epoch(),
|
|
615
|
+
client.stakePools(undefined, true),
|
|
616
|
+
client.stakePoolsPerformances().catch((err) => {
|
|
617
|
+
logger.warn(`stakePoolsPerformances unavailable, saturation stays 0: ${err?.message ?? err}`);
|
|
618
|
+
return null;
|
|
619
|
+
}),
|
|
620
|
+
(0, client_1.Method)({ method: 'queryLedgerState/delegateRepresentatives' }, {}, ctx),
|
|
621
|
+
(0, client_1.Method)({ method: 'queryLedgerState/treasuryAndReserves' }, {}, ctx),
|
|
622
|
+
]);
|
|
623
|
+
return mapOgmiosEpochState({
|
|
624
|
+
epoch: Number(epoch),
|
|
625
|
+
stakePools: (stakePools ?? {}),
|
|
626
|
+
performances: performances,
|
|
627
|
+
dreps: Array.isArray(dreps) ? dreps : [],
|
|
628
|
+
pots: pots ?? null,
|
|
629
|
+
});
|
|
630
|
+
}), this.name);
|
|
631
|
+
}
|
|
632
|
+
/** Not supported — Ogmios is a live state-query backend; use Blockfrost/Koios. */
|
|
381
633
|
async getAddressTransactions(_address) {
|
|
382
634
|
throw new errors_1.NotFoundError('Address transactions not available via Ogmios - use historical backend (Blockfrost/Koios)', this.name);
|
|
383
635
|
}
|
|
@@ -391,25 +643,27 @@ class OgmiosBackend {
|
|
|
391
643
|
await this.ensureConnected();
|
|
392
644
|
// Query from tip (no acquire needed) with stake included
|
|
393
645
|
const pools = await this.stateQueryClient.stakePools([{ id: poolId }], true);
|
|
394
|
-
//
|
|
646
|
+
// stakePools returns an object keyed by poolId
|
|
395
647
|
const pool = pools[poolId];
|
|
396
648
|
if (!pool)
|
|
397
649
|
throw new errors_1.NotFoundError('Pool', this.name);
|
|
398
650
|
return {
|
|
399
651
|
poolId,
|
|
400
|
-
vrfKeyHash: pool.
|
|
652
|
+
vrfKeyHash: pool.vrfVerificationKeyHash || '',
|
|
401
653
|
blocksMinted: 0,
|
|
402
|
-
|
|
654
|
+
// not in the ledger state; null = unavailable, as on Koios
|
|
655
|
+
blocksEpoch: null,
|
|
403
656
|
liveStake: pool.stake?.ada?.lovelace ? String(pool.stake.ada.lovelace) : '0',
|
|
404
|
-
|
|
405
|
-
|
|
657
|
+
// no total live stake to divide by; null = unavailable
|
|
658
|
+
liveSize: null,
|
|
659
|
+
// not in the ledger state; null = unavailable
|
|
660
|
+
liveDelegators: null,
|
|
406
661
|
liveSaturation: 0,
|
|
407
662
|
// activeStake is not available from Ogmios pool params — report 0 instead
|
|
408
663
|
// of fabricating it from the pledge
|
|
409
664
|
activeStake: '0',
|
|
410
665
|
activeSize: 0,
|
|
411
|
-
// pledge/cost are ValueAdaOnly objects in Ogmios v6
|
|
412
|
-
// yielded "[object Object]"; margin is a Ratio string ("1/10")
|
|
666
|
+
// pledge/cost are ValueAdaOnly objects in Ogmios v6; margin is a Ratio string ("1/10")
|
|
413
667
|
pledge: ogmiosValueToLovelaceString(pool.pledge),
|
|
414
668
|
margin: parseOgmiosRatio(pool.margin),
|
|
415
669
|
fixedCost: ogmiosValueToLovelaceString(pool.cost),
|
|
@@ -425,30 +679,33 @@ class OgmiosBackend {
|
|
|
425
679
|
async getAccount(stakeAddress) {
|
|
426
680
|
return (0, backend_request_handler_1.handleBackendRequest)(async () => {
|
|
427
681
|
await this.ensureConnected();
|
|
428
|
-
|
|
682
|
+
// Ogmios keeps key-hash and script-hash credentials in separate lists. A script stake address
|
|
683
|
+
// asked under `keys` is never found.
|
|
684
|
+
const rawResult = await this.stateQueryClient.rewardAccountSummaries((0, mappers_1.decodeShelleyAddress)(stakeAddress).isScript ? { scripts: [stakeAddress] } : { keys: [stakeAddress] });
|
|
429
685
|
// Ogmios returns a record keyed by stake address; normalize to array
|
|
430
686
|
const summaries = Array.isArray(rawResult)
|
|
431
687
|
? rawResult
|
|
432
688
|
: Object.values(rawResult);
|
|
433
|
-
// Ogmios API returns array of account summaries
|
|
434
689
|
const account = summaries && summaries.length > 0 ? summaries[0] : null;
|
|
690
|
+
// The summary lists only credentials delegated to a pool or a DRep. A registered credential without
|
|
691
|
+
// delegation is absent here, so "not found" does not mean "not registered".
|
|
435
692
|
if (!account) {
|
|
436
693
|
throw new errors_1.NotFoundError('Account', this.name);
|
|
437
694
|
}
|
|
438
695
|
return {
|
|
439
696
|
stakeaddress: stakeAddress,
|
|
440
|
-
//
|
|
441
|
-
// reaching this point (summary found) therefore implies the account is active.
|
|
697
|
+
// a summary exists only for a registered credential
|
|
442
698
|
active: true,
|
|
443
699
|
activeEpoch: 0,
|
|
444
|
-
|
|
700
|
+
// reward-account summaries carry no controlled amount and no withdrawal totals
|
|
701
|
+
controlledAmount: '0',
|
|
445
702
|
rewardsSum: ogmiosValueToLovelaceString(account.rewards),
|
|
446
|
-
withdrawalsSum:
|
|
703
|
+
withdrawalsSum: '0',
|
|
447
704
|
reservesSum: '0',
|
|
448
705
|
treasurySum: '0',
|
|
449
706
|
withdrawableAmount: ogmiosValueToLovelaceString(account.rewards),
|
|
450
|
-
poolId: account.
|
|
451
|
-
drepId: account.
|
|
707
|
+
poolId: account.stakePool?.id || null,
|
|
708
|
+
drepId: ogmiosDrepToId(account.delegateRepresentative),
|
|
452
709
|
addresses: []
|
|
453
710
|
};
|
|
454
711
|
}, this.name);
|
|
@@ -461,8 +718,22 @@ class OgmiosBackend {
|
|
|
461
718
|
async submitTransaction(signedTxCbor) {
|
|
462
719
|
return (0, backend_request_handler_1.handleBackendRequest)(async () => {
|
|
463
720
|
await this.ensureConnected();
|
|
464
|
-
|
|
465
|
-
|
|
721
|
+
try {
|
|
722
|
+
return await this.txSubmissionClient.submitTransaction(signedTxCbor);
|
|
723
|
+
}
|
|
724
|
+
catch (err) {
|
|
725
|
+
// JSON-RPC 3000-3999: the node rejected the transaction. Known kinds keep their class
|
|
726
|
+
// (already submitted = 409, script failure = 400); anything else becomes a 400 with its reason.
|
|
727
|
+
const known = (0, errors_1.normalizeBackendError)(err, this.name);
|
|
728
|
+
if (known.statusCode >= 400 && known.statusCode < 500)
|
|
729
|
+
throw known;
|
|
730
|
+
const e = err;
|
|
731
|
+
if (typeof e?.code === 'number' && e.code >= 3000 && e.code < 4000) {
|
|
732
|
+
const detail = e.data === undefined ? '' : ` ${JSON.stringify(e.data).slice(0, 800)}`;
|
|
733
|
+
throw new errors_1.TransactionValidationError(`node rejected the transaction (${e.code}): ${String(e.message ?? '')}${detail}`, err);
|
|
734
|
+
}
|
|
735
|
+
throw err;
|
|
736
|
+
}
|
|
466
737
|
}, this.name);
|
|
467
738
|
}
|
|
468
739
|
/**
|
|
@@ -473,8 +744,23 @@ class OgmiosBackend {
|
|
|
473
744
|
async evaluateTransaction(unsignedTxCbor) {
|
|
474
745
|
return (0, backend_request_handler_1.handleBackendRequest)(async () => {
|
|
475
746
|
await this.ensureConnected();
|
|
476
|
-
|
|
477
|
-
|
|
747
|
+
try {
|
|
748
|
+
const results = await this.txSubmissionClient.evaluateTransaction(unsignedTxCbor);
|
|
749
|
+
return results;
|
|
750
|
+
}
|
|
751
|
+
catch (err) {
|
|
752
|
+
// JSON-RPC 3000-3099 except 3003: the transaction cannot be evaluated as given, a 400 with its reason.
|
|
753
|
+
// 3003 means the node is still syncing, so it stays retryable.
|
|
754
|
+
const known = (0, errors_1.normalizeBackendError)(err, this.name);
|
|
755
|
+
if (known.statusCode >= 400 && known.statusCode < 500)
|
|
756
|
+
throw known;
|
|
757
|
+
const e = err;
|
|
758
|
+
if (typeof e?.code === 'number' && e.code >= 3000 && e.code < 3100 && e.code !== 3003) {
|
|
759
|
+
const detail = e.data === undefined ? '' : ` ${JSON.stringify(e.data).slice(0, 800)}`;
|
|
760
|
+
throw new errors_1.TransactionValidationError(`transaction cannot be evaluated (${e.code}): ${String(e.message ?? '')}${detail}`, err);
|
|
761
|
+
}
|
|
762
|
+
throw err;
|
|
763
|
+
}
|
|
478
764
|
}, this.name);
|
|
479
765
|
}
|
|
480
766
|
/**
|
|
@@ -516,7 +802,7 @@ class OgmiosBackend {
|
|
|
516
802
|
eMax: params.stakePoolRetirementEpochBound || 0,
|
|
517
803
|
nOpt: params.desiredNumberOfStakePools || 0,
|
|
518
804
|
a0: parseOgmiosRatio(params.stakePoolPledgeInfluence),
|
|
519
|
-
// ρ = monetaryExpansion, τ = treasuryExpansion
|
|
805
|
+
// ρ = monetaryExpansion, τ = treasuryExpansion
|
|
520
806
|
rho: parseOgmiosRatio(params.monetaryExpansion),
|
|
521
807
|
tau: parseOgmiosRatio(params.treasuryExpansion),
|
|
522
808
|
decentralisationParam: 0,
|
|
@@ -541,14 +827,14 @@ class OgmiosBackend {
|
|
|
541
827
|
]);
|
|
542
828
|
const { slot } = resolveOgmiosTip(tip);
|
|
543
829
|
// Network-aware epoch geometry + Shelley-anchored slot→time conversion
|
|
544
|
-
const startSlot = epochStartSlot(this.network, currentEpoch);
|
|
830
|
+
const startSlot = (0, epoch_slots_1.epochStartSlot)(this.network, currentEpoch);
|
|
545
831
|
const endSlot = startSlot + const_1.EPOCH_CONFIG_BY_NETWORK[this.network].slotsPerEpoch;
|
|
546
832
|
return {
|
|
547
833
|
epoch: currentEpoch,
|
|
548
|
-
start_time: slotToPosixSeconds(this.network, startSlot),
|
|
549
|
-
end_time: slotToPosixSeconds(this.network, endSlot),
|
|
550
|
-
first_block_time: slotToPosixSeconds(this.network, startSlot),
|
|
551
|
-
last_block_time: slotToPosixSeconds(this.network, slot),
|
|
834
|
+
start_time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, startSlot),
|
|
835
|
+
end_time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, endSlot),
|
|
836
|
+
first_block_time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, startSlot),
|
|
837
|
+
last_block_time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, slot),
|
|
552
838
|
block_count: 0, // Not available from Ogmios state queries
|
|
553
839
|
tx_count: 0, // Not available from Ogmios state queries
|
|
554
840
|
output: '0',
|
|
@@ -572,10 +858,10 @@ class OgmiosBackend {
|
|
|
572
858
|
]);
|
|
573
859
|
const { slot, hash } = resolveOgmiosTip(tip);
|
|
574
860
|
const height = resolveOgmiosHeight(blockHeight);
|
|
575
|
-
// network-aware slot-in-epoch
|
|
576
|
-
const epochSlot = Math.max(0, slot - epochStartSlot(this.network, epoch));
|
|
861
|
+
// network-aware slot-in-epoch
|
|
862
|
+
const epochSlot = Math.max(0, slot - (0, epoch_slots_1.epochStartSlot)(this.network, epoch));
|
|
577
863
|
return {
|
|
578
|
-
time: slotToPosixSeconds(this.network, slot), // seconds (mapBlock expects seconds)
|
|
864
|
+
time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, slot), // seconds (mapBlock expects seconds)
|
|
579
865
|
height,
|
|
580
866
|
hash,
|
|
581
867
|
slot,
|
|
@@ -585,6 +871,7 @@ class OgmiosBackend {
|
|
|
585
871
|
size: 0, // Not available via ledgerTip - would need full block data
|
|
586
872
|
txCount: 0, // Not available via ledgerTip - would need full block data
|
|
587
873
|
fees: '0', // Not available via ledgerTip - would need full block data
|
|
874
|
+
headerOnly: true,
|
|
588
875
|
};
|
|
589
876
|
}, this.name);
|
|
590
877
|
}
|
|
@@ -600,11 +887,9 @@ class OgmiosBackend {
|
|
|
600
887
|
return block.slot;
|
|
601
888
|
}
|
|
602
889
|
/**
|
|
603
|
-
*
|
|
604
|
-
* with an outputReferences filter. Empty result means spent or nonexistent.
|
|
890
|
+
* Unspent check via `queryLedgerState/utxo` with an outputReferences filter; empty = spent or nonexistent.
|
|
605
891
|
* @param txHash 64-char lowercase hex
|
|
606
892
|
* @param outputIndex non-negative integer
|
|
607
|
-
* @returns {Promise<boolean>} true iff the UTxO exists and is unspent
|
|
608
893
|
*/
|
|
609
894
|
async isUtxoUnspent(txHash, outputIndex) {
|
|
610
895
|
if (!Number.isInteger(outputIndex) || outputIndex < 0)
|
|
@@ -617,10 +902,19 @@ class OgmiosBackend {
|
|
|
617
902
|
return Array.isArray(result) && result.length > 0;
|
|
618
903
|
}, this.name);
|
|
619
904
|
}
|
|
620
|
-
/**
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
905
|
+
/** Outputs among `refs` that are unspent in the live ledger; spent or unknown references are absent. */
|
|
906
|
+
async getUnspentOutputs(refs) {
|
|
907
|
+
if (refs.length === 0)
|
|
908
|
+
return [];
|
|
909
|
+
return (0, backend_request_handler_1.handleBackendRequest)(async () => {
|
|
910
|
+
await this.ensureConnected();
|
|
911
|
+
const result = await this.stateQueryClient.utxo({
|
|
912
|
+
outputReferences: refs.map(r => ({ transaction: { id: r.txHash }, index: r.outputIndex })),
|
|
913
|
+
});
|
|
914
|
+
return result.map((u) => this.mapOgmiosUtxo(u));
|
|
915
|
+
}, this.name);
|
|
916
|
+
}
|
|
917
|
+
/** Close the WebSocket and mark the backend as shut down. */
|
|
624
918
|
async shutdown() {
|
|
625
919
|
if (this.isShutdown)
|
|
626
920
|
return;
|
|
@@ -639,13 +933,14 @@ class OgmiosBackend {
|
|
|
639
933
|
});
|
|
640
934
|
}
|
|
641
935
|
}
|
|
936
|
+
if (this.scanContext)
|
|
937
|
+
this.forceCloseContext(this.scanContext);
|
|
642
938
|
this.stateQueryClient = null;
|
|
643
939
|
this.txSubmissionClient = null;
|
|
644
940
|
this.context = null;
|
|
941
|
+
this.scanClient = null;
|
|
942
|
+
this.scanContext = null;
|
|
645
943
|
}
|
|
646
|
-
/**
|
|
647
|
-
* Check if backend is connected
|
|
648
|
-
*/
|
|
649
944
|
isConnected() {
|
|
650
945
|
if (this.isShutdown || !this.context?.socket) {
|
|
651
946
|
return false;
|
|
@@ -656,29 +951,23 @@ class OgmiosBackend {
|
|
|
656
951
|
// ---------------------------------------------------------------------------
|
|
657
952
|
// Helpers
|
|
658
953
|
// ---------------------------------------------------------------------------
|
|
659
|
-
/**
|
|
660
|
-
* Ensure the client is not shutdown before operations
|
|
661
|
-
*/
|
|
662
954
|
ensureNotShutdown() {
|
|
663
955
|
if (this.isShutdown) {
|
|
664
956
|
throw new errors_1.ProviderUnavailableError('Ogmios client has been shutdown', this.name);
|
|
665
957
|
}
|
|
666
958
|
}
|
|
667
959
|
/**
|
|
668
|
-
*
|
|
669
|
-
*
|
|
670
|
-
* Standard: [{ unit: 'lovelace', quantity: '1000000' }, { unit: 'policyId.assetName', quantity: 'N' }]
|
|
960
|
+
* Ogmios value `{ ada: { lovelace }, policyId: { assetName: qty } }` →
|
|
961
|
+
* `[{ unit: 'lovelace', quantity }, { unit: policyId+assetName, quantity }]`.
|
|
671
962
|
*/
|
|
672
963
|
convertOgmiosValue(value) {
|
|
673
964
|
const amounts = [];
|
|
674
|
-
// Handle ADA (lovelace)
|
|
675
965
|
if (value.ada?.lovelace) {
|
|
676
966
|
amounts.push({
|
|
677
967
|
unit: 'lovelace',
|
|
678
968
|
quantity: value.ada.lovelace.toString()
|
|
679
969
|
});
|
|
680
970
|
}
|
|
681
|
-
// handle native assets (policy.assetName)
|
|
682
971
|
for (const [policyId, assets] of Object.entries(value)) {
|
|
683
972
|
if (policyId === 'ada')
|
|
684
973
|
continue;
|
|
@@ -692,20 +981,12 @@ class OgmiosBackend {
|
|
|
692
981
|
return amounts;
|
|
693
982
|
}
|
|
694
983
|
// ---------------------------------------------------------------------------
|
|
695
|
-
// ChainSyncBackend — streamed forward sync for the chain crawler
|
|
984
|
+
// ChainSyncBackend — streamed forward sync for the chain crawler
|
|
696
985
|
// ---------------------------------------------------------------------------
|
|
697
986
|
/**
|
|
698
|
-
* Open a
|
|
699
|
-
*
|
|
700
|
-
*
|
|
701
|
-
* time in order, which the crawler needs for reorg detection and serial persist.
|
|
702
|
-
*
|
|
703
|
-
* KNOWN LIMITATIONS (documented, to harden against a live node — see CRAWLER_DESIGN.md):
|
|
704
|
-
* - Input address/amount are left empty: Ogmios chain-sync inputs are bare
|
|
705
|
-
* references ({txId,index}); the indexer resolves them from already-indexed
|
|
706
|
-
* outputs (indexBlockFull, C3).
|
|
707
|
-
* - Per-tx `size` and `deposit` are not surfaced by chain-sync (set 0).
|
|
708
|
-
* - Output `referenceScriptHash` is not derived from the inline script yet.
|
|
987
|
+
* Open a long-lived chain-sync stream on its own WebSocket. `sequential: true` + `inFlight: 1`
|
|
988
|
+
* deliver blocks strictly in order (required by reorg detection and serial persist). Inputs arrive
|
|
989
|
+
* as bare references (resolved by the indexer from indexed outputs); per-tx size/deposit are not surfaced.
|
|
709
990
|
*/
|
|
710
991
|
async openChainSync(from, callbacks) {
|
|
711
992
|
OgmiosBackend.validateOgmiosUrl(this.ogmiosUrl);
|
|
@@ -731,6 +1012,12 @@ class OgmiosBackend {
|
|
|
731
1012
|
logger.error('[OgmiosBackend] chain-sync onError callback failed:', callbackError);
|
|
732
1013
|
}
|
|
733
1014
|
};
|
|
1015
|
+
// A frame the client's parser cannot handle throws inside the library's un-awaited socket
|
|
1016
|
+
// handler and would end the process; the guard routes it here as a stream error instead.
|
|
1017
|
+
// Registered per open and removed on close, so concurrent streams each get the report.
|
|
1018
|
+
const unregisterFrameGuard = (0, ogmios_frame_guard_1.installOgmiosFrameGuard)(({ height, id, reason }) => {
|
|
1019
|
+
void reportStreamError(new errors_1.ChainSyncFrameError(height, id, reason));
|
|
1020
|
+
});
|
|
734
1021
|
const contextPromise = (0, client_1.createInteractionContext)((err) => {
|
|
735
1022
|
logger.error(`[OgmiosBackend] chain-sync context error: ${err.message}`);
|
|
736
1023
|
void reportStreamError(err);
|
|
@@ -738,7 +1025,7 @@ class OgmiosBackend {
|
|
|
738
1025
|
if (intentionalClose || this.isShutdown)
|
|
739
1026
|
return;
|
|
740
1027
|
const detail = reason?.toString() || 'no reason supplied';
|
|
741
|
-
const err = new errors_1.
|
|
1028
|
+
const err = new errors_1.ChainSyncClosedError(`Ogmios chain-sync socket closed unexpectedly (code ${code}: ${detail})`, this.name);
|
|
742
1029
|
logger.warn(`[OgmiosBackend] ${err.message}`);
|
|
743
1030
|
void reportStreamError(err);
|
|
744
1031
|
}, { connection });
|
|
@@ -750,14 +1037,13 @@ class OgmiosBackend {
|
|
|
750
1037
|
// A timeout rejects our race but cannot cancel the library's health probe /
|
|
751
1038
|
// handshake. If it resolves later, close that late socket as well.
|
|
752
1039
|
intentionalClose = true;
|
|
1040
|
+
unregisterFrameGuard();
|
|
753
1041
|
void contextPromise.then(lateContext => this.forceCloseContext(lateContext)).catch(() => undefined);
|
|
754
1042
|
throw err;
|
|
755
1043
|
}
|
|
756
|
-
// Both handlers are fully try/caught: the
|
|
757
|
-
//
|
|
758
|
-
//
|
|
759
|
-
// (stopping deterministically instead of skipping a block) and surface the error
|
|
760
|
-
// via callbacks.onError so the consumer can record it and close/restart.
|
|
1044
|
+
// Both handlers are fully try/caught: the client awaits them without a catch, and with
|
|
1045
|
+
// sequential+inFlight:1 a throw before nextBlock() stalls the stream. On error nextBlock()
|
|
1046
|
+
// is deliberately NOT called (stop, don't skip a block); the error goes to callbacks.onError.
|
|
761
1047
|
const handlers = {
|
|
762
1048
|
rollForward: async ({ block, tip }, nextBlock) => {
|
|
763
1049
|
try {
|
|
@@ -802,6 +1088,7 @@ class OgmiosBackend {
|
|
|
802
1088
|
}
|
|
803
1089
|
catch (err) {
|
|
804
1090
|
intentionalClose = true;
|
|
1091
|
+
unregisterFrameGuard();
|
|
805
1092
|
if (client) {
|
|
806
1093
|
try {
|
|
807
1094
|
await this.withInitTimeout(client.shutdown(), 'chainSync/failedOpenShutdown');
|
|
@@ -819,6 +1106,7 @@ class OgmiosBackend {
|
|
|
819
1106
|
// Idempotency matters when an operator stop races an onError-triggered halt.
|
|
820
1107
|
if (!closePromise) {
|
|
821
1108
|
intentionalClose = true;
|
|
1109
|
+
unregisterFrameGuard();
|
|
822
1110
|
closePromise = (async () => {
|
|
823
1111
|
try {
|
|
824
1112
|
await this.withInitTimeout(client.shutdown(), 'chainSync/shutdown');
|
|
@@ -834,24 +1122,22 @@ class OgmiosBackend {
|
|
|
834
1122
|
};
|
|
835
1123
|
}
|
|
836
1124
|
/**
|
|
837
|
-
* Map an Ogmios Praos block
|
|
838
|
-
* fees
|
|
839
|
-
*
|
|
1125
|
+
* Map an Ogmios Praos block to BlockData + transactions. Block fees are the sum of per-tx
|
|
1126
|
+
* fees; epoch/epochSlot derive from the slot via the Shelley anchor. A phase-2 failure without
|
|
1127
|
+
* `total_collateral` still carries its declared fee here; applyCollateralFees() corrects it.
|
|
840
1128
|
*/
|
|
841
1129
|
mapOgmiosBlock(block) {
|
|
842
1130
|
const txs = (block.transactions ?? []).map((t, i) => this.mapOgmiosTx(t, block, i));
|
|
843
1131
|
const totalFees = txs.reduce((sum, t) => sum + BigInt(t.fee || 0), 0n);
|
|
844
|
-
const
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
// instead of a second inline modulo formula
|
|
848
|
-
const epochSlot = block.slot - epochStartSlot(this.network, epoch);
|
|
1132
|
+
const epoch = (0, epoch_slots_1.epochOfSlot)(this.network, block.slot);
|
|
1133
|
+
// Shelley-anchored helpers (handle preview/preprod geometry and the Byron offset)
|
|
1134
|
+
const epochSlot = block.slot - (0, epoch_slots_1.epochStartSlot)(this.network, epoch);
|
|
849
1135
|
const blockData = {
|
|
850
|
-
time: slotToPosixSeconds(this.network, block.slot),
|
|
1136
|
+
time: (0, epoch_slots_1.slotToPosixSeconds)(this.network, block.slot),
|
|
851
1137
|
height: block.height,
|
|
852
1138
|
hash: block.id,
|
|
853
1139
|
slot: block.slot,
|
|
854
|
-
slotLeader: block.issuer?.verificationKey
|
|
1140
|
+
slotLeader: block.issuer?.verificationKey ? issuerKeyToPoolId(block.issuer.verificationKey) : '',
|
|
855
1141
|
epoch,
|
|
856
1142
|
epochSlot,
|
|
857
1143
|
size: block.size?.bytes ?? 0,
|
|
@@ -861,11 +1147,9 @@ class OgmiosBackend {
|
|
|
861
1147
|
return { block: blockData, txs };
|
|
862
1148
|
}
|
|
863
1149
|
/**
|
|
864
|
-
* Map
|
|
865
|
-
*
|
|
866
|
-
*
|
|
867
|
-
* partition: a phase-2-invalid transaction consumes collaterals and creates only
|
|
868
|
-
* its collateral-return output, never its declared regular inputs/outputs.
|
|
1150
|
+
* Map one chain-sync transaction. Inputs stay bare references (resolved by the indexer).
|
|
1151
|
+
* `spends` selects the ledger-applied partition: a phase-2-invalid tx consumes collaterals
|
|
1152
|
+
* and creates only its collateral-return output; the fee follows that partition too.
|
|
869
1153
|
*/
|
|
870
1154
|
mapOgmiosTx(tx, block, index) {
|
|
871
1155
|
const mapInput = (input, flags = {}) => ({
|
|
@@ -889,7 +1173,7 @@ class OgmiosBackend {
|
|
|
889
1173
|
dataHash: output.datumHash ?? null,
|
|
890
1174
|
inlineDatum: output.datum ?? null,
|
|
891
1175
|
isCollateral,
|
|
892
|
-
referenceScriptHash:
|
|
1176
|
+
referenceScriptHash: ogmiosScriptHash(output.script),
|
|
893
1177
|
});
|
|
894
1178
|
const outputs = spendsCollaterals
|
|
895
1179
|
? (tx.collateralReturn
|
|
@@ -905,24 +1189,95 @@ class OgmiosBackend {
|
|
|
905
1189
|
json: v.json,
|
|
906
1190
|
}))
|
|
907
1191
|
: [];
|
|
908
|
-
|
|
1192
|
+
// A phase-2 failure pays `total_collateral`, not the declared fee; the body often omits it,
|
|
1193
|
+
// so the indexer derives the rest from the resolved collateral inputs later.
|
|
1194
|
+
const declaredFee = (tx.fee?.ada?.lovelace ?? 0).toString();
|
|
1195
|
+
const totalCollateral = tx.totalCollateral ? tx.totalCollateral.ada.lovelace.toString() : null;
|
|
1196
|
+
// the same ledger view the pagination sources produce (ordering; the partition is already applied)
|
|
1197
|
+
return (0, mappers_1.ledgerView)({
|
|
909
1198
|
hash: tx.id,
|
|
910
1199
|
blockHash: block.id,
|
|
911
1200
|
blockHeight: block.height,
|
|
912
1201
|
slot: block.slot,
|
|
913
1202
|
index,
|
|
914
|
-
fee: (
|
|
1203
|
+
fee: spendsCollaterals ? (totalCollateral ?? declaredFee) : declaredFee,
|
|
1204
|
+
spendsCollaterals,
|
|
1205
|
+
totalCollateral,
|
|
915
1206
|
deposit: '0',
|
|
1207
|
+
// The ledger applies no mint when the script phase failed: the body's mint field is
|
|
1208
|
+
// declared but never enacted, so a phase-2 failure must report none at all.
|
|
1209
|
+
mint: spendsCollaterals ? undefined : this.convertOgmiosValue(tx.mint ?? {}),
|
|
916
1210
|
// null = unknown (chain-sync doesn't surface the serialized size) — matches the
|
|
917
1211
|
// lazy path's `size ?? null` convention; 0 would masquerade as a real size
|
|
918
1212
|
size: null,
|
|
919
|
-
blockTime: slotToPosixSeconds(this.network, block.slot),
|
|
1213
|
+
blockTime: (0, epoch_slots_1.slotToPosixSeconds)(this.network, block.slot),
|
|
920
1214
|
inputs,
|
|
921
1215
|
outputs,
|
|
922
1216
|
// undefined (not []) when absent — matches the Blockfrost path so
|
|
923
1217
|
// mapTransaction's hasMetadata flag stays false for metadata-less txs
|
|
924
1218
|
metadata: metadataEntries.length ? metadataEntries : undefined,
|
|
925
|
-
|
|
1219
|
+
certificates: this.mapOgmiosCertificates(tx.certificates ?? []),
|
|
1220
|
+
withdrawals: Object.entries(tx.withdrawals ?? {}).map(([stakeAddress, value]) => ({
|
|
1221
|
+
stakeAddress,
|
|
1222
|
+
amount: (value?.ada?.lovelace ?? 0).toString(),
|
|
1223
|
+
})),
|
|
1224
|
+
redeemers: mapOgmiosRedeemers(tx),
|
|
1225
|
+
});
|
|
1226
|
+
}
|
|
1227
|
+
/**
|
|
1228
|
+
* Normalize Ogmios certificates onto the shared `CertificateKind` vocabulary. A `stakeDelegation`
|
|
1229
|
+
* with both pool and DRep target is split into two entries with the same index (as db-sync
|
|
1230
|
+
* reports it); bare credential hashes are re-encoded as bech32 to match the other tables.
|
|
1231
|
+
*/
|
|
1232
|
+
mapOgmiosCertificates(certs) {
|
|
1233
|
+
const out = [];
|
|
1234
|
+
const lovelace = (v) => v?.ada?.lovelace != null ? v.ada.lovelace.toString() : null;
|
|
1235
|
+
const stakeAddr = (c) => c.credential ? (0, mappers_1.credentialToStakeAddress)(c.credential, c.from === 'script', this.network) : null;
|
|
1236
|
+
certs.forEach((c, certIndex) => {
|
|
1237
|
+
switch (c.type) {
|
|
1238
|
+
case 'stakeCredentialRegistration':
|
|
1239
|
+
out.push({ certIndex, kind: 'stake_registration', stakeAddress: stakeAddr(c), deposit: lovelace(c.deposit) });
|
|
1240
|
+
break;
|
|
1241
|
+
case 'stakeCredentialDeregistration':
|
|
1242
|
+
out.push({ certIndex, kind: 'stake_deregistration', stakeAddress: stakeAddr(c), deposit: lovelace(c.deposit) });
|
|
1243
|
+
break;
|
|
1244
|
+
case 'stakeDelegation': {
|
|
1245
|
+
const stakeAddress = stakeAddr(c);
|
|
1246
|
+
if (c.stakePool?.id)
|
|
1247
|
+
out.push({ certIndex, kind: 'pool_delegation', stakeAddress, poolId: c.stakePool.id });
|
|
1248
|
+
if (c.delegateRepresentative)
|
|
1249
|
+
out.push({ certIndex, kind: 'vote_delegation', stakeAddress, drepId: ogmiosDrepToId(c.delegateRepresentative) });
|
|
1250
|
+
break;
|
|
1251
|
+
}
|
|
1252
|
+
case 'stakePoolRegistration':
|
|
1253
|
+
out.push({ certIndex, kind: 'pool_registration', poolId: c.stakePool?.id ?? null });
|
|
1254
|
+
break;
|
|
1255
|
+
case 'stakePoolRetirement':
|
|
1256
|
+
out.push({ certIndex, kind: 'pool_retirement', poolId: c.stakePool?.id ?? null, epoch: c.stakePool?.retirementEpoch ?? null });
|
|
1257
|
+
break;
|
|
1258
|
+
case 'delegateRepresentativeRegistration':
|
|
1259
|
+
out.push({ certIndex, kind: 'drep_registration', drepId: ogmiosDrepToId(c.delegateRepresentative), deposit: lovelace(c.deposit) });
|
|
1260
|
+
break;
|
|
1261
|
+
case 'delegateRepresentativeUpdate':
|
|
1262
|
+
out.push({ certIndex, kind: 'drep_update', drepId: ogmiosDrepToId(c.delegateRepresentative) });
|
|
1263
|
+
break;
|
|
1264
|
+
case 'delegateRepresentativeRetirement':
|
|
1265
|
+
out.push({ certIndex, kind: 'drep_retirement', drepId: ogmiosDrepToId(c.delegateRepresentative), deposit: lovelace(c.deposit) });
|
|
1266
|
+
break;
|
|
1267
|
+
case 'constitutionalCommitteeDelegation':
|
|
1268
|
+
out.push({ certIndex, kind: 'committee_hot_auth' });
|
|
1269
|
+
break;
|
|
1270
|
+
case 'constitutionalCommitteeRetirement':
|
|
1271
|
+
out.push({ certIndex, kind: 'committee_resign' });
|
|
1272
|
+
break;
|
|
1273
|
+
case 'genesisDelegation':
|
|
1274
|
+
out.push({ certIndex, kind: 'genesis_delegation' });
|
|
1275
|
+
break;
|
|
1276
|
+
default:
|
|
1277
|
+
out.push({ certIndex, kind: c.type });
|
|
1278
|
+
}
|
|
1279
|
+
});
|
|
1280
|
+
return out;
|
|
926
1281
|
}
|
|
927
1282
|
}
|
|
928
1283
|
exports.OgmiosBackend = OgmiosBackend;
|