"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 addTransferRestriction_1 = require("../addTransferRestriction");
const mocks_1 = require("../../../testUtils/mocks");
const types_2 = require("../../../types");
const utilsConversionModule = __importStar(require("../../../utils/conversion"));
jest.mock('~/api/entities/Asset', require("../../../testUtils/mocks/entities").mockAssetModule('~/api/entities/Asset'));
jest.mock('~/api/entities/Identity', require("../../../testUtils/mocks/entities").mockIdentityModule('~/api/entities/Identity'));
describe('addTransferRestriction procedure', () => {
    let mockContext;
    let transferRestrictionToTransferManagerStub;
    let stringToTickerStub;
    let ticker;
    let count;
    let percentage;
    let countTm;
    let percentageTm;
    let rawTicker;
    let rawCount;
    let rawPercentage;
    let rawCountTm;
    let rawPercentageTm;
    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');
        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 };
    });
    let addTransactionStub;
    let addTransferManagerTransaction;
    let addExemptedEntitiesTransaction;
    beforeEach(() => {
        addTransactionStub = mocks_1.procedureMockUtils.getAddTransactionStub();
        addTransferManagerTransaction = mocks_1.dsMockUtils.createTxStub('statistics', 'addTransferManager');
        addExemptedEntitiesTransaction = mocks_1.dsMockUtils.createTxStub('statistics', 'addExemptedEntities');
        mockContext = mocks_1.dsMockUtils.getContextInstance();
        mocks_1.dsMockUtils.setConstMock('statistics', 'maxTransferManagersPerAsset', {
            returnValue: mocks_1.dsMockUtils.createMockU32(new bignumber_js_1.default(3)),
        });
        rawTicker = mocks_1.dsMockUtils.createMockTicker(ticker);
        rawCount = mocks_1.dsMockUtils.createMockU64(count);
        rawPercentage = mocks_1.dsMockUtils.createMockPermill(percentage.multipliedBy(10000));
        rawCountTm = mocks_1.dsMockUtils.createMockTransferManager({ CountTransferManager: rawCount });
        rawPercentageTm = mocks_1.dsMockUtils.createMockTransferManager({
            PercentageTransferManager: rawPercentage,
        });
        transferRestrictionToTransferManagerStub.withArgs(countTm, mockContext).returns(rawCountTm);
        transferRestrictionToTransferManagerStub
            .withArgs(percentageTm, mockContext)
            .returns(rawPercentageTm);
        stringToTickerStub.withArgs(ticker, mockContext).returns(rawTicker);
    });
    afterEach(() => {
        mocks_1.entityMockUtils.reset();
        mocks_1.procedureMockUtils.reset();
        mocks_1.dsMockUtils.reset();
    });
    afterAll(() => {
        mocks_1.procedureMockUtils.cleanup();
        mocks_1.dsMockUtils.cleanup();
    });
    test('should add an add transfer manager transaction to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        args = {
            type: types_2.TransferRestrictionType.Count,
            exemptedScopeIds: [],
            count,
            ticker,
        };
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        mocks_1.dsMockUtils.createQueryStub('statistics', 'activeTransferManagers', {
            returnValue: [],
        });
        let result = yield addTransferRestriction_1.prepareAddTransferRestriction.call(proc, args);
        sinon_1.default.assert.calledWith(addTransactionStub, {
            transaction: addTransferManagerTransaction,
            args: [rawTicker, rawCountTm],
        });
        expect(result).toEqual(new bignumber_js_1.default(1));
        args = {
            type: types_2.TransferRestrictionType.Percentage,
            exemptedScopeIds: [],
            percentage,
            ticker,
        };
        result = yield addTransferRestriction_1.prepareAddTransferRestriction.call(proc, args);
        sinon_1.default.assert.calledWith(addTransactionStub, {
            transaction: addTransferManagerTransaction,
            args: [rawTicker, rawPercentageTm],
        });
        expect(result).toEqual(new bignumber_js_1.default(1));
    }));
    test('should add an add exempted entities transaction to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        const did = 'someDid';
        const scopeId = 'someScopeId';
        const rawScopeId = mocks_1.dsMockUtils.createMockScopeId(scopeId);
        const identityScopeId = 'anotherScopeId';
        const rawIdentityScopeId = mocks_1.dsMockUtils.createMockScopeId(identityScopeId);
        mocks_1.entityMockUtils.configureMocks({ identityOptions: { getScopeId: identityScopeId } });
        args = {
            type: types_2.TransferRestrictionType.Count,
            exemptedScopeIds: [scopeId],
            exemptedIdentities: [did],
            count,
            ticker,
        };
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        mocks_1.dsMockUtils.createQueryStub('statistics', 'activeTransferManagers', {
            returnValue: [],
        });
        const stringToScopeIdStub = sinon_1.default.stub(utilsConversionModule, 'stringToScopeId');
        stringToScopeIdStub.withArgs(scopeId, mockContext).returns(rawScopeId);
        stringToScopeIdStub.withArgs(identityScopeId, mockContext).returns(rawIdentityScopeId);
        let result = yield addTransferRestriction_1.prepareAddTransferRestriction.call(proc, args);
        sinon_1.default.assert.calledWith(addTransactionStub, {
            transaction: addExemptedEntitiesTransaction,
            feeMultiplier: new bignumber_js_1.default(2),
            args: [rawTicker, rawCountTm, [rawScopeId, rawIdentityScopeId]],
        });
        expect(result).toEqual(new bignumber_js_1.default(1));
        result = yield addTransferRestriction_1.prepareAddTransferRestriction.call(proc, Object.assign(Object.assign({}, args), { exemptedIdentities: [mocks_1.entityMockUtils.getIdentityInstance()] }));
        sinon_1.default.assert.calledWith(addTransactionStub, {
            transaction: addExemptedEntitiesTransaction,
            feeMultiplier: new bignumber_js_1.default(2),
            args: [rawTicker, rawCountTm, [rawScopeId, rawIdentityScopeId]],
        });
        expect(result).toEqual(new bignumber_js_1.default(1));
    }));
    test('should throw an error if attempting to add a restriction that already exists', () => __awaiter(void 0, void 0, void 0, function* () {
        args = {
            type: types_2.TransferRestrictionType.Count,
            exemptedScopeIds: [],
            count,
            ticker,
        };
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        mocks_1.dsMockUtils.createQueryStub('statistics', 'activeTransferManagers', {
            returnValue: [rawCountTm],
        });
        let err;
        try {
            yield addTransferRestriction_1.prepareAddTransferRestriction.call(proc, args);
        }
        catch (error) {
            err = error;
        }
        expect(err.message).toBe('Cannot add the same restriction more than once');
    }));
    test('should throw an error if attempting to add a restriction when the restriction limit has been reached', () => __awaiter(void 0, void 0, void 0, function* () {
        args = {
            type: types_2.TransferRestrictionType.Count,
            count,
            ticker,
        };
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        mocks_1.dsMockUtils.createQueryStub('statistics', 'activeTransferManagers', {
            returnValue: [rawPercentageTm, rawPercentageTm, rawPercentageTm],
        });
        let err;
        try {
            yield addTransferRestriction_1.prepareAddTransferRestriction.call(proc, args);
        }
        catch (error) {
            err = error;
        }
        expect(err.message).toBe('Transfer Restriction limit reached');
        expect(err.data).toEqual({ limit: new bignumber_js_1.default(3) });
    }));
    test('should throw an error if exempted scope IDs are repeated', () => __awaiter(void 0, void 0, void 0, function* () {
        args = {
            type: types_2.TransferRestrictionType.Count,
            exemptedScopeIds: ['someScopeId', 'someScopeId'],
            count,
            ticker,
        };
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        mocks_1.dsMockUtils.createQueryStub('statistics', 'activeTransferManagers', {
            returnValue: [],
        });
        let err;
        try {
            yield addTransferRestriction_1.prepareAddTransferRestriction.call(proc, args);
        }
        catch (error) {
            err = error;
        }
        expect(err.message).toBe('One or more of the passed exempted Scope IDs/Identities are repeated');
    }));
    describe('getAuthorization', () => {
        test('should return the appropriate roles and permissions', () => {
            args = {
                ticker,
                count,
                type: types_2.TransferRestrictionType.Count,
            };
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
            const boundFunc = addTransferRestriction_1.getAuthorization.bind(proc);
            expect(boundFunc(args)).toEqual({
                permissions: {
                    assets: [expect.objectContaining({ ticker })],
                    transactions: [types_1.TxTags.statistics.AddTransferManager],
                    portfolios: [],
                },
            });
            expect(boundFunc(Object.assign(Object.assign({}, args), { exemptedScopeIds: ['someScopeId'] }))).toEqual({
                permissions: {
                    assets: [expect.objectContaining({ ticker })],
                    transactions: [
                        types_1.TxTags.statistics.AddTransferManager,
                        types_1.TxTags.statistics.AddExemptedEntities,
                    ],
                    portfolios: [],
                },
            });
        });
    });
});
//# sourceMappingURL=addTransferRestriction.js.map