"use strict";
/**
 * !Important!
 * Erigon support is not actively maintained by BitPay. If there
 *  are issues with connecting to Erigon that need fixing, please
 *  open a PR.
 */
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ErigonRPC = void 0;
const crypto_wallet_core_1 = require("@bitpay-labs/crypto-wallet-core");
const abi_decoder_1 = __importDefault(require("abi-decoder"));
const Loggify_1 = require("../../../../../decorators/Loggify");
const erc20_1 = require("../../abi/erc20");
const erc721_1 = require("../../abi/erc721");
const transaction_1 = require("../../models/transaction");
abi_decoder_1.default.addABI(erc20_1.ERC20Abi);
abi_decoder_1.default.addABI(erc721_1.ERC721Abi);
if (Symbol['asyncIterator'] === undefined)
    Symbol['asyncIterator'] = Symbol.for('asyncIterator');
let ErigonRPC = class ErigonRPC {
    constructor(web3) {
        this.web3 = web3;
    }
    getBlock(blockNumber) {
        return this.web3.eth.getBlock(blockNumber, true);
    }
    async traceBlock(blockNumber) {
        const txs = await this.send({
            method: 'trace_block',
            params: [crypto_wallet_core_1.Utils.toHex(blockNumber)],
            jsonrpc: '2.0',
            id: Date.now() + Math.round(Math.random() * 1000)
        });
        return txs;
    }
    async getTransactionsFromBlock(blockNumber) {
        const txs = (await this.traceBlock(blockNumber)) || [];
        return txs.map(tx => this.transactionFromErigonTrace(tx));
    }
    send(data) {
        return new Promise((resolve, reject) => {
            const provider = this.web3.eth.currentProvider; // Import type HttpProvider web3-core
            provider.send(data, function (err, data) {
                if (err)
                    return reject(err);
                resolve(data.result);
            });
        });
    }
    transactionFromErigonTrace(tx) {
        const abiType = transaction_1.EVMTransactionStorage.abiDecode(tx.action.input);
        const convertedTx = {
            ...tx
        };
        if (abiType) {
            convertedTx.abiType = abiType;
        }
        return convertedTx;
    }
    reconcileTraces(block, transactions, traceTxs) {
        const gasSum = transactions.reduce((sum, e) => sum + e.fee, 0);
        for (const tx of traceTxs) {
            if (tx.type === 'reward') {
                if (tx.action.rewardType && tx.action.rewardType === 'block') {
                    const totalReward = Number.parseInt(tx.action.value, 16) + gasSum;
                    block.reward = totalReward;
                }
                if (tx.action.rewardType && tx.action.rewardType === 'uncle') {
                    const uncles = block.uncleReward || [];
                    const uncleValue = Number.parseInt(tx.action.value, 16);
                    uncles.push(uncleValue);
                    block.uncleReward = uncles;
                }
            }
            if (tx && tx.action) {
                const foundIndex = transactions.findIndex(t => t.txid === tx.transactionHash &&
                    t.from !== tx.action.from &&
                    t.to.toLowerCase() !== (tx.action.to || '').toLowerCase());
                if (foundIndex > -1) {
                    transactions[foundIndex].internal.push(tx);
                }
                if (tx.error) {
                    const errorIndex = transactions.findIndex(t => t.txid === tx.transactionHash);
                    if (errorIndex && errorIndex > -1) {
                        transactions[errorIndex].error = tx.error;
                    }
                }
            }
        }
    }
};
exports.ErigonRPC = ErigonRPC;
exports.ErigonRPC = ErigonRPC = __decorate([
    Loggify_1.LoggifyClass
], ErigonRPC);
//# sourceMappingURL=erigonRpc.js.map