"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
const R = __importStar(require("ramda"));
const token_math_1 = require("@melonproject/token-math");
const constructEnvironment_1 = require("../environment/constructEnvironment");
const ensure_1 = require("../guards/ensure");
exports.prepareTransaction = (environment, transaction, optionsOrCallback) => __awaiter(this, void 0, void 0, function* () {
    const encoded = transaction.encodeABI();
    const options = Object.assign({ amguPayable: false, from: environment.wallet.address.toString() }, (typeof optionsOrCallback === 'function'
        ? optionsOrCallback(environment)
        : optionsOrCallback));
    const maxGasPrice = token_math_1.multiply(token_math_1.toBI(constructEnvironment_1.defaultOptions.gasLimit), token_math_1.toBI(constructEnvironment_1.defaultOptions.gasPrice));
    const balance = yield environment.eth.getBalance(options.from);
    const maxAmguInEth = token_math_1.subtract(token_math_1.toBI(balance), maxGasPrice);
    // We don't know the amgu price at this stage yet, so we just send all
    // available ETH for the gasEstimation. This should throw if amgu price
    // in ETH is bigger than the available balance.
    const amguOptions = options.amguPayable
        ? Object.assign({ value: `${maxAmguInEth}` }, options) : options;
    ensure_1.ensure(!(options.skipGasEstimation && !options.gas), 'Cannot skip gasEstimation if no options.gas is provided');
    try {
        const gasEstimation = options.skipGasEstimation
            ? 0
            : yield transaction.estimateGas(Object.assign({}, R.omit(['amguPayable', 'incentive'], amguOptions)));
        transaction.gasEstimation = Math.ceil(Math.min(gasEstimation * 1.1, parseInt(environment.options.gasLimit, 10)));
    }
    catch (e) {
        throw new Error(`Gas estimation (preflight) failed for ${transaction.name}(${transaction.arguments.map(JSON.stringify).join(', ')}): ${e.message}`);
    }
    const prepared = {
        encoded,
        gasEstimation: transaction.gasEstimation,
        name: transaction.name,
        transaction,
    };
    return prepared;
});
