"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 Environment_1 = require("~/utils/environment/Environment");
const deployAndInitTestEnv_1 = require("../../utils/deployAndInitTestEnv");
const setupInvestedTestFund_1 = require("~/tests/utils/setupInvestedTestFund");
const getExpectedRate_1 = require("~/contracts/exchanges/third-party/kyber/calls/getExpectedRate");
const Contracts_1 = require("~/Contracts");
const takeOrderOnKyber_1 = require("~/contracts/fund/trading/transactions/takeOrderOnKyber");
const balanceOf_1 = require("~/contracts/dependencies/token/calls/balanceOf");
const getTokenBySymbol_1 = require("~/utils/environment/getTokenBySymbol");
const register_1 = require("~/contracts/fund/policies/transactions/register");
const FunctionSignatures_1 = require("~/contracts/fund/trading/utils/FunctionSignatures");
const getPrice_1 = require("~/contracts/prices/calls/getPrice");
const setBaseRate_1 = require("~/contracts/exchanges/third-party/kyber/transactions/setBaseRate");
const toBeTrueWith_1 = require("~/tests/utils/toBeTrueWith");
const getFundHoldings_1 = require("~/contracts/fund/accounting/calls/getFundHoldings");
expect.extend({ toBeTrueWith: toBeTrueWith_1.toBeTrueWith });
describe('Happy Path', () => {
    const shared = {};
    beforeAll(() => __awaiter(this, void 0, void 0, function* () {
        shared.env = yield deployAndInitTestEnv_1.deployAndInitTestEnv();
        expect(shared.env.track).toBe(Environment_1.Tracks.TESTING);
        shared.accounts = yield shared.env.eth.getAccounts();
        shared.kyber =
            shared.env.deployment.exchangeConfigs[Contracts_1.Exchanges.KyberNetwork].exchange;
        shared.routes = yield setupInvestedTestFund_1.setupInvestedTestFund(shared.env);
        shared.weth = getTokenBySymbol_1.getTokenBySymbol(shared.env, 'WETH');
        shared.mln = getTokenBySymbol_1.getTokenBySymbol(shared.env, 'MLN');
        yield register_1.register(shared.env, shared.routes.policyManagerAddress, {
            method: FunctionSignatures_1.FunctionSignatures.takeOrder,
            policy: shared.env.deployment.melonContracts.policies.priceTolerance,
        });
        // Setting rates on kyber reserve
        const mlnPrice = yield getPrice_1.getPrice(shared.env, shared.env.deployment.melonContracts.priceSource.toString(), shared.mln);
        const ethPriceInMln = token_math_1.createPrice(mlnPrice.quote, mlnPrice.base);
        const prices = [
            {
                buy: ethPriceInMln,
                sell: mlnPrice,
            },
        ];
        yield setBaseRate_1.setBaseRate(shared.env, shared.env.deployment.thirdPartyContracts.exchanges.kyber.conversionRates, {
            prices,
        });
    }));
    test('Trade on kyber', () => __awaiter(this, void 0, void 0, function* () {
        yield getFundHoldings_1.getFundHoldings(shared.env, shared.routes.accountingAddress);
        const takerQuantity = token_math_1.createQuantity(shared.weth, 0.1);
        const expectedRate = yield getExpectedRate_1.getExpectedRate(shared.env, shared.kyber, {
            fillTakerQuantity: takerQuantity,
            makerAsset: shared.mln,
            takerAsset: shared.weth,
        });
        // Minimum quantity of dest asset expected to get in return in the trade
        const minMakerQuantity = token_math_1.valueIn(expectedRate, takerQuantity);
        const preMlnBalance = yield balanceOf_1.balanceOf(shared.env, shared.mln.address, {
            address: shared.routes.vaultAddress,
        });
        const result = yield takeOrderOnKyber_1.takeOrderOnKyber(shared.env, shared.routes.tradingAddress, {
            makerQuantity: minMakerQuantity,
            takerQuantity,
        });
        expect(result.takerQuantity).toBeTrueWith(token_math_1.isEqual, takerQuantity);
        expect(result.makerQuantity).toBeTrueWith(token_math_1.greaterThan, minMakerQuantity);
        const holdings = yield getFundHoldings_1.getFundHoldings(shared.env, shared.routes.accountingAddress);
        const wethHolding = holdings.find(holding => token_math_1.isEqual(holding.token, shared.weth));
        expect(token_math_1.add(wethHolding, takerQuantity)).toBeTrueWith(token_math_1.isEqual, token_math_1.createQuantity(shared.weth, 1));
        const postMlnBalance = yield balanceOf_1.balanceOf(shared.env, shared.mln.address, {
            address: shared.routes.vaultAddress,
        });
        expect(token_math_1.greaterThan(token_math_1.subtract(postMlnBalance, preMlnBalance), minMakerQuantity)).toBeTruthy();
    }));
    test('Price tolerance prevents ill priced trade', () => __awaiter(this, void 0, void 0, function* () {
        const takerQuantity = token_math_1.createQuantity(shared.weth, 0.1);
        // Minimum quantity of dest asset expected to get in return in the trade
        const minMakerQuantity = token_math_1.createQuantity(shared.mln, 0);
        yield expect(takeOrderOnKyber_1.takeOrderOnKyber(shared.env, shared.routes.tradingAddress, {
            makerQuantity: minMakerQuantity,
            takerQuantity,
        })).rejects.toThrow();
    }));
});
