"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 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 makeOasisDexOrder_1 = require("../../contracts/fund/trading/transactions/makeOasisDexOrder");
const testLogger_1 = require("../utils/testLogger");
const register_1 = require("../../contracts/fund/policies/transactions/register");
const FunctionSignatures_1 = require("../../contracts/fund/trading/utils/FunctionSignatures");
const deployContract_1 = require("../../utils/solidity/deployContract");
const takeOrderOnKyber_1 = require("../../contracts/fund/trading/transactions/takeOrderOnKyber");
const balanceOf_1 = require("../../contracts/dependencies/token/calls/balanceOf");
const getPolicyInformation_1 = require("../../contracts/fund/policies/calls/getPolicyInformation");
const approve_1 = require("../../contracts/dependencies/token/transactions/approve");
const requestInvestment_1 = require("../../contracts/fund/participation/transactions/requestInvestment");
const getToken_1 = require("../../contracts/dependencies/token/calls/getToken");
expect.extend({ toBeTrueWith: toBeTrueWith_1.toBeTrueWith });
const getLog = getLogCurried_1.getLogCurried('melon:protocol:systemTest:playground');
const shared = {};
describe('playground', () => {
    afterAll(() => __awaiter(this, void 0, void 0, function* () {
        yield testLogger_1.allLogsWritten();
    }));
    beforeAll(() => __awaiter(this, void 0, void 0, function* () {
        shared.master = yield getSystemTestEnvironment_1.getSystemTestEnvironment(Environment_1.Tracks.KYBER_PRICE);
        shared.investor = yield withNewAccount_1.withNewAccount(shared.master);
        yield sendEth_1.sendEth(shared.master, {
            howMuch: token_math_1.createQuantity('ETH', 5),
            to: shared.investor.wallet.address,
        });
        const depositAmount = token_math_1.createQuantity(getTokenBySymbol_1.getTokenBySymbol(shared.master, 'WETH'), 1);
        yield deposit_1.deposit(shared.investor, depositAmount.token.address, undefined, {
            value: depositAmount.quantity.toString(),
        });
    }));
    test('Happy path: Fund 1', () => __awaiter(this, void 0, void 0, function* () {
        const log = getLog(shared.master);
        const { melonContracts } = shared.master.deployment;
        const manager = yield withNewAccount_1.withNewAccount(shared.master);
        const trader = yield withNewAccount_1.withNewAccount(shared.master);
        const amguPrice = token_math_1.createQuantity('MLN', '1000000000');
        yield setAmguPrice_1.setAmguPrice(shared.master, melonContracts.engine, amguPrice);
        yield updateKyber_1.updateKyber(shared.master, melonContracts.priceSource);
        const weth = getTokenBySymbol_1.getTokenBySymbol(manager, 'WETH');
        const mln = getTokenBySymbol_1.getTokenBySymbol(manager, 'MLN');
        const dgx = getTokenBySymbol_1.getTokenBySymbol(manager, 'DGX');
        const dai = getTokenBySymbol_1.getTokenBySymbol(manager, 'DAI');
        try {
            const mlnPrice = yield getPrice_1.getPrice(shared.master, melonContracts.priceSource.toString(), mln);
            log.debug('MLN Price', mlnPrice);
        }
        catch (e) {
            throw new Error('Cannot get MLN Price from Kyber');
        }
        yield sendEth_1.sendEth(shared.master, {
            howMuch: token_math_1.createQuantity('ETH', 2),
            to: manager.wallet.address,
        });
        yield sendEth_1.sendEth(shared.master, {
            howMuch: token_math_1.createQuantity('ETH', 1),
            to: trader.wallet.address,
        });
        yield transfer_1.transfer(shared.master, {
            howMuch: token_math_1.createQuantity(mln, 5),
            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 assetBlacklist = yield deployContract_1.deployContract(shared.master, Contracts_1.Contracts.AssetBlacklist, [[dgx.address]]);
        const maxPositions = yield deployContract_1.deployContract(shared.master, Contracts_1.Contracts.MaxPositions, [
            2,
        ]);
        const maxConcentration = yield deployContract_1.deployContract(shared.master, Contracts_1.Contracts.MaxConcentration, ['100000000000000000']);
        const userWhitelist = yield deployContract_1.deployContract(shared.master, Contracts_1.Contracts.UserWhitelist, [
            [shared.investor.wallet.address],
        ]);
        const routes = yield setupInvestedTestFund_1.setupInvestedTestFund(manager);
        yield register_1.register(manager, routes.policyManagerAddress, [
            {
                method: FunctionSignatures_1.FunctionSignatures.makeOrder,
                policy: shared.master.deployment.melonContracts.policies.priceTolerance,
            },
            {
                method: FunctionSignatures_1.FunctionSignatures.takeOrder,
                policy: shared.master.deployment.melonContracts.policies.priceTolerance,
            },
            {
                method: FunctionSignatures_1.FunctionSignatures.makeOrder,
                policy: assetBlacklist,
            },
            {
                method: FunctionSignatures_1.FunctionSignatures.takeOrder,
                policy: assetBlacklist,
            },
            {
                method: FunctionSignatures_1.FunctionSignatures.makeOrder,
                policy: maxPositions,
            },
            {
                method: FunctionSignatures_1.FunctionSignatures.takeOrder,
                policy: maxPositions,
            },
            {
                method: FunctionSignatures_1.FunctionSignatures.makeOrder,
                policy: maxConcentration,
            },
            {
                method: FunctionSignatures_1.FunctionSignatures.takeOrder,
                policy: maxConcentration,
            },
            {
                method: FunctionSignatures_1.FunctionSignatures.requestInvestment,
                policy: userWhitelist,
            },
        ]);
        const policyInformation = yield getPolicyInformation_1.getPolicyInformation(manager, routes.policyManagerAddress);
        yield expect(policyInformation.filter(p => p.name === 'Price tolerance')[0].parameters).toBe('10%');
        yield expect(policyInformation.filter(p => p.name === 'Asset blacklist')[0].parameters).toBe('DGX');
        yield expect(policyInformation.filter(p => p.name === 'Max positions')[0].parameters).toBe('2');
        yield expect(policyInformation.filter(p => p.name === 'Max concentration')[0]
            .parameters).toBe('10%');
        yield expect(makeOasisDexOrder_1.makeOasisDexOrder(manager, routes.tradingAddress, {
            makerQuantity: token_math_1.createQuantity(weth, 0.5),
            takerQuantity: token_math_1.createQuantity(mln, 0.8),
        })).rejects.toThrow();
        yield expect(makeOasisDexOrder_1.makeOasisDexOrder(manager, routes.tradingAddress, {
            makerQuantity: token_math_1.createQuantity(weth, 0.5),
            takerQuantity: token_math_1.createQuantity(dgx, 100),
        })).rejects.toThrow();
        // await takeOasisDexOrder(manager, routes.tradingAddress, {
        //   id: orderFromTrader.id,
        //   maker: orderFromTrader.maker,
        //   makerQuantity: orderFromTrader.sell,
        //   takerQuantity: orderFromTrader.buy,
        // });
        yield expect(makeOasisDexOrder_1.makeOasisDexOrder(manager, routes.tradingAddress, {
            makerQuantity: token_math_1.createQuantity(weth, 0.5),
            takerQuantity: token_math_1.createQuantity(dai, 100),
        })).rejects.toThrow();
        const wethBalance = yield balanceOf_1.balanceOf(manager, weth.address, {
            address: routes.vaultAddress,
        });
        const mlnPrice = yield getPrice_1.getPrice(manager, manager.deployment.melonContracts.priceSource.toString(), mln);
        const ethPriceInMln = token_math_1.createPrice(mlnPrice.quote, mlnPrice.base);
        const mlnEquivalent = token_math_1.valueIn(ethPriceInMln, wethBalance);
        const makerQuantity = mlnEquivalent;
        yield expect(takeOrderOnKyber_1.takeOrderOnKyber(manager, routes.tradingAddress, {
            makerQuantity,
            takerQuantity: wethBalance,
        })).rejects.toThrow();
    }));
    test('Happy path: Fund 2', () => __awaiter(this, void 0, void 0, function* () {
        const manager = yield withNewAccount_1.withNewAccount(shared.master);
        const mln = getTokenBySymbol_1.getTokenBySymbol(manager, 'MLN');
        const dgx = getTokenBySymbol_1.getTokenBySymbol(manager, 'DGX');
        const weth = getTokenBySymbol_1.getTokenBySymbol(manager, 'WETH');
        yield sendEth_1.sendEth(shared.master, {
            howMuch: token_math_1.createQuantity('ETH', 2),
            to: manager.wallet.address,
        });
        const quantity = token_math_1.createQuantity(weth, 1);
        yield deposit_1.deposit(manager, quantity.token.address, undefined, {
            value: quantity.quantity.toString(),
        });
        const routes = yield setupInvestedTestFund_1.setupInvestedTestFund(manager);
        const assetWhitelist = yield deployContract_1.deployContract(shared.master, Contracts_1.Contracts.AssetWhitelist, [[mln.address]]);
        yield register_1.register(manager, routes.policyManagerAddress, [
            {
                method: FunctionSignatures_1.FunctionSignatures.makeOrder,
                policy: assetWhitelist,
            },
            {
                method: FunctionSignatures_1.FunctionSignatures.takeOrder,
                policy: assetWhitelist,
            },
            {
                method: FunctionSignatures_1.FunctionSignatures.requestInvestment,
                policy: assetWhitelist,
            },
        ]);
        yield expect(makeOasisDexOrder_1.makeOasisDexOrder(manager, routes.tradingAddress, {
            makerQuantity: token_math_1.createQuantity(weth, 0.5),
            takerQuantity: token_math_1.createQuantity(dgx, 100),
        })).rejects.toThrow();
        const investmentAmount = token_math_1.createQuantity(weth, 1);
        yield approve_1.approve(shared.investor, {
            howMuch: investmentAmount,
            spender: routes.participationAddress,
        });
        const fundToken = yield getToken_1.getToken(manager, routes.sharesAddress);
        yield expect(requestInvestment_1.requestInvestment(shared.investor, routes.participationAddress, {
            investmentAmount,
            requestedShares: token_math_1.createQuantity(fundToken, 1),
        })).rejects.toThrow();
    }));
});
