"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    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) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const types_1 = require("../../../polkadot/types");
const sinon_1 = __importDefault(require("sinon"));
const investInSto_1 = require("../investInSto");
const mocks_1 = require("../../../testUtils/mocks");
const types_2 = require("../../../types");
const utilsConversionModule = __importStar(require("../../../utils/conversion"));
jest.mock('~/api/entities/Sto', require("../../../testUtils/mocks/entities").mockStoModule('~/api/entities/Sto'));
jest.mock('~/api/entities/DefaultPortfolio', require("../../../testUtils/mocks/entities").mockDefaultPortfolioModule('~/api/entities/DefaultPortfolio'));
describe('investInSto procedure', () => {
    let mockContext;
    let stringToTickerStub;
    let portfolioIdToMeshPortfolioIdStub;
    let portfolioLikeToPortfolioIdStub;
    let numberToU64Stub;
    let numberToBalanceStub;
    let addTransactionStub;
    let id;
    let ticker;
    let purchasePortfolio;
    let purchasePortfolioId;
    let fundingPortfolio;
    let fundingPortfolioId;
    let purchaseAmount;
    let maxPrice;
    let rawId;
    let rawTicker;
    let rawPurchasePortfolio;
    let rawFundingPortfolio;
    let rawPurchaseAmount;
    let rawMaxPrice;
    let args;
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks();
        mocks_1.procedureMockUtils.initMocks();
        mocks_1.entityMockUtils.initMocks();
        stringToTickerStub = sinon_1.default.stub(utilsConversionModule, 'stringToTicker');
        portfolioIdToMeshPortfolioIdStub = sinon_1.default.stub(utilsConversionModule, 'portfolioIdToMeshPortfolioId');
        portfolioLikeToPortfolioIdStub = sinon_1.default.stub(utilsConversionModule, 'portfolioLikeToPortfolioId');
        numberToU64Stub = sinon_1.default.stub(utilsConversionModule, 'numberToU64');
        numberToBalanceStub = sinon_1.default.stub(utilsConversionModule, 'numberToBalance');
        id = new bignumber_js_1.default(id);
        rawId = mocks_1.dsMockUtils.createMockU64(id.toNumber());
        ticker = 'tickerFrozen';
        rawTicker = mocks_1.dsMockUtils.createMockTicker(ticker);
        purchasePortfolio = 'purchasePortfolioDid';
        fundingPortfolio = 'fundingPortfolioDid';
        purchasePortfolioId = { did: purchasePortfolio };
        fundingPortfolioId = { did: fundingPortfolio };
        purchaseAmount = new bignumber_js_1.default(50);
        maxPrice = new bignumber_js_1.default(1);
        rawPurchasePortfolio = mocks_1.dsMockUtils.createMockPortfolioId({
            did: mocks_1.dsMockUtils.createMockIdentityId(purchasePortfolio),
            kind: mocks_1.dsMockUtils.createMockPortfolioKind('Default'),
        });
        rawFundingPortfolio = mocks_1.dsMockUtils.createMockPortfolioId({
            did: mocks_1.dsMockUtils.createMockIdentityId(fundingPortfolio),
            kind: mocks_1.dsMockUtils.createMockPortfolioKind('Default'),
        });
        rawPurchaseAmount = mocks_1.dsMockUtils.createMockBalance(purchaseAmount.toNumber());
        rawMaxPrice = mocks_1.dsMockUtils.createMockBalance(maxPrice.toNumber());
    });
    beforeEach(() => {
        addTransactionStub = mocks_1.procedureMockUtils.getAddTransactionStub();
        mockContext = mocks_1.dsMockUtils.getContextInstance();
        stringToTickerStub.withArgs(ticker, mockContext).returns(rawTicker);
        portfolioLikeToPortfolioIdStub.withArgs(purchasePortfolio).returns(purchasePortfolioId);
        portfolioIdToMeshPortfolioIdStub
            .withArgs(purchasePortfolioId, mockContext)
            .returns(rawPurchasePortfolio);
        portfolioLikeToPortfolioIdStub.withArgs(fundingPortfolio).returns(fundingPortfolioId);
        portfolioIdToMeshPortfolioIdStub
            .withArgs(fundingPortfolioId, mockContext)
            .returns(rawFundingPortfolio);
        numberToU64Stub.withArgs(id, mockContext).returns(rawId);
        numberToBalanceStub.withArgs(purchaseAmount, mockContext).returns(rawPurchaseAmount);
        numberToBalanceStub.withArgs(maxPrice, mockContext).returns(rawMaxPrice);
        args = {
            id,
            ticker,
            purchasePortfolio,
            fundingPortfolio,
            purchaseAmount,
        };
    });
    afterEach(() => {
        mocks_1.entityMockUtils.reset();
        mocks_1.procedureMockUtils.reset();
        mocks_1.dsMockUtils.reset();
    });
    afterAll(() => {
        mocks_1.entityMockUtils.cleanup();
        mocks_1.procedureMockUtils.cleanup();
        mocks_1.dsMockUtils.cleanup();
    });
    test('should throw an error if the STO is not accepting investments', () => {
        mocks_1.entityMockUtils.configureMocks({
            stoOptions: {
                details: {
                    status: {
                        sale: types_2.StoSaleStatus.Frozen,
                        timing: types_2.StoTimingStatus.Started,
                        balance: types_2.StoBalanceStatus.Available,
                    },
                },
            },
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            purchasePortfolioId,
            fundingPortfolioId,
        });
        return expect(investInSto_1.prepareInvestInSto.call(proc, args)).rejects.toThrow('The STO is not accepting investments at the moment');
    });
    test('should throw an error if the minimum investment is not reached', () => __awaiter(void 0, void 0, void 0, function* () {
        mocks_1.entityMockUtils.configureMocks({
            stoOptions: {
                details: {
                    status: {
                        sale: types_2.StoSaleStatus.Live,
                        timing: types_2.StoTimingStatus.Started,
                        balance: types_2.StoBalanceStatus.Available,
                    },
                    end: new Date('12/12/2030'),
                    minInvestment: new bignumber_js_1.default(10),
                    tiers: [
                        {
                            remaining: new bignumber_js_1.default(0),
                            amount: new bignumber_js_1.default(100),
                            price: new bignumber_js_1.default(1),
                        },
                    ],
                },
            },
            defaultPortfolioOptions: {
                tokenBalances: [{ free: new bignumber_js_1.default(20) }],
            },
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            purchasePortfolioId,
            fundingPortfolioId,
        });
        let error;
        try {
            yield investInSto_1.prepareInvestInSto.call(proc, args);
        }
        catch (err) {
            error = err;
        }
        expect(error.message).toBe('Minimum investment not reached');
        expect(error.data.priceTotal).toEqual(new bignumber_js_1.default(0));
    }));
    test("should throw an error if the funding Portfolio doesn't have enough balance to purchase the tokens", () => __awaiter(void 0, void 0, void 0, function* () {
        mocks_1.entityMockUtils.configureMocks({
            stoOptions: {
                details: {
                    status: {
                        sale: types_2.StoSaleStatus.Live,
                        timing: types_2.StoTimingStatus.Started,
                        balance: types_2.StoBalanceStatus.Available,
                    },
                    end: new Date('12/12/2030'),
                    minInvestment: new bignumber_js_1.default(25),
                    tiers: [
                        {
                            remaining: new bignumber_js_1.default(50),
                            amount: new bignumber_js_1.default(100),
                            price: new bignumber_js_1.default(1),
                        },
                    ],
                },
            },
            defaultPortfolioOptions: {
                tokenBalances: [{ free: new bignumber_js_1.default(1) }],
            },
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            purchasePortfolioId,
            fundingPortfolioId,
        });
        let error;
        try {
            yield investInSto_1.prepareInvestInSto.call(proc, args);
        }
        catch (err) {
            error = err;
        }
        expect(error.message).toBe('The Portfolio does not have enough free balance for this investment');
        expect(error.data.free).toEqual(new bignumber_js_1.default(1));
        expect(error.data.priceTotal).toEqual(new bignumber_js_1.default(50));
    }));
    test('should throw an error if the STO does not have enough remaining tokens', () => __awaiter(void 0, void 0, void 0, function* () {
        mocks_1.entityMockUtils.configureMocks({
            stoOptions: {
                details: {
                    status: {
                        sale: types_2.StoSaleStatus.Live,
                        timing: types_2.StoTimingStatus.Started,
                        balance: types_2.StoBalanceStatus.Available,
                    },
                    end: new Date('12/12/2030'),
                    minInvestment: new bignumber_js_1.default(10),
                    tiers: [
                        {
                            remaining: new bignumber_js_1.default(10),
                            amount: new bignumber_js_1.default(100),
                            price: new bignumber_js_1.default(1),
                        },
                        {
                            remaining: new bignumber_js_1.default(30),
                            amount: new bignumber_js_1.default(100),
                            price: new bignumber_js_1.default(2),
                        },
                    ],
                },
            },
            defaultPortfolioOptions: {
                tokenBalances: [{ free: new bignumber_js_1.default(200) }],
            },
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            purchasePortfolioId,
            fundingPortfolioId,
        });
        yield expect(investInSto_1.prepareInvestInSto.call(proc, args)).rejects.toThrow('The STO does not have enough remaining tokens');
        return expect(investInSto_1.prepareInvestInSto.call(proc, Object.assign(Object.assign({}, args), { maxPrice }))).rejects.toThrow('The STO does not have enough remaining tokens below the stipulated max price');
    }));
    test('should add an invest transaction to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        mocks_1.entityMockUtils.configureMocks({
            stoOptions: {
                details: {
                    status: {
                        sale: types_2.StoSaleStatus.Live,
                        timing: types_2.StoTimingStatus.Started,
                        balance: types_2.StoBalanceStatus.Available,
                    },
                    end: new Date('12/12/2030'),
                    minInvestment: new bignumber_js_1.default(10),
                    tiers: [
                        {
                            remaining: new bignumber_js_1.default(100),
                            amount: new bignumber_js_1.default(100),
                            price: new bignumber_js_1.default(1),
                        },
                        {
                            remaining: new bignumber_js_1.default(100),
                            amount: new bignumber_js_1.default(100),
                            price: new bignumber_js_1.default(2),
                        },
                        {
                            remaining: new bignumber_js_1.default(200),
                            amount: new bignumber_js_1.default(200),
                            price: new bignumber_js_1.default(20),
                        },
                    ],
                },
            },
            defaultPortfolioOptions: {
                tokenBalances: [{ free: new bignumber_js_1.default(200) }],
            },
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            purchasePortfolioId,
            fundingPortfolioId,
        });
        const transaction = mocks_1.dsMockUtils.createTxStub('sto', 'invest');
        yield investInSto_1.prepareInvestInSto.call(proc, args);
        sinon_1.default.assert.calledWith(addTransactionStub, transaction, {}, rawPurchasePortfolio, rawFundingPortfolio, rawTicker, rawId, rawPurchaseAmount, null, null);
        yield investInSto_1.prepareInvestInSto.call(proc, Object.assign(Object.assign({}, args), { maxPrice }));
        sinon_1.default.assert.calledWith(addTransactionStub, transaction, {}, rawPurchasePortfolio, rawFundingPortfolio, rawTicker, rawId, rawPurchaseAmount, rawMaxPrice, null);
    }));
    describe('getAuthorization', () => {
        test('should return the appropriate roles and permissions', () => {
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
                purchasePortfolioId,
                fundingPortfolioId,
            });
            const boundFunc = investInSto_1.getAuthorization.bind(proc);
            const portfolioIdToPortfolioStub = sinon_1.default.stub(utilsConversionModule, 'portfolioIdToPortfolio');
            const portfolios = [
                'investment',
                'funding',
            ];
            portfolioIdToPortfolioStub.withArgs(purchasePortfolioId, mockContext).returns(portfolios[0]);
            portfolioIdToPortfolioStub.withArgs(fundingPortfolioId, mockContext).returns(portfolios[1]);
            const roles = [
                { type: types_2.RoleType.PortfolioCustodian, portfolioId: purchasePortfolioId },
                { type: types_2.RoleType.PortfolioCustodian, portfolioId: fundingPortfolioId },
            ];
            expect(boundFunc()).toEqual({
                roles,
                permissions: {
                    transactions: [types_1.TxTags.sto.Invest],
                    tokens: [],
                    portfolios,
                },
            });
        });
    });
    describe('prepareStorage', () => {
        test('should return the investment and funding portfolio ids', () => {
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
            const boundFunc = investInSto_1.prepareStorage.bind(proc);
            const result = boundFunc(args);
            expect(result).toEqual({
                purchasePortfolioId,
                fundingPortfolioId,
            });
        });
    });
});
//# sourceMappingURL=investInSto.js.map