"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 internal_1 = require("../../internal");
const queries_1 = require("../../middleware/queries");
const types_2 = require("../../middleware/types");
const mocks_1 = require("../../testUtils/mocks");
const dataSources_1 = require("../../testUtils/mocks/dataSources");
const types_3 = require("../../types");
const utils_1 = require("../../types/utils");
const constants_1 = require("../../utils/constants");
const utilsConversionModule = __importStar(require("../../utils/conversion"));
const utilsInternalModule = __importStar(require("../../utils/internal"));
jest.mock('@polkadot/api', require("../../testUtils/mocks/dataSources").mockPolkadotModule('@polkadot/api'));
jest.mock('~/api/entities/Identity', require("../../testUtils/mocks/entities").mockIdentityModule('~/api/entities/Identity'));
jest.mock('~/api/entities/Account', require("../../testUtils/mocks/entities").mockAccountModule('~/api/entities/Account'));
jest.mock('~/api/entities/DividendDistribution', require("../../testUtils/mocks/entities").mockDividendDistributionModule('~/api/entities/DividendDistribution'));
jest.mock('~/api/entities/DefaultPortfolio', require("../../testUtils/mocks/entities").mockDefaultPortfolioModule('~/api/entities/DefaultPortfolio'));
jest.mock('~/api/entities/NumberedPortfolio', require("../../testUtils/mocks/entities").mockNumberedPortfolioModule('~/api/entities/NumberedPortfolio'));
// TODO: refactor tests (too much repeated code)
describe('Context class', () => {
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks();
        mocks_1.entityMockUtils.initMocks();
    });
    beforeEach(() => {
        mocks_1.dsMockUtils.setConstMock('system', 'ss58Prefix', { returnValue: mocks_1.dsMockUtils.createMockU8(42) });
        mocks_1.dsMockUtils.createQueryStub('identity', 'keyToIdentityIds', {
            returnValue: mocks_1.dsMockUtils.createMockIdentityId('someDid'),
        });
    });
    afterEach(() => {
        mocks_1.dsMockUtils.reset();
        mocks_1.entityMockUtils.reset();
    });
    afterAll(() => {
        mocks_1.dsMockUtils.cleanup();
        mocks_1.entityMockUtils.cleanup();
    });
    test('should throw an error if accessing the transaction submodule without an active account', () => __awaiter(void 0, void 0, void 0, function* () {
        const context = yield internal_1.Context.create({
            polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
            middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
            keyring: mocks_1.dsMockUtils.getKeyringInstance({ getPairs: [] }),
        });
        expect(() => context.polymeshApi.tx).toThrow('Cannot perform transactions without an active Account');
    }));
    test('should throw an error if accessing the middleware client without an active connection', () => __awaiter(void 0, void 0, void 0, function* () {
        const newPair = {
            address: 'someAddress1',
            meta: {},
            publicKey: 'publicKey',
        };
        mocks_1.dsMockUtils.configureMocks({
            keyringOptions: {
                addFromSeed: newPair,
            },
        });
        const context = yield internal_1.Context.create({
            polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
            middlewareApi: null,
            accountSeed: '0x6'.padEnd(66, '0'),
        });
        expect(() => context.middlewareApi).toThrow('Cannot perform this action without an active middleware connection');
    }));
    test('should check if the middleware client is equal to the instance passed to the constructor', () => __awaiter(void 0, void 0, void 0, function* () {
        const newPair = {
            address: 'someAddress1',
            meta: {},
            publicKey: 'publicKey',
        };
        mocks_1.dsMockUtils.configureMocks({
            keyringOptions: {
                addFromSeed: newPair,
            },
        });
        const middlewareApi = mocks_1.dsMockUtils.getMiddlewareApi();
        const context = yield internal_1.Context.create({
            polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
            middlewareApi,
            accountSeed: '0x6'.padEnd(66, '0'),
        });
        expect(context.middlewareApi).toEqual(middlewareApi);
    }));
    describe('method: create', () => {
        beforeEach(() => {
            mocks_1.dsMockUtils.createQueryStub('balances', 'totalIssuance', {
                returnValue: mocks_1.dsMockUtils.createMockBalance(100),
            });
            mocks_1.dsMockUtils.createQueryStub('system', 'blockHash', {
                returnValue: mocks_1.dsMockUtils.createMockHash('someBlockHash'),
            });
        });
        test('should throw if seed parameter is not a 66 length string', () => {
            const context = internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: 'abc',
            });
            return expect(context).rejects.toThrow(new Error('Seed must be 66 characters in length'));
        });
        test('should create a Context object from a seed with Pair attached', () => __awaiter(void 0, void 0, void 0, function* () {
            const newPair = {
                address: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
                meta: {},
                publicKey: 'publicKey',
            };
            mocks_1.dsMockUtils.configureMocks({
                keyringOptions: {
                    getPairs: [newPair],
                },
            });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            expect(context.currentPair).toEqual(newPair);
        }));
        test('should create a Context object from a keyring with Pair attached', () => __awaiter(void 0, void 0, void 0, function* () {
            const pairs = [
                {
                    address: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
                    meta: {},
                    publicKey: 'publicKey',
                },
            ];
            mocks_1.dsMockUtils.configureMocks({
                keyringOptions: {
                    getPairs: pairs,
                },
            });
            sinon_1.default.stub(utilsInternalModule, 'assertFormatValid');
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                keyring: mocks_1.dsMockUtils.getKeyringInstance(),
            });
            expect(context.currentPair).toEqual(pairs[0]);
        }));
        test('should throw if keyring has incorrect ss58 format set', () => {
            const pairs = [
                {
                    address: '2HFAAoz9ZGHnLL84ytDhVBXggYv4avQCiS5ajtKLudRhUFrh',
                    meta: {},
                    publicKey: 'publicKey',
                },
            ];
            mocks_1.dsMockUtils.configureMocks({
                keyringOptions: {
                    getPairs: pairs,
                    encodeAddress: '2HFAAoz9ZGHnLL84ytDhVBXggYv4avQCiS5ajtKLudRhUFrh',
                },
            });
            const context = internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                keyring: mocks_1.dsMockUtils.getKeyringInstance(),
            });
            return expect(context).rejects.toThrow(new Error("The supplied keyring is not using the chain's SS58 format"));
        });
        test('should create a Context object from a uri with Pair attached', () => __awaiter(void 0, void 0, void 0, function* () {
            const newPair = {
                address: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
                meta: {},
                publicKey: 'publicKey',
            };
            mocks_1.dsMockUtils.configureMocks({
                keyringOptions: {
                    getPairs: [newPair],
                },
            });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountUri: '//Alice',
            });
            expect(context.currentPair).toEqual(newPair);
        }));
        test('should create a Context object from a mnemonic with Pair attached', () => __awaiter(void 0, void 0, void 0, function* () {
            const newPair = {
                address: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
                meta: {},
                publicKey: 'publicKey',
            };
            mocks_1.dsMockUtils.configureMocks({
                keyringOptions: {
                    getPairs: [newPair],
                },
            });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountMnemonic: 'lorem ipsum dolor sit amet consectetur adipiscing elit nam hendrerit consectetur sagittis',
            });
            expect(context.currentPair).toEqual(newPair);
        }));
        test('should create a Context object without Pair attached', () => __awaiter(void 0, void 0, void 0, function* () {
            mocks_1.dsMockUtils.configureMocks({
                keyringOptions: {
                    getPairs: [],
                },
            });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
            });
            expect(context.currentPair).toBe(undefined);
        }));
    });
    describe('method: getAccounts', () => {
        test('should retrieve an array of Accounts', () => __awaiter(void 0, void 0, void 0, function* () {
            const pairs = [
                {
                    address: '5GNWrbft4pJcYSak9tkvUy89e2AKimEwHb6CKaJq81KHEj8e',
                    meta: {
                        name: 'name 01',
                    },
                    somethingElse: false,
                    publicKey: 'publicKey',
                },
                {
                    address: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
                    meta: {},
                    somethingElse: false,
                    publicKey: 'publicKey',
                },
            ];
            mocks_1.dsMockUtils.configureMocks({
                keyringOptions: {
                    getPairs: pairs,
                },
            });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
            });
            let result = context.getAccounts();
            expect(result[0].address).toBe(pairs[0].address);
            expect(result[1].address).toBe(pairs[1].address);
            expect(result[0] instanceof internal_1.Account).toBe(true);
            expect(result[1] instanceof internal_1.Account).toBe(true);
            context.setPair(result[1].address);
            result = context.getAccounts();
            expect(result[1].address).toBe(pairs[0].address);
            expect(result[0].address).toBe(pairs[1].address);
            expect(result[0] instanceof internal_1.Account).toBe(true);
            expect(result[1] instanceof internal_1.Account).toBe(true);
        }));
        test('should throw an error if there is no Current Account', () => __awaiter(void 0, void 0, void 0, function* () {
            mocks_1.dsMockUtils.configureMocks({
                keyringOptions: {
                    getPairs: [],
                },
            });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
            });
            expect(() => context.getAccounts()).toThrow('There is no Account associated with the SDK');
        }));
    });
    describe('method: setPair', () => {
        test('should throw error if the pair does not exist in the keyring set', () => __awaiter(void 0, void 0, void 0, function* () {
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
            });
            mocks_1.dsMockUtils.getKeyringInstance().getPair.throws(new Error('failed'));
            return expect(() => context.setPair('012')).toThrow('The address is not present in the keyring set');
        }));
        test('should set new value for currentPair', () => __awaiter(void 0, void 0, void 0, function* () {
            const publicKey = 'publicKey';
            const newPublicKey = 'newPublicKey';
            const newAddress = 'newAddress';
            const accountId = mocks_1.dsMockUtils.createMockAccountId(newAddress);
            const newCurrentPair = {
                address: newAddress,
                meta: {},
                publicKey: newPublicKey,
            };
            mocks_1.dsMockUtils.configureMocks({
                keyringOptions: {
                    addFromSeed: {
                        address: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
                        meta: {},
                        publicKey,
                    },
                    getPair: newCurrentPair,
                },
            });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            sinon_1.default
                .stub(utilsConversionModule, 'stringToAccountId')
                .withArgs(newAddress, context)
                .returns(accountId);
            context.setPair(constants_1.DUMMY_ACCOUNT_ID);
            expect(context.currentPair).toEqual(newCurrentPair);
        }));
    });
    describe('method: accountBalance', () => {
        test('should throw if accountId or currentPair is not set', () => __awaiter(void 0, void 0, void 0, function* () {
            mocks_1.dsMockUtils.configureMocks({
                keyringOptions: {
                    getPairs: [],
                },
            });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
            });
            return expect(context.accountBalance()).rejects.toThrow('There is no Account associated with the current SDK instance');
        }));
        test('should return the account POLYX balance if currentPair is set', () => __awaiter(void 0, void 0, void 0, function* () {
            const freeBalance = mocks_1.dsMockUtils.createMockBalance(100);
            const returnValue = mocks_1.dsMockUtils.createMockAccountInfo({
                nonce: mocks_1.dsMockUtils.createMockIndex(),
                refcount: mocks_1.dsMockUtils.createMockRefCount(),
                data: mocks_1.dsMockUtils.createMockAccountData({
                    free: freeBalance,
                    reserved: mocks_1.dsMockUtils.createMockBalance(),
                    miscFrozen: mocks_1.dsMockUtils.createMockBalance(),
                    feeFrozen: mocks_1.dsMockUtils.createMockBalance(),
                }),
            });
            mocks_1.dsMockUtils.createQueryStub('system', 'account', { returnValue });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            const result = yield context.accountBalance();
            expect(result.free).toEqual(utilsConversionModule.balanceToBigNumber(freeBalance));
        }));
        test('should return the account POLYX balance if accountId is set', () => __awaiter(void 0, void 0, void 0, function* () {
            const freeBalance = mocks_1.dsMockUtils.createMockBalance(100);
            const returnValue = mocks_1.dsMockUtils.createMockAccountInfo({
                nonce: mocks_1.dsMockUtils.createMockIndex(),
                refcount: mocks_1.dsMockUtils.createMockRefCount(),
                data: mocks_1.dsMockUtils.createMockAccountData({
                    free: freeBalance,
                    reserved: mocks_1.dsMockUtils.createMockBalance(),
                    miscFrozen: mocks_1.dsMockUtils.createMockBalance(),
                    feeFrozen: mocks_1.dsMockUtils.createMockBalance(),
                }),
            });
            mocks_1.dsMockUtils.createQueryStub('system', 'account', { returnValue });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            const result = yield context.accountBalance('accountId');
            expect(result.free).toEqual(utilsConversionModule.balanceToBigNumber(freeBalance));
        }));
        test('should allow subscription', () => __awaiter(void 0, void 0, void 0, function* () {
            const unsubCallback = 'unsubCallback';
            const free = mocks_1.dsMockUtils.createMockBalance(100);
            const miscFrozen = mocks_1.dsMockUtils.createMockBalance(10);
            const feeFrozen = mocks_1.dsMockUtils.createMockBalance(12);
            const returnValue = mocks_1.dsMockUtils.createMockAccountInfo({
                nonce: mocks_1.dsMockUtils.createMockIndex(),
                refcount: mocks_1.dsMockUtils.createMockRefCount(),
                data: mocks_1.dsMockUtils.createMockAccountData({
                    free,
                    reserved: mocks_1.dsMockUtils.createMockBalance(),
                    miscFrozen,
                    feeFrozen,
                }),
            });
            mocks_1.dsMockUtils.createQueryStub('system', 'account').callsFake((_, cbFunc) => __awaiter(void 0, void 0, void 0, function* () {
                cbFunc(returnValue);
                return unsubCallback;
            }));
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            const callback = sinon_1.default.stub();
            const result = yield context.accountBalance('accountId', callback);
            expect(result).toEqual(unsubCallback);
            const freeBalance = utilsConversionModule.balanceToBigNumber(free);
            const feeFrozenBalance = utilsConversionModule.balanceToBigNumber(feeFrozen);
            sinon_1.default.assert.calledWithExactly(callback, {
                free: freeBalance,
                locked: feeFrozenBalance,
                total: freeBalance.plus(feeFrozenBalance),
            });
        }));
    });
    describe('method: accountSubsidy', () => {
        test('should throw if accountId or currentPair is not set', () => __awaiter(void 0, void 0, void 0, function* () {
            mocks_1.dsMockUtils.configureMocks({
                keyringOptions: {
                    getPairs: [],
                },
            });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
            });
            return expect(context.accountSubsidy()).rejects.toThrow('There is no Account associated with the current SDK instance');
        }));
        test('should return the account subsidizer and allowance if currentPair is set', () => __awaiter(void 0, void 0, void 0, function* () {
            const allowance = mocks_1.dsMockUtils.createMockBalance(100);
            const returnValue = mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockSubsidy({
                // eslint-disable-next-line @typescript-eslint/naming-convention
                paying_key: mocks_1.dsMockUtils.createMockAccountId('payingKey'),
                remaining: allowance,
            }));
            mocks_1.dsMockUtils.createQueryStub('relayer', 'subsidies', { returnValue });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            const result = yield context.accountSubsidy();
            expect(result).toEqual({
                allowance: utilsConversionModule.balanceToBigNumber(allowance),
                subsidizer: mocks_1.entityMockUtils.getAccountInstance({ address: 'payingKey' }),
            });
        }));
        test('should return the account subsidizer and allowance if accountId is set', () => __awaiter(void 0, void 0, void 0, function* () {
            const allowance = mocks_1.dsMockUtils.createMockBalance(100);
            const returnValue = mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockSubsidy({
                // eslint-disable-next-line @typescript-eslint/naming-convention
                paying_key: mocks_1.dsMockUtils.createMockAccountId('payingKey'),
                remaining: allowance,
            }));
            mocks_1.dsMockUtils.createQueryStub('relayer', 'subsidies', { returnValue });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            const result = yield context.accountSubsidy('accountId');
            expect(result).toEqual({
                allowance: utilsConversionModule.balanceToBigNumber(allowance),
                subsidizer: mocks_1.entityMockUtils.getAccountInstance({ address: 'payingKey' }),
            });
        }));
        test('should return null if the account has no subsidizer', () => __awaiter(void 0, void 0, void 0, function* () {
            const returnValue = mocks_1.dsMockUtils.createMockOption();
            mocks_1.dsMockUtils.createQueryStub('relayer', 'subsidies', { returnValue });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            const result = yield context.accountSubsidy();
            expect(result).toBeNull();
        }));
        test('should allow subscription', () => __awaiter(void 0, void 0, void 0, function* () {
            const unsubCallback = 'unsubCallback';
            const allowance = mocks_1.dsMockUtils.createMockBalance(100);
            const returnValue = mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockSubsidy({
                // eslint-disable-next-line @typescript-eslint/naming-convention
                paying_key: mocks_1.dsMockUtils.createMockAccountId('payingKey'),
                remaining: allowance,
            }));
            mocks_1.dsMockUtils.createQueryStub('relayer', 'subsidies').callsFake((_, cbFunc) => __awaiter(void 0, void 0, void 0, function* () {
                cbFunc(returnValue);
                return unsubCallback;
            }));
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            const callback = sinon_1.default.stub();
            const result = yield context.accountSubsidy('accountId', callback);
            expect(result).toEqual(unsubCallback);
            sinon_1.default.assert.calledWithExactly(callback, {
                allowance: utilsConversionModule.balanceToBigNumber(allowance),
                subsidizer: mocks_1.entityMockUtils.getAccountInstance({ address: 'payingKey' }),
            });
        }));
    });
    describe('method: getCurrentIdentity', () => {
        test('should return the current Identity', () => __awaiter(void 0, void 0, void 0, function* () {
            const did = 'someDid';
            mocks_1.dsMockUtils.createQueryStub('identity', 'keyToIdentityIds', {
                returnValue: mocks_1.dsMockUtils.createMockIdentityId(did),
            });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            const result = yield context.getCurrentIdentity();
            expect(result.did).toBe(did);
        }));
        test('should throw an error if there is no Identity associated to the Current Account', () => __awaiter(void 0, void 0, void 0, function* () {
            mocks_1.entityMockUtils.getAccountGetIdentityStub().resolves(null);
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            return expect(context.getCurrentIdentity()).rejects.toThrow('The current Account does not have an associated Identity');
        }));
    });
    describe('method: getCurrentAccount', () => {
        test('should return the current Account', () => __awaiter(void 0, void 0, void 0, function* () {
            const address = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
            const pair = {
                address,
                meta: {},
                publicKey: 'publicKey',
            };
            mocks_1.dsMockUtils.configureMocks({
                keyringOptions: {
                    getPairs: [pair],
                },
            });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            const result = context.getCurrentAccount();
            expect(result.address).toBe(address);
        }));
        test('should throw an error if there is no account associated with the SDK', () => __awaiter(void 0, void 0, void 0, function* () {
            mocks_1.dsMockUtils.configureMocks({
                keyringOptions: {
                    getPairs: [],
                },
            });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
            });
            let err;
            try {
                context.getCurrentAccount();
            }
            catch (e) {
                err = e;
            }
            expect(err.message).toBe('There is no Account associated with the current SDK instance');
        }));
    });
    describe('method: getCurrentPair', () => {
        test('should return the current keyring pair', () => __awaiter(void 0, void 0, void 0, function* () {
            const pair = {
                address: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
                meta: {},
                publicKey: 'publicKey',
            };
            mocks_1.dsMockUtils.configureMocks({
                keyringOptions: {
                    getPairs: [pair],
                },
            });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            const result = context.getCurrentPair();
            expect(result).toBe(pair);
        }));
        test("should throw an error if the current pair isn't defined", () => __awaiter(void 0, void 0, void 0, function* () {
            mocks_1.dsMockUtils.configureMocks({
                keyringOptions: {
                    getPairs: [],
                },
            });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
            });
            expect(() => context.getCurrentPair()).toThrow('There is no Account associated with the current SDK instance');
        }));
    });
    describe('method: getSigner', () => {
        test('should return the signer address if the current pair is locked', () => __awaiter(void 0, void 0, void 0, function* () {
            const pair = {
                address: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
                meta: {},
                publicKey: 'publicKey',
                isLocked: true,
            };
            mocks_1.dsMockUtils.configureMocks({
                keyringOptions: {
                    getPairs: [pair],
                },
            });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            expect(context.getSigner()).toBe(pair.address);
        }));
        test('should return the signer address if the current pair is locked', () => __awaiter(void 0, void 0, void 0, function* () {
            const pair = {
                address: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
                meta: {},
                publicKey: 'publicKey',
                isLocked: false,
            };
            mocks_1.dsMockUtils.configureMocks({
                keyringOptions: {
                    getPairs: [pair],
                },
            });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            expect(context.getSigner()).toEqual(pair);
        }));
    });
    describe('method: getInvalidDids', () => {
        /* eslint-disable @typescript-eslint/naming-convention */
        test('should return which DIDs in the input array are invalid', () => __awaiter(void 0, void 0, void 0, function* () {
            const inputDids = ['someDid', 'otherDid', 'invalidDid', 'otherInvalidDid'];
            mocks_1.dsMockUtils.createQueryStub('identity', 'didRecords', {
                multi: [
                    mocks_1.dsMockUtils.createMockDidRecord({
                        roles: [],
                        primary_key: dataSources_1.createMockAccountId('someId'),
                        secondary_keys: [],
                    }),
                    mocks_1.dsMockUtils.createMockDidRecord({
                        roles: [],
                        primary_key: dataSources_1.createMockAccountId('otherId'),
                        secondary_keys: [],
                    }),
                    mocks_1.dsMockUtils.createMockDidRecord(),
                    mocks_1.dsMockUtils.createMockDidRecord(),
                ],
            });
            const newPair = {
                address: 'someAddress',
                meta: {},
                publicKey: 'publicKey',
            };
            mocks_1.dsMockUtils.configureMocks({
                keyringOptions: {
                    addFromUri: newPair,
                },
            });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountUri: '//Alice',
            });
            const invalidDids = yield context.getInvalidDids(inputDids);
            expect(invalidDids).toEqual(inputDids.slice(2, 4));
        }));
        /* eslint-enable @typescript-eslint/naming-convention */
    });
    describe('method: getTransactionFees', () => {
        test('should return the fees associated to the supplied transaction', () => __awaiter(void 0, void 0, void 0, function* () {
            const pair = {
                address: 'someAddress1',
                meta: {},
                publicKey: 'publicKey',
            };
            mocks_1.dsMockUtils.configureMocks({
                keyringOptions: {
                    addFromSeed: pair,
                },
            });
            mocks_1.dsMockUtils.createQueryStub('protocolFee', 'coefficient', {
                returnValue: mocks_1.dsMockUtils.createMockPosRatio(1, 2),
            });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            const txTagToProtocolOpStub = sinon_1.default.stub(utilsConversionModule, 'txTagToProtocolOp');
            txTagToProtocolOpStub
                .withArgs(types_1.TxTags.asset.CreateAsset, context)
                .returns('someProtocolOp');
            txTagToProtocolOpStub.withArgs(types_1.TxTags.asset.Freeze, context).throws(); // transaction without fees
            mocks_1.dsMockUtils.createQueryStub('protocolFee', 'baseFees', {
                returnValue: mocks_1.dsMockUtils.createMockBalance(500000000),
            });
            let result = yield context.getTransactionFees(types_1.TxTags.asset.CreateAsset);
            expect(result).toEqual(new bignumber_js_1.default(250));
            result = yield context.getTransactionFees(types_1.TxTags.asset.Freeze);
            expect(result).toEqual(new bignumber_js_1.default(0));
        }));
    });
    describe('method: getTransactionArguments', () => {
        test('should return a representation of the arguments of a transaction', () => __awaiter(void 0, void 0, void 0, function* () {
            const pair = {
                address: 'someAddress1',
                meta: {},
                publicKey: 'publicKey',
            };
            mocks_1.dsMockUtils.configureMocks({
                keyringOptions: {
                    addFromSeed: pair,
                },
            });
            mocks_1.dsMockUtils.createQueryStub('protocolFee', 'coefficient', {
                returnValue: mocks_1.dsMockUtils.createMockPosRatio(1, 2),
            });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            mocks_1.dsMockUtils.createTxStub('asset', 'registerTicker', {
                meta: {
                    args: [
                        {
                            type: 'Ticker',
                            name: 'ticker',
                        },
                    ],
                },
            });
            expect(context.getTransactionArguments({ tag: types_1.TxTags.asset.RegisterTicker })).toMatchObject([
                {
                    name: 'ticker',
                    type: types_3.TransactionArgumentType.Text,
                    optional: false,
                },
            ]);
            mocks_1.dsMockUtils.createTxStub('identity', 'addClaim', {
                meta: {
                    args: [
                        {
                            type: 'IdentityId',
                            name: 'target',
                        },
                        {
                            type: 'PortfolioKind',
                            name: 'portfolioKind',
                        },
                        {
                            type: 'Option<Moment>',
                            name: 'expiry',
                        },
                        {
                            type: '(IdentityId, u32)',
                            name: 'identityPair',
                        },
                    ],
                },
            });
            expect(context.getTransactionArguments({ tag: types_1.TxTags.identity.AddClaim })).toMatchObject([
                {
                    name: 'target',
                    type: types_3.TransactionArgumentType.Did,
                    optional: false,
                },
                {
                    name: 'portfolioKind',
                    type: types_3.TransactionArgumentType.RichEnum,
                    optional: false,
                    internal: [
                        {
                            name: 'Default',
                            type: types_3.TransactionArgumentType.Null,
                            optional: false,
                        },
                        {
                            name: 'User',
                            type: types_3.TransactionArgumentType.Number,
                            optional: false,
                        },
                    ],
                },
                {
                    name: 'expiry',
                    type: types_3.TransactionArgumentType.Date,
                    optional: true,
                },
                {
                    name: 'identityPair',
                    type: types_3.TransactionArgumentType.Tuple,
                    optional: false,
                    internal: [
                        {
                            name: '0',
                            optional: false,
                            type: types_3.TransactionArgumentType.Did,
                        },
                        {
                            name: '1',
                            optional: false,
                            type: types_3.TransactionArgumentType.Number,
                        },
                    ],
                },
            ]);
            mocks_1.dsMockUtils.createTxStub('identity', 'cddRegisterDid', {
                meta: {
                    args: [
                        {
                            type: 'Compact<Bytes>',
                            name: 'someArg',
                        },
                    ],
                },
            });
            expect(context.getTransactionArguments({ tag: types_1.TxTags.identity.CddRegisterDid })).toMatchObject([
                {
                    type: types_3.TransactionArgumentType.Unknown,
                    name: 'someArg',
                    optional: false,
                },
            ]);
            mocks_1.dsMockUtils.createTxStub('asset', 'createAsset', {
                meta: {
                    args: [
                        {
                            type: 'Vec<IdentityId>',
                            name: 'dids',
                        },
                    ],
                },
            });
            expect(context.getTransactionArguments({ tag: types_1.TxTags.asset.CreateAsset })).toMatchObject([
                {
                    type: types_3.TransactionArgumentType.Array,
                    name: 'dids',
                    optional: false,
                    internal: {
                        name: '',
                        type: types_3.TransactionArgumentType.Did,
                        optional: false,
                    },
                },
            ]);
            mocks_1.dsMockUtils.createTxStub('asset', 'updateIdentifiers', {
                meta: {
                    args: [
                        {
                            type: '[u8;32]',
                            name: 'someArg',
                        },
                    ],
                },
            });
            expect(context.getTransactionArguments({ tag: types_1.TxTags.asset.UpdateIdentifiers })).toMatchObject([
                {
                    type: types_3.TransactionArgumentType.Text,
                    name: 'someArg',
                    optional: false,
                },
            ]);
            mocks_1.dsMockUtils.createTxStub('asset', 'setFundingRound', {
                meta: {
                    args: [
                        {
                            type: 'AssetOwnershipRelation',
                            name: 'relation',
                        },
                    ],
                },
            });
            expect(context.getTransactionArguments({ tag: types_1.TxTags.asset.SetFundingRound })).toMatchObject([
                {
                    type: types_3.TransactionArgumentType.SimpleEnum,
                    name: 'relation',
                    optional: false,
                    internal: ['NotOwned', 'TickerOwned', 'AssetOwned'],
                },
            ]);
            mocks_1.dsMockUtils.createTxStub('asset', 'unfreeze', {
                meta: {
                    args: [
                        {
                            type: 'VoteCountProposalFound',
                            name: 'voteCountProposalFound',
                        },
                    ],
                },
            });
            expect(context.getTransactionArguments({ tag: types_1.TxTags.asset.Unfreeze })).toMatchObject([
                {
                    type: types_3.TransactionArgumentType.Object,
                    name: 'voteCountProposalFound',
                    optional: false,
                    internal: [
                        {
                            name: 'ayes',
                            type: types_3.TransactionArgumentType.Number,
                        },
                        {
                            name: 'nays',
                            type: types_3.TransactionArgumentType.Number,
                        },
                    ],
                },
            ]);
            mocks_1.dsMockUtils.createTxStub('asset', 'claimClassicTicker', {
                meta: {
                    args: [
                        {
                            type: 'UInt<8>',
                            name: 'someArg',
                        },
                    ],
                },
            });
            expect(context.getTransactionArguments({ tag: types_1.TxTags.asset.ClaimClassicTicker })).toMatchObject([
                {
                    type: types_3.TransactionArgumentType.Unknown,
                    name: 'someArg',
                    optional: false,
                },
            ]);
        }));
    });
    describe('method: issuedClaims', () => {
        test('should return a result set of claims', () => __awaiter(void 0, void 0, void 0, function* () {
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            const targetDid = 'someTargetDid';
            const issuerDid = 'someIssuerDid';
            const date = 1589816265000;
            const customerDueDiligenceType = types_2.ClaimTypeEnum.CustomerDueDiligence;
            const claim = {
                target: new internal_1.Identity({ did: targetDid }, context),
                issuer: new internal_1.Identity({ did: issuerDid }, context),
                issuedAt: new Date(date),
            };
            const fakeClaims = [
                Object.assign(Object.assign({}, claim), { expiry: new Date(date), claim: {
                        type: customerDueDiligenceType,
                    } }),
                Object.assign(Object.assign({}, claim), { expiry: null, claim: {
                        type: customerDueDiligenceType,
                    } }),
            ];
            /* eslint-disable @typescript-eslint/naming-convention */
            const commonClaimData = {
                targetDID: targetDid,
                issuer: issuerDid,
                issuance_date: date,
                last_update_date: date,
            };
            const didsWithClaimsQueryResponse = {
                totalCount: 25,
                items: [
                    {
                        did: targetDid,
                        claims: [
                            Object.assign(Object.assign({}, commonClaimData), { expiry: date, type: customerDueDiligenceType }),
                            Object.assign(Object.assign({}, commonClaimData), { expiry: null, type: customerDueDiligenceType }),
                        ],
                    },
                ],
            };
            /* eslint-enabled @typescript-eslint/naming-convention */
            mocks_1.dsMockUtils.createApolloQueryStub(queries_1.didsWithClaims({
                dids: [targetDid],
                trustedClaimIssuers: [targetDid],
                claimTypes: [types_2.ClaimTypeEnum.Accredited],
                includeExpired: true,
                count: 1,
                skip: undefined,
            }), {
                didsWithClaims: didsWithClaimsQueryResponse,
            });
            let result = yield context.issuedClaims({
                targets: [targetDid],
                trustedClaimIssuers: [targetDid],
                claimTypes: [types_3.ClaimType.Accredited],
                includeExpired: true,
                size: 1,
            });
            expect(result.data).toEqual(fakeClaims);
            expect(result.count).toEqual(25);
            expect(result.next).toEqual(1);
            mocks_1.dsMockUtils.createApolloQueryStub(queries_1.didsWithClaims({
                dids: undefined,
                trustedClaimIssuers: undefined,
                claimTypes: undefined,
                includeExpired: true,
                count: undefined,
                skip: undefined,
            }), {
                didsWithClaims: didsWithClaimsQueryResponse,
            });
            result = yield context.issuedClaims();
            expect(result.data).toEqual(fakeClaims);
            expect(result.count).toEqual(25);
            expect(result.next).toBeNull();
        }));
        test('should return a result set of claims from chain', () => __awaiter(void 0, void 0, void 0, function* () {
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            const targetDid = 'someTargetDid';
            const issuerDid = 'someIssuerDid';
            const cddId = 'someCddId';
            const issuedAt = new Date('10/14/2019');
            const expiryOne = new Date('10/14/2020');
            const expiryTwo = new Date('10/14/2060');
            const claim1stKey = mocks_1.dsMockUtils.createMockClaim1stKey({
                target: mocks_1.dsMockUtils.createMockIdentityId(targetDid),
                claim_type: mocks_1.dsMockUtils.createMockClaimType(types_3.ClaimType.CustomerDueDiligence),
            });
            const identityClaim = {
                claim_issuer: mocks_1.dsMockUtils.createMockIdentityId(issuerDid),
                issuance_date: mocks_1.dsMockUtils.createMockMoment(issuedAt.getTime()),
                last_update_date: mocks_1.dsMockUtils.createMockMoment(),
                claim: mocks_1.dsMockUtils.createMockClaim({
                    CustomerDueDiligence: mocks_1.dsMockUtils.createMockCddId(cddId),
                }),
            };
            const fakeClaims = [
                {
                    target: new internal_1.Identity({ did: targetDid }, context),
                    issuer: new internal_1.Identity({ did: issuerDid }, context),
                    issuedAt,
                    expiry: expiryOne,
                    claim: {
                        type: types_3.ClaimType.CustomerDueDiligence,
                        id: cddId,
                    },
                },
                {
                    target: new internal_1.Identity({ did: targetDid }, context),
                    issuer: new internal_1.Identity({ did: issuerDid }, context),
                    issuedAt,
                    expiry: null,
                    claim: {
                        type: types_3.ClaimType.CustomerDueDiligence,
                        id: cddId,
                    },
                },
                {
                    target: new internal_1.Identity({ did: targetDid }, context),
                    issuer: new internal_1.Identity({ did: issuerDid }, context),
                    issuedAt,
                    expiry: expiryTwo,
                    claim: {
                        type: types_3.ClaimType.CustomerDueDiligence,
                        id: cddId,
                    },
                },
            ];
            mocks_1.dsMockUtils.configureMocks({
                contextOptions: {
                    middlewareAvailable: false,
                },
            });
            const entriesStub = sinon_1.default.stub();
            entriesStub.resolves([
                utils_1.tuple({ args: [claim1stKey] }, Object.assign(Object.assign({}, identityClaim), { expiry: mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockMoment(expiryOne.getTime())) })),
                utils_1.tuple({ args: [claim1stKey] }, Object.assign(Object.assign({}, identityClaim), { expiry: mocks_1.dsMockUtils.createMockOption() })),
                utils_1.tuple({ args: [claim1stKey] }, Object.assign(Object.assign({}, identityClaim), { expiry: mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockMoment(expiryTwo.getTime())) })),
            ]);
            mocks_1.dsMockUtils.createQueryStub('identity', 'claims').entries = entriesStub;
            let result = yield context.issuedClaims({
                targets: [targetDid],
                claimTypes: [types_3.ClaimType.CustomerDueDiligence],
            });
            expect(result.data).toEqual(fakeClaims);
            const { data } = yield context.issuedClaims({
                targets: [targetDid],
                claimTypes: [types_3.ClaimType.CustomerDueDiligence],
                includeExpired: false,
            });
            expect(data.length).toEqual(2);
            expect(data[0]).toEqual(fakeClaims[1]);
            expect(data[1]).toEqual(fakeClaims[2]);
            sinon_1.default.stub(utilsConversionModule, 'signerToString').returns(targetDid);
            result = yield context.issuedClaims({
                targets: [targetDid],
                claimTypes: [types_3.ClaimType.CustomerDueDiligence],
                trustedClaimIssuers: [targetDid],
            });
            expect(result.data.length).toEqual(0);
            result = yield context.issuedClaims({
                targets: [targetDid],
                trustedClaimIssuers: [targetDid],
            });
            expect(result.data.length).toEqual(0);
        }));
        test('should throw if the middleware is not available and targets or claimTypes are not set', () => __awaiter(void 0, void 0, void 0, function* () {
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            mocks_1.dsMockUtils.configureMocks({
                contextOptions: {
                    middlewareAvailable: false,
                },
            });
            return expect(context.issuedClaims()).rejects.toThrow('Cannot perform this action without an active middleware connection');
        }));
    });
    describe('method: queryMiddleware', () => {
        test('should throw if the middleware query fails', () => __awaiter(void 0, void 0, void 0, function* () {
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            mocks_1.dsMockUtils.throwOnMiddlewareQuery();
            yield expect(context.queryMiddleware('query')).rejects.toThrow('Error in middleware query: Error');
            mocks_1.dsMockUtils.throwOnMiddlewareQuery({ networkError: {}, message: 'Error' });
            yield expect(context.queryMiddleware('query')).rejects.toThrow('Error in middleware query: Error');
            mocks_1.dsMockUtils.throwOnMiddlewareQuery({ networkError: { result: { message: 'Some Message' } } });
            return expect(context.queryMiddleware('query')).rejects.toThrow('Error in middleware query: Some Message');
        }));
        test('should perform a middleware query and return the results', () => __awaiter(void 0, void 0, void 0, function* () {
            const fakeResult = 'res';
            const fakeQuery = 'fakeQuery';
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            mocks_1.dsMockUtils.createApolloQueryStub(fakeQuery, fakeResult);
            const res = yield context.queryMiddleware(fakeQuery);
            expect(res.data).toBe(fakeResult);
        }));
    });
    describe('method: getLatestBlock', () => {
        test('should return the latest block', () => __awaiter(void 0, void 0, void 0, function* () {
            const blockNumber = 100;
            mocks_1.dsMockUtils.createRpcStub('chain', 'getHeader', {
                returnValue: {
                    number: mocks_1.dsMockUtils.createMockCompact(mocks_1.dsMockUtils.createMockU32(blockNumber)),
                },
            });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            const result = yield context.getLatestBlock();
            expect(result).toEqual(new bignumber_js_1.default(blockNumber));
        }));
    });
    describe('method: getNetworkVersion', () => {
        test('should return the network version', () => __awaiter(void 0, void 0, void 0, function* () {
            const version = '1.0.0';
            mocks_1.dsMockUtils.createRpcStub('system', 'version', {
                returnValue: mocks_1.dsMockUtils.createMockText(version),
            });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            const result = yield context.getNetworkVersion();
            expect(result).toEqual(version);
        }));
    });
    describe('methd: isMiddlewareEnabled', () => {
        test('should return true if the middleware is enabled', () => __awaiter(void 0, void 0, void 0, function* () {
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            const result = context.isMiddlewareEnabled();
            expect(result).toBe(true);
        }));
        test('should return false if the middleware is not enabled', () => __awaiter(void 0, void 0, void 0, function* () {
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: null,
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            const result = context.isMiddlewareEnabled();
            expect(result).toBe(false);
        }));
    });
    describe('methd: isMiddlewareAvailable', () => {
        test('should return true if the middleware is available', () => __awaiter(void 0, void 0, void 0, function* () {
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            mocks_1.dsMockUtils.createApolloQueryStub(queries_1.heartbeat(), true);
            const result = yield context.isMiddlewareAvailable();
            expect(result).toBe(true);
        }));
        test('should return false if the middleware is not enabled', () => __awaiter(void 0, void 0, void 0, function* () {
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: null,
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            mocks_1.dsMockUtils.throwOnMiddlewareQuery();
            const result = yield context.isMiddlewareAvailable();
            expect(result).toBe(false);
        }));
    });
    describe('method: disconnect', () => {
        test('should disconnect everything and leave the instance unusable', () => __awaiter(void 0, void 0, void 0, function* () {
            const polymeshApi = mocks_1.dsMockUtils.getApiInstance();
            const middlewareApi = mocks_1.dsMockUtils.getMiddlewareApi();
            let context = yield internal_1.Context.create({
                polymeshApi,
                middlewareApi,
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            yield context.disconnect();
            polymeshApi.emit('disconnected');
            sinon_1.default.assert.calledOnce(polymeshApi.disconnect);
            sinon_1.default.assert.calledOnce(middlewareApi.stop);
            expect(() => context.getAccounts()).toThrow('Client disconnected. Please create a new instance via "Polymesh.connect()"');
            context = yield internal_1.Context.create({
                polymeshApi,
                middlewareApi: null,
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            yield context.disconnect();
            polymeshApi.emit('disconnected');
            sinon_1.default.assert.calledTwice(polymeshApi.disconnect);
            sinon_1.default.assert.calledOnce(middlewareApi.stop);
            expect(() => context.getAccounts()).toThrow('Client disconnected. Please create a new instance via "Polymesh.connect()"');
        }));
    });
    describe('method: addPair', () => {
        test('should add a new pair to the keyring via seed', () => __awaiter(void 0, void 0, void 0, function* () {
            const newPair = {
                address: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
                meta: {},
                publicKey: 'publicKey',
            };
            mocks_1.dsMockUtils.configureMocks({
                keyringOptions: {
                    getPairs: [newPair],
                },
            });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            const accountSeed = '0x7'.padEnd(66, '0');
            context.addPair({ accountSeed });
            sinon_1.default.assert.calledTwice(mocks_1.dsMockUtils.getKeyringInstance().addFromSeed);
        }));
        test('should add a new pair to the keyring via mnemonic', () => __awaiter(void 0, void 0, void 0, function* () {
            const newPair = {
                address: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
                meta: {},
                publicKey: 'publicKey',
            };
            mocks_1.dsMockUtils.configureMocks({
                keyringOptions: {
                    getPairs: [newPair],
                },
            });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            const accountMnemonic = 'something';
            context.addPair({ accountMnemonic });
            sinon_1.default.assert.calledWith(mocks_1.dsMockUtils.getKeyringInstance().addFromMnemonic, accountMnemonic);
        }));
        test('should add a new pair to the keyring via uri', () => __awaiter(void 0, void 0, void 0, function* () {
            const newPair = {
                address: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
                meta: {},
                publicKey: 'publicKey',
            };
            mocks_1.dsMockUtils.configureMocks({
                keyringOptions: {
                    getPairs: [newPair],
                },
            });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            const accountUri = 'something';
            context.addPair({ accountUri });
            sinon_1.default.assert.calledWith(mocks_1.dsMockUtils.getKeyringInstance().addFromUri, accountUri);
        }));
        test('should add a new pair to the keyring via pair', () => __awaiter(void 0, void 0, void 0, function* () {
            const newPair = {
                address: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
                meta: {},
                publicKey: 'publicKey',
            };
            mocks_1.dsMockUtils.configureMocks({
                keyringOptions: {
                    getPairs: [newPair],
                },
            });
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            const pair = 'something';
            context.addPair({ pair });
            sinon_1.default.assert.calledWith(mocks_1.dsMockUtils.getKeyringInstance().addPair, pair);
        }));
    });
    describe('method: getDividendDistributionsForTokens', () => {
        afterAll(() => {
            sinon_1.default.restore();
        });
        test('should return all distributions associated to the passed tokens', () => __awaiter(void 0, void 0, void 0, function* () {
            const tickers = ['TICKER_0', 'TICKER_1', 'TICKER_2'];
            const rawTickers = tickers.map(mocks_1.dsMockUtils.createMockTicker);
            const polymeshApi = mocks_1.dsMockUtils.getApiInstance();
            const middlewareApi = mocks_1.dsMockUtils.getMiddlewareApi();
            const context = yield internal_1.Context.create({
                polymeshApi,
                middlewareApi,
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            const corporateActions = [
                mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockCorporateAction({
                    kind: types_3.CorporateActionKind.PredictableBenefit,
                    decl_date: new Date('10/14/1987').getTime(),
                    record_date: mocks_1.dsMockUtils.createMockRecordDate({
                        date: new Date('10/14/2019').getTime(),
                        checkpoint: { Existing: mocks_1.dsMockUtils.createMockU64(2) },
                    }),
                    targets: {
                        identities: ['someDid'],
                        treatment: types_3.TargetTreatment.Exclude,
                    },
                    default_withholding_tax: 100000,
                    withholding_tax: [utils_1.tuple('someDid', 300000)],
                })),
                mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockCorporateAction({
                    kind: types_3.CorporateActionKind.Reorganization,
                    decl_date: new Date('10/14/1987').getTime(),
                    record_date: null,
                    targets: {
                        identities: [],
                        treatment: types_3.TargetTreatment.Exclude,
                    },
                    default_withholding_tax: 0,
                    withholding_tax: [],
                })),
                mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockCorporateAction({
                    kind: types_3.CorporateActionKind.UnpredictableBenefit,
                    decl_date: new Date('11/26/1989').getTime(),
                    record_date: mocks_1.dsMockUtils.createMockRecordDate({
                        date: new Date('11/26/2019').getTime(),
                        checkpoint: { Existing: mocks_1.dsMockUtils.createMockU64(5) },
                    }),
                    targets: {
                        identities: [],
                        treatment: types_3.TargetTreatment.Exclude,
                    },
                    default_withholding_tax: 150000,
                    withholding_tax: [utils_1.tuple('someDid', 200000)],
                })),
            ];
            const distributions = [
                mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockDistribution({
                    from: { kind: 'Default', did: 'someDid' },
                    currency: 'USD',
                    per_share: 10000000,
                    amount: 500000000000,
                    remaining: 400000000000,
                    reclaimed: false,
                    payment_at: new Date('10/14/1987').getTime(),
                    expires_at: null,
                })),
                mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockDistribution({
                    from: { kind: { User: mocks_1.dsMockUtils.createMockU64(2) }, did: 'someDid' },
                    currency: 'CAD',
                    per_share: 20000000,
                    amount: 300000000000,
                    remaining: 200000000000,
                    reclaimed: false,
                    payment_at: new Date('11/26/1989').getTime(),
                    expires_at: null,
                })),
                mocks_1.dsMockUtils.createMockOption(),
            ];
            const localIds = [1, 2, 3];
            const caIds = [
                mocks_1.dsMockUtils.createMockCAId({ ticker: rawTickers[0], local_id: localIds[0] }),
                mocks_1.dsMockUtils.createMockCAId({ ticker: rawTickers[1], local_id: localIds[1] }),
                mocks_1.dsMockUtils.createMockCAId({ ticker: rawTickers[1], local_id: localIds[2] }),
            ];
            mocks_1.dsMockUtils.createQueryStub('corporateAction', 'corporateActions', {
                entries: [
                    [[rawTickers[0], localIds[0]], corporateActions[0]],
                    [[rawTickers[1], localIds[1]], corporateActions[1]],
                    [[rawTickers[1], localIds[2]], corporateActions[2]],
                ],
            });
            const details = [
                mocks_1.dsMockUtils.createMockText('details1'),
                mocks_1.dsMockUtils.createMockText('details2'),
                mocks_1.dsMockUtils.createMockText('details3'),
            ];
            const corporateActionIdentifierToCaIdStub = sinon_1.default.stub(utilsConversionModule, 'corporateActionIdentifierToCaId');
            corporateActionIdentifierToCaIdStub
                .withArgs({ ticker: tickers[0], localId: new bignumber_js_1.default(localIds[0]) }, context)
                .returns(caIds[0]);
            corporateActionIdentifierToCaIdStub
                .withArgs({ ticker: tickers[1], localId: new bignumber_js_1.default(localIds[1]) }, context)
                .returns(caIds[1]);
            corporateActionIdentifierToCaIdStub
                .withArgs({ ticker: tickers[1], localId: new bignumber_js_1.default(localIds[2]) }, context)
                .returns(caIds[2]);
            const detailsStub = mocks_1.dsMockUtils.createQueryStub('corporateAction', 'details');
            detailsStub.withArgs(caIds[0]).resolves(details[0]);
            detailsStub.withArgs(caIds[1]).resolves(details[1]);
            detailsStub.withArgs(caIds[2]).resolves(details[2]);
            mocks_1.dsMockUtils.createQueryStub('capitalDistribution', 'distributions', {
                multi: distributions,
            });
            const stringToTickerStub = sinon_1.default.stub(utilsConversionModule, 'stringToTicker');
            tickers.forEach((ticker, index) => stringToTickerStub.withArgs(ticker, context).returns(rawTickers[index]));
            const result = yield context.getDividendDistributionsForTokens({
                tokens: tickers.map(ticker => mocks_1.entityMockUtils.getSecurityTokenInstance({ ticker })),
            });
            expect(result.length).toBe(2);
            expect(result[0].details.fundsReclaimed).toBe(false);
            expect(result[0].details.remainingFunds).toEqual(new bignumber_js_1.default(400000));
            expect(result[0].distribution.origin).toEqual(mocks_1.entityMockUtils.getDefaultPortfolioInstance({ did: 'someDid' }));
            expect(result[0].distribution.currency).toBe('USD');
            expect(result[0].distribution.perShare).toEqual(new bignumber_js_1.default(10));
            expect(result[0].distribution.maxAmount).toEqual(new bignumber_js_1.default(500000));
            expect(result[0].distribution.expiryDate).toBe(null);
            expect(result[0].distribution.paymentDate).toEqual(new Date('10/14/1987'));
            expect(result[1].details.fundsReclaimed).toBe(false);
            expect(result[1].details.remainingFunds).toEqual(new bignumber_js_1.default(200000));
            expect(result[1].distribution.origin).toEqual(mocks_1.entityMockUtils.getNumberedPortfolioInstance({ did: 'someDid', id: new bignumber_js_1.default(2) }));
            expect(result[1].distribution.currency).toBe('CAD');
            expect(result[1].distribution.perShare).toEqual(new bignumber_js_1.default(20));
            expect(result[1].distribution.maxAmount).toEqual(new bignumber_js_1.default(300000));
            expect(result[1].distribution.expiryDate).toBe(null);
            expect(result[1].distribution.paymentDate).toEqual(new Date('11/26/1989'));
        }));
    });
    describe('method: clone', () => {
        test('should return a cloned instance', () => __awaiter(void 0, void 0, void 0, function* () {
            const context = yield internal_1.Context.create({
                polymeshApi: mocks_1.dsMockUtils.getApiInstance(),
                middlewareApi: mocks_1.dsMockUtils.getMiddlewareApi(),
                accountSeed: '0x6'.padEnd(66, '0'),
            });
            const cloned = context.clone();
            expect(cloned).toEqual(context);
        }));
    });
});
//# sourceMappingURL=Context.js.map