"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 modifyInstructionAffirmation_1 = require("../modifyInstructionAffirmation");
const procedureUtilsModule = __importStar(require("../utils"));
const mocks_1 = require("../../../testUtils/mocks");
const types_2 = require("../../../types");
const internal_1 = require("../../../types/internal");
const utilsConversionModule = __importStar(require("../../../utils/conversion"));
jest.mock('~/api/entities/Instruction', require("../../../testUtils/mocks/entities").mockInstructionModule('~/api/entities/Instruction'));
jest.mock('~/api/entities/DefaultPortfolio', require("../../../testUtils/mocks/entities").mockDefaultPortfolioModule('~/api/entities/DefaultPortfolio'));
describe('modifyInstructionAffirmation procedure', () => {
    const id = new bignumber_js_1.default(1);
    const rawInstructionId = mocks_1.dsMockUtils.createMockU64(new bignumber_js_1.default(1));
    const rawPortfolioId = mocks_1.dsMockUtils.createMockPortfolioId({
        did: mocks_1.dsMockUtils.createMockIdentityId('someDid'),
        kind: mocks_1.dsMockUtils.createMockPortfolioKind('Default'),
    });
    const did = 'someDid';
    let portfolio;
    let legAmount;
    let rawLegAmount;
    const portfolioId = { did };
    const latestBlock = new bignumber_js_1.default(100);
    let mockContext;
    let bigNumberToU64Stub;
    let bigNumberToU32Stub;
    let portfolioLikeToPortfolioIdStub;
    let portfolioIdToMeshPortfolioIdStub;
    let meshAffirmationStatusToAffirmationStatusStub;
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks({
            contextOptions: {
                latestBlock,
            },
        });
        mocks_1.procedureMockUtils.initMocks();
        mocks_1.entityMockUtils.initMocks();
        portfolio = mocks_1.entityMockUtils.getDefaultPortfolioInstance({ did: 'someDid ' });
        legAmount = new bignumber_js_1.default(2);
        bigNumberToU64Stub = sinon_1.default.stub(utilsConversionModule, 'bigNumberToU64');
        bigNumberToU32Stub = sinon_1.default.stub(utilsConversionModule, 'bigNumberToU32');
        portfolioLikeToPortfolioIdStub = sinon_1.default.stub(utilsConversionModule, 'portfolioLikeToPortfolioId');
        portfolioIdToMeshPortfolioIdStub = sinon_1.default.stub(utilsConversionModule, 'portfolioIdToMeshPortfolioId');
        meshAffirmationStatusToAffirmationStatusStub = sinon_1.default.stub(utilsConversionModule, 'meshAffirmationStatusToAffirmationStatus');
        sinon_1.default.stub(procedureUtilsModule, 'assertInstructionValid');
    });
    let addTransactionStub;
    beforeEach(() => {
        rawLegAmount = mocks_1.dsMockUtils.createMockU32(new bignumber_js_1.default(2));
        mocks_1.dsMockUtils.createTxStub('settlement', 'affirmInstruction');
        mocks_1.dsMockUtils.createTxStub('settlement', 'withdrawAffirmation');
        mocks_1.dsMockUtils.createTxStub('settlement', 'rejectInstruction');
        addTransactionStub = mocks_1.procedureMockUtils.getAddTransactionStub();
        mockContext = mocks_1.dsMockUtils.getContextInstance();
        bigNumberToU64Stub.returns(rawInstructionId);
        bigNumberToU32Stub.returns(rawLegAmount);
        portfolioLikeToPortfolioIdStub.withArgs(portfolio).returns(portfolioId);
        portfolioIdToMeshPortfolioIdStub.withArgs(portfolioId, mockContext).returns(rawPortfolioId);
    });
    afterEach(() => {
        mocks_1.entityMockUtils.reset();
        mocks_1.procedureMockUtils.reset();
        mocks_1.dsMockUtils.reset();
    });
    afterAll(() => {
        mocks_1.procedureMockUtils.cleanup();
        mocks_1.dsMockUtils.cleanup();
    });
    test('should throw an error if the current identity is not the custodian of any of the involved portfolios', () => {
        const rawAffirmationStatus = mocks_1.dsMockUtils.createMockAffirmationStatus('Affirmed');
        mocks_1.dsMockUtils.createQueryStub('settlement', 'userAffirmations', {
            multi: [rawAffirmationStatus, rawAffirmationStatus],
        });
        meshAffirmationStatusToAffirmationStatusStub
            .withArgs(rawAffirmationStatus)
            .returns(types_2.AffirmationStatus.Affirmed);
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            portfolios: [],
            senderLegAmount: legAmount,
            totalLegAmount: legAmount,
        });
        return expect(modifyInstructionAffirmation_1.prepareModifyInstructionAffirmation.call(proc, {
            id,
            operation: internal_1.InstructionAffirmationOperation.Affirm,
        })).rejects.toThrow('Current Identity is not involved in this Instruction');
    });
    test("should throw an error if the operation is Affirm and all of the current Identity's Portfolios are affirmed", () => {
        const rawAffirmationStatus = mocks_1.dsMockUtils.createMockAffirmationStatus('Affirmed');
        mocks_1.dsMockUtils.createQueryStub('settlement', 'userAffirmations', {
            multi: [rawAffirmationStatus, rawAffirmationStatus],
        });
        meshAffirmationStatusToAffirmationStatusStub
            .withArgs(rawAffirmationStatus)
            .returns(types_2.AffirmationStatus.Affirmed);
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            portfolios: [portfolio, portfolio],
            senderLegAmount: legAmount,
            totalLegAmount: legAmount,
        });
        return expect(modifyInstructionAffirmation_1.prepareModifyInstructionAffirmation.call(proc, {
            id,
            operation: internal_1.InstructionAffirmationOperation.Affirm,
        })).rejects.toThrow('The Instruction is already affirmed');
    });
    test('should add an affirm instruction transaction to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        const rawAffirmationStatus = mocks_1.dsMockUtils.createMockAffirmationStatus('Pending');
        mocks_1.dsMockUtils.createQueryStub('settlement', 'userAffirmations', {
            multi: [rawAffirmationStatus, rawAffirmationStatus],
        });
        meshAffirmationStatusToAffirmationStatusStub
            .withArgs(rawAffirmationStatus)
            .returns(types_2.AffirmationStatus.Pending);
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            portfolios: [portfolio, portfolio],
            senderLegAmount: legAmount,
            totalLegAmount: legAmount,
        });
        const transaction = mocks_1.dsMockUtils.createTxStub('settlement', 'affirmInstruction');
        const result = yield modifyInstructionAffirmation_1.prepareModifyInstructionAffirmation.call(proc, {
            id,
            operation: internal_1.InstructionAffirmationOperation.Affirm,
        });
        sinon_1.default.assert.calledWith(addTransactionStub, {
            transaction,
            feeMultiplier: new bignumber_js_1.default(2),
            args: [rawInstructionId, [rawPortfolioId, rawPortfolioId], rawLegAmount],
        });
        expect(result.id).toEqual(id);
    }));
    test('should throw an error if operation is Withdraw and the current status of the instruction is pending', () => {
        const rawAffirmationStatus = mocks_1.dsMockUtils.createMockAffirmationStatus('Pending');
        mocks_1.dsMockUtils.createQueryStub('settlement', 'userAffirmations', {
            multi: [rawAffirmationStatus, rawAffirmationStatus],
        });
        meshAffirmationStatusToAffirmationStatusStub
            .withArgs(rawAffirmationStatus)
            .returns(types_2.AffirmationStatus.Pending);
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            portfolios: [portfolio, portfolio],
            senderLegAmount: legAmount,
            totalLegAmount: legAmount,
        });
        return expect(modifyInstructionAffirmation_1.prepareModifyInstructionAffirmation.call(proc, {
            id,
            operation: internal_1.InstructionAffirmationOperation.Withdraw,
        })).rejects.toThrow('The instruction is not affirmed');
    });
    test('should add a withdraw instruction transaction to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        const rawAffirmationStatus = mocks_1.dsMockUtils.createMockAffirmationStatus('Affirmed');
        mocks_1.dsMockUtils.createQueryStub('settlement', 'userAffirmations', {
            multi: [rawAffirmationStatus, rawAffirmationStatus],
        });
        meshAffirmationStatusToAffirmationStatusStub
            .withArgs(rawAffirmationStatus)
            .returns(types_2.AffirmationStatus.Affirmed);
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            portfolios: [portfolio, portfolio],
            senderLegAmount: legAmount,
            totalLegAmount: legAmount,
        });
        const transaction = mocks_1.dsMockUtils.createTxStub('settlement', 'withdrawAffirmation');
        const result = yield modifyInstructionAffirmation_1.prepareModifyInstructionAffirmation.call(proc, {
            id,
            operation: internal_1.InstructionAffirmationOperation.Withdraw,
        });
        sinon_1.default.assert.calledWith(addTransactionStub, {
            transaction,
            feeMultiplier: new bignumber_js_1.default(2),
            args: [rawInstructionId, [rawPortfolioId, rawPortfolioId], rawLegAmount],
        });
        expect(result.id).toEqual(id);
    }));
    test('should add a reject instruction transaction to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        const rawAffirmationStatus = mocks_1.dsMockUtils.createMockAffirmationStatus('Pending');
        mocks_1.dsMockUtils.createQueryStub('settlement', 'userAffirmations', {
            multi: [rawAffirmationStatus, rawAffirmationStatus],
        });
        meshAffirmationStatusToAffirmationStatusStub
            .withArgs(rawAffirmationStatus)
            .returns(types_2.AffirmationStatus.Pending);
        const isCustodiedByStub = sinon_1.default.stub();
        isCustodiedByStub.onCall(0).returns(true);
        isCustodiedByStub.onCall(1).returns(true);
        isCustodiedByStub.onCall(2).returns(false);
        isCustodiedByStub.onCall(3).returns(false);
        mocks_1.entityMockUtils.configureMocks({
            defaultPortfolioOptions: {
                isCustodiedBy: isCustodiedByStub,
            },
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            portfolios: [portfolio, portfolio],
            senderLegAmount: legAmount,
            totalLegAmount: legAmount,
        });
        const transaction = mocks_1.dsMockUtils.createTxStub('settlement', 'rejectInstruction');
        const result = yield modifyInstructionAffirmation_1.prepareModifyInstructionAffirmation.call(proc, {
            id,
            operation: internal_1.InstructionAffirmationOperation.Reject,
        });
        sinon_1.default.assert.calledWith(addTransactionStub, {
            transaction,
            feeMultiplier: new bignumber_js_1.default(2),
            args: [rawInstructionId, rawPortfolioId, rawLegAmount],
        });
        expect(result.id).toEqual(id);
    }));
    describe('getAuthorization', () => {
        test('should return the appropriate roles and permissions', () => __awaiter(void 0, void 0, void 0, function* () {
            const args = {
                id: new bignumber_js_1.default(1),
                operation: internal_1.InstructionAffirmationOperation.Affirm,
            };
            const from = mocks_1.entityMockUtils.getNumberedPortfolioInstance();
            const to = mocks_1.entityMockUtils.getDefaultPortfolioInstance();
            let proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
                portfolios: [from, to],
                senderLegAmount: legAmount,
                totalLegAmount: legAmount,
            });
            let boundFunc = modifyInstructionAffirmation_1.getAuthorization.bind(proc);
            let result = yield boundFunc(args);
            expect(result).toEqual({
                permissions: {
                    assets: [],
                    portfolios: [from, to],
                    transactions: [types_1.TxTags.settlement.AffirmInstruction],
                },
            });
            proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
                portfolios: [],
                senderLegAmount: legAmount,
                totalLegAmount: legAmount,
            });
            boundFunc = modifyInstructionAffirmation_1.getAuthorization.bind(proc);
            result = yield boundFunc(Object.assign(Object.assign({}, args), { operation: internal_1.InstructionAffirmationOperation.Reject }));
            expect(result).toEqual({
                permissions: {
                    assets: [],
                    portfolios: [],
                    transactions: [types_1.TxTags.settlement.RejectInstruction],
                },
            });
            result = yield boundFunc(Object.assign(Object.assign({}, args), { operation: internal_1.InstructionAffirmationOperation.Withdraw }));
            expect(result).toEqual({
                permissions: {
                    assets: [],
                    portfolios: [],
                    transactions: [types_1.TxTags.settlement.WithdrawAffirmation],
                },
            });
        }));
    });
    describe('prepareStorage', () => {
        test('should return the portfolios for which to modify affirmation status', () => __awaiter(void 0, void 0, void 0, function* () {
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
            const boundFunc = modifyInstructionAffirmation_1.prepareStorage.bind(proc);
            const fromDid = 'fromDid';
            const toDid = 'toDid';
            let from = mocks_1.entityMockUtils.getDefaultPortfolioInstance({ did: fromDid, isCustodiedBy: true });
            let to = mocks_1.entityMockUtils.getDefaultPortfolioInstance({ did: toDid, isCustodiedBy: true });
            const amount = new bignumber_js_1.default(1);
            const asset = mocks_1.entityMockUtils.getAssetInstance({ ticker: 'SOME_ASSET' });
            mocks_1.entityMockUtils.configureMocks({
                instructionOptions: {
                    getLegs: { data: [{ from, to, amount, asset }], next: null },
                },
            });
            let result = yield boundFunc({
                id: new bignumber_js_1.default(1),
                operation: internal_1.InstructionAffirmationOperation.Affirm,
            });
            expect(result).toEqual({
                portfolios: [
                    expect.objectContaining({ owner: expect.objectContaining({ did: fromDid }) }),
                    expect.objectContaining({ owner: expect.objectContaining({ did: toDid }) }),
                ],
                senderLegAmount: new bignumber_js_1.default(1),
                totalLegAmount: new bignumber_js_1.default(1),
            });
            from = mocks_1.entityMockUtils.getDefaultPortfolioInstance({ did: fromDid, isCustodiedBy: false });
            to = mocks_1.entityMockUtils.getDefaultPortfolioInstance({ did: toDid, isCustodiedBy: false });
            mocks_1.entityMockUtils.configureMocks({
                instructionOptions: {
                    getLegs: { data: [{ from, to, amount, asset }], next: null },
                },
            });
            result = yield boundFunc({
                id: new bignumber_js_1.default(1),
                operation: internal_1.InstructionAffirmationOperation.Affirm,
            });
            expect(result).toEqual({
                portfolios: [],
                senderLegAmount: new bignumber_js_1.default(0),
                totalLegAmount: new bignumber_js_1.default(1),
            });
        }));
    });
});
//# sourceMappingURL=modifyInstructionAffirmation.js.map