"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 getBalance_1 = require("../../utils/evm/getBalance");
const withNewAccount_1 = require("../../utils/environment/withNewAccount");
const token_math_1 = require("@melonproject/token-math");
const sendEth_1 = require("../../utils/evm/sendEth");
const setupInvestedTestFund_1 = require("../utils/setupInvestedTestFund");
const deposit_1 = require("../../contracts/dependencies/token/transactions/deposit");
const getTokenBySymbol_1 = require("../../utils/environment/getTokenBySymbol");
const updateKyber_1 = require("../../contracts/prices/transactions/updateKyber");
const getPrice_1 = require("../../contracts/prices/calls/getPrice");
const toBeTrueWith_1 = require("../utils/toBeTrueWith");
const getSystemTestEnvironment_1 = require("../utils/getSystemTestEnvironment");
const Environment_1 = require("../../utils/environment/Environment");
const setAmguPrice_1 = require("../../contracts/engine/transactions/setAmguPrice");
const Contracts_1 = require("../../Contracts");
const getLogCurried_1 = require("../../utils/environment/getLogCurried");
const transfer_1 = require("../../contracts/dependencies/token/transactions/transfer");
const makeOrderFromAccountOasisDex_1 = require("../../contracts/exchanges/transactions/makeOrderFromAccountOasisDex");
const performCalculations_1 = require("../../contracts/fund/accounting/calls/performCalculations");
const takeOasisDexOrder_1 = require("../../contracts/fund/trading/transactions/takeOasisDexOrder");
const makeOasisDexOrder_1 = require("../../contracts/fund/trading/transactions/makeOasisDexOrder");
const cancelOasisDexOrder_1 = require("../../contracts/fund/trading/transactions/cancelOasisDexOrder");
const shutDownFund_1 = require("../../contracts/fund/hub/transactions/shutDownFund");
const isShutDown_1 = require("../../contracts/fund/hub/calls/isShutDown");
const createOrder_1 = require("../../contracts/exchanges/third-party/0x/utils/createOrder");
const signOrder_1 = require("../../contracts/exchanges/third-party/0x/utils/signOrder");
const take0xOrder_1 = require("../../contracts/fund/trading/transactions/take0xOrder");
const takeOrderOnKyber_1 = require("../../contracts/fund/trading/transactions/takeOrderOnKyber");
const balanceOf_1 = require("../../contracts/dependencies/token/calls/balanceOf");
const testLogger_1 = require("../utils/testLogger");
expect.extend({ toBeTrueWith: toBeTrueWith_1.toBeTrueWith });
const getLog = getLogCurried_1.getLogCurried('melon:protocol:systemTest:playground');
describe('playground', () => {
    afterAll(() => __awaiter(this, void 0, void 0, function* () {
        yield testLogger_1.allLogsWritten();
    }));
    test('Happy path', () => __awaiter(this, void 0, void 0, function* () {
        const master = yield getSystemTestEnvironment_1.getSystemTestEnvironment(Environment_1.Tracks.KYBER_PRICE);
        const log = getLog(master);
        const { melonContracts } = master.deployment;
        const matchingMarket = master.deployment.exchangeConfigs[Contracts_1.Exchanges.MatchingMarket].exchange;
        const zeroEx = master.deployment.exchangeConfigs[Contracts_1.Exchanges.ZeroEx].exchange;
        // const kyber =
        //   master.deployment.exchangeConfigs[Exchanges.KyberNetwork].exchange;
        const manager = yield withNewAccount_1.withNewAccount(master);
        const trader = yield withNewAccount_1.withNewAccount(master);
        const amguPrice = token_math_1.createQuantity('MLN', '1000000000');
        yield setAmguPrice_1.setAmguPrice(master, melonContracts.engine, amguPrice);
        yield updateKyber_1.updateKyber(master, melonContracts.priceSource);
        const weth = getTokenBySymbol_1.getTokenBySymbol(manager, 'WETH');
        const mln = getTokenBySymbol_1.getTokenBySymbol(manager, 'MLN');
        try {
            const mlnPrice = yield getPrice_1.getPrice(master, melonContracts.priceSource.toString(), mln);
            log.debug('MLN Price', mlnPrice);
        }
        catch (e) {
            throw new Error('Cannot get MLN Price from Kyber');
        }
        const masterBalance = yield getBalance_1.getBalance(master);
        expect(masterBalance).toBeTrueWith(token_math_1.greaterThan, token_math_1.createQuantity(masterBalance.token, 6));
        yield sendEth_1.sendEth(master, {
            howMuch: token_math_1.createQuantity('ETH', 2),
            to: manager.wallet.address,
        });
        yield sendEth_1.sendEth(master, {
            howMuch: token_math_1.createQuantity('ETH', 1),
            to: trader.wallet.address,
        });
        yield transfer_1.transfer(master, {
            howMuch: token_math_1.createQuantity(mln, 2),
            to: trader.wallet.address,
        });
        const quantity = token_math_1.createQuantity(weth, 1);
        yield deposit_1.deposit(manager, quantity.token.address, undefined, {
            value: quantity.quantity.toString(),
        });
        const orderFromTrader = yield makeOrderFromAccountOasisDex_1.makeOrderFromAccountOasisDex(trader, matchingMarket, {
            buy: token_math_1.createQuantity(weth, 0.1),
            sell: token_math_1.createQuantity(mln, 1),
        });
        const routes = yield setupInvestedTestFund_1.setupInvestedTestFund(manager);
        const preCalculations = yield performCalculations_1.performCalculations(manager, routes.accountingAddress);
        log.debug({ preCalculations });
        log.debug('After first investment, share price is: ', token_math_1.toFixed(preCalculations.sharePrice));
        expect(token_math_1.toFixed(preCalculations.sharePrice)).toEqual('1.000000');
        const orderFromFund = yield makeOasisDexOrder_1.makeOasisDexOrder(manager, routes.tradingAddress, {
            makerQuantity: token_math_1.createQuantity(weth, 0.5),
            takerQuantity: token_math_1.createQuantity(mln, 8),
        });
        log.debug('Made an order ', orderFromFund);
        let calculations = yield performCalculations_1.performCalculations(manager, routes.accountingAddress);
        expect(token_math_1.toFixed(calculations.sharePrice)).toEqual('1.000000');
        yield cancelOasisDexOrder_1.cancelOasisDexOrder(manager, routes.tradingAddress, {
            id: orderFromFund.id,
            maker: orderFromFund.maker,
            makerAsset: orderFromFund.sell.token.address,
            takerAsset: orderFromFund.buy.token.address,
        });
        log.debug('Canceled order ', orderFromFund.id);
        yield takeOasisDexOrder_1.takeOasisDexOrder(manager, routes.tradingAddress, {
            id: orderFromTrader.id,
            maker: orderFromTrader.maker,
            makerQuantity: orderFromTrader.sell,
            takerQuantity: orderFromTrader.buy,
        });
        calculations = yield performCalculations_1.performCalculations(manager, routes.accountingAddress);
        log.debug('After taking an order, share price is: ', token_math_1.toFixed(calculations.sharePrice));
        log.debug({ calculations });
        expect(calculations.gav).toBeTrueWith(token_math_1.greaterThan, token_math_1.createQuantity(weth, 0.8));
        const unsignedZeroExOrder = yield createOrder_1.createOrder(trader, zeroEx, {
            makerQuantity: token_math_1.createQuantity(mln, 0.75),
            takerQuantity: token_math_1.createQuantity(weth, 0.075),
        });
        const signedZeroExOrder = yield signOrder_1.signOrder(trader, unsignedZeroExOrder);
        yield createOrder_1.approveOrder(trader, zeroEx, signedZeroExOrder);
        const filledOrder = yield take0xOrder_1.take0xOrder(manager, routes.tradingAddress, {
            signedOrder: signedZeroExOrder,
        });
        expect(filledOrder.makerFilledAmount).toBeTrueWith(token_math_1.isEqual, token_math_1.createQuantity(mln, 0.75));
        const preMlnBalance = yield balanceOf_1.balanceOf(manager, mln.address, {
            address: routes.vaultAddress,
        });
        const makerQuantity = token_math_1.createQuantity(mln, 0.75);
        yield takeOrderOnKyber_1.takeOrderOnKyber(manager, routes.tradingAddress, {
            makerQuantity,
            takerQuantity: token_math_1.createQuantity(weth, 0.075),
        });
        const postMlnBalance = yield balanceOf_1.balanceOf(manager, mln.address, {
            address: routes.vaultAddress,
        });
        log.debug({ postMlnBalance, preMlnBalance, makerQuantity });
        expect(token_math_1.greaterThan(token_math_1.subtract(postMlnBalance, preMlnBalance), makerQuantity)).toBeTruthy();
        log.debug('Take order from Kyber');
        yield shutDownFund_1.shutDownFund(manager, melonContracts.version, {
            hub: routes.hubAddress,
        });
        log.debug('Shut down fund');
        const isFundShutDown = yield isShutDown_1.isShutDown(manager, routes.hubAddress);
        expect(isFundShutDown).toBeTruthy();
    }));
});
