"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 sinon_1 = __importDefault(require("sinon"));
const internal_1 = require("../../../../internal");
const queries_1 = require("../../../../middleware/queries");
const mocks_1 = require("../../../../testUtils/mocks");
const types_1 = require("../../../../types");
const utils_1 = require("../../../../types/utils");
const utilsConversionModule = __importStar(require("../../../../utils/conversion"));
jest.mock('~/api/entities/TickerReservation', require("../../../../testUtils/mocks/entities").mockTickerReservationModule('~/api/entities/TickerReservation'));
jest.mock('~/api/entities/SecurityToken', require("../../../../testUtils/mocks/entities").mockSecurityTokenModule('~/api/entities/SecurityToken'));
jest.mock('~/api/entities/Account', require("../../../../testUtils/mocks/entities").mockAccountModule('~/api/entities/Account'));
jest.mock('~/api/entities/Venue', require("../../../../testUtils/mocks/entities").mockVenueModule('~/api/entities/Venue'));
jest.mock('~/api/entities/NumberedPortfolio', require("../../../../testUtils/mocks/entities").mockNumberedPortfolioModule('~/api/entities/NumberedPortfolio'));
jest.mock('~/api/entities/DefaultPortfolio', require("../../../../testUtils/mocks/entities").mockDefaultPortfolioModule('~/api/entities/DefaultPortfolio'));
jest.mock('~/api/entities/Instruction', require("../../../../testUtils/mocks/entities").mockInstructionModule('~/api/entities/Instruction'));
describe('Identity class', () => {
    let context;
    let stringToIdentityIdStub;
    let identityIdToStringStub;
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks();
        mocks_1.entityMockUtils.initMocks();
        stringToIdentityIdStub = sinon_1.default.stub(utilsConversionModule, 'stringToIdentityId');
        identityIdToStringStub = sinon_1.default.stub(utilsConversionModule, 'identityIdToString');
    });
    beforeEach(() => {
        context = mocks_1.dsMockUtils.getContextInstance();
    });
    afterEach(() => {
        mocks_1.dsMockUtils.reset();
        mocks_1.entityMockUtils.reset();
    });
    afterAll(() => {
        mocks_1.dsMockUtils.cleanup();
        mocks_1.entityMockUtils.cleanup();
    });
    test('should extend Entity', () => {
        expect(internal_1.Identity.prototype instanceof internal_1.Entity).toBe(true);
    });
    describe('constructor', () => {
        test('should assign did to instance', () => {
            const did = 'abc';
            const identity = new internal_1.Identity({ did }, context);
            expect(identity.did).toBe(did);
        });
    });
    describe('method: isUniqueIdentifiers', () => {
        test('should return true if the object conforms to the interface', () => {
            expect(internal_1.Identity.isUniqueIdentifiers({ did: 'someDid' })).toBe(true);
            expect(internal_1.Identity.isUniqueIdentifiers({})).toBe(false);
            expect(internal_1.Identity.isUniqueIdentifiers({ did: 3 })).toBe(false);
        });
    });
    describe('method: checkRoles', () => {
        beforeAll(() => {
            mocks_1.entityMockUtils.initMocks();
        });
        afterEach(() => {
            mocks_1.entityMockUtils.reset();
        });
        afterAll(() => {
            mocks_1.entityMockUtils.cleanup();
        });
        test('should return whether the Identity possesses all roles', () => __awaiter(void 0, void 0, void 0, function* () {
            const identity = new internal_1.Identity({ did: 'someDid' }, context);
            const roles = [
                { type: types_1.RoleType.TickerOwner, ticker: 'someTicker' },
                { type: types_1.RoleType.TickerOwner, ticker: 'otherTicker' },
            ];
            let result = yield identity.checkRoles(roles);
            expect(result).toEqual({
                result: true,
            });
            mocks_1.entityMockUtils.reset();
            const stub = mocks_1.entityMockUtils.getTickerReservationDetailsStub();
            stub.onSecondCall().returns({
                owner: null,
            });
            result = yield identity.checkRoles(roles);
            expect(result).toEqual({
                result: false,
                missingRoles: [{ type: types_1.RoleType.TickerOwner, ticker: 'otherTicker' }],
            });
        }));
    });
    describe('method: hasRole and hasRoles', () => {
        beforeAll(() => {
            mocks_1.entityMockUtils.initMocks();
        });
        afterEach(() => {
            mocks_1.entityMockUtils.reset();
        });
        afterAll(() => {
            mocks_1.entityMockUtils.cleanup();
        });
        test('hasRole should check whether the Identity has the Ticker Owner role', () => __awaiter(void 0, void 0, void 0, function* () {
            const identity = new internal_1.Identity({ did: 'someDid' }, context);
            const role = { type: types_1.RoleType.TickerOwner, ticker: 'someTicker' };
            let hasRole = yield identity.hasRole(role);
            expect(hasRole).toBe(true);
            identity.did = 'otherDid';
            hasRole = yield identity.hasRole(role);
            expect(hasRole).toBe(false);
        }));
        test('hasRole should check whether the Identity has the CDD Provider role', () => __awaiter(void 0, void 0, void 0, function* () {
            const did = 'someDid';
            const identity = new internal_1.Identity({ did }, context);
            const role = { type: types_1.RoleType.CddProvider };
            const rawDid = mocks_1.dsMockUtils.createMockIdentityId(did);
            mocks_1.dsMockUtils.createQueryStub('cddServiceProviders', 'activeMembers').resolves([rawDid]);
            identityIdToStringStub.withArgs(rawDid).returns(did);
            let hasRole = yield identity.hasRole(role);
            expect(hasRole).toBe(true);
            identity.did = 'otherDid';
            hasRole = yield identity.hasRole(role);
            expect(hasRole).toBe(false);
        }));
        test('hasRole should check whether the Identity has the Venue Owner role', () => __awaiter(void 0, void 0, void 0, function* () {
            const did = 'someDid';
            const identity = new internal_1.Identity({ did }, context);
            const role = { type: types_1.RoleType.VenueOwner, venueId: new bignumber_js_1.default(10) };
            mocks_1.entityMockUtils.configureMocks({
                venueOptions: { details: { owner: new internal_1.Identity({ did }, context) } },
            });
            let hasRole = yield identity.hasRole(role);
            expect(hasRole).toBe(true);
            identity.did = 'otherDid';
            hasRole = yield identity.hasRole(role);
            expect(hasRole).toBe(false);
        }));
        test('hasRole should check whether the Identity has the Portfolio Custodian role', () => __awaiter(void 0, void 0, void 0, function* () {
            const did = 'someDid';
            const identity = new internal_1.Identity({ did }, context);
            const portfolioId = {
                did,
                number: new bignumber_js_1.default(1),
            };
            let role = { type: types_1.RoleType.PortfolioCustodian, portfolioId };
            mocks_1.entityMockUtils.configureMocks({
                numberedPortfolioOptions: { isCustodiedBy: true },
                defaultPortfolioOptions: { isCustodiedBy: false },
            });
            let hasRole = yield identity.hasRole(role);
            expect(hasRole).toBe(true);
            role = { type: types_1.RoleType.PortfolioCustodian, portfolioId: { did } };
            hasRole = yield identity.hasRole(role);
            expect(hasRole).toBe(false);
        }));
        test('hasRole should check whether the Identity has the Identity role', () => __awaiter(void 0, void 0, void 0, function* () {
            const did = 'someDid';
            const identity = new internal_1.Identity({ did }, context);
            const role = { type: types_1.RoleType.Identity, did };
            let hasRole = yield identity.hasRole(role);
            expect(hasRole).toBe(true);
            identity.did = 'otherDid';
            hasRole = yield identity.hasRole(role);
            expect(hasRole).toBe(false);
        }));
        test('hasRole should throw an error if the role is not recognized', () => {
            const identity = new internal_1.Identity({ did: 'someDid' }, context);
            const type = 'Fake';
            const role = { type, ticker: 'someTicker' };
            const hasRole = identity.hasRole(role);
            return expect(hasRole).rejects.toThrow(`Unrecognized role "${JSON.stringify(role)}"`);
        });
        test('hasRoles should return true if the Identity possesses all roles', () => __awaiter(void 0, void 0, void 0, function* () {
            const identity = new internal_1.Identity({ did: 'someDid' }, context);
            const roles = [
                { type: types_1.RoleType.TickerOwner, ticker: 'someTicker' },
                { type: types_1.RoleType.TickerOwner, ticker: 'otherTicker' },
            ];
            const hasRole = yield identity.hasRoles(roles);
            expect(hasRole).toBe(true);
        }));
        test("hasRoles should return false if at least one role isn't possessed by the Identity", () => __awaiter(void 0, void 0, void 0, function* () {
            const identity = new internal_1.Identity({ did: 'someDid' }, context);
            const roles = [
                { type: types_1.RoleType.TickerOwner, ticker: 'someTicker' },
                { type: types_1.RoleType.TickerOwner, ticker: 'otherTicker' },
            ];
            const stub = mocks_1.entityMockUtils.getTickerReservationDetailsStub();
            stub.onSecondCall().returns({
                owner: null,
            });
            const hasRole = yield identity.hasRoles(roles);
            expect(hasRole).toBe(false);
        }));
    });
    describe('method: getTokenBalance', () => {
        let ticker;
        let did;
        let rawTicker;
        let rawIdentityId;
        let fakeValue;
        let fakeBalance;
        let mockContext;
        let balanceOfStub;
        let tokensStub;
        let identity;
        beforeAll(() => {
            ticker = 'TEST';
            did = 'someDid';
            rawTicker = mocks_1.dsMockUtils.createMockTicker(ticker);
            rawIdentityId = mocks_1.dsMockUtils.createMockIdentityId(did);
            fakeValue = new bignumber_js_1.default(100);
            fakeBalance = mocks_1.dsMockUtils.createMockBalance(fakeValue.toNumber());
            mockContext = mocks_1.dsMockUtils.getContextInstance();
            balanceOfStub = mocks_1.dsMockUtils.createQueryStub('asset', 'balanceOf');
            tokensStub = mocks_1.dsMockUtils.createQueryStub('asset', 'tokens');
            stringToIdentityIdStub.withArgs(did, mockContext).returns(rawIdentityId);
            identity = new internal_1.Identity({ did }, mockContext);
            sinon_1.default
                .stub(utilsConversionModule, 'stringToTicker')
                .withArgs(ticker, mockContext)
                .returns(rawTicker);
            sinon_1.default
                .stub(utilsConversionModule, 'balanceToBigNumber')
                .withArgs(fakeBalance)
                .returns(fakeValue);
        });
        beforeEach(() => {
            /* eslint-disable @typescript-eslint/naming-convention */
            tokensStub.withArgs(rawTicker).resolves(mocks_1.dsMockUtils.createMockSecurityToken({
                owner_did: mocks_1.dsMockUtils.createMockIdentityId('tokenOwner'),
                total_supply: mocks_1.dsMockUtils.createMockBalance(3000),
                divisible: mocks_1.dsMockUtils.createMockBool(true),
                asset_type: mocks_1.dsMockUtils.createMockAssetType('EquityCommon'),
            }));
            /* eslint-enable @typescript-eslint/naming-convention */
        });
        test('should return the balance of a given token', () => __awaiter(void 0, void 0, void 0, function* () {
            balanceOfStub.withArgs(rawTicker, rawIdentityId).resolves(fakeBalance);
            const result = yield identity.getTokenBalance({ ticker });
            expect(result).toEqual(fakeValue);
        }));
        test('should allow subscription', () => __awaiter(void 0, void 0, void 0, function* () {
            const unsubCallback = 'unsubCallback';
            const callback = sinon_1.default.stub();
            balanceOfStub.withArgs(rawTicker, rawIdentityId).callsFake((_a, _b, cbFunc) => __awaiter(void 0, void 0, void 0, function* () {
                cbFunc(fakeBalance);
                return unsubCallback;
            }));
            const result = yield identity.getTokenBalance({ ticker }, callback);
            expect(result).toEqual(unsubCallback);
            sinon_1.default.assert.calledWithExactly(callback, fakeValue);
        }));
        test("should throw an error if the token doesn't exist", () => __awaiter(void 0, void 0, void 0, function* () {
            tokensStub.withArgs(rawTicker).resolves(mocks_1.dsMockUtils.createMockSecurityToken());
            let error;
            try {
                yield identity.getTokenBalance({ ticker });
            }
            catch (err) {
                error = err;
            }
            expect(error.message).toBe(`There is no Security Token with ticker "${ticker}"`);
        }));
    });
    describe('method: hasValidCdd', () => {
        test('should return whether the Identity has valid CDD', () => __awaiter(void 0, void 0, void 0, function* () {
            const did = 'someDid';
            const statusResponse = true;
            const mockContext = mocks_1.dsMockUtils.getContextInstance();
            const rawIdentityId = mocks_1.dsMockUtils.createMockIdentityId(did);
            const fakeHasValidCdd = mocks_1.dsMockUtils.createMockCddStatus({
                Ok: rawIdentityId,
            });
            stringToIdentityIdStub.withArgs(did, mockContext).returns(rawIdentityId);
            mocks_1.dsMockUtils
                .createRpcStub('identity', 'isIdentityHasValidCdd')
                .withArgs(rawIdentityId)
                .resolves(fakeHasValidCdd);
            sinon_1.default
                .stub(utilsConversionModule, 'cddStatusToBoolean')
                .withArgs(fakeHasValidCdd)
                .returns(statusResponse);
            const identity = new internal_1.Identity({ did }, context);
            const result = yield identity.hasValidCdd();
            expect(result).toEqual(statusResponse);
        }));
    });
    describe('method: isGcMember', () => {
        test('should return whether the Identity is GC member', () => __awaiter(void 0, void 0, void 0, function* () {
            const did = 'someDid';
            const rawDid = mocks_1.dsMockUtils.createMockIdentityId(did);
            const mockContext = mocks_1.dsMockUtils.getContextInstance();
            const identity = new internal_1.Identity({ did }, mockContext);
            identityIdToStringStub.withArgs(rawDid).returns(did);
            mocks_1.dsMockUtils
                .createQueryStub('committeeMembership', 'activeMembers')
                .resolves([rawDid, mocks_1.dsMockUtils.createMockIdentityId('otherDid')]);
            const result = yield identity.isGcMember();
            expect(result).toBeTruthy();
        }));
    });
    describe('method: isCddProvider', () => {
        test('should return whether the Identity is a CDD provider', () => __awaiter(void 0, void 0, void 0, function* () {
            const did = 'someDid';
            const rawDid = mocks_1.dsMockUtils.createMockIdentityId(did);
            const mockContext = mocks_1.dsMockUtils.getContextInstance();
            const identity = new internal_1.Identity({ did }, mockContext);
            identityIdToStringStub.withArgs(rawDid).returns(did);
            mocks_1.dsMockUtils
                .createQueryStub('cddServiceProviders', 'activeMembers')
                .resolves([rawDid, mocks_1.dsMockUtils.createMockIdentityId('otherDid')]);
            const result = yield identity.isCddProvider();
            expect(result).toBeTruthy();
        }));
    });
    describe('method: getPrimaryKey', () => {
        const did = 'someDid';
        const accountId = '5EYCAe5ijAx5xEfZdpCna3grUpY1M9M5vLUH5vpmwV1EnaYR';
        let accountIdToStringStub;
        let didRecordsStub;
        let rawDidRecord;
        beforeAll(() => {
            accountIdToStringStub = sinon_1.default.stub(utilsConversionModule, 'accountIdToString');
            accountIdToStringStub.returns(accountId);
        });
        beforeEach(() => {
            didRecordsStub = mocks_1.dsMockUtils.createQueryStub('identity', 'didRecords');
            /* eslint-disable @typescript-eslint/naming-convention */
            rawDidRecord = mocks_1.dsMockUtils.createMockDidRecord({
                roles: [],
                primary_key: mocks_1.dsMockUtils.createMockAccountId(accountId),
                secondary_keys: [],
            });
            /* eslint-enabled @typescript-eslint/naming-convention */
        });
        test('should return a PrimaryKey', () => __awaiter(void 0, void 0, void 0, function* () {
            const mockContext = mocks_1.dsMockUtils.getContextInstance();
            const identity = new internal_1.Identity({ did }, mockContext);
            didRecordsStub.returns(rawDidRecord);
            const result = yield identity.getPrimaryKey();
            expect(result).toEqual(mocks_1.entityMockUtils.getAccountInstance({ address: accountId }));
        }));
        test('should allow subscription', () => __awaiter(void 0, void 0, void 0, function* () {
            const mockContext = mocks_1.dsMockUtils.getContextInstance();
            const identity = new internal_1.Identity({ did }, mockContext);
            const unsubCallback = 'unsubCallBack';
            didRecordsStub.callsFake((_, cbFunc) => __awaiter(void 0, void 0, void 0, function* () {
                cbFunc(rawDidRecord);
                return unsubCallback;
            }));
            const callback = sinon_1.default.stub();
            const result = yield identity.getPrimaryKey(callback);
            expect(result).toBe(unsubCallback);
            sinon_1.default.assert.calledWithExactly(callback, mocks_1.entityMockUtils.getAccountInstance({ address: accountId }));
        }));
    });
    describe('method: getTrustingTokens', () => {
        const did = 'someDid';
        const tickers = ['TOKEN1\0\0', 'TOKEN2\0\0'];
        test('should return a list of security tokens', () => __awaiter(void 0, void 0, void 0, function* () {
            const identity = new internal_1.Identity({ did }, context);
            mocks_1.dsMockUtils.createApolloQueryStub(queries_1.tokensByTrustedClaimIssuer({ claimIssuerDid: did }), {
                tokensByTrustedClaimIssuer: tickers,
            });
            const result = yield identity.getTrustingTokens();
            expect(result[0].ticker).toBe('TOKEN1');
            expect(result[1].ticker).toBe('TOKEN2');
        }));
    });
    describe('method: getHeldTokens', () => {
        const did = 'someDid';
        const tickers = ['TOKEN1', 'TOKEN2'];
        test('should return a list of security tokens', () => __awaiter(void 0, void 0, void 0, function* () {
            const identity = new internal_1.Identity({ did }, context);
            mocks_1.dsMockUtils.createApolloQueryStub(queries_1.tokensHeldByDid({ did, count: undefined, skip: undefined, order: types_1.Order.Asc }), {
                tokensHeldByDid: { items: tickers, totalCount: 2 },
            });
            const result = yield identity.getHeldTokens();
            expect(result.data[0].ticker).toBe(tickers[0]);
            expect(result.data[1].ticker).toBe(tickers[1]);
        }));
    });
    describe('method: getVenues', () => {
        let did;
        let venueId;
        let rawDid;
        let rawVenueId;
        beforeAll(() => {
            did = 'someDid';
            venueId = new bignumber_js_1.default(10);
            rawDid = mocks_1.dsMockUtils.createMockIdentityId(did);
            rawVenueId = mocks_1.dsMockUtils.createMockU64(venueId.toNumber());
        });
        beforeEach(() => {
            stringToIdentityIdStub.withArgs(did, context).returns(rawDid);
        });
        afterAll(() => {
            sinon_1.default.restore();
        });
        test('should return a list of Venues', () => __awaiter(void 0, void 0, void 0, function* () {
            const fakeResult = [mocks_1.entityMockUtils.getVenueInstance({ id: venueId })];
            mocks_1.dsMockUtils
                .createQueryStub('settlement', 'userVenues')
                .withArgs(rawDid)
                .resolves([rawVenueId]);
            const identity = new internal_1.Identity({ did }, context);
            const result = yield identity.getVenues();
            expect(result).toEqual(fakeResult);
        }));
        test('should allow subscription', () => __awaiter(void 0, void 0, void 0, function* () {
            const unsubCallback = 'unsubCallBack';
            const fakeResult = [mocks_1.entityMockUtils.getVenueInstance({ id: venueId })];
            mocks_1.dsMockUtils.createQueryStub('settlement', 'userVenues').callsFake((_, cbFunc) => __awaiter(void 0, void 0, void 0, function* () {
                cbFunc([rawVenueId]);
                return unsubCallback;
            }));
            const identity = new internal_1.Identity({ did }, context);
            const callback = sinon_1.default.stub();
            const result = yield identity.getVenues(callback);
            expect(result).toEqual(unsubCallback);
            sinon_1.default.assert.calledWithExactly(callback, fakeResult);
        }));
    });
    describe('method: exists', () => {
        test('should return whether the Identity exists', () => __awaiter(void 0, void 0, void 0, function* () {
            const identity = new internal_1.Identity({ did: 'someDid' }, context);
            mocks_1.dsMockUtils.createQueryStub('identity', 'didRecords', {
                size: 10,
            });
            yield expect(identity.exists()).resolves.toBe(true);
            mocks_1.dsMockUtils.createQueryStub('identity', 'didRecords', {
                size: 0,
            });
            return expect(identity.exists()).resolves.toBe(false);
        }));
    });
    describe('method: getScopeId', () => {
        let did;
        let ticker;
        let scopeId;
        let rawDid;
        let rawTicker;
        let rawScopeId;
        let stringToTickerStub;
        beforeAll(() => {
            did = 'someDid';
            ticker = 'SOME_TICKER';
            scopeId = 'someScopeId';
            rawDid = mocks_1.dsMockUtils.createMockIdentityId(did);
            rawTicker = mocks_1.dsMockUtils.createMockTicker(ticker);
            rawScopeId = mocks_1.dsMockUtils.createMockScopeId(scopeId);
            stringToTickerStub = sinon_1.default.stub(utilsConversionModule, 'stringToTicker');
        });
        beforeEach(() => {
            stringToIdentityIdStub.withArgs(did, context).returns(rawDid);
            stringToTickerStub.withArgs(ticker, context).returns(rawTicker);
            mocks_1.dsMockUtils.createQueryStub('asset', 'scopeIdOf', {
                returnValue: rawScopeId,
            });
        });
        afterAll(() => {
            sinon_1.default.restore();
        });
        test("should return the Identity's scopeId associated to the token", () => __awaiter(void 0, void 0, void 0, function* () {
            const identity = new internal_1.Identity({ did }, context);
            let result = yield identity.getScopeId({ token: ticker });
            expect(result).toEqual(scopeId);
            result = yield identity.getScopeId({
                token: mocks_1.entityMockUtils.getSecurityTokenInstance({ ticker }),
            });
            expect(result).toEqual(scopeId);
        }));
    });
    describe('method: getInstructions', () => {
        afterAll(() => {
            sinon_1.default.restore();
        });
        test('should return all instructions in which the identity is involved, grouped by status', () => __awaiter(void 0, void 0, void 0, function* () {
            const id1 = new bignumber_js_1.default(1);
            const id2 = new bignumber_js_1.default(2);
            const id3 = new bignumber_js_1.default(3);
            const id4 = new bignumber_js_1.default(4);
            const id5 = new bignumber_js_1.default(5);
            const did = 'someDid';
            const identity = new internal_1.Identity({ did }, context);
            const defaultPortfolioDid = 'someDid';
            const numberedPortfolioDid = 'someDid';
            const numberedPortfolioId = new bignumber_js_1.default(1);
            const defaultPortfolio = mocks_1.entityMockUtils.getDefaultPortfolioInstance({
                did: defaultPortfolioDid,
                isCustodiedBy: true,
            });
            const numberedPortfolio = mocks_1.entityMockUtils.getNumberedPortfolioInstance({
                did: numberedPortfolioDid,
                id: numberedPortfolioId,
                isCustodiedBy: false,
            });
            identity.portfolios.getPortfolios = sinon_1.default
                .stub()
                .resolves([defaultPortfolio, numberedPortfolio]);
            identity.portfolios.getCustodiedPortfolios = sinon_1.default.stub().resolves({ data: [], next: null });
            const portfolioLikeToPortfolioIdStub = sinon_1.default.stub(utilsConversionModule, 'portfolioLikeToPortfolioId');
            portfolioLikeToPortfolioIdStub
                .withArgs(defaultPortfolio)
                .returns({ did: defaultPortfolioDid, number: undefined });
            portfolioLikeToPortfolioIdStub
                .withArgs(numberedPortfolio)
                .returns({ did: numberedPortfolioDid, number: numberedPortfolioId });
            const rawPortfolio = mocks_1.dsMockUtils.createMockPortfolioId({
                did: mocks_1.dsMockUtils.createMockIdentityId(did),
                kind: mocks_1.dsMockUtils.createMockPortfolioKind('Default'),
            });
            const portfolioIdToMeshPortfolioIdStub = sinon_1.default.stub(utilsConversionModule, 'portfolioIdToMeshPortfolioId');
            portfolioIdToMeshPortfolioIdStub
                .withArgs({ did, number: undefined }, context)
                .returns(rawPortfolio);
            const userAuthsStub = mocks_1.dsMockUtils.createQueryStub('settlement', 'userAffirmations');
            const rawId1 = mocks_1.dsMockUtils.createMockU64(id1.toNumber());
            const rawId2 = mocks_1.dsMockUtils.createMockU64(id2.toNumber());
            const rawId3 = mocks_1.dsMockUtils.createMockU64(id3.toNumber());
            const rawId4 = mocks_1.dsMockUtils.createMockU64(id4.toNumber());
            const rawId5 = mocks_1.dsMockUtils.createMockU64(id5.toNumber());
            const entriesStub = sinon_1.default.stub();
            entriesStub
                .withArgs(rawPortfolio)
                .resolves([
                utils_1.tuple({ args: [rawPortfolio, rawId1] }, mocks_1.dsMockUtils.createMockAffirmationStatus('Affirmed')),
                utils_1.tuple({ args: [rawPortfolio, rawId2] }, mocks_1.dsMockUtils.createMockAffirmationStatus('Pending')),
                utils_1.tuple({ args: [rawPortfolio, rawId3] }, mocks_1.dsMockUtils.createMockAffirmationStatus('Unknown')),
                utils_1.tuple({ args: [rawPortfolio, rawId4] }, mocks_1.dsMockUtils.createMockAffirmationStatus('Affirmed')),
                utils_1.tuple({ args: [rawPortfolio, rawId5] }, mocks_1.dsMockUtils.createMockAffirmationStatus('Unknown')),
            ]);
            userAuthsStub.entries = entriesStub;
            const instructionDetailsStub = mocks_1.dsMockUtils.createQueryStub('settlement', 'instructionDetails', {
                multi: [],
            });
            const multiStub = sinon_1.default.stub();
            multiStub.withArgs([rawId1, rawId2, rawId3, rawId4, rawId5]).resolves([
                mocks_1.dsMockUtils.createMockInstruction({
                    instruction_id: mocks_1.dsMockUtils.createMockU64(id1.toNumber()),
                    venue_id: mocks_1.dsMockUtils.createMockU64(),
                    status: mocks_1.dsMockUtils.createMockInstructionStatus('Pending'),
                    settlement_type: mocks_1.dsMockUtils.createMockSettlementType('SettleOnAffirmation'),
                    created_at: mocks_1.dsMockUtils.createMockOption(),
                    trade_date: mocks_1.dsMockUtils.createMockOption(),
                    value_date: mocks_1.dsMockUtils.createMockOption(),
                }),
                mocks_1.dsMockUtils.createMockInstruction({
                    instruction_id: mocks_1.dsMockUtils.createMockU64(id2.toNumber()),
                    venue_id: mocks_1.dsMockUtils.createMockU64(),
                    status: mocks_1.dsMockUtils.createMockInstructionStatus('Pending'),
                    settlement_type: mocks_1.dsMockUtils.createMockSettlementType('SettleOnAffirmation'),
                    created_at: mocks_1.dsMockUtils.createMockOption(),
                    trade_date: mocks_1.dsMockUtils.createMockOption(),
                    value_date: mocks_1.dsMockUtils.createMockOption(),
                }),
                mocks_1.dsMockUtils.createMockInstruction({
                    instruction_id: mocks_1.dsMockUtils.createMockU64(id3.toNumber()),
                    venue_id: mocks_1.dsMockUtils.createMockU64(),
                    status: mocks_1.dsMockUtils.createMockInstructionStatus('Unknown'),
                    settlement_type: mocks_1.dsMockUtils.createMockSettlementType('SettleOnAffirmation'),
                    created_at: mocks_1.dsMockUtils.createMockOption(),
                    trade_date: mocks_1.dsMockUtils.createMockOption(),
                    value_date: mocks_1.dsMockUtils.createMockOption(),
                }),
                mocks_1.dsMockUtils.createMockInstruction({
                    instruction_id: mocks_1.dsMockUtils.createMockU64(id4.toNumber()),
                    venue_id: mocks_1.dsMockUtils.createMockU64(),
                    status: mocks_1.dsMockUtils.createMockInstructionStatus('Failed'),
                    settlement_type: mocks_1.dsMockUtils.createMockSettlementType('SettleOnAffirmation'),
                    created_at: mocks_1.dsMockUtils.createMockOption(),
                    trade_date: mocks_1.dsMockUtils.createMockOption(),
                    value_date: mocks_1.dsMockUtils.createMockOption(),
                }),
                mocks_1.dsMockUtils.createMockInstruction({
                    instruction_id: mocks_1.dsMockUtils.createMockU64(id4.toNumber()),
                    venue_id: mocks_1.dsMockUtils.createMockU64(),
                    status: mocks_1.dsMockUtils.createMockInstructionStatus('Unknown'),
                    settlement_type: mocks_1.dsMockUtils.createMockSettlementType('SettleOnAffirmation'),
                    created_at: mocks_1.dsMockUtils.createMockOption(),
                    trade_date: mocks_1.dsMockUtils.createMockOption(),
                    value_date: mocks_1.dsMockUtils.createMockOption(),
                }),
            ]);
            instructionDetailsStub.multi = multiStub;
            const result = yield identity.getInstructions();
            expect(result.affirmed).toEqual([mocks_1.entityMockUtils.getInstructionInstance({ id: id1 })]);
            expect(result.pending).toEqual([mocks_1.entityMockUtils.getInstructionInstance({ id: id2 })]);
            expect(result.failed).toEqual([mocks_1.entityMockUtils.getInstructionInstance({ id: id4 })]);
        }));
    });
    describe('method: getPendingInstructions', () => {
        afterAll(() => {
            sinon_1.default.restore();
        });
        test('should return all pending instructions in which the identity is involved', () => __awaiter(void 0, void 0, void 0, function* () {
            const id1 = new bignumber_js_1.default(1);
            const id2 = new bignumber_js_1.default(2);
            const id3 = new bignumber_js_1.default(3);
            const id4 = new bignumber_js_1.default(4);
            const did = 'someDid';
            const identity = new internal_1.Identity({ did }, context);
            const defaultPortfolioDid = 'someDid';
            const numberedPortfolioDid = 'someDid';
            const numberedPortfolioId = new bignumber_js_1.default(1);
            const defaultPortfolio = mocks_1.entityMockUtils.getDefaultPortfolioInstance({
                did: defaultPortfolioDid,
                isCustodiedBy: true,
            });
            const numberedPortfolio = mocks_1.entityMockUtils.getNumberedPortfolioInstance({
                did: numberedPortfolioDid,
                id: numberedPortfolioId,
                isCustodiedBy: false,
            });
            identity.portfolios.getPortfolios = sinon_1.default
                .stub()
                .resolves([defaultPortfolio, numberedPortfolio]);
            identity.portfolios.getCustodiedPortfolios = sinon_1.default.stub().resolves({ data: [], next: null });
            const portfolioLikeToPortfolioIdStub = sinon_1.default.stub(utilsConversionModule, 'portfolioLikeToPortfolioId');
            portfolioLikeToPortfolioIdStub
                .withArgs(defaultPortfolio)
                .returns({ did: defaultPortfolioDid, number: undefined });
            portfolioLikeToPortfolioIdStub
                .withArgs(numberedPortfolio)
                .returns({ did: numberedPortfolioDid, number: numberedPortfolioId });
            const rawPortfolio = mocks_1.dsMockUtils.createMockPortfolioId({
                did: mocks_1.dsMockUtils.createMockIdentityId(did),
                kind: mocks_1.dsMockUtils.createMockPortfolioKind('Default'),
            });
            const portfolioIdToMeshPortfolioIdStub = sinon_1.default.stub(utilsConversionModule, 'portfolioIdToMeshPortfolioId');
            portfolioIdToMeshPortfolioIdStub
                .withArgs({ did, number: undefined }, context)
                .returns(rawPortfolio);
            const userAuthsStub = mocks_1.dsMockUtils.createQueryStub('settlement', 'userAffirmations');
            const rawId1 = mocks_1.dsMockUtils.createMockU64(id1.toNumber());
            const rawId2 = mocks_1.dsMockUtils.createMockU64(id2.toNumber());
            const rawId3 = mocks_1.dsMockUtils.createMockU64(id3.toNumber());
            const entriesStub = sinon_1.default.stub();
            entriesStub
                .withArgs(rawPortfolio)
                .resolves([
                utils_1.tuple({ args: [rawPortfolio, rawId1] }, mocks_1.dsMockUtils.createMockAffirmationStatus('Pending')),
                utils_1.tuple({ args: [rawPortfolio, rawId2] }, mocks_1.dsMockUtils.createMockAffirmationStatus('Pending')),
                utils_1.tuple({ args: [rawPortfolio, rawId3] }, mocks_1.dsMockUtils.createMockAffirmationStatus('Pending')),
            ]);
            userAuthsStub.entries = entriesStub;
            /* eslint-disable @typescript-eslint/naming-convention */
            const instructionDetailsStub = mocks_1.dsMockUtils.createQueryStub('settlement', 'instructionDetails', {
                multi: [],
            });
            const multiStub = sinon_1.default.stub();
            multiStub.withArgs([rawId1, rawId2, rawId3]).resolves([
                mocks_1.dsMockUtils.createMockInstruction({
                    instruction_id: mocks_1.dsMockUtils.createMockU64(id1.toNumber()),
                    venue_id: mocks_1.dsMockUtils.createMockU64(),
                    status: mocks_1.dsMockUtils.createMockInstructionStatus('Pending'),
                    settlement_type: mocks_1.dsMockUtils.createMockSettlementType('SettleOnAffirmation'),
                    created_at: mocks_1.dsMockUtils.createMockOption(),
                    trade_date: mocks_1.dsMockUtils.createMockOption(),
                    value_date: mocks_1.dsMockUtils.createMockOption(),
                }),
                mocks_1.dsMockUtils.createMockInstruction({
                    instruction_id: mocks_1.dsMockUtils.createMockU64(id2.toNumber()),
                    venue_id: mocks_1.dsMockUtils.createMockU64(),
                    status: mocks_1.dsMockUtils.createMockInstructionStatus('Pending'),
                    settlement_type: mocks_1.dsMockUtils.createMockSettlementType('SettleOnAffirmation'),
                    created_at: mocks_1.dsMockUtils.createMockOption(),
                    trade_date: mocks_1.dsMockUtils.createMockOption(),
                    value_date: mocks_1.dsMockUtils.createMockOption(),
                }),
                mocks_1.dsMockUtils.createMockInstruction({
                    instruction_id: mocks_1.dsMockUtils.createMockU64(id3.toNumber()),
                    venue_id: mocks_1.dsMockUtils.createMockU64(),
                    status: mocks_1.dsMockUtils.createMockInstructionStatus('Unknown'),
                    settlement_type: mocks_1.dsMockUtils.createMockSettlementType('SettleOnAffirmation'),
                    created_at: mocks_1.dsMockUtils.createMockOption(),
                    trade_date: mocks_1.dsMockUtils.createMockOption(),
                    value_date: mocks_1.dsMockUtils.createMockOption(),
                }),
                mocks_1.dsMockUtils.createMockInstruction({
                    instruction_id: mocks_1.dsMockUtils.createMockU64(id4.toNumber()),
                    venue_id: mocks_1.dsMockUtils.createMockU64(),
                    status: mocks_1.dsMockUtils.createMockInstructionStatus('Pending'),
                    settlement_type: mocks_1.dsMockUtils.createMockSettlementType('SettleOnAffirmation'),
                    created_at: mocks_1.dsMockUtils.createMockOption(),
                    trade_date: mocks_1.dsMockUtils.createMockOption(),
                    value_date: mocks_1.dsMockUtils.createMockOption(),
                }),
            ]);
            instructionDetailsStub.multi = multiStub;
            /* eslint-enable @typescript-eslint/naming-convention */
            const result = yield identity.getPendingInstructions();
            expect(result.length).toBe(3);
            expect(result[0].id).toEqual(id1);
            expect(result[1].id).toEqual(id2);
            expect(result[2].id).toEqual(id4);
        }));
    });
    describe('method: areSecondaryKeysFrozen', () => {
        let frozenStub;
        let boolValue;
        let rawBoolValue;
        beforeAll(() => {
            boolValue = true;
            rawBoolValue = mocks_1.dsMockUtils.createMockBool(boolValue);
        });
        beforeEach(() => {
            frozenStub = mocks_1.dsMockUtils.createQueryStub('identity', 'isDidFrozen');
        });
        test('should return whether secondary key is frozen or not', () => __awaiter(void 0, void 0, void 0, function* () {
            const identity = new internal_1.Identity({ did: 'someDid' }, context);
            frozenStub.resolves(rawBoolValue);
            const result = yield identity.areSecondaryKeysFrozen();
            expect(result).toBe(boolValue);
        }));
        test('should allow subscription', () => __awaiter(void 0, void 0, void 0, function* () {
            const identity = new internal_1.Identity({ did: 'someDid' }, context);
            const unsubCallback = 'unsubCallBack';
            frozenStub.callsFake((_, cbFunc) => __awaiter(void 0, void 0, void 0, function* () {
                cbFunc(rawBoolValue);
                return unsubCallback;
            }));
            const callback = sinon_1.default.stub();
            const result = yield identity.areSecondaryKeysFrozen(callback);
            expect(result).toBe(unsubCallback);
            sinon_1.default.assert.calledWithExactly(callback, boolValue);
        }));
    });
    describe('method: getPendingDistributions', () => {
        let tokens;
        let distributions;
        let expectedDistribution;
        beforeAll(() => {
            tokens = [
                mocks_1.entityMockUtils.getSecurityTokenInstance({ ticker: 'TICKER_1' }),
                mocks_1.entityMockUtils.getSecurityTokenInstance({ ticker: 'TICKER_2' }),
            ];
            const distributionTemplate = {
                expiryDate: null,
                perShare: new bignumber_js_1.default(1),
                checkpoint: mocks_1.entityMockUtils.getCheckpointInstance({
                    balance: new bignumber_js_1.default(1000),
                }),
                paymentDate: new Date('10/14/1987'),
            };
            const detailsTemplate = {
                remainingFunds: new bignumber_js_1.default(10000),
                fundsReclaimed: false,
            };
            expectedDistribution = {
                distribution: mocks_1.entityMockUtils.getDividendDistributionInstance(distributionTemplate),
                details: detailsTemplate,
            };
            distributions = [
                expectedDistribution,
                {
                    distribution: mocks_1.entityMockUtils.getDividendDistributionInstance(Object.assign(Object.assign({}, distributionTemplate), { expiryDate: new Date('10/14/1987') })),
                    details: detailsTemplate,
                },
                {
                    distribution: mocks_1.entityMockUtils.getDividendDistributionInstance(Object.assign(Object.assign({}, distributionTemplate), { paymentDate: new Date(new Date().getTime() + 3 * 60 * 1000) })),
                    details: detailsTemplate,
                },
                {
                    distribution: mocks_1.entityMockUtils.getDividendDistributionInstance(Object.assign(Object.assign({}, distributionTemplate), { id: new bignumber_js_1.default(5), ticker: 'HOLDER_PAID' })),
                    details: detailsTemplate,
                },
            ];
        });
        beforeEach(() => {
            context.getDividendDistributionsForTokens.withArgs({ tokens }).resolves(distributions);
        });
        afterAll(() => {
            sinon_1.default.restore();
        });
        test('should return all distributions where the Identity can claim funds', () => __awaiter(void 0, void 0, void 0, function* () {
            const holderPaidStub = mocks_1.dsMockUtils.createQueryStub('capitalDistribution', 'holderPaid');
            // eslint-disable-next-line @typescript-eslint/naming-convention
            const rawCaId = mocks_1.dsMockUtils.createMockCAId({ ticker: 'HOLDER_PAID', local_id: 5 });
            const rawIdentityId = mocks_1.dsMockUtils.createMockIdentityId('someDid');
            sinon_1.default
                .stub(utilsConversionModule, 'stringToIdentityId')
                .withArgs('someDid', context)
                .returns(rawIdentityId);
            sinon_1.default
                .stub(utilsConversionModule, 'corporateActionIdentifierToCaId')
                .withArgs({ ticker: 'HOLDER_PAID', localId: new bignumber_js_1.default(5) }, context)
                .returns(rawCaId);
            holderPaidStub.resolves(mocks_1.dsMockUtils.createMockBool(false));
            holderPaidStub.withArgs([rawCaId, rawIdentityId]).resolves(mocks_1.dsMockUtils.createMockBool(true));
            const identity = new internal_1.Identity({ did: 'someDid' }, context);
            const heldTokensStub = sinon_1.default.stub(identity, 'getHeldTokens');
            heldTokensStub.onFirstCall().resolves({ data: [tokens[0]], next: 1 });
            heldTokensStub.onSecondCall().resolves({ data: [tokens[1]], next: null });
            const result = yield identity.getPendingDistributions();
            expect(result).toEqual([expectedDistribution]);
        }));
    });
    describe('method: getSecondaryKeys', () => {
        const did = 'someDid';
        const accountId = 'someAccountId';
        const signerValues = [
            { value: did, type: types_1.SignerType.Identity },
            { value: accountId, type: types_1.SignerType.Account },
        ];
        const signerIdentityId = mocks_1.dsMockUtils.createMockSignatory({
            Identity: mocks_1.dsMockUtils.createMockIdentityId(did),
        });
        const signerAccountId = mocks_1.dsMockUtils.createMockSignatory({
            Account: mocks_1.dsMockUtils.createMockAccountId(accountId),
        });
        let account;
        let fakeIdentity;
        let fakeResult;
        let signatoryToSignerValueStub;
        let signerValueToSignerStub;
        let didRecordsStub;
        let rawDidRecord;
        beforeAll(() => {
            fakeIdentity = mocks_1.entityMockUtils.getIdentityInstance();
            signatoryToSignerValueStub = sinon_1.default.stub(utilsConversionModule, 'signatoryToSignerValue');
            signatoryToSignerValueStub.withArgs(signerIdentityId).returns(signerValues[0]);
            signatoryToSignerValueStub.withArgs(signerAccountId).returns(signerValues[1]);
            account = mocks_1.entityMockUtils.getAccountInstance({ address: accountId });
            signerValueToSignerStub = sinon_1.default.stub(utilsConversionModule, 'signerValueToSigner');
            signerValueToSignerStub.withArgs(signerValues[0], sinon_1.default.match.object).returns(fakeIdentity);
            signerValueToSignerStub.withArgs(signerValues[1], sinon_1.default.match.object).returns(account);
            fakeResult = [
                {
                    signer: fakeIdentity,
                    permissions: {
                        tokens: null,
                        portfolios: null,
                        transactions: null,
                        transactionGroups: [],
                    },
                },
                {
                    signer: account,
                    permissions: {
                        tokens: null,
                        portfolios: null,
                        transactions: null,
                        transactionGroups: [],
                    },
                },
            ];
        });
        beforeEach(() => {
            didRecordsStub = mocks_1.dsMockUtils.createQueryStub('identity', 'didRecords');
            /* eslint-disable @typescript-eslint/naming-convention */
            rawDidRecord = mocks_1.dsMockUtils.createMockDidRecord({
                roles: [],
                primary_key: mocks_1.dsMockUtils.createMockAccountId(),
                secondary_keys: [
                    mocks_1.dsMockUtils.createMockSecondaryKey({
                        signer: signerIdentityId,
                        permissions: mocks_1.dsMockUtils.createMockPermissions({
                            asset: mocks_1.dsMockUtils.createMockAssetPermissions(),
                            extrinsic: mocks_1.dsMockUtils.createMockExtrinsicPermissions(),
                            portfolio: mocks_1.dsMockUtils.createMockPortfolioPermissions(),
                        }),
                    }),
                    mocks_1.dsMockUtils.createMockSecondaryKey({
                        signer: signerAccountId,
                        permissions: mocks_1.dsMockUtils.createMockPermissions({
                            asset: mocks_1.dsMockUtils.createMockAssetPermissions('Whole'),
                            extrinsic: mocks_1.dsMockUtils.createMockExtrinsicPermissions('Whole'),
                            portfolio: mocks_1.dsMockUtils.createMockPortfolioPermissions('Whole'),
                        }),
                    }),
                ],
            });
            /* eslint-enabled @typescript-eslint/naming-convention */
        });
        test('should return a list of Signers', () => __awaiter(void 0, void 0, void 0, function* () {
            const identity = new internal_1.Identity({ did: 'someDid' }, context);
            didRecordsStub.resolves(rawDidRecord);
            const result = yield identity.getSecondaryKeys();
            expect(result).toEqual(fakeResult);
        }));
        test('should allow subscription', () => __awaiter(void 0, void 0, void 0, function* () {
            const identity = new internal_1.Identity({ did: 'someDid' }, context);
            const unsubCallback = 'unsubCallBack';
            didRecordsStub.callsFake((_, cbFunc) => __awaiter(void 0, void 0, void 0, function* () {
                cbFunc(rawDidRecord);
                return unsubCallback;
            }));
            const callback = sinon_1.default.stub();
            const result = yield identity.getSecondaryKeys(callback);
            expect(result).toBe(unsubCallback);
            sinon_1.default.assert.calledWithExactly(callback, fakeResult);
        }));
    });
    describe('method: toJson', () => {
        test('should return a human readable version of the entity', () => {
            const identity = new internal_1.Identity({ did: 'someDid' }, context);
            expect(identity.toJson()).toBe('someDid');
        });
    });
});
//# sourceMappingURL=index.js.map