"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 addInstruction_1 = require("../addInstruction");
const internal_1 = require("../../../internal");
const mocks_1 = require("../../../testUtils/mocks");
const types_2 = require("../../../types");
const utilsConversionModule = __importStar(require("../../../utils/conversion"));
const utilsInternalModule = __importStar(require("../../../utils/internal"));
jest.mock('~/api/entities/Venue', require("../../../testUtils/mocks/entities").mockVenueModule('~/api/entities/Venue'));
describe('addInstruction procedure', () => {
    let mockContext;
    let portfolioIdToMeshPortfolioIdStub;
    let portfolioLikeToPortfolioIdStub;
    let portfolioLikeToPortfolioStub;
    let getCustodianStub;
    let stringToTickerStub;
    let numberToU64Stub;
    let numberToBalanceStub;
    let endConditionToSettlementTypeStub;
    let dateToMomentStub;
    let venueId;
    let amount;
    let from;
    let to;
    let fromDid;
    let toDid;
    let fromPortfolio;
    let toPortfolio;
    let token;
    let tradeDate;
    let valueDate;
    let endBlock;
    let args;
    let venue;
    let rawVenueId;
    let rawAmount;
    let rawFrom;
    let rawTo;
    let rawToken;
    let rawTradeDate;
    let rawValueDate;
    let rawEndBlock;
    let rawAuthSettlementType;
    let rawBlockSettlementType;
    let rawLeg;
    let instruction;
    let addBatchTransactionStub;
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks({
            contextOptions: {
                balance: { free: new bignumber_js_1.default(500), locked: new bignumber_js_1.default(0), total: new bignumber_js_1.default(500) },
            },
        });
        mocks_1.procedureMockUtils.initMocks();
        mocks_1.entityMockUtils.initMocks();
        portfolioIdToMeshPortfolioIdStub = sinon_1.default.stub(utilsConversionModule, 'portfolioIdToMeshPortfolioId');
        portfolioLikeToPortfolioIdStub = sinon_1.default.stub(utilsConversionModule, 'portfolioLikeToPortfolioId');
        portfolioLikeToPortfolioStub = sinon_1.default.stub(utilsConversionModule, 'portfolioLikeToPortfolio');
        getCustodianStub = mocks_1.entityMockUtils.getNumberedPortfolioGetCustodianStub();
        stringToTickerStub = sinon_1.default.stub(utilsConversionModule, 'stringToTicker');
        numberToU64Stub = sinon_1.default.stub(utilsConversionModule, 'numberToU64');
        numberToBalanceStub = sinon_1.default.stub(utilsConversionModule, 'numberToBalance');
        endConditionToSettlementTypeStub = sinon_1.default.stub(utilsConversionModule, 'endConditionToSettlementType');
        dateToMomentStub = sinon_1.default.stub(utilsConversionModule, 'dateToMoment');
        venueId = new bignumber_js_1.default(1);
        amount = new bignumber_js_1.default(100);
        from = 'fromDid';
        to = 'toDid';
        fromDid = 'fromDid';
        toDid = 'toDid';
        fromPortfolio = mocks_1.entityMockUtils.getNumberedPortfolioInstance({
            did: fromDid,
            id: new bignumber_js_1.default(1),
        });
        toPortfolio = mocks_1.entityMockUtils.getNumberedPortfolioInstance({
            did: toDid,
            id: new bignumber_js_1.default(2),
        });
        token = 'SOME_TOKEN';
        const now = new Date();
        tradeDate = new Date(now.getTime() + 24 * 60 * 60 * 1000);
        valueDate = new Date(now.getTime() + 24 * 60 * 60 * 1000 + 1);
        endBlock = new bignumber_js_1.default(1000);
        rawVenueId = mocks_1.dsMockUtils.createMockU64(venueId.toNumber());
        rawAmount = mocks_1.dsMockUtils.createMockBalance(amount.toNumber());
        rawFrom = mocks_1.dsMockUtils.createMockPortfolioId({
            did: mocks_1.dsMockUtils.createMockIdentityId(from),
            kind: mocks_1.dsMockUtils.createMockPortfolioKind('Default'),
        });
        rawTo = mocks_1.dsMockUtils.createMockPortfolioId({
            did: mocks_1.dsMockUtils.createMockIdentityId(to),
            kind: mocks_1.dsMockUtils.createMockPortfolioKind('Default'),
        });
        rawToken = mocks_1.dsMockUtils.createMockTicker(token);
        rawTradeDate = mocks_1.dsMockUtils.createMockMoment(tradeDate.getTime());
        rawValueDate = mocks_1.dsMockUtils.createMockMoment(valueDate.getTime());
        rawEndBlock = mocks_1.dsMockUtils.createMockU32(endBlock.toNumber());
        rawAuthSettlementType = mocks_1.dsMockUtils.createMockSettlementType('SettleOnAffirmation');
        rawBlockSettlementType = mocks_1.dsMockUtils.createMockSettlementType({ SettleOnBlock: rawEndBlock });
        rawLeg = {
            from: rawFrom,
            to: rawTo,
            amount: rawAmount,
            asset: rawToken,
        };
        instruction = ['instruction'];
    });
    let addAndAuthorizeInstructionTransaction;
    let addInstructionTransaction;
    beforeEach(() => {
        addBatchTransactionStub = mocks_1.procedureMockUtils
            .getAddBatchTransactionStub()
            .returns([instruction]);
        mocks_1.entityMockUtils.getTickerReservationDetailsStub().resolves({
            owner: mocks_1.entityMockUtils.getIdentityInstance(),
            expiryDate: null,
            status: types_2.TickerReservationStatus.Free,
        });
        addAndAuthorizeInstructionTransaction = mocks_1.dsMockUtils.createTxStub('settlement', 'addAndAffirmInstruction');
        addInstructionTransaction = mocks_1.dsMockUtils.createTxStub('settlement', 'addInstruction');
        mockContext = mocks_1.dsMockUtils.getContextInstance();
        portfolioLikeToPortfolioIdStub.withArgs(from).returns({ did: fromDid });
        portfolioLikeToPortfolioIdStub.withArgs(to).returns({ did: toDid });
        portfolioLikeToPortfolioIdStub.withArgs(fromPortfolio).returns({ did: fromDid });
        portfolioLikeToPortfolioIdStub.withArgs(toPortfolio).returns({ did: toDid });
        portfolioLikeToPortfolioStub.withArgs(from, mockContext).returns(fromPortfolio);
        portfolioLikeToPortfolioStub.withArgs(to, mockContext).returns(toPortfolio);
        portfolioIdToMeshPortfolioIdStub.withArgs({ did: fromDid }, mockContext).returns(rawFrom);
        portfolioIdToMeshPortfolioIdStub.withArgs({ did: toDid }, mockContext).returns(rawTo);
        getCustodianStub.onCall(0).returns({ did: fromDid });
        getCustodianStub.onCall(1).returns({ did: toDid });
        stringToTickerStub.withArgs(token, mockContext).returns(rawToken);
        numberToU64Stub.withArgs(venueId, mockContext).returns(rawVenueId);
        numberToBalanceStub.withArgs(amount, mockContext).returns(rawAmount);
        endConditionToSettlementTypeStub
            .withArgs({ type: types_2.InstructionType.SettleOnBlock, value: endBlock }, mockContext)
            .returns(rawBlockSettlementType);
        endConditionToSettlementTypeStub
            .withArgs({ type: types_2.InstructionType.SettleOnAffirmation }, mockContext)
            .returns(rawAuthSettlementType);
        dateToMomentStub.withArgs(tradeDate, mockContext).returns(rawTradeDate);
        dateToMomentStub.withArgs(valueDate, mockContext).returns(rawValueDate);
        venue = mocks_1.entityMockUtils.getVenueInstance({ id: venueId });
        args = {
            venue,
            instructions: [
                {
                    legs: [
                        {
                            from,
                            to,
                            token,
                            amount,
                        },
                    ],
                },
            ],
        };
    });
    afterEach(() => {
        mocks_1.entityMockUtils.reset();
        mocks_1.procedureMockUtils.reset();
        mocks_1.dsMockUtils.reset();
        sinon_1.default.reset();
    });
    afterAll(() => {
        mocks_1.entityMockUtils.cleanup();
        mocks_1.procedureMockUtils.cleanup();
        mocks_1.dsMockUtils.cleanup();
    });
    test('should throw an error if the legs array is empty', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            portfoliosToAffirm: [],
        });
        let error;
        try {
            yield addInstruction_1.prepareAddInstruction.call(proc, { venue, instructions: [{ legs: [] }] });
        }
        catch (err) {
            error = err;
        }
        expect(error.message).toBe("The legs array can't be empty");
        expect(error.data.failedInstructionIndexes[0]).toBe(0);
    }));
    test('should throw an error if the legs array exceeds limit', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            portfoliosToAffirm: [],
        });
        mocks_1.entityMockUtils.configureMocks({
            venueOptions: {
                exists: true,
            },
        });
        let error;
        const legs = Array(11).fill({
            from,
            to,
            amount,
            token: mocks_1.entityMockUtils.getSecurityTokenInstance({ ticker: token }),
        });
        try {
            yield addInstruction_1.prepareAddInstruction.call(proc, { venue, instructions: [{ legs }] });
        }
        catch (err) {
            error = err;
        }
        expect(error.message).toBe('The legs array exceeds the maximum allowed length');
    }));
    test('should throw an error if the end block is in the past', () => __awaiter(void 0, void 0, void 0, function* () {
        mocks_1.dsMockUtils.configureMocks({ contextOptions: { latestBlock: new bignumber_js_1.default(1000) } });
        mocks_1.entityMockUtils.configureMocks({
            venueOptions: {
                exists: true,
            },
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            portfoliosToAffirm: [],
        });
        let error;
        try {
            yield addInstruction_1.prepareAddInstruction.call(proc, {
                venue,
                instructions: [
                    {
                        legs: [
                            {
                                from,
                                to,
                                amount,
                                token: mocks_1.entityMockUtils.getSecurityTokenInstance({ ticker: token }),
                            },
                        ],
                        endBlock: new bignumber_js_1.default(100),
                    },
                ],
            });
        }
        catch (err) {
            error = err;
        }
        expect(error.message).toBe('End block must be a future block');
        expect(error.data.failedInstructionIndexes[0]).toBe(0);
    }));
    test('should throw an error if the value date is before the trade date', () => __awaiter(void 0, void 0, void 0, function* () {
        mocks_1.dsMockUtils.configureMocks({ contextOptions: { latestBlock: new bignumber_js_1.default(1000) } });
        mocks_1.entityMockUtils.configureMocks({
            venueOptions: {
                exists: true,
            },
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            portfoliosToAffirm: [],
        });
        let error;
        try {
            yield addInstruction_1.prepareAddInstruction.call(proc, {
                venue,
                instructions: [
                    {
                        legs: [
                            {
                                from,
                                to,
                                token,
                                amount,
                            },
                        ],
                        tradeDate: new Date(valueDate.getTime() + 1),
                        valueDate,
                    },
                ],
            });
        }
        catch (err) {
            error = err;
        }
        expect(error.message).toBe('Value date must be after trade date');
        expect(error.data.failedInstructionIndexes[0]).toBe(0);
    }));
    test('should add an add and authorize instruction transaction to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        mocks_1.dsMockUtils.configureMocks({ contextOptions: { did: fromDid } });
        mocks_1.entityMockUtils.configureMocks({
            venueOptions: {
                exists: true,
            },
        });
        getCustodianStub.onCall(1).returns({ did: fromDid });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            portfoliosToAffirm: [[fromPortfolio, toPortfolio]],
        });
        const result = yield addInstruction_1.prepareAddInstruction.call(proc, args);
        sinon_1.default.assert.calledWith(addBatchTransactionStub, addAndAuthorizeInstructionTransaction, sinon_1.default.match({
            resolvers: sinon_1.default.match.array,
        }), [[rawVenueId, rawAuthSettlementType, null, null, [rawLeg], [rawFrom, rawTo]]]);
        expect(result).toBe(instruction);
    }));
    test('should add an add instruction transaction to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        mocks_1.dsMockUtils.configureMocks({ contextOptions: { did: fromDid } });
        mocks_1.entityMockUtils.configureMocks({
            venueOptions: {
                exists: true,
            },
        });
        getCustodianStub.onCall(0).returns({ did: toDid });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            portfoliosToAffirm: [[]],
        });
        const result = yield addInstruction_1.prepareAddInstruction.call(proc, {
            venue,
            instructions: [
                {
                    legs: [
                        {
                            from,
                            to,
                            amount,
                            token: mocks_1.entityMockUtils.getSecurityTokenInstance({ ticker: token }),
                        },
                    ],
                    tradeDate,
                    valueDate,
                    endBlock,
                },
            ],
        });
        sinon_1.default.assert.calledWith(addBatchTransactionStub, addInstructionTransaction, sinon_1.default.match({
            resolvers: sinon_1.default.match.array,
        }), [[rawVenueId, rawBlockSettlementType, rawTradeDate, rawValueDate, [rawLeg]]]);
        expect(result).toBe(instruction);
    }));
    describe('getAuthorization', () => {
        test('should return the appropriate roles and permissions', () => __awaiter(void 0, void 0, void 0, function* () {
            let proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
                portfoliosToAffirm: [[fromPortfolio, toPortfolio]],
            });
            let boundFunc = addInstruction_1.getAuthorization.bind(proc);
            let result = yield boundFunc({
                venue,
                instructions: [
                    { legs: [{ from: fromPortfolio, to: toPortfolio, amount, token: 'SOME_TOKEN' }] },
                ],
            });
            expect(result).toEqual({
                roles: [{ type: types_2.RoleType.VenueOwner, venueId }],
                permissions: {
                    tokens: [],
                    portfolios: [fromPortfolio, toPortfolio],
                    transactions: [types_1.TxTags.settlement.AddAndAffirmInstruction],
                },
            });
            proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
                portfoliosToAffirm: [[]],
            });
            boundFunc = addInstruction_1.getAuthorization.bind(proc);
            result = yield boundFunc({
                venue,
                instructions: [
                    { legs: [{ from: fromPortfolio, to: toPortfolio, amount, token: 'SOME_TOKEN' }] },
                ],
            });
            expect(result).toEqual({
                roles: [{ type: types_2.RoleType.VenueOwner, venueId }],
                permissions: {
                    tokens: [],
                    portfolios: [],
                    transactions: [types_1.TxTags.settlement.AddInstruction],
                },
            });
        }));
    });
    describe('prepareStorage', () => {
        test('should return the list of portfolios that will be affirmed', () => __awaiter(void 0, void 0, void 0, function* () {
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
            const boundFunc = addInstruction_1.prepareStorage.bind(proc);
            fromPortfolio = mocks_1.entityMockUtils.getNumberedPortfolioInstance({ isCustodiedBy: true });
            toPortfolio = mocks_1.entityMockUtils.getNumberedPortfolioInstance({ isCustodiedBy: true });
            portfolioLikeToPortfolioStub.withArgs(from, mockContext).returns(fromPortfolio);
            portfolioLikeToPortfolioStub.withArgs(to, mockContext).returns(toPortfolio);
            let result = yield boundFunc(args);
            expect(result).toEqual({
                portfoliosToAffirm: [[fromPortfolio, toPortfolio]],
            });
            fromPortfolio = mocks_1.entityMockUtils.getNumberedPortfolioInstance({ isCustodiedBy: false });
            toPortfolio = mocks_1.entityMockUtils.getNumberedPortfolioInstance({ isCustodiedBy: false });
            portfolioLikeToPortfolioStub.withArgs(from, mockContext).returns(fromPortfolio);
            portfolioLikeToPortfolioStub.withArgs(to, mockContext).returns(toPortfolio);
            result = yield boundFunc(args);
            expect(result).toEqual({
                portfoliosToAffirm: [[]],
            });
        }));
    });
});
describe('createAddInstructionResolver', () => {
    const filterEventRecordsStub = sinon_1.default.stub(utilsInternalModule, 'filterEventRecords');
    const id = new bignumber_js_1.default(10);
    const rawId = mocks_1.dsMockUtils.createMockU64(id.toNumber());
    beforeAll(() => {
        mocks_1.entityMockUtils.initMocks({
            instructionOptions: {
                id,
            },
        });
    });
    beforeEach(() => {
        filterEventRecordsStub.returns([mocks_1.dsMockUtils.createMockIEvent(['did', 'venueId', rawId])]);
    });
    afterEach(() => {
        filterEventRecordsStub.reset();
    });
    test('should return the new Instruction', () => {
        const fakeContext = {};
        const result = addInstruction_1.createAddInstructionResolver(fakeContext)({});
        expect(result[0].id).toEqual(id);
    });
    test('should return a list of new Instructions', () => {
        const fakeContext = {};
        const previousInstructionId = new bignumber_js_1.default(2);
        const previousInstructions = {
            value: [new internal_1.Instruction({ id: previousInstructionId }, fakeContext)],
        };
        const result = addInstruction_1.createAddInstructionResolver(fakeContext, previousInstructions)({});
        expect(result.length).toEqual(2);
        expect(result[0].id).toEqual(previousInstructionId);
        expect(result[1].id).toEqual(id);
    });
});
//# sourceMappingURL=addInstruction.js.map