"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 Contracts_1 = require("../../../../../Contracts");
const callFactory_1 = require("../../../../../utils/solidity/callFactory");
const getTokenBySymbol_1 = require("../../../../../utils/environment/getTokenBySymbol");
const kyberEthAddress_1 = require("../../../../../utils/constants/kyberEthAddress");
const prepareArgs = (environment, { nativeAsset = getTokenBySymbol_1.getTokenBySymbol(environment, 'WETH'), makerAsset, takerAsset, fillTakerQuantity, }) => {
    const srcTokenAddress = takerAsset.address === nativeAsset.address
        ? kyberEthAddress_1.kyberEthAddress
        : takerAsset.address;
    const destTokenAddress = makerAsset.address === nativeAsset.address
        ? kyberEthAddress_1.kyberEthAddress
        : makerAsset.address;
    const args = [
        srcTokenAddress,
        destTokenAddress,
        fillTakerQuantity.quantity.toString(),
    ];
    return args;
};
const postProcess = (_, result, prepared) => __awaiter(this, void 0, void 0, function* () {
    const { 1: price } = result;
    // The price is always returned with 18 decimals, hence we need to
    // adjust it to the number of decimals of the respective maker asset.
    const length = prepared.params.makerAsset.decimals + price.length - 18;
    const truncated = price.substr(0, length);
    const base = token_math_1.createQuantity(prepared.params.takerAsset, 1);
    const quote = token_math_1.createQuantity(prepared.params.makerAsset, truncated);
    return token_math_1.createPrice(base, quote);
});
const getExpectedRate = callFactory_1.callFactory('getExpectedRate', Contracts_1.Contracts.KyberNetworkProxy, {
    postProcess,
    prepareArgs,
});
exports.getExpectedRate = getExpectedRate;
