"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
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 token_math_1 = require("@melonproject/token-math");
const Contracts_1 = require("../../Contracts");
const getContract_1 = require("./getContract");
const prepareTransaction_1 = require("./prepareTransaction");
const ensure_1 = require("../guards/ensure");
const signTransaction_1 = require("../environment/signTransaction");
const EnsureError_1 = require("../guards/EnsureError");
const getBalance_1 = require("../evm/getBalance");
const getLogCurried_1 = require("../environment/getLogCurried");
const getLog = getLogCurried_1.getLogCurried('melon:protocol:utils:solidity:transactionFactory');
exports.defaultGuard = () => __awaiter(this, void 0, void 0, function* () { });
exports.defaultPrepareArgs = (environment, params, contractAddress) => __awaiter(this, void 0, void 0, function* () { return Object.values(params || {}).map(v => v.toString()); });
exports.defaultPostProcess = () => __awaiter(this, void 0, void 0, function* () { return true; });
/**
 * The transaction factory returns a function "execute" (You have to rename it
 * to the actual name of the transaction, for example: "transfer"). As a
 * minimum, one needs to provide the transaction name and the contract path:
 *
 * ```typescript
 * const transfer = transactionFactory('transfer', Contract.Token);
 * ```
 *
 * This transfer function can then be executed directly:
 *
 * ```typescript
 * await transfer(new Address('0xdeadbeef'));
 * ```
 *
 * Or sliced into a prepare and a send part:
 * ```typescript
 * const preparedTransaction: PreparedTransaction =
 *    await transfer.prepare(new Address('0xdeadbeef'));
 *
 * // pass that prepared transaction to the signer
 * const result = await transfer.send(new Address('0xdeadbeef'),
 *    preparedTransaction);
 * ```
 */
const transactionFactory = (name, contract, guard = exports.defaultGuard, prepareArgs = exports.defaultPrepareArgs, postProcess = exports.defaultPostProcess, defaultOptions = {}) => {
    const prepare = (environment, contractAddress, params, optionsOrCallback = defaultOptions) => __awaiter(this, void 0, void 0, function* () {
        const log = getLog(environment);
        const options = typeof optionsOrCallback === 'function'
            ? optionsOrCallback(environment)
            : optionsOrCallback;
        if (!options.skipGuards) {
            yield guard(environment, params, contractAddress, options);
        }
        const args = yield prepareArgs(environment, params, contractAddress);
        const txId = `${contract}@${contractAddress}.${name}(${args
            .map(JSON.stringify)
            .join(',')})`;
        log.info('Prepare transaction', txId);
        try {
            const contractInstance = getContract_1.getContract(environment, contract, contractAddress);
            ensure_1.ensure(!!contractInstance.methods[name], `Method ${name} does not exist on contract ${contract}`);
            const transaction = contractInstance.methods[name](...args);
            transaction.name = name;
            const prepared = yield prepareTransaction_1.prepareTransaction(environment, transaction, options);
            // HACK: To avoid circular dependencies (?)
            const { calcAmguInEth, } = yield Promise.resolve().then(() => __importStar(require('../../contracts/engine/calls/calcAmguInEth')));
            const amguInEth = options.amguPayable
                ? yield calcAmguInEth(environment, contractAddress, prepared.gasEstimation)
                : token_math_1.createQuantity('eth', '0'); /*;*/
            const incentiveInEth = options.incentive
                ? token_math_1.createQuantity('eth', '10000000000000000')
                : token_math_1.createQuantity('eth', '0');
            const melonTransaction = {
                amguInEth,
                contract,
                name,
                params,
                rawTransaction: {
                    data: prepared.encoded,
                    from: `${options.from || environment.wallet.address}`,
                    gas: `${options.gas || prepared.gasEstimation}`,
                    gasPrice: `${options.gasPrice || environment.options.gasPrice}`,
                    to: `${contractAddress}`,
                    value: `${options.value ||
                        token_math_1.add(amguInEth.quantity, incentiveInEth.quantity)}`,
                },
                transactionArgs: prepared.transaction.arguments,
            };
            const totalCost = token_math_1.createQuantity('ETH', token_math_1.add(token_math_1.toBI(melonTransaction.rawTransaction.value), token_math_1.multiply(token_math_1.toBI(melonTransaction.rawTransaction.gas), token_math_1.toBI(melonTransaction.rawTransaction.gasPrice))));
            const balance = yield getBalance_1.getBalance(environment);
            ensure_1.ensure(token_math_1.greaterThan(balance, totalCost), `Insufficent balance. Got: ${token_math_1.toFixed(balance)}, need: ${token_math_1.toFixed(totalCost)}`);
            log.debug('Transaction prepared', melonTransaction);
            return melonTransaction;
        }
        catch (e) {
            log.error(txId, e);
            if (e instanceof EnsureError_1.EnsureError) {
                throw e;
            }
            else {
                throw new Error(
                // tslint:disable-next-line:max-line-length
                `Error in prepare transaction ${txId}): ${e.message}`);
            }
        }
    });
    const send = (environment, contractAddress, signedTransactionData, 
    // prepared,
    params) => __awaiter(this, void 0, void 0, function* () {
        const log = getLog(environment);
        const receipt = yield environment.eth
            .sendSignedTransaction(signedTransactionData)
            .then(null, error => {
            throw new Error(`Transaction failed for ${name}: ${error.message}`);
        });
        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;
            }
        }, {});
        receipt.events = events;
        log.debug(`Receipt for ${name}`, receipt);
        const postprocessed = yield postProcess(environment, receipt, params, contractAddress);
        return postprocessed;
    });
    const execute = (environment, contractAddress, params, options = defaultOptions) => __awaiter(this, void 0, void 0, function* () {
        const prepared = yield prepare(environment, contractAddress, params, options);
        const signedTransactionData = yield signTransaction_1.signTransaction(environment, prepared.rawTransaction);
        const result = yield send(environment, contractAddress, signedTransactionData, 
        // prepared,
        params, options);
        return result;
    });
    execute.prepare = prepare;
    execute.send = send;
    return execute;
};
exports.transactionFactory = transactionFactory;
