"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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const token_math_1 = require("@melonproject/token-math");
const transactionFactory_1 = require("../../../utils/solidity/transactionFactory");
const getContract_1 = require("../../../utils/solidity/getContract");
const getToken_1 = require("../../dependencies/token/calls/getToken");
const allowance_1 = require("../../dependencies/token/calls/allowance");
const ensure_1 = require("../../../utils/guards/ensure");
const Contracts_1 = require("../../../Contracts");
const guard = (environment, { quantity }, contractAddress) => __awaiter(this, void 0, void 0, function* () {
    const engine = getContract_1.getContract(environment, Contracts_1.Contracts.Engine, contractAddress);
    const mlnAddress = yield engine.methods.mlnToken().call();
    const mlnToken = yield getToken_1.getToken(environment, mlnAddress);
    token_math_1.ensureSameToken(quantity.token, mlnToken);
    const allowedMln = yield allowance_1.allowance(environment, mlnAddress, {
        owner: environment.wallet.address,
        spender: contractAddress.toString(),
    });
    ensure_1.ensure(token_math_1.isEqual(allowedMln, quantity) || token_math_1.greaterThan(allowedMln, quantity), `Amount must be approved prior to calling this function.`);
});
const prepareArgs = (_, { quantity }) => __awaiter(this, void 0, void 0, function* () {
    return [`${quantity.quantity}`];
});
const postProcess = (_, receipt) => __awaiter(this, void 0, void 0, function* () { return receipt; });
// Gas behaves kinda weird for this function:
// Estimation: 88289, Effective usage: 58289
// const options = { gas: '89399' };
// NOTE: Fixed with gas boost
exports.sellAndBurnMln = transactionFactory_1.transactionFactory('sellAndBurnMln', Contracts_1.Contracts.Engine, guard, prepareArgs, postProcess);
