"use strict";
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 api_1 = require("@polkadot/api");
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const lodash_1 = require("lodash");
const types_1 = require("../../polkadot/types");
const sinon_1 = __importDefault(require("sinon"));
const internal_1 = require("../../internal");
const types_2 = require("../../middleware/types");
const mocks_1 = require("../../testUtils/mocks");
const types_3 = require("../../types");
const utils_1 = require("../../types/utils");
const constants_1 = require("../constants");
const internal_2 = require("../internal");
describe('delay', () => {
    beforeAll(() => {
        jest.useFakeTimers('legacy');
    });
    afterAll(() => {
        jest.useRealTimers();
    });
    test('should resolve after the supplied timeout', () => {
        const delayPromise = internal_2.delay(5000);
        jest.advanceTimersByTime(5000);
        return expect(delayPromise).resolves.toBeUndefined();
    });
});
describe('serialize and unserialize', () => {
    const entityType = 'someEntity';
    const pojo1 = {
        foo: 'Foo',
        bar: 'Bar',
    };
    const inversePojo1 = {
        bar: 'Bar',
        foo: 'Foo',
    };
    const pojo2 = {
        baz: 'baz',
    };
    test('serialize returns the same unique id for the same pojo', () => {
        expect(internal_2.serialize(entityType, pojo1)).toBe(internal_2.serialize(entityType, pojo1));
        expect(internal_2.serialize(entityType, pojo1)).toBe(internal_2.serialize(entityType, inversePojo1));
    });
    test('serialize returns a different unique id for different pojos', () => {
        expect(internal_2.serialize(entityType, pojo1)).not.toBe(internal_2.serialize(entityType, pojo2));
    });
    test('unserialize recovers the serialized object', () => {
        expect(internal_2.unserialize(internal_2.serialize(entityType, pojo1))).toEqual(pojo1);
        expect(internal_2.unserialize(internal_2.serialize(entityType, inversePojo1))).toEqual(pojo1);
    });
    const errorMsg = 'Wrong ID format';
    test('unserialize throws an error if the argument has an incorrect format', () => {
        expect(() => internal_2.unserialize('unformatted')).toThrowError(errorMsg);
    });
    test('unserialize throws an error if the serialized string is not valid JSON', () => {
        const fakeSerialized = Buffer.from('someEntity:nonJsonString').toString('base64');
        expect(() => internal_2.unserialize(fakeSerialized)).toThrowError(errorMsg);
    });
});
describe('getDid', () => {
    let context;
    let did;
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks();
        did = 'aDid';
    });
    beforeEach(() => {
        context = mocks_1.dsMockUtils.getContextInstance();
    });
    afterEach(() => {
        mocks_1.dsMockUtils.reset();
    });
    afterAll(() => {
        mocks_1.dsMockUtils.cleanup();
    });
    test('getDid should extract the DID from an Identity', () => __awaiter(void 0, void 0, void 0, function* () {
        mocks_1.entityMockUtils.initMocks();
        const result = yield internal_2.getDid(mocks_1.entityMockUtils.getIdentityInstance({ did }), context);
        expect(result).toBe(did);
    }));
    test('getDid should return the passed DID', () => __awaiter(void 0, void 0, void 0, function* () {
        const result = yield internal_2.getDid(did, context);
        expect(result).toBe(did);
    }));
    test('getDid should return the current Identity DID if nothing is passed', () => __awaiter(void 0, void 0, void 0, function* () {
        const result = yield internal_2.getDid(undefined, context);
        expect(result).toBe((yield context.getCurrentIdentity()).did);
    }));
});
describe('unwrapValue', () => {
    test('should unwrap a Post Transaction Value', () => __awaiter(void 0, void 0, void 0, function* () {
        const wrapped = new internal_1.PostTransactionValue(() => __awaiter(void 0, void 0, void 0, function* () { return 1; }));
        yield wrapped.run({});
        const unwrapped = internal_2.unwrapValue(wrapped);
        expect(unwrapped).toEqual(1);
    }));
    test('should return a non Post Transaction Value as is', () => {
        expect(internal_2.unwrapValue(1)).toBe(1);
    });
});
describe('unwrapValues', () => {
    test('should unwrap all Post Transaction Values in the array', () => __awaiter(void 0, void 0, void 0, function* () {
        const values = [1, 2, 3, 4, 5];
        const wrapped = values.map(value => new internal_1.PostTransactionValue(() => __awaiter(void 0, void 0, void 0, function* () { return value; })));
        yield Promise.all(wrapped.map(postValue => postValue.run({})));
        const unwrapped = internal_2.unwrapValues(wrapped);
        expect(unwrapped).toEqual(values);
    }));
});
describe('filterEventRecords', () => {
    const filterRecordsStub = sinon_1.default.stub();
    const mockReceipt = {
        filterRecords: filterRecordsStub,
    };
    afterEach(() => {
        filterRecordsStub.reset();
    });
    test('returns the corresponding Event Record', () => {
        const mod = 'asset';
        const eventName = 'TickerRegistered';
        const fakeResult = 'event';
        filterRecordsStub.withArgs(mod, eventName).returns([{ event: fakeResult }]);
        const eventRecord = internal_2.filterEventRecords(mockReceipt, mod, eventName);
        expect(eventRecord[0]).toBe(fakeResult);
    });
    test("throws if the Event wasn't fired", () => {
        const mod = 'asset';
        const eventName = 'TickerRegistered';
        filterRecordsStub.withArgs(mod, eventName).returns([]);
        expect(() => internal_2.filterEventRecords(mockReceipt, mod, eventName)).toThrow(`Event "${mod}.${eventName}" wasn't fired even though the corresponding transaction was completed. Please report this to the Polymath team`);
    });
});
describe('createClaim', () => {
    test('createClaim should create Claim objects from claims data provided by middleware', () => {
        let type = 'Jurisdiction';
        const jurisdiction = 'CL';
        let scope = { type: types_2.ClaimScopeTypeEnum.Identity, value: 'someScope' };
        let result = internal_2.createClaim(type, jurisdiction, scope, null, undefined);
        expect(result).toEqual({
            type: types_3.ClaimType.Jurisdiction,
            code: types_3.CountryCode.Cl,
            scope,
        });
        type = 'BuyLockup';
        scope = { type: types_2.ClaimScopeTypeEnum.Identity, value: 'someScope' };
        result = internal_2.createClaim(type, null, scope, null, undefined);
        expect(result).toEqual({
            type: types_3.ClaimType.BuyLockup,
            scope,
        });
        type = 'NoData';
        result = internal_2.createClaim(type, null, null, null, undefined);
        expect(result).toEqual({
            type: types_3.ClaimType.NoData,
        });
        type = 'CustomerDueDiligence';
        const id = 'someId';
        result = internal_2.createClaim(type, null, null, id, undefined);
        expect(result).toEqual({
            type: types_3.ClaimType.CustomerDueDiligence,
            id,
        });
        type = 'InvestorUniqueness';
        scope = { type: types_2.ClaimScopeTypeEnum.Ticker, value: 'someTicker' };
        result = internal_2.createClaim(type, null, scope, id, undefined);
        expect(result).toEqual({
            type: types_3.ClaimType.InvestorUniqueness,
            scope: scope,
            cddId: id,
        });
        type = 'InvestorUniquenessV2';
        result = internal_2.createClaim(type, null, null, id, undefined);
        expect(result).toEqual({
            type: types_3.ClaimType.InvestorUniquenessV2,
            cddId: id,
        });
    });
});
describe('padString', () => {
    test('should pad a string on the right side to cover the supplied length', () => {
        const value = 'someString';
        const fakeResult = `${value}\0\0`;
        const result = internal_2.padString(value, 12);
        expect(result).toBe(fakeResult);
    });
});
describe('removePadding', () => {
    test('should remove all null character padding from the input', () => {
        const expected = 'someString';
        const result = internal_2.removePadding(`${expected}\0\0\0`);
        expect(result).toBe(expected);
    });
});
describe('requestPaginated', () => {
    test('should fetch and return entries and the hex value of the last key', () => __awaiter(void 0, void 0, void 0, function* () {
        const queryStub = mocks_1.dsMockUtils.createQueryStub('asset', 'tickers', {
            entries: [
                utils_1.tuple(['ticker0'], mocks_1.dsMockUtils.createMockU32(0)),
                utils_1.tuple(['ticker1'], mocks_1.dsMockUtils.createMockU32(1)),
                utils_1.tuple(['ticker2'], mocks_1.dsMockUtils.createMockU32(2)),
            ],
        });
        let res = yield internal_2.requestPaginated(queryStub, {
            paginationOpts: undefined,
        });
        expect(res.lastKey).toBeNull();
        sinon_1.default.assert.calledOnce(queryStub.entries);
        sinon_1.default.resetHistory();
        res = yield internal_2.requestPaginated(queryStub, {
            paginationOpts: { size: 3 },
        });
        expect(typeof res.lastKey).toBe('string');
        sinon_1.default.assert.calledOnce(queryStub.entriesPaged);
        sinon_1.default.resetHistory();
        res = yield internal_2.requestPaginated(queryStub, {
            paginationOpts: { size: 4 },
            arg: 'something',
        });
        expect(res.lastKey).toBeNull();
        sinon_1.default.assert.calledOnce(queryStub.entriesPaged);
    }));
});
describe('requestAtBlock', () => {
    test('should fetch and return the value at a certain block (current if left empty)', () => __awaiter(void 0, void 0, void 0, function* () {
        const context = mocks_1.dsMockUtils.getContextInstance({
            isArchiveNode: true,
        });
        const returnValue = mocks_1.dsMockUtils.createMockU32(5);
        const queryStub = mocks_1.dsMockUtils.createQueryStub('asset', 'tickers', {
            returnValue,
        });
        const blockHash = 'someBlockHash';
        const ticker = 'ticker';
        let res = yield internal_2.requestAtBlock(queryStub, {
            blockHash,
            args: [ticker],
        }, context);
        sinon_1.default.assert.calledWith(queryStub.at, blockHash, ticker);
        expect(res).toBe(returnValue);
        res = yield internal_2.requestAtBlock(queryStub, {
            args: [ticker],
        }, context);
        sinon_1.default.assert.calledWith(queryStub, ticker);
        expect(res).toBe(returnValue);
    }));
    test('should throw an error if the node is not archive', () => {
        const context = mocks_1.dsMockUtils.getContextInstance({
            isArchiveNode: false,
        });
        const queryStub = mocks_1.dsMockUtils.createQueryStub('asset', 'tickers', {
            returnValue: mocks_1.dsMockUtils.createMockU32(5),
        });
        return expect(internal_2.requestAtBlock(queryStub, {
            blockHash: 'someBlockHash',
            args: ['ticker'],
        }, context)).rejects.toThrow('Cannot query previous blocks in a non-archive node');
    });
});
describe('batchArguments', () => {
    test('should return chunks of data', () => {
        const tag = types_1.TxTags.asset.AddDocuments;
        const expectedBatchLength = constants_1.MAX_BATCH_ELEMENTS[tag];
        const elements = lodash_1.range(0, 3 * expectedBatchLength + 1);
        const batches = internal_2.batchArguments(elements, tag);
        expect(batches.length).toBe(4);
        expect(batches[0].length).toBe(expectedBatchLength);
        expect(batches[1].length).toBe(expectedBatchLength);
        expect(batches[2].length).toBe(expectedBatchLength);
        expect(batches[3].length).toBe(1);
    });
    test('should use a custom batching function to group elements', () => {
        const tag = types_1.TxTags.corporateAction.InitiateCorporateAction;
        const expectedBatchLength = constants_1.DEFAULT_MAX_BATCH_ELEMENTS;
        const elements = lodash_1.range(0, 2 * expectedBatchLength);
        let batches = internal_2.batchArguments(elements, tag, element => `${element % 2}`); // separate odd from even
        expect(batches.length).toBe(2);
        expect(batches[0]).toEqual(lodash_1.range(0, 2 * expectedBatchLength, 2));
        expect(batches[1]).toEqual(lodash_1.range(1, 2 * expectedBatchLength, 2));
        batches = internal_2.batchArguments(elements, tag, element => `${element % 5}`); // separate in 5 groups
        expect(batches.length).toBe(3);
        expect(batches[0].length).toBeLessThan(expectedBatchLength);
        expect(batches[1].length).toBeLessThan(expectedBatchLength);
        expect(batches[2].length).toBeLessThan(expectedBatchLength);
    });
    test('should throw an error if a custom batch has a size bigger than the limit', () => {
        const tag = types_1.TxTags.asset.AddDocuments;
        const expectedBatchLength = constants_1.MAX_BATCH_ELEMENTS[tag];
        const elements = lodash_1.range(0, 3 * expectedBatchLength);
        expect(() => internal_2.batchArguments(elements, tag, element => `${element % 2}`)).toThrowError('Batch size exceeds limit');
    });
});
describe('calculateNextKey', () => {
    test('should return NextKey null as there are less elements than the default page size', () => {
        const totalCount = 20;
        const nextKey = internal_2.calculateNextKey(totalCount);
        expect(nextKey).toBeNull();
    });
    test('should return NextKey null as it is the last page', () => {
        const totalCount = 50;
        const currentPageSize = 30;
        const currentStart = 31;
        const nextKey = internal_2.calculateNextKey(totalCount, currentPageSize, currentStart);
        expect(nextKey).toBeNull();
    });
    test('should return NextKey', () => {
        const totalCount = 50;
        const currentPageSize = 30;
        const currentStart = 0;
        const nextKey = internal_2.calculateNextKey(totalCount, currentPageSize, currentStart);
        expect(nextKey).toEqual(30);
    });
});
describe('isPrintableAscii', () => {
    test('should return true if the string only contains printable ASCII characters', () => {
        expect(internal_2.isPrintableAscii('TICKER')).toBe(true);
    });
    test("should return false if the string doesn't contain only printable ASCII characters", () => {
        expect(internal_2.isPrintableAscii(String.fromCharCode(10000000))).toBe(false);
    });
});
describe('createProcedureMethod', () => {
    let context;
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks();
    });
    beforeEach(() => {
        context = mocks_1.dsMockUtils.getContextInstance();
    });
    afterEach(() => {
        mocks_1.dsMockUtils.reset();
    });
    afterAll(() => {
        mocks_1.dsMockUtils.cleanup();
    });
    test('should return a ProcedureMethod object', () => __awaiter(void 0, void 0, void 0, function* () {
        const prepare = sinon_1.default.stub();
        const checkAuthorization = sinon_1.default.stub();
        const transformer = sinon_1.default.stub();
        const fakeProcedure = () => ({
            prepare,
            checkAuthorization,
        });
        const method = internal_2.createProcedureMethod({ getProcedureAndArgs: args => [fakeProcedure, args], transformer }, context);
        const procArgs = 1;
        yield method(procArgs);
        sinon_1.default.assert.calledWithExactly(prepare, { args: procArgs, transformer }, context, {});
        yield method.checkAuthorization(procArgs);
        sinon_1.default.assert.calledWithExactly(checkAuthorization, procArgs, context, {});
    }));
    test('should return a NoArgsProcedureMethod object', () => __awaiter(void 0, void 0, void 0, function* () {
        const prepare = sinon_1.default.stub();
        const checkAuthorization = sinon_1.default.stub();
        const transformer = sinon_1.default.stub();
        const fakeProcedure = () => ({
            prepare,
            checkAuthorization,
        });
        const method = internal_2.createProcedureMethod({ getProcedureAndArgs: () => [fakeProcedure, undefined], transformer, voidArgs: true }, context);
        yield method();
        sinon_1.default.assert.calledWithExactly(prepare, { transformer, args: undefined }, context, {});
        yield method.checkAuthorization();
        sinon_1.default.assert.calledWithExactly(checkAuthorization, undefined, context, {});
    }));
});
describe('assertIsInteger', () => {
    test('should not throw if the argument is an integer', () => __awaiter(void 0, void 0, void 0, function* () {
        try {
            internal_2.assertIsInteger(new bignumber_js_1.default(1));
        }
        catch (_) {
            expect(true).toBe(false);
        }
    }));
    test('assertIsInteger should throw an error if the argument is not an integer', () => __awaiter(void 0, void 0, void 0, function* () {
        expect(() => internal_2.assertIsInteger('noInteger')).toThrow('The number must be an integer');
        expect(() => internal_2.assertIsInteger(new bignumber_js_1.default(1.2))).toThrow('The number must be an integer');
    }));
});
describe('assertIsPositive', () => {
    test('should not throw an error if the argument is positive', () => {
        expect(() => internal_2.assertIsPositive(new bignumber_js_1.default(43))).not.toThrow();
    });
    test('should throw an error if the argument is negative', () => __awaiter(void 0, void 0, void 0, function* () {
        expect(() => internal_2.assertIsPositive(new bignumber_js_1.default(-3))).toThrow('The number must be positive');
    }));
});
describe('getCommonKeyring', () => {
    test('should return a common keyring', () => __awaiter(void 0, void 0, void 0, function* () {
        const fakeKeyring = 'keyring';
        let result = internal_2.getCommonKeyring(fakeKeyring);
        expect(result).toBe(fakeKeyring);
        result = internal_2.getCommonKeyring({ keyring: fakeKeyring });
        expect(result).toBe(fakeKeyring);
    }));
});
describe('assertFormatValid', () => {
    const ss58Format = 42;
    test('should throw an error if the address is prefixed with an invalid ss58', () => __awaiter(void 0, void 0, void 0, function* () {
        expect(() => internal_2.assertFormatValid('ajYMsCKsEAhEvHpeA4XqsfiA9v1CdzZPrCfS6pEfeGHW9j8', ss58Format)).toThrow("The supplied address is not encoded with the chain's SS58 format");
    }));
    test('should not throw if the address is prefixed with valid ss58', () => __awaiter(void 0, void 0, void 0, function* () {
        expect(() => internal_2.assertFormatValid('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', ss58Format)).not.toThrow();
    }));
});
describe('assertKeyringFormatValid', () => {
    const ss58Format = 42;
    const keyring = new api_1.Keyring({ ss58Format });
    test('should not throw if the keyring is set with valid ss58', () => __awaiter(void 0, void 0, void 0, function* () {
        expect(() => internal_2.assertKeyringFormatValid(keyring, ss58Format)).not.toThrow();
    }));
    test('should throw an error if the keyring is set with an invalid ss58', () => __awaiter(void 0, void 0, void 0, function* () {
        keyring.setSS58Format(12);
        expect(() => internal_2.assertKeyringFormatValid(keyring, ss58Format)).toThrow("The supplied keyring is not using the chain's SS58 format");
    }));
});
describe('getTicker', () => {
    test('should return an Asset symbol', () => __awaiter(void 0, void 0, void 0, function* () {
        const symbol = 'ASSET';
        let result = internal_2.getTicker(symbol);
        expect(result).toBe(symbol);
        result = internal_2.getTicker(new internal_1.Asset({ ticker: symbol }, mocks_1.dsMockUtils.getContextInstance()));
        expect(result).toBe(symbol);
    }));
});
describe('periodComplexity', () => {
    test('should calculate complexity for any period', () => {
        const period = {
            unit: types_3.CalendarUnit.Second,
            amount: 1,
        };
        let result = internal_2.periodComplexity(period);
        expect(result).toBe(31536000);
        period.unit = types_3.CalendarUnit.Minute;
        result = internal_2.periodComplexity(period);
        expect(result).toBe(525600);
        period.unit = types_3.CalendarUnit.Hour;
        result = internal_2.periodComplexity(period);
        expect(result).toBe(8760);
        period.unit = types_3.CalendarUnit.Day;
        result = internal_2.periodComplexity(period);
        expect(result).toBe(365);
        period.unit = types_3.CalendarUnit.Week;
        result = internal_2.periodComplexity(period);
        expect(result).toBe(52);
        period.unit = types_3.CalendarUnit.Month;
        result = internal_2.periodComplexity(period);
        expect(result).toBe(12);
        period.unit = types_3.CalendarUnit.Year;
        result = internal_2.periodComplexity(period);
        expect(result).toBe(2);
        period.amount = 0;
        result = internal_2.periodComplexity(period);
        expect(result).toBe(1);
    });
});
describe('optionize', () => {
    test('should transform a conversion util into a version that returns null if the first input is falsy, passing along the rest if not', () => {
        const number = 1;
        const toString = (value, foo, bar) => `${value.toString()}${foo}${bar}`;
        let result = internal_2.optionize(toString)(number, 'notNeeded', 1);
        expect(result).toBe(toString(number, 'notNeeded', 1));
        result = internal_2.optionize(toString)(null, 'stillNotNeeded', 2);
        expect(result).toBeNull();
    });
});
describe('isModuleOrTagMatch', () => {
    test("should return true if two tags/modules are equal, or if one is the other one's module", () => {
        let result = internal_2.isModuleOrTagMatch(types_1.TxTags.identity.AddInvestorUniquenessClaim, types_1.ModuleName.Sto);
        expect(result).toEqual(false);
        result = internal_2.isModuleOrTagMatch(types_1.ModuleName.Sto, types_1.TxTags.identity.AddInvestorUniquenessClaim);
        expect(result).toEqual(false);
        result = internal_2.isModuleOrTagMatch(types_1.TxTags.identity.AddInvestorUniquenessClaim, types_1.TxTags.identity.AddClaim);
        expect(result).toEqual(false);
    });
});
describe('getCheckpointValue', () => {
    let context;
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks();
    });
    beforeEach(() => {
        context = mocks_1.dsMockUtils.getContextInstance();
    });
    afterEach(() => {
        mocks_1.dsMockUtils.reset();
    });
    afterAll(() => {
        mocks_1.dsMockUtils.cleanup();
    });
    test('should return value as it is for valid params of type Checkpoint, CheckpointSchedule or Date', () => __awaiter(void 0, void 0, void 0, function* () {
        const mockCheckpointSchedule = mocks_1.entityMockUtils.getCheckpointScheduleInstance();
        const mockAsset = mocks_1.entityMockUtils.getAssetInstance();
        let result = yield internal_2.getCheckpointValue(mockCheckpointSchedule, mockAsset, context);
        expect(result).toEqual(mockCheckpointSchedule);
        const mockCheckpoint = mocks_1.entityMockUtils.getCheckpointInstance();
        result = yield internal_2.getCheckpointValue(mockCheckpoint, mockAsset, context);
        expect(result).toEqual(mockCheckpoint);
        const mockCheckpointDate = new Date();
        result = yield internal_2.getCheckpointValue(mockCheckpointDate, mockAsset, context);
        expect(result).toEqual(mockCheckpointDate);
    }));
    test('should return Checkpoint instance for params with type `Existing`', () => __awaiter(void 0, void 0, void 0, function* () {
        const mockCheckpoint = mocks_1.entityMockUtils.getCheckpointInstance();
        const mockCaCheckpointTypeParams = {
            id: new bignumber_js_1.default(1),
            type: types_3.CaCheckpointType.Existing,
        };
        const mockAsset = mocks_1.entityMockUtils.getAssetInstance({
            checkpointsGetOne: mockCheckpoint,
        });
        const result = yield internal_2.getCheckpointValue(mockCaCheckpointTypeParams, mockAsset, context);
        expect(result).toEqual(mockCheckpoint);
    }));
    test('should return Checkpoint instance for params with type `Scheduled`', () => __awaiter(void 0, void 0, void 0, function* () {
        const mockCheckpointSchedule = mocks_1.entityMockUtils.getCheckpointScheduleInstance();
        const mockCaCheckpointTypeParams = {
            id: new bignumber_js_1.default(1),
            type: types_3.CaCheckpointType.Schedule,
        };
        const mockAsset = mocks_1.entityMockUtils.getAssetInstance({
            checkpointsSchedulesGetOne: { schedule: mockCheckpointSchedule },
        });
        const result = yield internal_2.getCheckpointValue(mockCaCheckpointTypeParams, mockAsset, context);
        expect(result).toEqual(mockCheckpointSchedule);
    }));
});
describe('hasSameElements', () => {
    it('should use provided comparator for matching the elements ', () => {
        let result = internal_2.hasSameElements([
            { id: 1, name: 'X' },
            { id: 2, name: 'Y' },
        ], [
            { id: 1, name: 'X' },
            { id: 2, name: 'Z' },
        ], (a, b) => a.id === b.id);
        expect(result).toEqual(true);
        result = internal_2.hasSameElements([
            { id: 1, name: 'X' },
            { id: 2, name: 'Y' },
        ], [
            { id: 1, name: 'X' },
            { id: 3, name: 'Z' },
        ], (a, b) => a.id === b.id);
        expect(result).toEqual(false);
    });
    it('should use the lodash `isEqual` if no comparator is provided', () => {
        let result = internal_2.hasSameElements([1, 2], [2, 1]);
        expect(result).toEqual(true);
        result = internal_2.hasSameElements([1, 2], [2, 3]);
        expect(result).toEqual(false);
    });
});
describe('getPortfolioIdByName', () => {
    let context;
    let nameToNumberStub;
    let portfoliosStub;
    let rawName;
    let identityId;
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks();
        mocks_1.entityMockUtils.initMocks();
    });
    beforeEach(() => {
        context = mocks_1.dsMockUtils.getContextInstance();
        rawName = mocks_1.dsMockUtils.createMockText('someName');
        identityId = mocks_1.dsMockUtils.createMockIdentityId('someDid');
        nameToNumberStub = mocks_1.dsMockUtils.createQueryStub('portfolio', 'nameToNumber');
        portfoliosStub = mocks_1.dsMockUtils.createQueryStub('portfolio', 'portfolios');
    });
    afterEach(() => {
        mocks_1.dsMockUtils.reset();
        mocks_1.entityMockUtils.reset();
    });
    afterAll(() => {
        mocks_1.dsMockUtils.cleanup();
        mocks_1.entityMockUtils.cleanup();
    });
    test('should return null if no portfolio with given name is found', () => __awaiter(void 0, void 0, void 0, function* () {
        nameToNumberStub.returns(mocks_1.dsMockUtils.createMockU64(1));
        portfoliosStub.returns(mocks_1.dsMockUtils.createMockText('randomName'));
        const result = yield internal_2.getPortfolioIdByName(identityId, rawName, context);
        expect(result).toBeNull();
    }));
    test('should return portfolio number for given portfolio name', () => __awaiter(void 0, void 0, void 0, function* () {
        nameToNumberStub.returns(mocks_1.dsMockUtils.createMockU64(2));
        let result = yield internal_2.getPortfolioIdByName(identityId, rawName, context);
        expect(result).toEqual(new bignumber_js_1.default(2));
        nameToNumberStub.returns(mocks_1.dsMockUtils.createMockU64(1));
        portfoliosStub.returns(rawName);
        result = yield internal_2.getPortfolioIdByName(identityId, rawName, context);
        expect(result).toEqual(new bignumber_js_1.default(1));
    }));
});
//# sourceMappingURL=internal.js.map