"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.enrichLeaves = enrichLeaves;
const checkpoint_core_1 = require("@dbis/checkpoint-core");
const config_1 = require("./config");
const usdEnrich_1 = require("./usdEnrich");
async function enrichLeaves(leaves, blockscoutApi) {
    const api = blockscoutApi.replace(/\/$/, '');
    const out = [];
    for (const leaf of leaves) {
        const copy = { ...leaf };
        const txHash = String(leaf.txHash || '');
        const needsToken = config_1.checkpointIndexerConfig.enrichTokenTransfers &&
            /^0x[a-fA-F0-9]{64}$/.test(txHash) &&
            !copy.token &&
            BigInt(String(copy.value ?? copy.nativeValueWei ?? '0')) === 0n;
        let allErc20 = [];
        if (needsToken || (config_1.checkpointIndexerConfig.usdEnrichEnabled && /^0x[a-fA-F0-9]{64}$/.test(txHash))) {
            allErc20 = await (0, checkpoint_core_1.fetchAllTokenTransfersForTx)(api, txHash);
            if (needsToken) {
                (0, checkpoint_core_1.applyPrimaryTransferToLeaf)(copy, (0, checkpoint_core_1.pickPrimaryFromSummaries)(allErc20));
            }
        }
        const withUsd = await (0, usdEnrich_1.enrichLeafUsdRecord)(copy, {
            apiBaseUrl: config_1.checkpointIndexerConfig.tokenAggregationApiUrl,
            chainId: 138,
            enabled: config_1.checkpointIndexerConfig.usdEnrichEnabled,
            requestDelayMs: config_1.checkpointIndexerConfig.usdRequestDelayMs,
            blockscoutApi: api,
            preloadedErc20: allErc20,
        });
        out.push(withUsd);
        await sleep(60);
    }
    return out;
}
function sleep(ms) {
    return new Promise((r) => setTimeout(r, ms));
}
