"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 order_utils_1 = require("@0x/order-utils");
const contract_wrappers_1 = require("@0x/contract-wrappers");
const token_math_1 = require("@melonproject/token-math");
const Contracts_1 = require("../../../../../Contracts");
const transactionFactory_1 = require("../../../../../utils/solidity/transactionFactory");
const ensure_1 = require("../../../../../utils/guards/ensure");
const approve_1 = require("../../../../dependencies/token/transactions/approve");
const stringifyStruct_1 = require("../../../../../utils/solidity/stringifyStruct");
const getToken_1 = require("../../../../dependencies/token/calls/getToken");
const getOrderInfo_1 = require("../calls/getOrderInfo");
const isValidSignature_1 = require("../calls/isValidSignature");
const getAssetProxy_1 = require("../calls/getAssetProxy");
const getFeeToken_1 = require("../calls/getFeeToken");
const guard = (environment, { signedOrder, takerQuantity: providedTakerQuantity }, contractAddress) => __awaiter(this, void 0, void 0, function* () {
    const orderInfo = yield getOrderInfo_1.getOrderInfo(environment, contractAddress, {
        signedOrder,
    });
    ensure_1.ensure(orderInfo.status === `${contract_wrappers_1.OrderStatus.FILLABLE}`, `Order is not fillable. Got status: ${contract_wrappers_1.OrderStatus[orderInfo.status]}`);
    const validSignature = yield isValidSignature_1.isValidSignature(environment, contractAddress, {
        signedOrder,
    });
    ensure_1.ensure(validSignature, 'Signature invalid');
    const { tokenAddress } = order_utils_1.assetDataUtils.decodeERC20AssetData(signedOrder.takerAssetData);
    const takerToken = yield getToken_1.getToken(environment, tokenAddress);
    const takerQuantity = providedTakerQuantity ||
        token_math_1.createQuantity(takerToken, signedOrder.takerAssetAmount.toString());
    const erc20Proxy = yield getAssetProxy_1.getAssetProxy(environment, contractAddress);
    yield approve_1.approve(environment, { howMuch: takerQuantity, spender: erc20Proxy });
});
const prepareArgs = (_, { signedOrder, takerQuantity }) => __awaiter(this, void 0, void 0, function* () {
    const stringifiedSignedOrder = stringifyStruct_1.stringifyStruct(signedOrder);
    const takerAssetAmount = takerQuantity
        ? takerQuantity.quantity.toString()
        : stringifiedSignedOrder.takerAssetAmount;
    const signature = stringifiedSignedOrder.signature;
    return [
        R.omit(['signature'], stringifiedSignedOrder),
        takerAssetAmount,
        signature,
    ];
});
const parse0xFillReceipt = (environment, { fillValues, feeToken }) => __awaiter(this, void 0, void 0, function* () {
    const makerToken = yield getToken_1.getToken(environment, order_utils_1.assetDataUtils.decodeERC20AssetData(fillValues.makerAssetData).tokenAddress);
    const takerToken = yield getToken_1.getToken(environment, order_utils_1.assetDataUtils.decodeERC20AssetData(fillValues.takerAssetData).tokenAddress);
    const result = {
        makerFeePaid: token_math_1.createQuantity(feeToken, fillValues.makerFeePaid),
        makerFilledAmount: token_math_1.createQuantity(makerToken, fillValues.makerAssetFilledAmount.toString()),
        takerFeePaid: token_math_1.createQuantity(feeToken, fillValues.takerFeePaid),
        takerFilledAmount: token_math_1.createQuantity(takerToken, fillValues.takerAssetFilledAmount.toString()),
    };
    return result;
});
exports.parse0xFillReceipt = parse0xFillReceipt;
const postProcess = (environment, receipt, params, contractAddress) => __awaiter(this, void 0, void 0, function* () {
    const fillValues = receipt.events.Fill.returnValues;
    const feeToken = yield getFeeToken_1.getFeeToken(environment, contractAddress);
    const result = yield parse0xFillReceipt(environment, {
        feeToken,
        fillValues,
    });
    return result;
});
const fillOrder = transactionFactory_1.transactionFactory('fillOrder', Contracts_1.Contracts.ZeroExExchange, guard, prepareArgs, postProcess);
exports.fillOrder = fillOrder;
