"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 setTransferRestrictions_1 = require("../setTransferRestrictions");
const mocks_1 = require("../../../testUtils/mocks");
const types_2 = require("../../../types");
const utilsConversionModule = __importStar(require("../../../utils/conversion"));
jest.mock('~/api/entities/SecurityToken', require("../../../testUtils/mocks/entities").mockSecurityTokenModule('~/api/entities/SecurityToken'));
jest.mock('~/api/entities/Identity', require("../../../testUtils/mocks/entities").mockIdentityModule('~/api/entities/Identity'));
describe('setTransferRestrictions procedure', () => {
    let mockContext;
    let transferRestrictionToTransferManagerStub;
    let stringToTickerStub;
    let stringToScopeIdStub;
    let ticker;
    let count;
    let percentage;
    let countTm;
    let percentageTm;
    let scopeId;
    let rawTicker;
    let rawCount;
    let rawPercentage;
    let rawCountTm;
    let rawPercentageTm;
    let rawScopeId;
    let args;
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks();
        mocks_1.procedureMockUtils.initMocks();
        mocks_1.entityMockUtils.initMocks();
        transferRestrictionToTransferManagerStub = sinon_1.default.stub(utilsConversionModule, 'transferRestrictionToTransferManager');
        stringToTickerStub = sinon_1.default.stub(utilsConversionModule, 'stringToTicker');
        stringToScopeIdStub = sinon_1.default.stub(utilsConversionModule, 'stringToScopeId');
        ticker = 'someTicker';
        count = new bignumber_js_1.default(10);
        percentage = new bignumber_js_1.default(49);
        countTm = { type: types_2.TransferRestrictionType.Count, value: count };
        percentageTm = { type: types_2.TransferRestrictionType.Percentage, value: percentage };
        scopeId = 'scopeId';
        args = {
            ticker,
            restrictions: [{ count }],
            type: types_2.TransferRestrictionType.Count,
        };
    });
    let addBatchTransactionStub;
    let addTransferManagerTransaction;
    let addExemptedEntitiesTransaction;
    let removeTransferManagerTransaction;
    let removeExemptedEntitiesTransaction;
    beforeEach(() => {
        mocks_1.dsMockUtils.setConstMock('statistics', 'maxTransferManagersPerAsset', {
            returnValue: mocks_1.dsMockUtils.createMockU32(3),
        });
        addBatchTransactionStub = mocks_1.procedureMockUtils.getAddBatchTransactionStub();
        mocks_1.entityMockUtils.getTickerReservationDetailsStub().resolves({
            owner: mocks_1.entityMockUtils.getIdentityInstance(),
            expiryDate: null,
            status: types_2.TickerReservationStatus.Free,
        });
        addTransferManagerTransaction = mocks_1.dsMockUtils.createTxStub('statistics', 'addTransferManager');
        addExemptedEntitiesTransaction = mocks_1.dsMockUtils.createTxStub('statistics', 'addExemptedEntities');
        removeTransferManagerTransaction = mocks_1.dsMockUtils.createTxStub('statistics', 'removeTransferManager');
        removeExemptedEntitiesTransaction = mocks_1.dsMockUtils.createTxStub('statistics', 'removeExemptedEntities');
        mockContext = mocks_1.dsMockUtils.getContextInstance();
        rawTicker = mocks_1.dsMockUtils.createMockTicker(ticker);
        rawCount = mocks_1.dsMockUtils.createMockU64(count.toNumber());
        rawPercentage = mocks_1.dsMockUtils.createMockPermill(percentage.toNumber() * 10000);
        rawCountTm = mocks_1.dsMockUtils.createMockTransferManager({ CountTransferManager: rawCount });
        rawPercentageTm = mocks_1.dsMockUtils.createMockTransferManager({
            PercentageTransferManager: rawPercentage,
        });
        rawScopeId = mocks_1.dsMockUtils.createMockScopeId(scopeId);
        transferRestrictionToTransferManagerStub.withArgs(countTm, mockContext).returns(rawCountTm);
        transferRestrictionToTransferManagerStub
            .withArgs(percentageTm, mockContext)
            .returns(rawPercentageTm);
        stringToTickerStub.withArgs(ticker, mockContext).returns(rawTicker);
        stringToScopeIdStub.withArgs(scopeId, mockContext).returns(rawScopeId);
    });
    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 add a batch of add transfer manager transactions to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            restrictionsToRemove: [],
            restrictionsToAdd: [[rawTicker, rawCountTm]],
            exemptionsToAdd: [],
            exemptionsToRemove: [],
            occupiedSlots: 0,
            exemptionsRepeated: false,
        });
        const result = yield setTransferRestrictions_1.prepareSetTransferRestrictions.call(proc, args);
        sinon_1.default.assert.calledWith(addBatchTransactionStub, addTransferManagerTransaction, {}, [
            [rawTicker, rawCountTm],
        ]);
        expect(result).toEqual(1);
    }));
    test('should add a batch of remove transfer manager transactions to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        args = {
            type: types_2.TransferRestrictionType.Count,
            restrictions: [],
            ticker,
        };
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            restrictionsToRemove: [[rawTicker, rawCountTm]],
            restrictionsToAdd: [],
            exemptionsToAdd: [],
            exemptionsToRemove: [],
            occupiedSlots: 0,
            exemptionsRepeated: false,
        });
        const result = yield setTransferRestrictions_1.prepareSetTransferRestrictions.call(proc, args);
        sinon_1.default.assert.calledWith(addBatchTransactionStub, removeTransferManagerTransaction, {}, [
            [rawTicker, rawCountTm],
        ]);
        expect(result).toEqual(0);
    }));
    test('should add a batch of add exempted entities transaction to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            restrictionsToRemove: [],
            restrictionsToAdd: [],
            exemptionsToAdd: [[rawTicker, rawCountTm, [rawScopeId]]],
            exemptionsToRemove: [],
            occupiedSlots: 0,
            exemptionsRepeated: false,
        });
        const result = yield setTransferRestrictions_1.prepareSetTransferRestrictions.call(proc, args);
        sinon_1.default.assert.calledWith(addBatchTransactionStub, addExemptedEntitiesTransaction, {}, [
            [rawTicker, rawCountTm, [rawScopeId]],
        ]);
        expect(result).toEqual(0);
    }));
    test('should add a batch of remove exempted entities transaction to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            restrictionsToRemove: [],
            restrictionsToAdd: [],
            exemptionsToAdd: [],
            exemptionsToRemove: [[rawTicker, rawCountTm, [rawScopeId]]],
            occupiedSlots: 0,
            exemptionsRepeated: false,
        });
        const result = yield setTransferRestrictions_1.prepareSetTransferRestrictions.call(proc, args);
        sinon_1.default.assert.calledWith(addBatchTransactionStub, removeExemptedEntitiesTransaction, {}, [
            [rawTicker, rawCountTm, [rawScopeId]],
        ]);
        expect(result).toEqual(0);
    }));
    test('should throw an error if attempting to add restrictions that already exist', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            restrictionsToRemove: [],
            restrictionsToAdd: [],
            exemptionsToAdd: [],
            exemptionsToRemove: [],
            occupiedSlots: 0,
            exemptionsRepeated: false,
        });
        let err;
        try {
            yield setTransferRestrictions_1.prepareSetTransferRestrictions.call(proc, {
                ticker,
                restrictions: [{ count }],
                type: types_2.TransferRestrictionType.Count,
            });
        }
        catch (error) {
            err = error;
        }
        expect(err.message).toBe('The supplied restrictions are already in place');
    }));
    test('should throw an error if attempting to remove an empty restriction list', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            restrictionsToRemove: [],
            restrictionsToAdd: [],
            exemptionsToAdd: [],
            exemptionsToRemove: [],
            occupiedSlots: 0,
            exemptionsRepeated: false,
        });
        let err;
        try {
            yield setTransferRestrictions_1.prepareSetTransferRestrictions.call(proc, args);
        }
        catch (error) {
            err = error;
        }
        expect(err.message).toBe('There are no restrictions to remove');
    }));
    test('should throw an error if attempting to add more restrictions than there are slots available', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            restrictionsToRemove: [],
            restrictionsToAdd: [[rawTicker, rawCountTm]],
            exemptionsToAdd: [],
            exemptionsToRemove: [],
            occupiedSlots: 3,
            exemptionsRepeated: false,
        });
        let err;
        try {
            yield setTransferRestrictions_1.prepareSetTransferRestrictions.call(proc, args);
        }
        catch (error) {
            err = error;
        }
        expect(err.message).toBe('Cannot set more Transfer Restrictions than there are slots available');
        expect(err.data).toEqual({ availableSlots: 0 });
    }));
    test('should throw an error if exempted scope IDs are repeated for a restriction', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            restrictionsToRemove: [],
            restrictionsToAdd: [],
            exemptionsToAdd: [],
            exemptionsToRemove: [],
            occupiedSlots: 0,
            exemptionsRepeated: true,
        });
        let err;
        try {
            yield setTransferRestrictions_1.prepareSetTransferRestrictions.call(proc, args);
        }
        catch (error) {
            err = error;
        }
        expect(err.message).toBe('One or more restrictions have repeated exempted Scope IDs/Identities');
    }));
    describe('getAuthorization', () => {
        test('should return the appropriate roles and permissions', () => {
            let proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
                restrictionsToRemove: [],
                restrictionsToAdd: [[rawTicker, rawCountTm]],
                exemptionsToAdd: [],
                exemptionsToRemove: [],
                occupiedSlots: 0,
                exemptionsRepeated: false,
            });
            let boundFunc = setTransferRestrictions_1.getAuthorization.bind(proc);
            expect(boundFunc(args)).toEqual({
                permissions: {
                    tokens: [mocks_1.entityMockUtils.getSecurityTokenInstance({ ticker })],
                    transactions: [types_1.TxTags.statistics.AddTransferManager],
                    portfolios: [],
                },
            });
            proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
                restrictionsToRemove: [],
                restrictionsToAdd: [],
                exemptionsToAdd: [[rawTicker, rawCountTm, [rawScopeId]]],
                exemptionsToRemove: [],
                occupiedSlots: 0,
                exemptionsRepeated: false,
            });
            boundFunc = setTransferRestrictions_1.getAuthorization.bind(proc);
            expect(boundFunc(args)).toEqual({
                permissions: {
                    tokens: [mocks_1.entityMockUtils.getSecurityTokenInstance({ ticker })],
                    transactions: [types_1.TxTags.statistics.AddExemptedEntities],
                    portfolios: [],
                },
            });
            proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
                restrictionsToRemove: [[rawTicker, rawCountTm]],
                restrictionsToAdd: [],
                exemptionsToAdd: [],
                exemptionsToRemove: [],
                occupiedSlots: 0,
                exemptionsRepeated: false,
            });
            boundFunc = setTransferRestrictions_1.getAuthorization.bind(proc);
            expect(boundFunc(args)).toEqual({
                permissions: {
                    tokens: [mocks_1.entityMockUtils.getSecurityTokenInstance({ ticker })],
                    transactions: [types_1.TxTags.statistics.RemoveTransferManager],
                    portfolios: [],
                },
            });
            proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
                restrictionsToRemove: [],
                restrictionsToAdd: [],
                exemptionsToAdd: [],
                exemptionsToRemove: [[rawTicker, rawCountTm, [rawScopeId]]],
                occupiedSlots: 0,
                exemptionsRepeated: false,
            });
            boundFunc = setTransferRestrictions_1.getAuthorization.bind(proc);
            expect(boundFunc(args)).toEqual({
                permissions: {
                    tokens: [mocks_1.entityMockUtils.getSecurityTokenInstance({ ticker })],
                    transactions: [types_1.TxTags.statistics.RemoveExemptedEntities],
                    portfolios: [],
                },
            });
        });
    });
    describe('prepareStorage', () => {
        let did;
        let identityScopeId;
        let rawIdentityScopeId;
        beforeAll(() => {
            did = 'someDid';
            identityScopeId = 'someScopeId';
            rawIdentityScopeId = mocks_1.dsMockUtils.createMockScopeId(identityScopeId);
        });
        beforeEach(() => {
            stringToScopeIdStub.withArgs(identityScopeId, mockContext).returns(rawIdentityScopeId);
        });
        afterAll(() => {
            sinon_1.default.restore();
        });
        test('should fetch, process and return shared data', () => __awaiter(void 0, void 0, void 0, function* () {
            mocks_1.entityMockUtils.configureMocks({
                identityOptions: {
                    getScopeId: identityScopeId,
                },
            });
            const getCountStub = mocks_1.entityMockUtils.getSecurityTokenTransferRestrictionsCountGetStub({
                restrictions: [],
                availableSlots: 1,
            });
            const getPercentageStub = mocks_1.entityMockUtils.getSecurityTokenTransferRestrictionsPercentageGetStub({
                restrictions: [{ percentage }],
                availableSlots: 1,
            });
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
            const boundFunc = setTransferRestrictions_1.prepareStorage.bind(proc);
            args = {
                ticker,
                type: types_2.TransferRestrictionType.Count,
                restrictions: [
                    {
                        count,
                    },
                ],
            };
            let result = yield boundFunc(args);
            expect(result).toEqual({
                restrictionsToAdd: [[rawTicker, rawCountTm]],
                restrictionsToRemove: [],
                exemptionsToAdd: [],
                exemptionsToRemove: [],
                occupiedSlots: 1,
                exemptionsRepeated: false,
            });
            args.restrictions = [];
            getCountStub.resolves({ restrictions: [{ count }], avaliableSlots: 1 });
            result = yield boundFunc(args);
            expect(result).toEqual({
                restrictionsToAdd: [],
                restrictionsToRemove: [[rawTicker, rawCountTm]],
                exemptionsToAdd: [],
                exemptionsToRemove: [],
                occupiedSlots: 1,
                exemptionsRepeated: false,
            });
            getCountStub.resolves({
                restrictions: [{ count, exemptedScopeIds: [scopeId] }],
                avaliableSlots: 1,
            });
            result = yield boundFunc(args);
            expect(result).toEqual({
                restrictionsToAdd: [],
                restrictionsToRemove: [[rawTicker, rawCountTm]],
                exemptionsToAdd: [],
                exemptionsToRemove: [[rawTicker, rawCountTm, [rawScopeId]]],
                occupiedSlots: 1,
                exemptionsRepeated: false,
            });
            getPercentageStub.resolves({
                restrictions: [{ percentage }],
                avaliableSlots: 1,
            });
            args = {
                restrictions: [
                    {
                        percentage,
                        exemptedScopeIds: [scopeId],
                    },
                ],
                ticker,
                type: types_2.TransferRestrictionType.Percentage,
            };
            result = yield boundFunc(args);
            expect(result).toEqual({
                restrictionsToAdd: [],
                restrictionsToRemove: [],
                exemptionsToAdd: [[rawTicker, rawPercentageTm, [rawScopeId]]],
                exemptionsToRemove: [],
                occupiedSlots: 1,
                exemptionsRepeated: false,
            });
            getPercentageStub.resolves({
                restrictions: [],
                avaliableSlots: 1,
            });
            args = {
                restrictions: [
                    {
                        percentage,
                        exemptedScopeIds: [scopeId],
                    },
                ],
                ticker,
                type: types_2.TransferRestrictionType.Percentage,
            };
            result = yield boundFunc(args);
            expect(result).toEqual({
                restrictionsToAdd: [[rawTicker, rawPercentageTm]],
                restrictionsToRemove: [],
                exemptionsToAdd: [[rawTicker, rawPercentageTm, [rawScopeId]]],
                exemptionsToRemove: [],
                occupiedSlots: 1,
                exemptionsRepeated: false,
            });
            getPercentageStub.resolves({
                restrictions: [{ percentage, exemptedScopeIds: [scopeId] }],
                avaliableSlots: 1,
            });
            args = {
                restrictions: [
                    {
                        percentage,
                    },
                ],
                ticker,
                type: types_2.TransferRestrictionType.Percentage,
            };
            result = yield boundFunc(args);
            expect(result).toEqual({
                restrictionsToAdd: [],
                restrictionsToRemove: [],
                exemptionsToAdd: [],
                exemptionsToRemove: [[rawTicker, rawPercentageTm, [rawScopeId]]],
                occupiedSlots: 1,
                exemptionsRepeated: false,
            });
            getPercentageStub.resolves({
                restrictions: [{ percentage, exemptedScopeIds: [] }],
                avaliableSlots: 1,
            });
            args = {
                restrictions: [
                    {
                        percentage,
                        exemptedScopeIds: [scopeId],
                    },
                ],
                ticker,
                type: types_2.TransferRestrictionType.Percentage,
            };
            result = yield boundFunc(args);
            expect(result).toEqual({
                restrictionsToAdd: [],
                restrictionsToRemove: [],
                exemptionsToAdd: [[rawTicker, rawPercentageTm, [rawScopeId]]],
                exemptionsToRemove: [],
                occupiedSlots: 1,
                exemptionsRepeated: false,
            });
            args = {
                restrictions: [
                    {
                        percentage,
                        exemptedScopeIds: [scopeId],
                        exemptedIdentities: [did],
                    },
                ],
                ticker,
                type: types_2.TransferRestrictionType.Percentage,
            };
            result = yield boundFunc(args);
            expect(result).toEqual({
                restrictionsToAdd: [],
                restrictionsToRemove: [],
                exemptionsToAdd: [[rawTicker, rawPercentageTm, [rawScopeId, rawIdentityScopeId]]],
                exemptionsToRemove: [],
                occupiedSlots: 1,
                exemptionsRepeated: false,
            });
            args = {
                restrictions: [
                    {
                        percentage,
                        exemptedScopeIds: [scopeId, scopeId],
                        exemptedIdentities: [mocks_1.entityMockUtils.getIdentityInstance()],
                    },
                ],
                ticker,
                type: types_2.TransferRestrictionType.Percentage,
            };
            result = yield boundFunc(args);
            expect(result).toEqual({
                restrictionsToAdd: [],
                restrictionsToRemove: [],
                exemptionsToAdd: [
                    [rawTicker, rawPercentageTm, [rawScopeId, rawScopeId, rawIdentityScopeId]],
                ],
                exemptionsToRemove: [],
                occupiedSlots: 1,
                exemptionsRepeated: true,
            });
        }));
    });
});
//# sourceMappingURL=setTransferRestrictions.js.map