"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const R = __importStar(require("ramda"));
const web3_eth_abi_1 = __importDefault(require("web3-eth-abi"));
const Contracts_1 = require("../../Contracts");
const parseReceiptLogs = (receipt, log) => {
    const events = receipt.logs.reduce((carry, txLog) => {
        const eventABI = Contracts_1.eventSignatureABIMap[txLog.topics[0]];
        // Ignore event if not found in eventSignaturesABI map;
        if (!eventABI) {
            log.debug('No Event-ABI found for', txLog);
            return carry;
        }
        try {
            const decoded = web3_eth_abi_1.default.decodeLog(eventABI.inputs, txLog.data !== '0x' && txLog.data, eventABI.anonymous ? txLog.topics : txLog.topics.slice(1));
            const keys = R.map(R.prop('name'), eventABI.inputs);
            const picked = R.pick(keys, decoded);
            const current = R.cond([
                [
                    Array.isArray,
                    existingEventLog => [...existingEventLog, { returnValues: picked }],
                ],
                [R.isNil, R.always({ returnValues: picked })],
                [R.T, existingEventLog => [existingEventLog, { returnValues: picked }]],
            ])(carry[eventABI.name]);
            return Object.assign({}, carry, { [eventABI.name]: current });
        }
        catch (e) {
            log.warn('Error with parsing logs', eventABI, txLog, e);
            return carry;
        }
    }, {});
    return Object.assign({}, receipt, { events });
};
exports.parseReceiptLogs = parseReceiptLogs;
