"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const types_1 = require("../polkadot/types");
const sinon_1 = __importDefault(require("sinon"));
const queries_1 = require("../middleware/queries");
const types_2 = require("../middleware/types");
const Network_1 = require("../Network");
const mocks_1 = require("../testUtils/mocks");
jest.mock('~/api/entities/Account', require("../testUtils/mocks/entities").mockAccountModule('~/api/entities/Account'));
jest.mock('~/base/Procedure', require("../testUtils/mocks/procedure").mockProcedureModule('~/base/Procedure'));
describe('Network Class', () => {
    let context;
    let network;
    beforeEach(() => {
        context = mocks_1.dsMockUtils.getContextInstance();
        network = new Network_1.Network(context);
    });
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks();
        mocks_1.entityMockUtils.initMocks();
        mocks_1.procedureMockUtils.initMocks();
    });
    afterEach(() => {
        mocks_1.dsMockUtils.reset();
        mocks_1.entityMockUtils.reset();
        mocks_1.procedureMockUtils.reset();
    });
    afterAll(() => {
        mocks_1.dsMockUtils.cleanup();
        mocks_1.procedureMockUtils.cleanup();
    });
    describe('method: getLatestBlock', () => {
        test('should return the latest block number', () => __awaiter(void 0, void 0, void 0, function* () {
            const blockNumber = new bignumber_js_1.default(100);
            mocks_1.dsMockUtils.configureMocks({ contextOptions: { withSeed: true, latestBlock: blockNumber } });
            mocks_1.dsMockUtils.createApolloQueryStub(queries_1.heartbeat(), true);
            const result = yield network.getLatestBlock();
            expect(result).toEqual(blockNumber);
        }));
    });
    describe('method: getNetworkVersion', () => {
        test('should return the network version', () => __awaiter(void 0, void 0, void 0, function* () {
            const networkVersion = '1.0.0';
            mocks_1.dsMockUtils.configureMocks({ contextOptions: { withSeed: true, networkVersion } });
            mocks_1.dsMockUtils.createApolloQueryStub(queries_1.heartbeat(), true);
            const result = yield network.getVersion();
            expect(result).toEqual(networkVersion);
        }));
    });
    describe('method: getNetworkProperties', () => {
        test('should return current network information', () => __awaiter(void 0, void 0, void 0, function* () {
            const name = 'someName';
            const version = new bignumber_js_1.default(1);
            const fakeResult = {
                name,
                version,
            };
            mocks_1.dsMockUtils.setRuntimeVersion({ specVersion: mocks_1.dsMockUtils.createMockU32(version) });
            mocks_1.dsMockUtils.createRpcStub('system', 'chain').resolves(mocks_1.dsMockUtils.createMockText(name));
            const result = yield network.getNetworkProperties();
            expect(result).toEqual(fakeResult);
        }));
    });
    describe('method: getProtocolFees', () => {
        test('should return the fees associated to the supplied transaction', () => __awaiter(void 0, void 0, void 0, function* () {
            mocks_1.dsMockUtils.configureMocks({ contextOptions: { transactionFee: new bignumber_js_1.default(500) } });
            const fee = yield network.getProtocolFees({ tag: types_1.TxTags.asset.CreateAsset });
            expect(fee).toEqual(new bignumber_js_1.default(500));
        }));
    });
    describe('method: getTreasuryAccount', () => {
        test('should return the treasury account', () => __awaiter(void 0, void 0, void 0, function* () {
            const treasuryAddress = '5EYCAe5ijAx5xEfZdpCna3grUpY1M9M5vLUH5vpmwV1EnaYR';
            expect(network.getTreasuryAccount().address).toEqual(treasuryAddress);
        }));
    });
    describe('method: getTreasuryBalance', () => {
        let fakeBalance;
        beforeAll(() => {
            fakeBalance = {
                free: new bignumber_js_1.default(500000),
                locked: new bignumber_js_1.default(0),
                total: new bignumber_js_1.default(500000),
            };
            mocks_1.entityMockUtils.configureMocks({ accountOptions: { getBalance: fakeBalance } });
        });
        test('should return the POLYX balance of the treasury account', () => __awaiter(void 0, void 0, void 0, function* () {
            const result = yield network.getTreasuryBalance();
            expect(result).toEqual(fakeBalance.free);
        }));
        test('should allow subscription', () => __awaiter(void 0, void 0, void 0, function* () {
            const unsubCallback = 'unsubCallback';
            mocks_1.entityMockUtils.configureMocks({
                accountOptions: {
                    getBalance: sinon_1.default.stub().callsFake((cbFunc) => __awaiter(void 0, void 0, void 0, function* () {
                        cbFunc(fakeBalance);
                        return unsubCallback;
                    })),
                },
            });
            const callback = sinon_1.default.stub();
            const result = yield network.getTreasuryBalance(callback);
            expect(result).toEqual(unsubCallback);
            sinon_1.default.assert.calledWithExactly(callback, fakeBalance.free);
        }));
    });
    describe('method: transferPolyx', () => {
        test('should prepare the procedure with the correct arguments and context, and return the resulting transaction queue', () => __awaiter(void 0, void 0, void 0, function* () {
            const args = {
                to: 'someAccount',
                amount: new bignumber_js_1.default(50),
            };
            const expectedQueue = '';
            mocks_1.procedureMockUtils
                .getPrepareStub()
                .withArgs({ args, transformer: undefined }, context)
                .resolves(expectedQueue);
            const queue = yield network.transferPolyx(args);
            expect(queue).toBe(expectedQueue);
        }));
    });
    describe('method: getEventByIndexedArgs', () => {
        const variables = {
            moduleId: types_2.ModuleIdEnum.Asset,
            eventId: types_2.EventIdEnum.AssetCreated,
        };
        test('should return a single event', () => __awaiter(void 0, void 0, void 0, function* () {
            const blockNumber = new bignumber_js_1.default(1234);
            const blockDate = new Date('4/14/2020');
            const eventIdx = new bignumber_js_1.default(1);
            const fakeResult = { blockNumber, blockDate, eventIndex: eventIdx };
            mocks_1.dsMockUtils.configureMocks({ contextOptions: { withSeed: true } });
            mocks_1.dsMockUtils.createApolloQueryStub(queries_1.eventByIndexedArgs(Object.assign(Object.assign({}, variables), { eventArg0: undefined, eventArg1: undefined, eventArg2: undefined })), {
                /* eslint-disable @typescript-eslint/naming-convention */
                eventByIndexedArgs: {
                    block_id: blockNumber.toNumber(),
                    block: { datetime: blockDate },
                    event_idx: eventIdx,
                },
                /* eslint-enable @typescript-eslint/naming-convention */
            });
            const result = yield network.getEventByIndexedArgs(variables);
            expect(result).toEqual(fakeResult);
        }));
        test('should return null if the query result is empty', () => __awaiter(void 0, void 0, void 0, function* () {
            mocks_1.dsMockUtils.createApolloQueryStub(queries_1.eventByIndexedArgs(Object.assign(Object.assign({}, variables), { eventArg0: 'someDid', eventArg1: undefined, eventArg2: undefined })), {});
            const result = yield network.getEventByIndexedArgs(Object.assign(Object.assign({}, variables), { eventArg0: 'someDid' }));
            expect(result).toBeNull();
        }));
    });
    describe('method: getEventsByIndexedArgs', () => {
        const variables = {
            moduleId: types_2.ModuleIdEnum.Asset,
            eventId: types_2.EventIdEnum.AssetCreated,
        };
        test('should return a list of events', () => __awaiter(void 0, void 0, void 0, function* () {
            const blockNumber = new bignumber_js_1.default(1234);
            const blockDate = new Date('4/14/2020');
            const eventIdx = new bignumber_js_1.default(1);
            const fakeResult = [{ blockNumber, blockDate, eventIndex: eventIdx }];
            mocks_1.dsMockUtils.configureMocks({ contextOptions: { withSeed: true } });
            mocks_1.dsMockUtils.createApolloQueryStub(queries_1.eventsByIndexedArgs(Object.assign(Object.assign({}, variables), { eventArg0: undefined, eventArg1: undefined, eventArg2: undefined, count: 1, skip: 0 })), {
                /* eslint-disable @typescript-eslint/naming-convention */
                eventsByIndexedArgs: [
                    {
                        block_id: blockNumber.toNumber(),
                        block: { datetime: blockDate },
                        event_idx: eventIdx.toNumber(),
                    },
                ],
                /* eslint-enable @typescript-eslint/naming-convention */
            });
            const result = yield network.getEventsByIndexedArgs(Object.assign(Object.assign({}, variables), { start: new bignumber_js_1.default(0), size: new bignumber_js_1.default(1) }));
            expect(result).toEqual(fakeResult);
        }));
        test('should return null if the query result is empty', () => __awaiter(void 0, void 0, void 0, function* () {
            mocks_1.dsMockUtils.createApolloQueryStub(queries_1.eventsByIndexedArgs(Object.assign(Object.assign({}, variables), { eventArg0: 'someDid', eventArg1: undefined, eventArg2: undefined, count: undefined, skip: undefined })), {});
            const result = yield network.getEventsByIndexedArgs(Object.assign(Object.assign({}, variables), { eventArg0: 'someDid' }));
            expect(result).toBeNull();
        }));
    });
    describe('method: getTransactionByHash', () => {
        const variable = { txHash: 'someHash' };
        test('should return a transaction', () => __awaiter(void 0, void 0, void 0, function* () {
            const blockNumber = new bignumber_js_1.default(1);
            const blockHash = 'someHash';
            const extrinsicIdx = new bignumber_js_1.default(2);
            const address = 'someAddress';
            const specVersionId = new bignumber_js_1.default(2006);
            mocks_1.dsMockUtils.configureMocks({ contextOptions: { withSeed: true } });
            mocks_1.dsMockUtils.createApolloQueryStub(queries_1.transactionByHash({ transactionHash: variable.txHash }), {
                /* eslint-disable @typescript-eslint/naming-convention */
                transactionByHash: {
                    module_id: types_2.ModuleIdEnum.Asset,
                    call_id: types_2.CallIdEnum.RegisterTicker,
                    extrinsic_idx: extrinsicIdx.toNumber(),
                    spec_version_id: specVersionId.toNumber(),
                    params: [],
                    block_id: blockNumber.toNumber(),
                    address,
                    success: 0,
                    block: {
                        hash: blockHash,
                    },
                },
                /* eslint-enable @typescript-eslint/naming-convention */
            });
            let result = yield network.getTransactionByHash(variable);
            expect(result).toEqual({
                blockNumber,
                blockHash,
                extrinsicIdx: extrinsicIdx,
                address,
                nonce: null,
                txTag: 'asset.registerTicker',
                params: [],
                success: false,
                specVersionId,
                extrinsicHash: undefined,
            });
            mocks_1.dsMockUtils.createApolloQueryStub(queries_1.transactionByHash({ transactionHash: variable.txHash }), {
                /* eslint-disable @typescript-eslint/naming-convention */
                transactionByHash: {
                    module_id: types_2.ModuleIdEnum.Asset,
                    call_id: types_2.CallIdEnum.RegisterTicker,
                    extrinsic_idx: extrinsicIdx,
                    spec_version_id: specVersionId,
                    params: [],
                    nonce: 12345,
                    block_id: blockNumber.toNumber(),
                    address: null,
                    success: 0,
                    block: {
                        hash: blockHash,
                    },
                },
                /* eslint-enable @typescript-eslint/naming-convention */
            });
            result = yield network.getTransactionByHash(variable);
            expect(result).toEqual({
                blockNumber,
                blockHash,
                extrinsicIdx: extrinsicIdx,
                address: null,
                nonce: new bignumber_js_1.default(12345),
                txTag: 'asset.registerTicker',
                params: [],
                success: false,
                specVersionId,
                extrinsicHash: undefined,
            });
        }));
        test('should return null if the query result is empty', () => __awaiter(void 0, void 0, void 0, function* () {
            mocks_1.dsMockUtils.createApolloQueryStub(queries_1.transactionByHash({
                transactionHash: variable.txHash,
            }), {});
            const result = yield network.getTransactionByHash(variable);
            expect(result).toBeNull();
        }));
    });
});
//# sourceMappingURL=Network.js.map