@odatano/core 2.0.0-rc.5 → 2.0.0-rc.50
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 +99 -51
- package/@cds-models/CardanoAgentService/index.js +15 -0
- package/@cds-models/CardanoBackendService/index.d.ts +347 -0
- package/@cds-models/CardanoBackendService/index.js +40 -0
- package/@cds-models/CardanoIndexerService/index.d.ts +496 -11
- package/@cds-models/CardanoIndexerService/index.js +64 -0
- package/@cds-models/CardanoODataService/index.d.ts +414 -57
- package/@cds-models/CardanoODataService/index.js +42 -0
- package/@cds-models/CardanoSignService/index.d.ts +32 -19
- package/@cds-models/CardanoSignService/index.js +3 -0
- package/@cds-models/CardanoTransactionService/index.d.ts +58 -44
- package/@cds-models/CardanoTransactionService/index.js +4 -0
- package/@cds-models/CardanoWorkerService/index.d.ts +7 -22
- package/@cds-models/index.d.ts +101 -1
- package/@cds-models/index.js +16 -1
- package/@cds-models/odatano/cardano/index.d.ts +437 -32
- package/@cds-models/odatano/cardano/index.js +48 -0
- package/README.md +207 -167
- package/db/schema.cds +2402 -1705
- package/db/types.cds +446 -295
- package/package.json +41 -16
- package/scripts/migrate-schema.mjs +334 -0
- package/scripts/migrate-slot-leader.mjs +96 -0
- package/src/index.d.ts +20 -21
- package/src/index.js +45 -31
- package/src/plugin.js +17 -35
- package/srv/blockchain/asset-decimals.d.ts +7 -0
- package/srv/blockchain/asset-decimals.js +91 -0
- package/srv/blockchain/backends/blockfrost-backend.d.ts +25 -135
- package/srv/blockchain/backends/blockfrost-backend.js +66 -172
- package/srv/blockchain/backends/cardano-backend.d.ts +94 -186
- package/srv/blockchain/backends/cardano-backend.js +29 -5
- package/srv/blockchain/backends/koios-backend.d.ts +103 -168
- package/srv/blockchain/backends/koios-backend.js +428 -360
- package/srv/blockchain/backends/odatano-backend.d.ts +54 -0
- package/srv/blockchain/backends/odatano-backend.js +169 -0
- package/srv/blockchain/backends/ogmios-backend.d.ts +123 -190
- package/srv/blockchain/backends/ogmios-backend.js +637 -315
- package/srv/blockchain/backends/ogmios-frame-guard.d.ts +14 -0
- package/srv/blockchain/backends/ogmios-frame-guard.js +89 -0
- package/srv/blockchain/cardano-client.d.ts +61 -241
- package/srv/blockchain/cardano-client.js +253 -293
- package/srv/blockchain/cardano-indexer.d.ts +282 -281
- package/srv/blockchain/cardano-indexer.js +1551 -484
- package/srv/blockchain/cardano-tx-builder.d.ts +25 -89
- package/srv/blockchain/cardano-tx-builder.js +164 -140
- package/srv/blockchain/circuit-breaker.d.ts +1 -13
- package/srv/blockchain/circuit-breaker.js +5 -15
- package/srv/blockchain/crawler/account-snapshots.d.ts +29 -0
- package/srv/blockchain/crawler/account-snapshots.js +153 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.d.ts +15 -0
- package/srv/blockchain/crawler/asset-decimals-backfill.js +56 -0
- package/srv/blockchain/crawler/asset-registry-backfill.d.ts +43 -0
- package/srv/blockchain/crawler/asset-registry-backfill.js +153 -0
- package/srv/blockchain/crawler/certificate-backfill.d.ts +52 -0
- package/srv/blockchain/crawler/certificate-backfill.js +162 -0
- package/srv/blockchain/crawler/crawler.d.ts +104 -81
- package/srv/blockchain/crawler/crawler.js +532 -160
- package/srv/blockchain/crawler/credential-backfill.d.ts +28 -0
- package/srv/blockchain/crawler/credential-backfill.js +124 -0
- package/srv/blockchain/crawler/hooks.d.ts +2 -17
- package/srv/blockchain/crawler/index.d.ts +1 -8
- package/srv/blockchain/crawler/index.js +31 -17
- package/srv/blockchain/crawler/input-asset-copies.d.ts +34 -0
- package/srv/blockchain/crawler/input-asset-copies.js +171 -0
- package/srv/blockchain/crawler/metadata-position-backfill.d.ts +16 -0
- package/srv/blockchain/crawler/metadata-position-backfill.js +55 -0
- package/srv/blockchain/crawler/output-datum-backfill.d.ts +39 -0
- package/srv/blockchain/crawler/output-datum-backfill.js +110 -0
- package/srv/blockchain/crawler/sync-state.d.ts +27 -47
- package/srv/blockchain/crawler/sync-state.js +113 -63
- package/srv/blockchain/crawler/transaction-backfill.d.ts +44 -0
- package/srv/blockchain/crawler/transaction-backfill.js +278 -0
- package/srv/blockchain/crawler/utxo-set-import.d.ts +66 -0
- package/srv/blockchain/crawler/utxo-set-import.js +399 -0
- package/srv/blockchain/ledger-state.d.ts +62 -0
- package/srv/blockchain/ledger-state.js +419 -0
- package/srv/blockchain/pending-spends.d.ts +16 -0
- package/srv/blockchain/pending-spends.js +81 -0
- package/srv/blockchain/pool-metadata.d.ts +15 -0
- package/srv/blockchain/pool-metadata.js +132 -0
- package/srv/blockchain/request-coalescer.d.ts +2 -16
- package/srv/blockchain/request-coalescer.js +2 -16
- package/srv/blockchain/signing/cose-verifier.d.ts +3 -17
- package/srv/blockchain/signing/cose-verifier.js +146 -70
- package/srv/blockchain/signing/external-signer.d.ts +15 -115
- package/srv/blockchain/signing/external-signer.js +17 -126
- package/srv/blockchain/signing/hsm-signer.d.ts +10 -54
- package/srv/blockchain/signing/hsm-signer.js +28 -79
- package/srv/blockchain/signing/signature-verifier.d.ts +9 -47
- package/srv/blockchain/signing/signature-verifier.js +70 -83
- package/srv/blockchain/signing/submission-finalizer.d.ts +23 -45
- package/srv/blockchain/signing/submission-finalizer.js +219 -86
- package/srv/blockchain/stored-chain.d.ts +20 -0
- package/srv/blockchain/stored-chain.js +237 -0
- package/srv/blockchain/transaction-building/buildooor-tx.d.ts +31 -229
- package/srv/blockchain/transaction-building/buildooor-tx.js +652 -416
- package/srv/blockchain/transaction-building/cardano-tx.d.ts +9 -37
- package/srv/blockchain/transaction-presence.d.ts +5 -0
- package/srv/blockchain/transaction-presence.js +29 -0
- package/srv/blockchain/transaction-rows.d.ts +12 -0
- package/srv/blockchain/transaction-rows.js +44 -0
- package/srv/blockchain/wallet-worker/build-request.d.ts +5 -20
- package/srv/blockchain/wallet-worker/build-request.js +47 -30
- package/srv/blockchain/wallet-worker/confirmation-tracker.d.ts +5 -46
- package/srv/blockchain/wallet-worker/confirmation-tracker.js +25 -45
- package/srv/blockchain/wallet-worker/index.d.ts +1 -1
- package/srv/blockchain/wallet-worker/index.js +3 -11
- package/srv/blockchain/wallet-worker/job-store.d.ts +30 -148
- package/srv/blockchain/wallet-worker/job-store.js +101 -201
- package/srv/blockchain/wallet-worker/lease-heartbeat.d.ts +2 -26
- package/srv/blockchain/wallet-worker/lease-heartbeat.js +6 -28
- package/srv/blockchain/wallet-worker/signers.d.ts +5 -24
- package/srv/blockchain/wallet-worker/signers.js +4 -12
- package/srv/blockchain/wallet-worker/wallet-worker.d.ts +8 -80
- package/srv/blockchain/wallet-worker/wallet-worker.js +107 -155
- package/srv/cardano-agent-service.cds +122 -84
- package/srv/cardano-agent-service.js +4 -9
- package/srv/cardano-backend-service.cds +78 -0
- package/srv/cardano-backend-service.d.ts +2 -0
- package/srv/cardano-backend-service.js +242 -0
- package/srv/cardano-indexer-service.cds +387 -73
- package/srv/cardano-indexer-service.d.ts +5 -1
- package/srv/cardano-indexer-service.js +532 -16
- package/srv/cardano-service.cds +424 -269
- package/srv/cardano-service.js +289 -201
- package/srv/cardano-sign-service.cds +201 -180
- package/srv/cardano-sign-service.js +71 -201
- package/srv/cardano-tx-service.cds +451 -370
- package/srv/cardano-tx-service.js +271 -289
- package/srv/cardano-ui.cds +16 -16
- package/srv/cardano-worker-service.cds +118 -125
- package/srv/cardano-worker-service.js +52 -61
- package/srv/cbor/cip68.d.ts +13 -0
- package/srv/cbor/cip68.js +56 -0
- package/srv/cbor/index.d.ts +3 -1
- package/srv/cbor/index.js +9 -1
- package/srv/cbor/parse.d.ts +30 -18
- package/srv/cbor/parse.js +44 -9
- package/srv/cbor/plutus-data-json.d.ts +20 -0
- package/srv/cbor/plutus-data-json.js +32 -0
- package/srv/config.d.ts +113 -0
- package/srv/config.js +409 -0
- package/srv/server.d.ts +15 -110
- package/srv/server.js +84 -404
- package/srv/utils/agent-access.d.ts +9 -0
- package/srv/utils/agent-access.js +67 -0
- package/srv/utils/agent-grants-config.d.ts +0 -46
- package/srv/utils/agent-grants-config.js +17 -85
- package/srv/utils/agent-grants.d.ts +106 -122
- package/srv/utils/agent-grants.js +538 -236
- package/srv/utils/agent-token-auth.d.ts +4 -99
- package/srv/utils/agent-token-auth.js +18 -182
- package/srv/utils/backend-request-handler.d.ts +3 -17
- package/srv/utils/backend-request-handler.js +3 -18
- package/srv/utils/collections.d.ts +3 -10
- package/srv/utils/collections.js +3 -10
- package/srv/utils/const.d.ts +23 -74
- package/srv/utils/const.js +32 -79
- package/srv/utils/crypto.d.ts +3 -12
- package/srv/utils/crypto.js +6 -21
- package/srv/utils/db-indexes.d.ts +27 -0
- package/srv/utils/db-indexes.js +120 -0
- package/srv/utils/db-sanitize.d.ts +20 -0
- package/srv/utils/db-sanitize.js +80 -0
- package/srv/utils/deep-json.d.ts +6 -0
- package/srv/utils/deep-json.js +240 -0
- package/srv/utils/epoch-slots.d.ts +13 -0
- package/srv/utils/epoch-slots.js +38 -0
- package/srv/utils/error-codes.d.ts +22 -75
- package/srv/utils/error-codes.js +23 -72
- package/srv/utils/errors.d.ts +46 -187
- package/srv/utils/errors.js +114 -230
- package/srv/utils/liveness.d.ts +12 -0
- package/srv/utils/liveness.js +35 -0
- package/srv/utils/mappers.d.ts +102 -223
- package/srv/utils/mappers.js +387 -316
- package/srv/utils/network-context.js +2 -13
- package/srv/utils/paging.d.ts +31 -0
- package/srv/utils/paging.js +43 -0
- package/srv/utils/pg-inline-json.d.ts +8 -0
- package/srv/utils/pg-inline-json.js +58 -0
- package/srv/utils/pg-order-nulls.d.ts +14 -0
- package/srv/utils/pg-order-nulls.js +54 -0
- package/srv/utils/plutus-placeholders.d.ts +16 -22
- package/srv/utils/plutus-placeholders.js +62 -33
- package/srv/utils/rate-limiter.d.ts +2 -21
- package/srv/utils/rate-limiter.js +5 -17
- package/srv/utils/readiness.d.ts +12 -0
- package/srv/utils/readiness.js +29 -0
- package/srv/utils/reference-script.d.ts +19 -0
- package/srv/utils/reference-script.js +84 -0
- package/srv/utils/result-numbers.d.ts +15 -0
- package/srv/utils/result-numbers.js +61 -0
- package/srv/utils/service-events.d.ts +0 -24
- package/srv/utils/service-events.js +3 -25
- package/srv/utils/signing-helper.d.ts +3 -20
- package/srv/utils/signing-helper.js +35 -64
- package/srv/utils/tx-build-helper.d.ts +10 -105
- package/srv/utils/tx-build-helper.js +81 -144
- package/srv/utils/tx-request-parsers.d.ts +82 -33
- package/srv/utils/tx-request-parsers.js +401 -49
- package/srv/utils/tx-utils.d.ts +3 -27
- package/srv/utils/tx-utils.js +32 -50
- package/srv/utils/types.d.ts +261 -191
- package/srv/utils/types.js +2 -6
- package/srv/utils/validators.d.ts +22 -92
- package/srv/utils/validators.js +50 -149
package/srv/utils/mappers.js
CHANGED
|
@@ -3,9 +3,18 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.BARE_ASSET_STAMP = exports.TX_SEQ_SLOT_FACTOR = void 0;
|
|
7
|
+
exports.txSeqOf = txSeqOf;
|
|
6
8
|
exports.mapTransaction = mapTransaction;
|
|
7
9
|
exports.mapTransactionInputs = mapTransactionInputs;
|
|
8
10
|
exports.mapTransactionInputAssets = mapTransactionInputAssets;
|
|
11
|
+
exports.mapTransactionCertificates = mapTransactionCertificates;
|
|
12
|
+
exports.mapTransactionWithdrawals = mapTransactionWithdrawals;
|
|
13
|
+
exports.compareOutRef = compareOutRef;
|
|
14
|
+
exports.ledgerInputOrder = ledgerInputOrder;
|
|
15
|
+
exports.ledgerView = ledgerView;
|
|
16
|
+
exports.mapTransactionRedeemers = mapTransactionRedeemers;
|
|
17
|
+
exports.mapTransactionDatums = mapTransactionDatums;
|
|
9
18
|
exports.mapTransactionOutputs = mapTransactionOutputs;
|
|
10
19
|
exports.mapTransactionOutputAssets = mapTransactionOutputAssets;
|
|
11
20
|
exports.mapAddress = mapAddress;
|
|
@@ -17,8 +26,12 @@ exports.mapNetworkInfo = mapNetworkInfo;
|
|
|
17
26
|
exports.mapBlock = mapBlock;
|
|
18
27
|
exports.mapEpoch = mapEpoch;
|
|
19
28
|
exports.mapTransactionMetadata = mapTransactionMetadata;
|
|
29
|
+
exports.metadataIdFor = metadataIdFor;
|
|
30
|
+
exports.mapPoolSnapshot = mapPoolSnapshot;
|
|
31
|
+
exports.mapDrepSnapshot = mapDrepSnapshot;
|
|
20
32
|
exports.mapPool = mapPool;
|
|
21
33
|
exports.mapAsset = mapAsset;
|
|
34
|
+
exports.mapBareAsset = mapBareAsset;
|
|
22
35
|
exports.mapAssetHistory = mapAssetHistory;
|
|
23
36
|
exports.mapDrep = mapDrep;
|
|
24
37
|
exports.mapAccount = mapAccount;
|
|
@@ -31,70 +44,73 @@ exports.mapTransactionSubmission = mapTransactionSubmission;
|
|
|
31
44
|
exports.mapAddressSigningRequest = mapAddressSigningRequest;
|
|
32
45
|
exports.mapAddressTransactionBuild = mapAddressTransactionBuild;
|
|
33
46
|
exports.normalizeCostModels = normalizeCostModels;
|
|
47
|
+
exports.decodeAssetName = decodeAssetName;
|
|
34
48
|
exports.computeCip14Fingerprint = computeCip14Fingerprint;
|
|
35
49
|
exports.scriptHashToEnterpriseAddress = scriptHashToEnterpriseAddress;
|
|
50
|
+
exports.credentialToStakeAddress = credentialToStakeAddress;
|
|
51
|
+
exports.decodeShelleyAddress = decodeShelleyAddress;
|
|
52
|
+
exports.paymentCredentialOf = paymentCredentialOf;
|
|
53
|
+
exports.credentialToDrepId = credentialToDrepId;
|
|
54
|
+
exports.sumUtxoAmounts = sumUtxoAmounts;
|
|
36
55
|
const cds_1 = __importDefault(require("@sap/cds"));
|
|
56
|
+
const node_util_1 = require("node:util");
|
|
37
57
|
const blake2b_1 = __importDefault(require("blake2b"));
|
|
38
58
|
const bech32_1 = require("bech32");
|
|
39
|
-
const
|
|
59
|
+
const deep_json_1 = require("./deep-json");
|
|
40
60
|
const cardano_costmodels_ts_1 = require("@harmoniclabs/cardano-costmodels-ts");
|
|
41
61
|
const logger = cds_1.default.log('mappers');
|
|
42
62
|
const errors_1 = require("./errors");
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
*
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
* @returns {TransactionRow} mapped transaction row
|
|
51
|
-
*/
|
|
63
|
+
const const_1 = require("./const");
|
|
64
|
+
/** Key of a transaction's input/output rows: chain position, ascending, below 2^53 for any real slot. */
|
|
65
|
+
exports.TX_SEQ_SLOT_FACTOR = 65536;
|
|
66
|
+
function txSeqOf(slot, txIndex) {
|
|
67
|
+
return slot * exports.TX_SEQ_SLOT_FACTOR + txIndex;
|
|
68
|
+
}
|
|
69
|
+
/** Provider transaction to TransactionRow. */
|
|
52
70
|
function mapTransaction(providerTx) {
|
|
53
|
-
//
|
|
54
|
-
// length check matters: the Ogmios chain-sync mapper produced `[]` for metadata-less
|
|
55
|
-
// txs, which the old `Array.isArray` test counted as "has metadata"
|
|
71
|
+
// length check: chain-sync delivers `[]` for metadata-less txs
|
|
56
72
|
const hasMetadata = Array.isArray(providerTx.metadata) && providerTx.metadata.length > 0;
|
|
57
73
|
const hasInputs = Array.isArray(providerTx.inputs) && providerTx.inputs.length > 0;
|
|
58
74
|
const hasOutputs = Array.isArray(providerTx.outputs) && providerTx.outputs.length > 0;
|
|
59
75
|
return {
|
|
60
76
|
hash: providerTx.hash,
|
|
77
|
+
txSeq: txSeqOf(providerTx.slot, providerTx.index),
|
|
61
78
|
blockHash: providerTx.blockHash,
|
|
62
79
|
blockHeight: providerTx.blockHeight ?? null,
|
|
63
80
|
blockTime: providerTx.blockTime ?? null,
|
|
64
81
|
slot: providerTx.slot ?? null,
|
|
65
82
|
txIndex: providerTx.index ?? null,
|
|
66
83
|
fee: providerTx.fee != null ? providerTx.fee : '0',
|
|
67
|
-
deposit: providerTx.deposit
|
|
84
|
+
deposit: providerTx.deposit ?? null,
|
|
68
85
|
size: providerTx.size ?? null,
|
|
69
86
|
hasInputs: hasInputs,
|
|
70
87
|
hasOutputs: hasOutputs,
|
|
71
88
|
hasMetadata: hasMetadata,
|
|
72
89
|
};
|
|
73
90
|
}
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
* @param txHash transaction hash
|
|
78
|
-
* @param txInputs transaction inputs from provider
|
|
79
|
-
* @returns {TransactionInputRow[]} mapped transaction input rows
|
|
80
|
-
*/
|
|
81
|
-
function mapTransactionInputs(txHash, txInputs) {
|
|
91
|
+
// Provider transaction inputs to TransactionInputRows, keyed by position in the tx.
|
|
92
|
+
// byReference: an input whose spent output is stored points at it and keeps no copy of its assets.
|
|
93
|
+
function mapTransactionInputs(txSeq, txInputs, byReference = false) {
|
|
82
94
|
return txInputs.map((input, idx) => {
|
|
83
|
-
//
|
|
84
|
-
// Note: input.outputIndex is the output index from the ORIGINAL UTxO being spent, not for keying here
|
|
95
|
+
// Position in this tx's inputs; input.outputIndex is the spent UTxO's index, not a key here
|
|
85
96
|
const inputIndex = idx;
|
|
86
|
-
// check presence of address and amount arrays
|
|
87
97
|
const hasAddress = !!input.address?.length;
|
|
88
98
|
const hasAssets = Array.isArray(input.amount) && input.amount.length > 0;
|
|
89
99
|
return {
|
|
90
|
-
|
|
100
|
+
txSeq,
|
|
91
101
|
inputIndex: inputIndex,
|
|
92
|
-
//
|
|
93
|
-
// dangling empty-string Addresses association (lazy-path inputs are never empty)
|
|
102
|
+
// unresolved chain-sync inputs carry '': persist a null FK, not an empty-string association
|
|
94
103
|
address_address: input.address || null,
|
|
95
104
|
utxoData_dataHash: input.dataHash || null,
|
|
96
105
|
utxoData_inlineDatum: input.inlineDatum || null,
|
|
97
106
|
utxoData_referenceScriptHash: input.referenceScriptHash || null,
|
|
107
|
+
utxoData_referenceScriptSize: input.referenceScriptSize ?? null,
|
|
108
|
+
utxoData_referenceScriptType: input.referenceScriptType ?? null,
|
|
109
|
+
utxoData_paymentCredential: paymentCredentialOf(input.address),
|
|
110
|
+
// outpoint of the consumed UTxO
|
|
111
|
+
spentTxHash: input.txHash || null,
|
|
112
|
+
spentOutputIndex: Number.isInteger(input.outputIndex) ? input.outputIndex : null,
|
|
113
|
+
spentTxSeq: byReference ? input.spentTxSeq ?? null : null,
|
|
98
114
|
isCollateral: Boolean(input.isCollateral),
|
|
99
115
|
isReference: Boolean(input.isReference),
|
|
100
116
|
hasAddresses: hasAddress,
|
|
@@ -102,23 +118,18 @@ function mapTransactionInputs(txHash, txInputs) {
|
|
|
102
118
|
};
|
|
103
119
|
});
|
|
104
120
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
* @param txHash transaction hash
|
|
109
|
-
* @param inputs transaction inputs from provider
|
|
110
|
-
* @returns {TransactionInputAssetRow[]} mapped transaction input asset rows
|
|
111
|
-
*/
|
|
112
|
-
function mapTransactionInputAssets(txHash, inputs) {
|
|
121
|
+
// Provider transaction input assets to the rows kept as a copy. Must be called with the same
|
|
122
|
+
// byReference as mapTransactionInputs: an input that points at its output gets no copy.
|
|
123
|
+
function mapTransactionInputAssets(txSeq, inputs, byReference = false) {
|
|
113
124
|
return inputs.flatMap((input, idx) => {
|
|
114
|
-
//
|
|
125
|
+
// must match mapTransactionInputs
|
|
115
126
|
const inputIndex = idx;
|
|
116
|
-
if (!Array.isArray(input.amount))
|
|
127
|
+
if (!Array.isArray(input.amount) || (byReference && input.spentTxSeq != null))
|
|
117
128
|
return [];
|
|
118
129
|
return input.amount.map(a => {
|
|
119
130
|
const { policyId, assetName } = parseAssetUnit(a.unit);
|
|
120
131
|
return {
|
|
121
|
-
|
|
132
|
+
input_txSeq: txSeq,
|
|
122
133
|
input_inputIndex: inputIndex,
|
|
123
134
|
unit: a.unit,
|
|
124
135
|
asset_quantity: a.quantity,
|
|
@@ -128,38 +139,98 @@ function mapTransactionInputAssets(txHash, inputs) {
|
|
|
128
139
|
});
|
|
129
140
|
});
|
|
130
141
|
}
|
|
131
|
-
/**
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
142
|
+
/** Normalized certificates to TransactionCertificateRows, one per (certIndex, kind). */
|
|
143
|
+
function mapTransactionCertificates(txHash, certificates) {
|
|
144
|
+
return certificates.map((c) => ({
|
|
145
|
+
tx_hash: txHash,
|
|
146
|
+
certIndex: c.certIndex,
|
|
147
|
+
kind: c.kind,
|
|
148
|
+
stakeAddress: c.stakeAddress || null,
|
|
149
|
+
poolId: c.poolId || null,
|
|
150
|
+
drepId: c.drepId || null,
|
|
151
|
+
deposit: c.deposit != null ? String(c.deposit) : null,
|
|
152
|
+
epoch: c.epoch ?? null,
|
|
153
|
+
}));
|
|
154
|
+
}
|
|
155
|
+
/** Normalized withdrawals to TransactionWithdrawalRows, one per reward account. */
|
|
156
|
+
function mapTransactionWithdrawals(txHash, withdrawals) {
|
|
157
|
+
return withdrawals
|
|
158
|
+
.filter((w) => !!w.stakeAddress)
|
|
159
|
+
.map((w) => ({
|
|
160
|
+
tx_hash: txHash,
|
|
161
|
+
stakeAddress: w.stakeAddress,
|
|
162
|
+
lovelace: String(w.amount ?? '0'),
|
|
163
|
+
}));
|
|
164
|
+
}
|
|
165
|
+
/** Ledger order of output references: transaction hash bytewise, then output index. */
|
|
166
|
+
function compareOutRef(a, b) {
|
|
167
|
+
const ha = a.txHash.toLowerCase(), hb = b.txHash.toLowerCase();
|
|
168
|
+
return ha < hb ? -1 : ha > hb ? 1 : a.outputIndex - b.outputIndex;
|
|
169
|
+
}
|
|
170
|
+
// Inputs in chain-sync order: regular, collateral, reference, each sorted like the ledger's sets.
|
|
171
|
+
// inputIndex and spend-redeemer indices rely on this order.
|
|
172
|
+
function ledgerInputOrder(inputs) {
|
|
173
|
+
const rank = (i) => (i.isReference ? 2 : i.isCollateral ? 1 : 0);
|
|
174
|
+
return [...inputs].sort((a, b) => rank(a) - rank(b) || compareOutRef(a, b));
|
|
175
|
+
}
|
|
176
|
+
// The transaction as the ledger applied it, identical for every source. After a phase-2 failure only
|
|
177
|
+
// collateral and reference inputs and the collateral return remain: no mint, certificate or withdrawal.
|
|
178
|
+
// Unknown validity keeps what the source reported.
|
|
179
|
+
function ledgerView(tx) {
|
|
180
|
+
const inputs = ledgerInputOrder(tx.inputs ?? []);
|
|
181
|
+
if (tx.spendsCollaterals === undefined)
|
|
182
|
+
return { ...tx, inputs };
|
|
183
|
+
const failed = tx.spendsCollaterals;
|
|
184
|
+
return {
|
|
185
|
+
...tx,
|
|
186
|
+
inputs: failed ? inputs.filter(i => i.isCollateral || i.isReference) : inputs,
|
|
187
|
+
outputs: (tx.outputs ?? []).filter(o => (failed ? o.isCollateral : !o.isCollateral)),
|
|
188
|
+
mint: failed ? undefined : tx.mint,
|
|
189
|
+
certificates: failed && tx.certificates ? [] : tx.certificates,
|
|
190
|
+
withdrawals: failed && tx.withdrawals ? [] : tx.withdrawals,
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
/** Normalized redeemers to TransactionRedeemerRows, keyed (tx, purpose, index). */
|
|
194
|
+
function mapTransactionRedeemers(txHash, redeemers) {
|
|
195
|
+
return redeemers.map((r) => ({
|
|
196
|
+
tx_hash: txHash,
|
|
197
|
+
purpose: r.purpose,
|
|
198
|
+
redeemerIndex: r.index,
|
|
199
|
+
data: r.data,
|
|
200
|
+
mem: Number(r.mem),
|
|
201
|
+
steps: Number(r.steps),
|
|
202
|
+
spentTxHash: r.txHash ?? null,
|
|
203
|
+
spentOutputIndex: r.outputIndex ?? null,
|
|
204
|
+
policyId: r.policyId ?? null,
|
|
205
|
+
}));
|
|
206
|
+
}
|
|
207
|
+
/** Witness-set datums to TransactionDatumRows, keyed (tx, dataHash). */
|
|
208
|
+
function mapTransactionDatums(txHash, datums) {
|
|
209
|
+
return datums.map((d) => ({ tx_hash: txHash, dataHash: d.hash, datum: d.cbor }));
|
|
210
|
+
}
|
|
211
|
+
/** Provider transaction outputs to TransactionOutputRows. */
|
|
212
|
+
function mapTransactionOutputs(txSeq, txOutputs) {
|
|
139
213
|
return txOutputs.map((output) => {
|
|
140
214
|
const outputIndex = output.outputIndex;
|
|
141
215
|
const hasAddresses = !!output.address?.length;
|
|
142
216
|
const hasAssets = Array.isArray(output.amount) && output.amount.length > 0;
|
|
143
217
|
return {
|
|
144
|
-
|
|
218
|
+
txSeq,
|
|
145
219
|
outputIndex: outputIndex,
|
|
146
220
|
address_address: output.address,
|
|
147
221
|
utxo_dataHash: output.dataHash || null,
|
|
148
222
|
utxo_inlineDatum: output.inlineDatum || null,
|
|
149
223
|
utxo_referenceScriptHash: output.referenceScriptHash || null,
|
|
224
|
+
utxo_referenceScriptSize: output.referenceScriptSize ?? null,
|
|
225
|
+
utxo_referenceScriptType: output.referenceScriptType ?? null,
|
|
226
|
+
utxo_paymentCredential: paymentCredentialOf(output.address),
|
|
150
227
|
hasAddresses: hasAddresses,
|
|
151
228
|
hasAssets: hasAssets,
|
|
152
229
|
};
|
|
153
230
|
});
|
|
154
231
|
}
|
|
155
|
-
/**
|
|
156
|
-
|
|
157
|
-
* Converts provider transaction output asset data into TransactionOutputAssetRow format
|
|
158
|
-
* @param txHash transaction hash
|
|
159
|
-
* @param outputs transaction outputs from provider
|
|
160
|
-
* @returns {TransactionOutputAssetRow[]} mapped transaction output asset rows
|
|
161
|
-
*/
|
|
162
|
-
function mapTransactionOutputAssets(txHash, outputs) {
|
|
232
|
+
/** Provider transaction output assets to TransactionOutputAssetRows. */
|
|
233
|
+
function mapTransactionOutputAssets(txSeq, outputs) {
|
|
163
234
|
return outputs.flatMap((output) => {
|
|
164
235
|
const outputIndex = output.outputIndex;
|
|
165
236
|
if (!Array.isArray(output.amount))
|
|
@@ -167,7 +238,7 @@ function mapTransactionOutputAssets(txHash, outputs) {
|
|
|
167
238
|
return output.amount.map(a => {
|
|
168
239
|
const { policyId, assetName } = parseAssetUnit(a.unit);
|
|
169
240
|
return {
|
|
170
|
-
|
|
241
|
+
output_txSeq: txSeq,
|
|
171
242
|
output_outputIndex: outputIndex,
|
|
172
243
|
unit: a.unit,
|
|
173
244
|
asset_quantity: a.quantity,
|
|
@@ -177,13 +248,7 @@ function mapTransactionOutputAssets(txHash, outputs) {
|
|
|
177
248
|
});
|
|
178
249
|
});
|
|
179
250
|
}
|
|
180
|
-
/**
|
|
181
|
-
* Map Address Data
|
|
182
|
-
* Converts provider address data into AddressRow format
|
|
183
|
-
* @param address address string
|
|
184
|
-
* @param addressData address data from provider
|
|
185
|
-
* @returns {AddressRow} mapped address row
|
|
186
|
-
*/
|
|
251
|
+
/** Provider address to a temporal AddressRow valid for `maxAge` ms. */
|
|
187
252
|
function mapAddress(address, addressData, maxAge) {
|
|
188
253
|
const now = Date.now();
|
|
189
254
|
const nowIso = new Date(now).toISOString();
|
|
@@ -194,7 +259,7 @@ function mapAddress(address, addressData, maxAge) {
|
|
|
194
259
|
const utxoCount = Array.isArray(addressData.utxos) ? addressData.utxos.length : 0;
|
|
195
260
|
const hasUtxos = utxoCount > 0;
|
|
196
261
|
const hasAssets = Array.isArray(addressData.amount) && addressData.amount.some((a) => a.unit !== 'lovelace');
|
|
197
|
-
//
|
|
262
|
+
// set to true by indexAddress() once transactions are indexed
|
|
198
263
|
const hasTransactions = false;
|
|
199
264
|
return {
|
|
200
265
|
address,
|
|
@@ -210,19 +275,9 @@ function mapAddress(address, addressData, maxAge) {
|
|
|
210
275
|
hasTransactions: hasTransactions,
|
|
211
276
|
};
|
|
212
277
|
}
|
|
213
|
-
/**
|
|
214
|
-
* Map Address Transactions
|
|
215
|
-
* Converts provider address transaction data into AddressTransactionRow format
|
|
216
|
-
* @param addr address string
|
|
217
|
-
* @param addressTxsData address transactions data from provider
|
|
218
|
-
* @returns {AddressTransactionRow[]} mapped address transaction rows
|
|
219
|
-
* */
|
|
220
|
-
// AddressTransactions is keyed by (address, tx) and the per-tx net amounts are
|
|
221
|
-
// immutable once confirmed — no temporal validity. The entity has no
|
|
222
|
-
// validFrom/validTo columns, so the previous TTL plumbing was silently dropped.
|
|
278
|
+
/** Provider transactions to AddressTransactionRows with the address's net amounts; non-temporal. */
|
|
223
279
|
function mapAddressTransactions(addr, addressTxsData) {
|
|
224
280
|
return addressTxsData.map((tx) => {
|
|
225
|
-
// Calculate net amounts for this address in this transaction
|
|
226
281
|
const { netLovelace, netAssets } = calculateNetAmounts(addr, tx);
|
|
227
282
|
return {
|
|
228
283
|
address_address: addr,
|
|
@@ -234,17 +289,11 @@ function mapAddressTransactions(addr, addressTxsData) {
|
|
|
234
289
|
};
|
|
235
290
|
});
|
|
236
291
|
}
|
|
237
|
-
/**
|
|
238
|
-
* Calculate net lovelace and asset changes for an address in a transaction
|
|
239
|
-
* @param addr the address to calculate for
|
|
240
|
-
* @param tx the transaction data
|
|
241
|
-
* @returns object with netLovelace and netAssets array
|
|
242
|
-
*/
|
|
292
|
+
/** Net lovelace and asset changes of an address in a transaction (outputs minus inputs). */
|
|
243
293
|
function calculateNetAmounts(addr, tx) {
|
|
244
294
|
let inputLovelace = 0n;
|
|
245
295
|
let outputLovelace = 0n;
|
|
246
296
|
const assetBalances = new Map(); // unit -> net quantity
|
|
247
|
-
// Process inputs belonging to this address (subtract)
|
|
248
297
|
for (const input of tx.inputs ?? []) {
|
|
249
298
|
if (input.address === addr) {
|
|
250
299
|
for (const amount of input.amount ?? []) {
|
|
@@ -252,14 +301,12 @@ function calculateNetAmounts(addr, tx) {
|
|
|
252
301
|
inputLovelace += BigInt(amount.quantity || '0');
|
|
253
302
|
}
|
|
254
303
|
else {
|
|
255
|
-
// Native asset
|
|
256
304
|
const current = assetBalances.get(amount.unit) || 0n;
|
|
257
305
|
assetBalances.set(amount.unit, current - BigInt(amount.quantity || '0'));
|
|
258
306
|
}
|
|
259
307
|
}
|
|
260
308
|
}
|
|
261
309
|
}
|
|
262
|
-
// Process outputs going to this address (add)
|
|
263
310
|
for (const output of tx.outputs ?? []) {
|
|
264
311
|
if (output.address === addr) {
|
|
265
312
|
for (const amount of output.amount ?? []) {
|
|
@@ -267,19 +314,16 @@ function calculateNetAmounts(addr, tx) {
|
|
|
267
314
|
outputLovelace += BigInt(amount.quantity || '0');
|
|
268
315
|
}
|
|
269
316
|
else {
|
|
270
|
-
// Native asset
|
|
271
317
|
const current = assetBalances.get(amount.unit) || 0n;
|
|
272
318
|
assetBalances.set(amount.unit, current + BigInt(amount.quantity || '0'));
|
|
273
319
|
}
|
|
274
320
|
}
|
|
275
321
|
}
|
|
276
322
|
}
|
|
277
|
-
//
|
|
323
|
+
// zero balances are dropped
|
|
278
324
|
const netAssets = [];
|
|
279
325
|
for (const [unit, quantity] of assetBalances) {
|
|
280
326
|
if (quantity !== 0n) {
|
|
281
|
-
// Parse unit into policyId and assetName
|
|
282
|
-
// Format: policyId (56 chars) + assetNameHex
|
|
283
327
|
const policyId = unit.substring(0, 56);
|
|
284
328
|
const assetNameHex = unit.substring(56);
|
|
285
329
|
const assetName = hexToUtf8(assetNameHex);
|
|
@@ -297,14 +341,7 @@ function calculateNetAmounts(addr, tx) {
|
|
|
297
341
|
netAssets
|
|
298
342
|
};
|
|
299
343
|
}
|
|
300
|
-
/**
|
|
301
|
-
* Map Address UTxOs
|
|
302
|
-
* @param addr address string
|
|
303
|
-
* @param validFrom validFrom
|
|
304
|
-
* @param validTo validTo
|
|
305
|
-
* @param addressUtxosData address UTxOs data from provider
|
|
306
|
-
* @returns {AddressUTxORow[]} mapped address UTxO rows
|
|
307
|
-
*/
|
|
344
|
+
/** Provider UTxOs to temporal AddressUTxORows. */
|
|
308
345
|
function mapAddressUtxos(addr, validFrom, validTo, addressUtxosData) {
|
|
309
346
|
return addressUtxosData.map((utxo) => {
|
|
310
347
|
const amounts = Array.isArray(utxo.amount) ? utxo.amount : [];
|
|
@@ -317,11 +354,12 @@ function mapAddressUtxos(addr, validFrom, validTo, addressUtxosData) {
|
|
|
317
354
|
blockHash: utxo.blockHash,
|
|
318
355
|
utxodata_dataHash: utxo.datumHash,
|
|
319
356
|
utxodata_inlineDatum: utxo.inlineDatum || null,
|
|
320
|
-
//
|
|
321
|
-
//
|
|
322
|
-
// script CBOR (used by the tx-builder, but it would truncate this hash
|
|
323
|
-
// column) — only persist hash-length values here.
|
|
357
|
+
// Hash column: Blockfrost/Ogmios give a 56-hex hash, Koios the full script CBOR, so only
|
|
358
|
+
// hash-length values are persisted
|
|
324
359
|
utxodata_referenceScriptHash: utxo.scriptRef && utxo.scriptRef.length <= 64 ? utxo.scriptRef : null,
|
|
360
|
+
utxodata_referenceScriptSize: utxo.scriptRefSize ?? null,
|
|
361
|
+
utxodata_referenceScriptType: utxo.scriptRefType ?? null,
|
|
362
|
+
utxodata_paymentCredential: paymentCredentialOf(addr),
|
|
325
363
|
lovelace: lovelace,
|
|
326
364
|
validFrom: validFrom,
|
|
327
365
|
validTo: validTo,
|
|
@@ -329,15 +367,7 @@ function mapAddressUtxos(addr, validFrom, validTo, addressUtxosData) {
|
|
|
329
367
|
};
|
|
330
368
|
});
|
|
331
369
|
}
|
|
332
|
-
/**
|
|
333
|
-
* Map Address Assets
|
|
334
|
-
* Converts provider address asset data into AddressAssetRow format
|
|
335
|
-
* @param addr address string
|
|
336
|
-
* @param validFrom validFrom
|
|
337
|
-
* @param validTo validTo
|
|
338
|
-
* @param AssetAssets address assets from provider
|
|
339
|
-
* @returns {AddressAssetRow[]} mapped address asset rows
|
|
340
|
-
*/
|
|
370
|
+
/** Provider address amounts (without lovelace) to temporal AddressAssetRows. */
|
|
341
371
|
function mapAddressAssets(addr, validFrom, validTo, AssetAssets) {
|
|
342
372
|
return AssetAssets
|
|
343
373
|
.filter((asset) => asset.unit !== 'lovelace')
|
|
@@ -354,14 +384,7 @@ function mapAddressAssets(addr, validFrom, validTo, AssetAssets) {
|
|
|
354
384
|
};
|
|
355
385
|
});
|
|
356
386
|
}
|
|
357
|
-
/**
|
|
358
|
-
* Map UTxO Assets
|
|
359
|
-
* Converts provider address UTxO asset data into UTxOAssetRow format
|
|
360
|
-
* @param addressUtxosData address UTxOs data from provider
|
|
361
|
-
* @param validFrom validFrom
|
|
362
|
-
* @param validTo validTo
|
|
363
|
-
* @returns {UTxOAssetRow[]} mapped UTxO asset rows
|
|
364
|
-
*/
|
|
387
|
+
/** Native assets of provider UTxOs to temporal UTxOAssetRows. */
|
|
365
388
|
function mapAddressUtxoAssets(addressUtxosData, validFrom, validTo) {
|
|
366
389
|
const assets = [];
|
|
367
390
|
addressUtxosData.forEach((utxo) => {
|
|
@@ -385,12 +408,7 @@ function mapAddressUtxoAssets(addressUtxosData, validFrom, validTo) {
|
|
|
385
408
|
});
|
|
386
409
|
return assets;
|
|
387
410
|
}
|
|
388
|
-
/**
|
|
389
|
-
* Map Network Information
|
|
390
|
-
* Converts provider network information data into NetworkInfoRow format
|
|
391
|
-
* @param providerNetworkData
|
|
392
|
-
* @returns {NetworkInfoRow} mapped network information row
|
|
393
|
-
*/
|
|
411
|
+
/** Provider network information to a temporal NetworkInfoRow. */
|
|
394
412
|
function mapNetworkInfo(providerNetworkData, max_age, network) {
|
|
395
413
|
const now = Date.now();
|
|
396
414
|
const nowIso = new Date(now).toISOString();
|
|
@@ -409,23 +427,16 @@ function mapNetworkInfo(providerNetworkData, max_age, network) {
|
|
|
409
427
|
activeStake: providerNetworkData.stake.active,
|
|
410
428
|
};
|
|
411
429
|
}
|
|
412
|
-
/**
|
|
413
|
-
* Map Block Data
|
|
414
|
-
* Converts provider block data into BlockRow format
|
|
415
|
-
* @param providerBlockData block data from provider
|
|
416
|
-
* @param epochData epoch data for the block's epoch
|
|
417
|
-
* @returns {BlockRow} mapped block row
|
|
418
|
-
*/
|
|
430
|
+
/** Provider block to BlockRow. */
|
|
419
431
|
function mapBlock(providerBlockData, epochData) {
|
|
420
432
|
return {
|
|
421
433
|
time: new Date(providerBlockData.time * 1000).toISOString(),
|
|
422
434
|
height: providerBlockData.height,
|
|
423
435
|
hash: providerBlockData.hash,
|
|
424
|
-
// was `String(x ?? null)` → persisted the literal string "null" when absent
|
|
425
436
|
slotLeader: providerBlockData.slotLeader ?? null,
|
|
426
437
|
epochNumber: epochData?.epoch ?? providerBlockData.epoch,
|
|
427
438
|
epoch: epochData,
|
|
428
|
-
// absolute slot
|
|
439
|
+
// absolute slot: the crawler's reorg cut axis (same as Transactions.slot)
|
|
429
440
|
slot: providerBlockData.slot ?? null,
|
|
430
441
|
epochSlot: providerBlockData.epochSlot,
|
|
431
442
|
size: providerBlockData.size,
|
|
@@ -433,12 +444,7 @@ function mapBlock(providerBlockData, epochData) {
|
|
|
433
444
|
fees: providerBlockData.fees ?? '0',
|
|
434
445
|
};
|
|
435
446
|
}
|
|
436
|
-
/**
|
|
437
|
-
* Map Epoch Data
|
|
438
|
-
* Converts provider epoch data into EpochRow format
|
|
439
|
-
* @param providerEpochData epoch data from provider
|
|
440
|
-
* @returns {EpochRow} mapped epoch row
|
|
441
|
-
*/
|
|
447
|
+
/** Provider epoch to EpochRow. */
|
|
442
448
|
function mapEpoch(providerEpochData) {
|
|
443
449
|
return {
|
|
444
450
|
epoch: providerEpochData.epoch,
|
|
@@ -453,44 +459,92 @@ function mapEpoch(providerEpochData) {
|
|
|
453
459
|
activeStake: providerEpochData.active_stake,
|
|
454
460
|
};
|
|
455
461
|
}
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
* @param providerLabels array of metadata label data from provider
|
|
460
|
-
* @returns {TransactionMetadataRow[]} mapped transaction metadata rows
|
|
461
|
-
*/
|
|
462
|
-
function mapTransactionMetadata(providerLabels) {
|
|
462
|
+
// Provider metadata labels to TransactionMetadataRows; non-uint64 labels are skipped.
|
|
463
|
+
// Without txSeq the column is left out, so an UPSERT keeps a stored position.
|
|
464
|
+
function mapTransactionMetadata(providerLabels, txSeq) {
|
|
463
465
|
const rows = [];
|
|
464
466
|
for (const lbl of providerLabels) {
|
|
465
|
-
const
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
467
|
+
const id = metadataIdFor(lbl.label);
|
|
468
|
+
if (id === null) {
|
|
469
|
+
// a NaN key would fail the whole bulk write on PostgreSQL
|
|
470
|
+
logger.warn(`Metadata label ${JSON.stringify(lbl.label)} of tx ${lbl.txHash} is not a uint64, row skipped`);
|
|
471
|
+
continue;
|
|
470
472
|
}
|
|
471
473
|
rows.push({
|
|
472
|
-
|
|
474
|
+
// exact int64 key (see metadataIdFor); `label` keeps the original string
|
|
475
|
+
id: id,
|
|
473
476
|
tx_hash: lbl.txHash,
|
|
474
477
|
label: lbl.label.toString(),
|
|
475
|
-
// Ogmios
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
payload: lbl.json !== undefined ? client_1.safeJSON.stringify(lbl.json) : null,
|
|
478
|
+
// Ogmios exposes numeric metadata as bigint; written as exact number tokens
|
|
479
|
+
payload: lbl.json !== undefined ? (0, deep_json_1.stringifyJson)(lbl.json) : null,
|
|
480
|
+
...(txSeq == null ? {} : { txSeq }),
|
|
479
481
|
});
|
|
480
482
|
}
|
|
481
483
|
return rows;
|
|
482
484
|
}
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
485
|
+
// Maps a uint64 metadata label to the int64 id key. Labels >= 2^63 wrap by two's complement.
|
|
486
|
+
// Values beyond 2^53 are returned as a decimal string. Null when the label is no non-negative integer.
|
|
487
|
+
function metadataIdFor(label) {
|
|
488
|
+
let big;
|
|
489
|
+
if (typeof label === 'number') {
|
|
490
|
+
if (!Number.isFinite(label))
|
|
491
|
+
return null;
|
|
492
|
+
big = BigInt(Math.trunc(label));
|
|
493
|
+
}
|
|
494
|
+
else {
|
|
495
|
+
const text = String(label).trim();
|
|
496
|
+
if (!/^\d+$/.test(text))
|
|
497
|
+
return null;
|
|
498
|
+
big = BigInt(text);
|
|
499
|
+
}
|
|
500
|
+
const wrapped = BigInt.asIntN(64, big);
|
|
501
|
+
const safe = wrapped >= BigInt(Number.MIN_SAFE_INTEGER) && wrapped <= BigInt(Number.MAX_SAFE_INTEGER);
|
|
502
|
+
return safe ? Number(wrapped) : wrapped.toString();
|
|
503
|
+
}
|
|
504
|
+
/** Pool observation at an epoch boundary to a non-temporal PoolEpochSnapshotRow dated by (epoch, snapshotSlot). */
|
|
505
|
+
function mapPoolSnapshot(providerPoolData, epoch, at, origin = { source: 'koios' }) {
|
|
506
|
+
return {
|
|
507
|
+
poolId: providerPoolData.poolId,
|
|
508
|
+
epoch,
|
|
509
|
+
snapshotSlot: at.slot,
|
|
510
|
+
snapshotTime: at.time,
|
|
511
|
+
snapshotHash: origin.hash ?? null,
|
|
512
|
+
source: origin.source,
|
|
513
|
+
blocksMinted: providerPoolData.blocksMinted,
|
|
514
|
+
blocksEpoch: providerPoolData.blocksEpoch,
|
|
515
|
+
liveStake: providerPoolData.liveStake,
|
|
516
|
+
liveSize: providerPoolData.liveSize == null ? null : Number(providerPoolData.liveSize),
|
|
517
|
+
liveSaturation: Number(providerPoolData.liveSaturation),
|
|
518
|
+
liveDelegators: providerPoolData.liveDelegators,
|
|
519
|
+
activeStake: providerPoolData.activeStake,
|
|
520
|
+
activeSize: Number(providerPoolData.activeSize),
|
|
521
|
+
pledge: providerPoolData.pledge,
|
|
522
|
+
margin: Number(providerPoolData.margin),
|
|
523
|
+
fixedCost: providerPoolData.fixedCost,
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
/** DRep observation at an epoch boundary to a non-temporal DrepEpochSnapshotRow. */
|
|
527
|
+
function mapDrepSnapshot(providerDrepData, epoch, at, origin = { source: 'koios' }) {
|
|
528
|
+
return {
|
|
529
|
+
drepId: providerDrepData.drepId,
|
|
530
|
+
epoch,
|
|
531
|
+
snapshotSlot: at.slot,
|
|
532
|
+
snapshotTime: at.time,
|
|
533
|
+
snapshotHash: origin.hash ?? null,
|
|
534
|
+
source: origin.source,
|
|
535
|
+
deposit: providerDrepData.deposit ?? null,
|
|
536
|
+
expiresEpoch: providerDrepData.expiresEpoch ?? null,
|
|
537
|
+
delegatorCount: providerDrepData.delegatorCount ?? null,
|
|
538
|
+
amount: providerDrepData.amount,
|
|
539
|
+
hasScript: providerDrepData.hasScript,
|
|
540
|
+
lastActiveEpoch: providerDrepData.lastActiveEpoch,
|
|
541
|
+
retired: providerDrepData.retired,
|
|
542
|
+
expired: providerDrepData.expired,
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
/** Provider pool to a temporal PoolRow valid for `max_age` ms. */
|
|
489
546
|
function mapPool(providerPoolData, max_age) {
|
|
490
|
-
//
|
|
491
|
-
// epoch, so a slice expires after max_age and the index-on-miss read re-fetches.
|
|
492
|
-
// Read the clock ONCE — separate Date.now() calls for validFrom/validTo let the
|
|
493
|
-
// millisecond tick over between them, making the span max_age+1.
|
|
547
|
+
// one clock read, so validTo - validFrom is exactly max_age
|
|
494
548
|
const now = Date.now();
|
|
495
549
|
const validFrom = new Date(now).toISOString();
|
|
496
550
|
const validTo = new Date(now + max_age).toISOString();
|
|
@@ -509,21 +563,19 @@ function mapPool(providerPoolData, max_age) {
|
|
|
509
563
|
margin: Number(providerPoolData.margin),
|
|
510
564
|
fixedCost: providerPoolData.fixedCost,
|
|
511
565
|
rewardAccount: providerPoolData.rewardAccount,
|
|
566
|
+
metadataUrl: providerPoolData.metadataUrl ?? null,
|
|
567
|
+
metadataHash: providerPoolData.metadataHash ?? null,
|
|
568
|
+
name: providerPoolData.name ?? null,
|
|
569
|
+
ticker: providerPoolData.ticker ?? null,
|
|
570
|
+
homepage: providerPoolData.homepage ?? null,
|
|
571
|
+
description: providerPoolData.description ?? null,
|
|
512
572
|
validFrom,
|
|
513
573
|
validTo,
|
|
514
574
|
};
|
|
515
575
|
}
|
|
516
|
-
/**
|
|
517
|
-
* Map Asset Info Data
|
|
518
|
-
* Converts provider asset info into AssetRow format. Provider data is already
|
|
519
|
-
* normalized by the backend mapper into the canonical AssetInfo shape, so this
|
|
520
|
-
* function just stamps temporal validity and JSON-stringifies the on-chain metadata.
|
|
521
|
-
* @param providerAssetInfo canonical asset info from backend
|
|
522
|
-
* @param max_age TTL window in ms for the temporal validity
|
|
523
|
-
* @returns {AssetRow} mapped asset row
|
|
524
|
-
*/
|
|
576
|
+
/** Canonical asset info to a temporal AssetRow valid for `max_age` ms; on-chain metadata is JSON-stringified. */
|
|
525
577
|
function mapAsset(providerAssetInfo, max_age) {
|
|
526
|
-
//
|
|
578
|
+
// one clock read (see mapPool)
|
|
527
579
|
const now = Date.now();
|
|
528
580
|
const validFrom = new Date(now).toISOString();
|
|
529
581
|
const validTo = new Date(now + max_age).toISOString();
|
|
@@ -538,11 +590,13 @@ function mapAsset(providerAssetInfo, max_age) {
|
|
|
538
590
|
initialMintTxHash: providerAssetInfo.initialMintTxHash,
|
|
539
591
|
initialMintTime: providerAssetInfo.initialMintTime,
|
|
540
592
|
onchainMetadata: providerAssetInfo.onchainMetadata
|
|
541
|
-
?
|
|
593
|
+
? (0, deep_json_1.stringifyJson)(providerAssetInfo.onchainMetadata)
|
|
542
594
|
: null,
|
|
543
595
|
registryName: providerAssetInfo.registryName,
|
|
544
596
|
registryTicker: providerAssetInfo.registryTicker,
|
|
545
597
|
registryDecimals: providerAssetInfo.registryDecimals,
|
|
598
|
+
// the registry value until the caller resolves a CIP-68 reference datum
|
|
599
|
+
decimals: providerAssetInfo.registryDecimals,
|
|
546
600
|
registryDescription: providerAssetInfo.registryDescription,
|
|
547
601
|
registryUrl: providerAssetInfo.registryUrl,
|
|
548
602
|
registryLogo: providerAssetInfo.registryLogo,
|
|
@@ -550,12 +604,41 @@ function mapAsset(providerAssetInfo, max_age) {
|
|
|
550
604
|
validTo,
|
|
551
605
|
};
|
|
552
606
|
}
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
607
|
+
// Epoch-zero stamp for bare Assets rows. The row is born expired and hidden by the temporal filter,
|
|
608
|
+
// and its key never collides with an enriched row.
|
|
609
|
+
exports.BARE_ASSET_STAMP = '1970-01-01T00:00:00.000Z';
|
|
610
|
+
// Asset row built from the unit alone, without a provider call. Its stamp hides it from reads, so the
|
|
611
|
+
// first keyed read still misses and the lazy path enriches it. Null for a non-asset unit.
|
|
612
|
+
function mapBareAsset(unit) {
|
|
613
|
+
// same unit definition isAssetUnit() enforces on the API
|
|
614
|
+
if (!const_1.ASSET_UNIT_REGEX.test(unit))
|
|
615
|
+
return null;
|
|
616
|
+
const policyId = unit.slice(0, 56);
|
|
617
|
+
const assetNameHex = unit.slice(56);
|
|
618
|
+
return {
|
|
619
|
+
unit,
|
|
620
|
+
policyId,
|
|
621
|
+
assetNameHex,
|
|
622
|
+
// hex fallback for non-text and NUL-bearing names
|
|
623
|
+
assetName: assetNameHex.length > 0 ? decodeAssetName(assetNameHex) : '',
|
|
624
|
+
fingerprint: computeCip14Fingerprint(policyId, assetNameHex),
|
|
625
|
+
totalSupply: null,
|
|
626
|
+
mintOrBurnCount: null,
|
|
627
|
+
initialMintTxHash: null,
|
|
628
|
+
initialMintTime: null,
|
|
629
|
+
onchainMetadata: null,
|
|
630
|
+
registryName: null,
|
|
631
|
+
registryTicker: null,
|
|
632
|
+
registryDecimals: null,
|
|
633
|
+
decimals: null,
|
|
634
|
+
registryDescription: null,
|
|
635
|
+
registryUrl: null,
|
|
636
|
+
registryLogo: null,
|
|
637
|
+
validFrom: exports.BARE_ASSET_STAMP,
|
|
638
|
+
validTo: exports.BARE_ASSET_STAMP,
|
|
639
|
+
};
|
|
640
|
+
}
|
|
641
|
+
/** Asset history events to non-temporal AssetHistoryRows (immutable, keyed on unit + txHash). */
|
|
559
642
|
function mapAssetHistory(entries) {
|
|
560
643
|
return entries.map((e) => ({
|
|
561
644
|
unit: e.unit,
|
|
@@ -566,16 +649,9 @@ function mapAssetHistory(entries) {
|
|
|
566
649
|
blockHeight: e.blockHeight,
|
|
567
650
|
}));
|
|
568
651
|
}
|
|
569
|
-
/**
|
|
570
|
-
* Map Drep Data
|
|
571
|
-
* Converts provider drep data into DrepRow format
|
|
572
|
-
* @param providerDrepData drep data from provider
|
|
573
|
-
* @returns {DrepRow} mapped drep row
|
|
574
|
-
*/
|
|
652
|
+
/** Provider DRep to a temporal DrepRow valid for `max_age` ms. */
|
|
575
653
|
function mapDrep(providerDrepData, max_age) {
|
|
576
|
-
//
|
|
577
|
-
// after max_age so the index-on-miss read re-fetches fresh state.
|
|
578
|
-
// Read the clock once so the span is exactly max_age (see mapPool).
|
|
654
|
+
// one clock read (see mapPool)
|
|
579
655
|
const now = Date.now();
|
|
580
656
|
const validFrom = new Date(now).toISOString();
|
|
581
657
|
const validTo = new Date(now + max_age).toISOString();
|
|
@@ -591,14 +667,9 @@ function mapDrep(providerDrepData, max_age) {
|
|
|
591
667
|
validTo,
|
|
592
668
|
};
|
|
593
669
|
}
|
|
594
|
-
/**
|
|
595
|
-
* Map Account Data
|
|
596
|
-
* Converts provider account data into AccountRow format
|
|
597
|
-
* @param providerAccountData account data from provider
|
|
598
|
-
* @returns {AccountRow} mapped account row
|
|
599
|
-
*/
|
|
670
|
+
/** Provider account to a temporal AccountRow valid for `max_age` ms. */
|
|
600
671
|
function mapAccount(providerAccountData, max_age) {
|
|
601
|
-
//
|
|
672
|
+
// one clock read (see mapPool)
|
|
602
673
|
const now = Date.now();
|
|
603
674
|
const validFrom = new Date(now).toISOString();
|
|
604
675
|
const validTo = new Date(now + max_age).toISOString();
|
|
@@ -614,35 +685,24 @@ function mapAccount(providerAccountData, max_age) {
|
|
|
614
685
|
reservesSum: providerAccountData.reservesSum,
|
|
615
686
|
treasurySum: providerAccountData.treasurySum,
|
|
616
687
|
withdrawableAmount: providerAccountData.withdrawableAmount,
|
|
688
|
+
poolId_poolId: providerAccountData.poolId ?? null,
|
|
689
|
+
drepId_drepId: providerAccountData.drepId ?? null,
|
|
617
690
|
hasAddresses: providerAccountData.addresses.length > 0,
|
|
618
691
|
};
|
|
619
692
|
}
|
|
620
|
-
/**
|
|
621
|
-
* Map Backend Error
|
|
622
|
-
* Converts BackendError or unknown error into OData request rejection
|
|
623
|
-
* @param req OData request
|
|
624
|
-
* @param err error object (BackendError or unknown)
|
|
625
|
-
* @param ctx context string for error message
|
|
626
|
-
*/
|
|
693
|
+
/** Rejects the OData request for a BackendError; unknown errors are logged and answered as a sanitized 500. */
|
|
627
694
|
function mapError(req, err, ctx) {
|
|
628
695
|
if (err instanceof errors_1.BackendError) {
|
|
629
|
-
return req.reject(err.statusCode, fmt(err.code, ctx, err.message), err.target);
|
|
696
|
+
return req.reject({ status: err.statusCode, code: err.code, message: fmt(err.code, ctx, err.message), target: err.target });
|
|
630
697
|
}
|
|
631
|
-
// Handle non-BackendError (plain Error, string, etc.)
|
|
632
|
-
// Log full error server-side, but return sanitized message to client
|
|
633
698
|
const internalMsg = err instanceof Error ? err.message : String(err);
|
|
634
699
|
logger.error({ error: internalMsg }, `Unexpected error in ${ctx}`);
|
|
635
700
|
return req.reject(500, fmt('INTERNAL_ERROR', ctx, 'An internal error occurred'));
|
|
636
701
|
}
|
|
637
|
-
/**
|
|
638
|
-
* Map Transaction Build Result
|
|
639
|
-
* Converts provider transaction build result into TransactionBuildRow format
|
|
640
|
-
* @param txbuildResult transaction build result from provider
|
|
641
|
-
* @returns {TransactionBuildRow} mapped transaction build row
|
|
642
|
-
*/
|
|
702
|
+
/** Build result to a temporal TransactionBuildRow with a fresh build id. */
|
|
643
703
|
function mapBuildResult(txbuildResult, max_age) {
|
|
644
704
|
const buildId = cds_1.default.utils.uuid();
|
|
645
|
-
//
|
|
705
|
+
// one clock read (see mapPool)
|
|
646
706
|
const nowMs = Date.now();
|
|
647
707
|
const now = Math.floor(nowMs / 1000);
|
|
648
708
|
const validFrom = new Date(nowMs).toISOString();
|
|
@@ -660,25 +720,19 @@ function mapBuildResult(txbuildResult, max_age) {
|
|
|
660
720
|
unsignedTxCbor: txbuildResult.unsignedTxCbor,
|
|
661
721
|
txBodyHash: txbuildResult.txBodyHash,
|
|
662
722
|
fee: txbuildResult.feeLovelace,
|
|
663
|
-
size: txbuildResult.sizeBytes, //
|
|
723
|
+
size: txbuildResult.sizeBytes, // bytes
|
|
664
724
|
createdAt: now, // epoch seconds
|
|
665
725
|
submission: null,
|
|
666
|
-
hasInputs: hasInputs,
|
|
667
|
-
hasOutputs: hasOutputs,
|
|
668
|
-
wasSubmitted: false,
|
|
726
|
+
hasInputs: hasInputs,
|
|
727
|
+
hasOutputs: hasOutputs,
|
|
728
|
+
wasSubmitted: false,
|
|
669
729
|
scriptHash: txbuildResult.scriptHash ?? null,
|
|
670
730
|
mintScriptHash: txbuildResult.mintScriptHash ?? null,
|
|
671
731
|
forcedInputsUsed: txbuildResult.forcedInputsUsed ?? 0,
|
|
672
732
|
referenceInputsUsed: txbuildResult.referenceInputsUsed ?? 0,
|
|
673
733
|
};
|
|
674
734
|
}
|
|
675
|
-
/**
|
|
676
|
-
* Map Transaction Build Inputs
|
|
677
|
-
* Converts transaction build result inputs into TransactionBuildInputRow format
|
|
678
|
-
* @param buildId the transaction build ID
|
|
679
|
-
* @param inputs transaction build result inputs
|
|
680
|
-
* @returns {TransactionBuildInputRow[]} mapped transaction build input rows
|
|
681
|
-
*/
|
|
735
|
+
/** Build result inputs to TransactionBuildInputRows. */
|
|
682
736
|
function mapBuildInputs(buildId, inputs) {
|
|
683
737
|
return inputs.map((input, idx) => ({
|
|
684
738
|
build_id: buildId,
|
|
@@ -690,14 +744,7 @@ function mapBuildInputs(buildId, inputs) {
|
|
|
690
744
|
hasAssets: false, // simple ADA transfers don't have assets
|
|
691
745
|
}));
|
|
692
746
|
}
|
|
693
|
-
/**
|
|
694
|
-
* Map Transaction Build Outputs
|
|
695
|
-
* Converts transaction build result outputs into TransactionBuildOutputRow format
|
|
696
|
-
* @param buildId the transaction build ID
|
|
697
|
-
* @param outputs transaction build result outputs
|
|
698
|
-
* @param changeAddress the change address to identify change outputs
|
|
699
|
-
* @returns {TransactionBuildOutputRow[]} mapped transaction build output rows
|
|
700
|
-
*/
|
|
747
|
+
/** Build result outputs to TransactionBuildOutputRows; `changeAddress` marks the change output. */
|
|
701
748
|
function mapBuildOutputs(buildId, outputs, changeAddress) {
|
|
702
749
|
return outputs.map((output, idx) => ({
|
|
703
750
|
build_id: buildId,
|
|
@@ -708,12 +755,7 @@ function mapBuildOutputs(buildId, outputs, changeAddress) {
|
|
|
708
755
|
hasAssets: false, // simple ADA transfers don't have assets
|
|
709
756
|
}));
|
|
710
757
|
}
|
|
711
|
-
/**
|
|
712
|
-
* Map Protocol Parameters
|
|
713
|
-
* Converts provider protocol parameters into ProtocolParameterRow format
|
|
714
|
-
* @param providerParams protocol parameters from provider
|
|
715
|
-
* @returns {ProtocolParameterRow} mapped protocol parameter row
|
|
716
|
-
*/
|
|
758
|
+
/** Provider protocol parameters to ProtocolParameterRow. */
|
|
717
759
|
function mapProtocolParameters(providerParams) {
|
|
718
760
|
return {
|
|
719
761
|
network: providerParams.network,
|
|
@@ -748,17 +790,12 @@ function mapProtocolParameters(providerParams) {
|
|
|
748
790
|
collateralPercent: providerParams.collateralPercent,
|
|
749
791
|
maxCollateralInputs: providerParams.maxCollateralInputs,
|
|
750
792
|
coinsPerUtxoSize: providerParams.coinsPerUtxoSize,
|
|
793
|
+
minFeeRefScriptCostPerByte: providerParams.minFeeRefScriptCostPerByte,
|
|
751
794
|
fetchedAt: providerParams.fetchedAt,
|
|
752
795
|
source: providerParams.source,
|
|
753
796
|
};
|
|
754
797
|
}
|
|
755
|
-
/**
|
|
756
|
-
* Map Transaction Submission
|
|
757
|
-
* Converts signed transaction CBOR and hash into TransactionSubmissionRow format
|
|
758
|
-
* @param signedTxCbor signed transaction in CBOR hex format
|
|
759
|
-
* @param txHash transaction hash
|
|
760
|
-
* @returns {TransactionSubmissionRow} mapped transaction submission row
|
|
761
|
-
*/
|
|
798
|
+
/** Signed tx CBOR and hash to a TransactionSubmissionRow stamped now (epoch seconds). */
|
|
762
799
|
function mapTransactionSubmission(signedTxCbor, txHash) {
|
|
763
800
|
const now = Math.floor(Date.now() / 1000);
|
|
764
801
|
return {
|
|
@@ -767,26 +804,14 @@ function mapTransactionSubmission(signedTxCbor, txHash) {
|
|
|
767
804
|
submittedAt: now,
|
|
768
805
|
};
|
|
769
806
|
}
|
|
770
|
-
/**
|
|
771
|
-
* Map Address Signing Requests
|
|
772
|
-
* Creates AddressSigningRequest row for address-signing request association
|
|
773
|
-
* @param addr bech32 address
|
|
774
|
-
* @param signingRequestId signing request UUID
|
|
775
|
-
* @returns {AddressSigningRequestRow} mapped address signing request row
|
|
776
|
-
*/
|
|
807
|
+
/** Address to signing-request association row. */
|
|
777
808
|
function mapAddressSigningRequest(addr, signingRequestId) {
|
|
778
809
|
return {
|
|
779
810
|
address_address: addr,
|
|
780
811
|
signingRequest_id: signingRequestId,
|
|
781
812
|
};
|
|
782
813
|
}
|
|
783
|
-
/**
|
|
784
|
-
* Map Address Transaction Builds
|
|
785
|
-
* Creates AddressTransactionBuild row for address-build association
|
|
786
|
-
* @param addr bech32 address
|
|
787
|
-
* @param buildId transaction build UUID
|
|
788
|
-
* @returns {AddressTransactionBuildRow} mapped address transaction build row
|
|
789
|
-
*/
|
|
814
|
+
/** Address to transaction-build association row. */
|
|
790
815
|
function mapAddressTransactionBuild(addr, buildId) {
|
|
791
816
|
return {
|
|
792
817
|
address_address: addr,
|
|
@@ -796,33 +821,18 @@ function mapAddressTransactionBuild(addr, buildId) {
|
|
|
796
821
|
//-----------------------------------------------------------------------
|
|
797
822
|
// Helper Functions
|
|
798
823
|
//-----------------------------------------------------------------------
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
*
|
|
802
|
-
* Blockfrost's cost_models (named keys) has known key-value mapping bugs for
|
|
803
|
-
* PlutusV3 (shifted values in the quotientInteger/remainderInteger region).
|
|
804
|
-
* The Blockfrost backend now prefers cost_models_raw (canonical arrays from the
|
|
805
|
-
* node) which bypasses this issue entirely.
|
|
806
|
-
*
|
|
807
|
-
* For V3 arrays: already in canonical order, just pad to 297 via toCostModelArrV3.
|
|
808
|
-
* For V3 objects (Ogmios named format): toCostModelArrV3(obj) maps via canonical keys.
|
|
809
|
-
* For V1/V2: alphabetical order IS the canonical order (no reordering needed).
|
|
810
|
-
*
|
|
811
|
-
* @param raw - Raw cost models from any backend (Blockfrost, Ogmios, Koios)
|
|
812
|
-
* @returns Object with all cost model values as number arrays in canonical order
|
|
813
|
-
*/
|
|
824
|
+
// Cost models as number arrays in canonical Plutus parameter order.
|
|
825
|
+
// For V1 and V2 the alphabetical key order is the canonical order.
|
|
814
826
|
function normalizeCostModels(raw) {
|
|
815
827
|
const result = {};
|
|
816
828
|
for (const [key, value] of Object.entries(raw)) {
|
|
817
829
|
const isV3 = key === 'PlutusV3' || key === 'plutus:v3';
|
|
818
830
|
if (Array.isArray(value)) {
|
|
819
831
|
if (isV3) {
|
|
820
|
-
//
|
|
821
|
-
// toCostModelArrV3 pads to 297 (Chang 2) with defaults if the array is shorter.
|
|
832
|
+
// already canonical; toCostModelArrV3 pads short arrays to 297 with defaults
|
|
822
833
|
result[key] = Array.from((0, cardano_costmodels_ts_1.toCostModelArrV3)(value)).map(Number);
|
|
823
834
|
}
|
|
824
835
|
else {
|
|
825
|
-
// V1/V2: pass through (already in canonical order)
|
|
826
836
|
result[key] = value;
|
|
827
837
|
}
|
|
828
838
|
}
|
|
@@ -832,7 +842,6 @@ function normalizeCostModels(raw) {
|
|
|
832
842
|
result[key] = Array.from((0, cardano_costmodels_ts_1.toCostModelArrV3)(obj)).map(Number);
|
|
833
843
|
}
|
|
834
844
|
else {
|
|
835
|
-
// V1/V2: alphabetical sort IS correct for those versions
|
|
836
845
|
result[key] = Object.keys(obj).sort()
|
|
837
846
|
.map(k => obj[k]);
|
|
838
847
|
}
|
|
@@ -840,25 +849,27 @@ function normalizeCostModels(raw) {
|
|
|
840
849
|
}
|
|
841
850
|
return result;
|
|
842
851
|
}
|
|
843
|
-
/**
|
|
844
|
-
* Convert hex string to UTF-8 string, falling back to hex if conversion fails.
|
|
845
|
-
* This helper reduces code duplication and improves performance by centralizing
|
|
846
|
-
* the conversion logic.
|
|
847
|
-
*
|
|
848
|
-
* @param hex - Hexadecimal string to convert
|
|
849
|
-
* @returns {string} UTF-8 string or original hex if conversion fails
|
|
850
|
-
*/
|
|
852
|
+
/** Hex to UTF-8 display string, hex fallback (see decodeAssetName). */
|
|
851
853
|
function hexToUtf8(hex) {
|
|
854
|
+
return decodeAssetName(hex);
|
|
855
|
+
}
|
|
856
|
+
// ignoreBOM: a leading U+FEFF is part of the asset name's bytes and must survive the round trip
|
|
857
|
+
const strictUtf8 = new node_util_1.TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
|
|
858
|
+
// Display string for a hex asset name. Invalid UTF-8 or names with U+0000 return the hex unchanged,
|
|
859
|
+
// because PostgreSQL rejects NUL in text.
|
|
860
|
+
function decodeAssetName(hex) {
|
|
852
861
|
if (!hex)
|
|
853
862
|
return hex;
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
863
|
+
let text;
|
|
864
|
+
try {
|
|
865
|
+
text = strictUtf8.decode(Buffer.from(hex, 'hex'));
|
|
866
|
+
}
|
|
867
|
+
catch {
|
|
868
|
+
return hex;
|
|
869
|
+
}
|
|
870
|
+
return text.includes('\u0000') ? hex : text;
|
|
871
|
+
}
|
|
872
|
+
/** Split an asset unit into policyId and decoded assetName; `lovelace` and malformed units get a null policyId. */
|
|
862
873
|
function parseAssetUnit(unit) {
|
|
863
874
|
if (unit === 'lovelace') {
|
|
864
875
|
return { policyId: null, assetName: 'lovelace' };
|
|
@@ -871,13 +882,7 @@ function parseAssetUnit(unit) {
|
|
|
871
882
|
const assetName = assetNameHex.length > 0 ? hexToUtf8(assetNameHex) : '';
|
|
872
883
|
return { policyId, assetName };
|
|
873
884
|
}
|
|
874
|
-
/**
|
|
875
|
-
* Compute CIP-14 asset fingerprint from policyId and assetName.
|
|
876
|
-
* Algorithm: bech32_encode("asset", blake2b_160(policyId_bytes + assetName_bytes))
|
|
877
|
-
* @param policyIdHex - Policy ID as hex string (56 chars / 28 bytes)
|
|
878
|
-
* @param assetNameHex - Asset name as hex string (variable length)
|
|
879
|
-
* @returns CIP-14 fingerprint string (e.g. "asset1...")
|
|
880
|
-
*/
|
|
885
|
+
/** CIP-14 fingerprint: bech32("asset", blake2b_160(policyId_bytes + assetName_bytes)). */
|
|
881
886
|
function computeCip14Fingerprint(policyIdHex, assetNameHex) {
|
|
882
887
|
const input = Buffer.from(policyIdHex + assetNameHex, 'hex');
|
|
883
888
|
const out = Buffer.alloc(20);
|
|
@@ -885,11 +890,7 @@ function computeCip14Fingerprint(policyIdHex, assetNameHex) {
|
|
|
885
890
|
const words = bech32_1.bech32.toWords(out);
|
|
886
891
|
return bech32_1.bech32.encode('asset', words);
|
|
887
892
|
}
|
|
888
|
-
/**
|
|
889
|
-
* Derive an enterprise script address from a script hash and network.
|
|
890
|
-
* Enterprise address = header_byte + 28-byte script hash, bech32-encoded.
|
|
891
|
-
* Header: 0x71 (mainnet, type 7 network 1) or 0x70 (testnet, type 7 network 0).
|
|
892
|
-
*/
|
|
893
|
+
/** Enterprise script address: header 0x71 (mainnet) / 0x70 (testnet) + 28-byte script hash, bech32. */
|
|
893
894
|
function scriptHashToEnterpriseAddress(scriptHashHex, network) {
|
|
894
895
|
const headerByte = network === 'mainnet' ? 0x71 : 0x70;
|
|
895
896
|
const payload = Buffer.alloc(29);
|
|
@@ -899,14 +900,84 @@ function scriptHashToEnterpriseAddress(scriptHashHex, network) {
|
|
|
899
900
|
const hrp = network === 'mainnet' ? 'addr' : 'addr_test';
|
|
900
901
|
return bech32_1.bech32.encode(hrp, words, 120);
|
|
901
902
|
}
|
|
902
|
-
/**
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
903
|
+
/** Stake credential to bech32 reward account; header nibbles 0xe key / 0xf script, network 1 mainnet / 0 testnets. */
|
|
904
|
+
function credentialToStakeAddress(credentialHex, isScript, network) {
|
|
905
|
+
const header = (isScript ? 0xf0 : 0xe0) | (network === 'mainnet' ? 0x01 : 0x00);
|
|
906
|
+
const payload = Buffer.alloc(29);
|
|
907
|
+
payload[0] = header;
|
|
908
|
+
Buffer.from(credentialHex, 'hex').copy(payload, 1);
|
|
909
|
+
const hrp = network === 'mainnet' ? 'stake' : 'stake_test';
|
|
910
|
+
return bech32_1.bech32.encode(hrp, bech32_1.bech32.toWords(payload), 120);
|
|
911
|
+
}
|
|
912
|
+
// Decodes the CIP-19 address header. Base addresses also yield the stake credential as a reward account.
|
|
913
|
+
// Byron addresses yield type byron, unparsable input yields unknown.
|
|
914
|
+
function decodeShelleyAddress(address) {
|
|
915
|
+
const none = { type: 'unknown', isScript: false, stakeAddress: null, paymentCredential: null, networkId: null };
|
|
916
|
+
if (typeof address !== 'string' || !address.length)
|
|
917
|
+
return none;
|
|
918
|
+
let bytes;
|
|
919
|
+
try {
|
|
920
|
+
const decoded = bech32_1.bech32.decode(address, 120);
|
|
921
|
+
if (decoded.prefix !== 'addr' && decoded.prefix !== 'addr_test' && decoded.prefix !== 'stake' && decoded.prefix !== 'stake_test')
|
|
922
|
+
return none;
|
|
923
|
+
bytes = Buffer.from(bech32_1.bech32.fromWords(decoded.words));
|
|
924
|
+
}
|
|
925
|
+
catch {
|
|
926
|
+
// Byron addresses are base58 and start with Ae2 / DdzFF (mainnet) or 2cWKM… (testnets)
|
|
927
|
+
return /^(Ae2|DdzFF|2cWKM|37btj|KjgoiX)/.test(address) ? { ...none, type: 'byron' } : none;
|
|
928
|
+
}
|
|
929
|
+
if (!bytes.length)
|
|
930
|
+
return none;
|
|
931
|
+
const header = bytes[0];
|
|
932
|
+
const type = header >> 4;
|
|
933
|
+
const networkId = header & 0x0f;
|
|
934
|
+
const net = networkId === 1 ? 'mainnet' : 'preview';
|
|
935
|
+
const paymentCredential = type <= 7 && bytes.length >= 29 ? bytes.subarray(1, 29).toString('hex') : null;
|
|
936
|
+
switch (type) {
|
|
937
|
+
case 0:
|
|
938
|
+
case 1:
|
|
939
|
+
case 2:
|
|
940
|
+
case 3: {
|
|
941
|
+
const stakeAddress = bytes.length >= 57
|
|
942
|
+
? credentialToStakeAddress(bytes.subarray(29, 57).toString('hex'), type >= 2, net)
|
|
943
|
+
: null;
|
|
944
|
+
return { type: 'base', isScript: type === 1 || type === 3, stakeAddress, paymentCredential, networkId };
|
|
945
|
+
}
|
|
946
|
+
case 4:
|
|
947
|
+
case 5:
|
|
948
|
+
return { type: 'pointer', isScript: type === 5, stakeAddress: null, paymentCredential, networkId };
|
|
949
|
+
case 6:
|
|
950
|
+
case 7:
|
|
951
|
+
return { type: 'enterprise', isScript: type === 7, stakeAddress: null, paymentCredential, networkId };
|
|
952
|
+
case 14:
|
|
953
|
+
case 15:
|
|
954
|
+
return { type: 'reward', isScript: type === 15, stakeAddress: address, paymentCredential: null, networkId };
|
|
955
|
+
default:
|
|
956
|
+
return { ...none, networkId };
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
/** Payment credential (hex) of a bech32 address; null for Byron, reward and unresolved ('') addresses. */
|
|
960
|
+
function paymentCredentialOf(address) {
|
|
961
|
+
return address ? decodeShelleyAddress(address).paymentCredential : null;
|
|
962
|
+
}
|
|
963
|
+
/** DRep credential to CIP-129 DRep ID (29 bytes): header 0x22 key hash / 0x23 script hash. */
|
|
964
|
+
function credentialToDrepId(credentialHex, isScript) {
|
|
965
|
+
const payload = Buffer.alloc(29);
|
|
966
|
+
payload[0] = isScript ? 0x23 : 0x22;
|
|
967
|
+
Buffer.from(credentialHex, 'hex').copy(payload, 1);
|
|
968
|
+
return bech32_1.bech32.encode('drep', bech32_1.bech32.toWords(payload), 120);
|
|
969
|
+
}
|
|
970
|
+
/** `[code] ctx: msg` */
|
|
909
971
|
function fmt(code, ctx, msg) {
|
|
910
972
|
return `[${code}] ${ctx}: ${msg}`;
|
|
911
973
|
}
|
|
974
|
+
/** Address balance from its UTxOs: lovelace first, then every native asset summed per unit. */
|
|
975
|
+
function sumUtxoAmounts(utxos) {
|
|
976
|
+
const totals = new Map([['lovelace', 0n]]);
|
|
977
|
+
for (const u of utxos) {
|
|
978
|
+
for (const a of u.amount ?? [])
|
|
979
|
+
totals.set(a.unit, (totals.get(a.unit) ?? 0n) + BigInt(a.quantity || '0'));
|
|
980
|
+
}
|
|
981
|
+
return [...totals].map(([unit, q]) => ({ unit, quantity: q.toString() }));
|
|
982
|
+
}
|
|
912
983
|
//# sourceMappingURL=mappers.js.map
|