"use strict";
/* istanbul ignore file */
/* eslint-disable @typescript-eslint/naming-convention */
/* eslint-disable @typescript-eslint/no-explicit-any */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _a, _b;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createMockHash = exports.createMockBytes = exports.createMockPermill = exports.createMockU64 = exports.createMockU32 = exports.createMockU8 = exports.createMockTickerRegistration = exports.createMockMoment = exports.createMockCompact = exports.createMockOption = exports.createMockDocumentType = exports.createMockDocumentHash = exports.createMockDocumentUri = exports.createMockDocumentName = exports.createMockBalance = exports.createMockAccountId = exports.createMockTicker = exports.createMockEthereumAddress = exports.createMockEcdsaSignature = exports.createMockAgentGroup = exports.createMockIdentityId = exports.setRuntimeVersion = exports.getKeyringInstance = exports.getContextCreateStub = exports.getContextInstance = exports.getCreateTypeStub = exports.getMiddlewareApi = exports.getApiInstance = exports.setContextAccountBalance = exports.throwOnApiCreation = exports.throwOnContextCreation = exports.throwOnMiddlewareQuery = exports.updateTxStatus = exports.getQueryMultiStub = exports.setConstMock = exports.createRpcStub = exports.createQueryStub = exports.createApolloMultipleQueriesStub = exports.createApolloQueryStub = exports.createTxStub = exports.reset = exports.cleanup = exports.initMocks = exports.configureMocks = exports.mockWebSocketAsPromisedModule = exports.mockApolloModule = exports.mockContextModule = exports.mockPolkadotModule = exports.TxFailReason = exports.MockTxStatus = void 0;
exports.createMockComplianceRequirement = exports.createMockConditionResult = exports.createMockCondition = exports.createMockTrustedIssuer = exports.createMockTrustedFor = exports.createMockClaim1stKey = exports.createMockClaimType = exports.createMockConditionType = exports.createMockTargetIdentity = exports.createMockIdentityClaim = exports.createMockClaim = exports.createMockInvestorZKProofData = exports.createMockScopeId = exports.createMockCddId = exports.createMockScope = exports.createMockCountryCode = exports.createMockCddStatus = exports.createMockIEvent = exports.createMockEventRecord = exports.createMockAuthorization = exports.createMockAuthorizationData = exports.createMockDispatchableNames = exports.createMockPortfolioPermissions = exports.createMockExtrinsicPermissions = exports.createMockAssetPermissions = exports.createMockPermissions = exports.createMockFundraiserName = exports.createMockDispatchableName = exports.createMockPalletName = exports.createMockFundingRoundName = exports.createMockAssetIdentifier = exports.createMockU8aFixed = exports.createMockAuthorizationType = exports.createMockSignatory = exports.createMockSubsidy = exports.createMockAccountInfo = exports.createMockRefCount = exports.createMockIndex = exports.createMockAccountData = exports.createMockPalletPermissions = exports.createMockDocument = exports.createMockSecurityToken = exports.createMockTickerRegistrationConfig = exports.createMockAssetType = exports.createMockMovePortfolioItem = exports.createMockPortfolioId = exports.createMockPortfolioKind = exports.createMockBool = exports.createMockPosRatio = exports.createMockAssetName = void 0;
exports.createMockHeader = exports.createMockBlock = exports.createMockSignedBlock = exports.createMockClassicTickerRegistration = exports.createMockGranularCanTransferResult = exports.createMockPortfolioValidityResult = exports.createMockTransferManagerResult = exports.createMockDistribution = exports.createMockCAId = exports.createMockCorporateAction = exports.createMockCAKind = exports.createMockScopeClaimProof = exports.createMockTargetIdentities = exports.createMockTargetTreatment = exports.createMockZkProofData = exports.createMockSignature = exports.createMockRecordDate = exports.createMockCACheckpoint = exports.createMockRistrettoPoint = exports.createMockRecordDateSpec = exports.createMockScalar = exports.createMockScheduleSpec = exports.createMockStoredSchedule = exports.createMockCheckpointSchedule = exports.createMockCalendarPeriod = exports.createMockCalendarUnit = exports.createMockPriceTier = exports.createMockFundraiser = exports.createMockFundraiserStatus = exports.createMockFundraiserTier = exports.createMockTransferManager = exports.createMockInstruction = exports.createMockAffirmationStatus = exports.createMockSettlementType = exports.createMockInstructionStatus = exports.createMockVenue = exports.createMockVenueType = exports.createMockVenueDetails = exports.createMockPipId = exports.createMockSecondaryKey = exports.createMockPipsMetadata = exports.createMockPip = exports.createMockProposalState = exports.createMockAssetOwnershipRelation = exports.createMockText = exports.createMockCanTransferResult = exports.createMockDidRecord = exports.createMockAssetComplianceResult = exports.createMockComplianceRequirementResult = void 0;
const util_1 = require("@polkadot/util");
const bignumber_js_1 = require("bignumber.js");
const events_1 = require("events");
const lodash_1 = require("lodash");
const sinon_1 = __importDefault(require("sinon"));
const types_1 = require("../../types");
const utils_1 = require("../../types/utils");
let apiEmitter;
/**
 * Create a mock instance of the Polkadot API
 */
function createApi() {
    apiEmitter = new events_1.EventEmitter();
    apiEmitter.on('error', () => undefined);
    return {
        emit: (event) => apiEmitter.emit(event),
        on: (event, listener) => apiEmitter.on(event, listener),
        off: (event, listener) => apiEmitter.off(event, listener),
        setSigner: sinon_1.default.stub(),
        disconnect: sinon_1.default.stub(),
    };
}
/**
 * Create a mock instance of the Apollo client
 */
function createApolloClient() {
    return {
        stop: sinon_1.default.stub(),
    };
}
let apolloConstructorStub;
/**
 * Create a mock instance of the WebSocketAsPromised lib
 */
function createWebSocketAsPromised() {
    return {
        open: sinon_1.default.stub(),
        send: sinon_1.default.stub(),
        sendRequest: sinon_1.default.stub().resolves({ result: '4.1.0' }),
        close: sinon_1.default.stub(),
    };
}
let webSocketAsPromisedConstructorStub;
var MockTxStatus;
(function (MockTxStatus) {
    MockTxStatus["Ready"] = "Ready";
    MockTxStatus["Succeeded"] = "Succeeded";
    MockTxStatus["Failed"] = "Failed";
    MockTxStatus["Aborted"] = "Aborted";
    MockTxStatus["Rejected"] = "Rejected";
    MockTxStatus["Intermediate"] = "Intermediate";
    MockTxStatus["InBlock"] = "InBlock";
    MockTxStatus["BatchFailed"] = "BatchFailed";
    MockTxStatus["FinalizedFailed"] = "FinalizedFailed";
})(MockTxStatus = exports.MockTxStatus || (exports.MockTxStatus = {}));
const MockApolloClientClass = class {
    /**
     * @hidden
     */
    constructor() {
        return apolloConstructorStub();
    }
};
const mockInstanceContainer = {
    contextInstance: {},
    apiInstance: createApi(),
    keyringInstance: {},
    apolloInstance: createApolloClient(),
    webSocketAsPromisedInstance: createWebSocketAsPromised(),
};
const MockWebSocketAsPromisedClass = class {
    /**
     * @hidden
     */
    constructor() {
        return webSocketAsPromisedConstructorStub();
    }
};
let apiPromiseCreateStub;
const MockApiPromiseClass = (_a = class {
    },
    /**
     * @hidden
     */
    _a.create = apiPromiseCreateStub,
    _a);
const MockWsProviderClass = class {
};
let keyringConstructorStub;
const MockKeyringClass = class {
    /**
     * @hidden
     */
    constructor() {
        return keyringConstructorStub();
    }
};
let contextCreateStub;
const MockContextClass = (_b = class {
    },
    /**
     * @hidden
     */
    _b.create = contextCreateStub,
    _b);
let errorStub;
var TxFailReason;
(function (TxFailReason) {
    TxFailReason["BadOrigin"] = "BadOrigin";
    TxFailReason["CannotLookup"] = "CannotLookup";
    TxFailReason["Module"] = "Module";
    TxFailReason["Other"] = "Other";
})(TxFailReason = exports.TxFailReason || (exports.TxFailReason = {}));
const defaultReceipt = {
    status: { isReady: true },
    findRecord: () => undefined,
    filterRecords: () => [],
    isCompleted: false,
    isError: false,
    isFinalized: false,
    isInBlock: false,
    isWarning: false,
    events: [],
    toHuman: () => ({}),
};
const intermediateReceipt = lodash_1.merge({}, defaultReceipt, {
    status: { isReady: false, isInBlock: false },
    isCompleted: true,
    isInBlock: false,
});
const inBlockReceipt = lodash_1.merge({}, defaultReceipt, {
    status: { isReady: false, isInBlock: true, asInBlock: 'blockHash' },
    isCompleted: true,
    isInBlock: true,
});
const successReceipt = lodash_1.merge({}, defaultReceipt, {
    status: { isReady: false, isFinalized: true, asFinalized: 'blockHash' },
    isCompleted: true,
    isFinalized: true,
});
const batchFailedReceipt = lodash_1.merge({}, successReceipt, {
    findRecord: (mod, event) => mod === 'utility' && event === 'BatchInterrupted'
        ? { event: { data: [{ toString: () => '1' }, 'Some Error'] } }
        : undefined,
});
/**
 * @hidden
 */
const createFailReceipt = (err, baseReceipt = inBlockReceipt) => lodash_1.merge({}, baseReceipt, {
    findRecord: () => ({ event: { data: [err] } }),
});
const badOriginFailReceipt = createFailReceipt({ isBadOrigin: true });
const cannotLookupFailReceipt = createFailReceipt({ isCannotLookup: true });
const otherFailReceipt = createFailReceipt({ isOther: true });
const moduleFailReceipt = createFailReceipt({
    isModule: true,
    asModule: {
        error: { toNumber: () => 1 },
        index: { toNumber: () => 1 },
        registry: {
            findMetaError: () => ({
                section: 'someModule',
                name: 'SomeError',
                docs: ['This is very bad'],
            }),
        },
    },
});
const abortReceipt = lodash_1.merge({}, defaultReceipt, {
    status: { isInvalid: true, isReady: false },
    isError: true,
    isCompleted: true,
});
const finalizedErrorReceipt = createFailReceipt({}, successReceipt);
/**
 * @hidden
 */
const failReasonToReceipt = (failReason) => {
    if (!failReason || failReason === TxFailReason.Module) {
        return moduleFailReceipt;
    }
    if (failReason === TxFailReason.BadOrigin) {
        return badOriginFailReceipt;
    }
    if (failReason === TxFailReason.CannotLookup) {
        return cannotLookupFailReceipt;
    }
    return otherFailReceipt;
};
/**
 * @hidden
 */
const statusToReceipt = (status, failReason) => {
    if (status === MockTxStatus.Aborted) {
        return abortReceipt;
    }
    if (status === MockTxStatus.Failed) {
        return failReasonToReceipt(failReason);
    }
    if (status === MockTxStatus.Succeeded) {
        return successReceipt;
    }
    if (status === MockTxStatus.Ready) {
        return defaultReceipt;
    }
    if (status === MockTxStatus.Intermediate) {
        return intermediateReceipt;
    }
    if (status === MockTxStatus.InBlock) {
        return inBlockReceipt;
    }
    if (status === MockTxStatus.BatchFailed) {
        return batchFailedReceipt;
    }
    if (status === MockTxStatus.FinalizedFailed) {
        return finalizedErrorReceipt;
    }
    throw new Error(`There is no receipt associated with status ${status}`);
};
const mockPolkadotModule = (path) => () => (Object.assign(Object.assign({}, jest.requireActual(path)), { ApiPromise: MockApiPromiseClass, WsProvider: MockWsProviderClass, Keyring: MockKeyringClass }));
exports.mockPolkadotModule = mockPolkadotModule;
const mockContextModule = (path) => () => (Object.assign(Object.assign({}, jest.requireActual(path)), { Context: MockContextClass }));
exports.mockContextModule = mockContextModule;
const mockApolloModule = (path) => () => (Object.assign(Object.assign({}, jest.requireActual(path)), { ApolloClient: MockApolloClientClass }));
exports.mockApolloModule = mockApolloModule;
const mockWebSocketAsPromisedModule = () => () => MockWebSocketAsPromisedClass;
exports.mockWebSocketAsPromisedModule = mockWebSocketAsPromisedModule;
const txMocksData = new Map();
let txModule = {};
let queryModule = {};
let constsModule = {};
// TODO cast rpcModule to a better type
let rpcModule = {};
let queryMultiStub = sinon_1.default.stub();
const defaultContextOptions = {
    did: 'someDid',
    withSeed: true,
    balance: {
        free: new bignumber_js_1.BigNumber(100),
        locked: new bignumber_js_1.BigNumber(10),
        total: new bignumber_js_1.BigNumber(110),
    },
    hasRoles: true,
    checkRoles: {
        result: true,
    },
    hasPermissions: true,
    checkPermissions: {
        result: true,
    },
    hasAssetPermissions: true,
    checkAssetPermissions: {
        result: true,
    },
    validCdd: true,
    assetBalance: new bignumber_js_1.BigNumber(1000),
    invalidDids: [],
    transactionFee: new bignumber_js_1.BigNumber(200),
    currentPairAddress: '0xdummy',
    currentPairIsLocked: false,
    issuedClaims: {
        data: [
            {
                target: 'targetIdentity',
                issuer: 'issuerIdentity',
                issuedAt: new Date(),
                expiry: null,
                claim: { type: types_1.ClaimType.NoData },
            },
        ],
        next: 1,
        count: 1,
    },
    getIdentityClaimsFromChain: [
        {
            target: 'targetIdentity',
            issuer: 'issuerIdentity',
            issuedAt: new Date(),
            expiry: null,
            claim: { type: types_1.ClaimType.NoData },
        },
    ],
    getIdentityClaimsFromMiddleware: {
        data: [
            {
                target: 'targetIdentity',
                issuer: 'issuerIdentity',
                issuedAt: new Date(),
                expiry: null,
                claim: { type: types_1.ClaimType.NoData },
            },
        ],
        next: 1,
        count: 1,
    },
    primaryAccount: 'primaryAccount',
    secondaryAccounts: [],
    transactionHistory: {
        data: [],
        next: null,
        count: 1,
    },
    latestBlock: new bignumber_js_1.BigNumber(100),
    middlewareEnabled: true,
    middlewareAvailable: true,
    sentAuthorizations: {
        data: [{}],
        next: 1,
        count: 1,
    },
    isArchiveNode: true,
    ss58Format: 42,
    getDividendDistributionsForAssets: [],
    areSecondaryAccountsFrozen: false,
    isFrozen: false,
    addPair: {
        address: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
        meta: {},
        isLocked: false,
        publicKey: 'someKey',
    },
    getAccounts: [],
    currentIdentityIsEqual: true,
    networkVersion: '1.0.0',
    supportsSubsidy: true,
};
let contextOptions = defaultContextOptions;
const defaultKeyringOptions = {
    getPair: {
        address: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
        meta: {},
        publicKey: 'publicKey1',
    },
    getPairs: [
        {
            address: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
            meta: {},
            publicKey: 'publicKey2',
        },
    ],
    addFromSeed: {
        address: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
        meta: {},
        publicKey: 'publicKey3',
    },
    addFromUri: {
        address: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
        meta: {},
        publicKey: 'publicKey4',
    },
    addFromMnemonic: {
        address: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
        meta: {},
        publicKey: 'publicKey5',
    },
    encodeAddress: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY',
};
let keyringOptions = defaultKeyringOptions;
/**
 * @hidden
 */
function configureContext(opts) {
    const getCurrentIdentity = sinon_1.default.stub();
    const identity = {
        did: opts.did,
        hasRoles: sinon_1.default.stub().resolves(opts.hasRoles),
        checkRoles: sinon_1.default.stub().resolves(opts.checkRoles),
        hasValidCdd: sinon_1.default.stub().resolves(opts.validCdd),
        getAssetBalance: sinon_1.default.stub().resolves(opts.assetBalance),
        getPrimaryAccount: sinon_1.default.stub().resolves({
            account: {
                address: opts.primaryAccount,
            },
            permissions: {
                tokens: null,
                transactions: null,
                transactionGroups: [],
                portfolios: null,
            },
        }),
        getSecondaryAccounts: sinon_1.default.stub().resolves(opts.secondaryAccounts),
        authorizations: {
            getSent: sinon_1.default.stub().resolves(opts.sentAuthorizations),
        },
        assetPermissions: {
            hasPermissions: sinon_1.default.stub().resolves(opts.hasAssetPermissions),
            checkPermissions: sinon_1.default.stub().resolves(opts.checkAssetPermissions),
        },
        areSecondaryAccountsFrozen: sinon_1.default.stub().resolves(opts.areSecondaryAccountsFrozen),
        isEqual: sinon_1.default.stub().returns(opts.currentIdentityIsEqual),
    };
    opts.withSeed
        ? getCurrentIdentity.resolves(identity)
        : getCurrentIdentity.throws(new Error('The current Account does not have an associated identity'));
    const getCurrentAccount = sinon_1.default.stub();
    opts.withSeed
        ? getCurrentAccount.returns({
            address: opts.currentPairAddress,
            getBalance: sinon_1.default.stub().resolves(opts.balance),
            getSubsidy: sinon_1.default.stub().resolves(opts.subsidy),
            getIdentity: sinon_1.default.stub().resolves(identity),
            getTransactionHistory: sinon_1.default.stub().resolves(opts.transactionHistory),
            hasPermissions: sinon_1.default.stub().resolves(opts.hasPermissions),
            checkPermissions: sinon_1.default.stub().resolves(opts.checkPermissions),
            isFrozen: sinon_1.default.stub().resolves(opts.isFrozen),
        })
        : getCurrentAccount.throws(new Error('There is no Account associated with the SDK'));
    const currentPair = opts.withSeed
        ? {
            address: opts.currentPairAddress,
            isLocked: opts.currentPairIsLocked,
        }
        : undefined;
    const getCurrentPair = sinon_1.default.stub();
    opts.withSeed
        ? getCurrentPair.returns(currentPair)
        : getCurrentPair.throws(new Error('There is no Account associated with the current SDK instance'));
    const contextInstance = {
        currentPair,
        getCurrentIdentity,
        getCurrentAccount,
        getCurrentPair,
        accountBalance: sinon_1.default.stub().resolves(opts.balance),
        accountSubsidy: sinon_1.default.stub().resolves(opts.subsidy),
        getAccounts: sinon_1.default.stub().returns(opts.getAccounts),
        setPair: sinon_1.default.stub().callsFake(address => {
            contextInstance.currentPair = { address };
        }),
        getSigner: sinon_1.default.stub().returns(currentPair),
        polymeshApi: mockInstanceContainer.apiInstance,
        middlewareApi: mockInstanceContainer.apolloInstance,
        queryMiddleware: sinon_1.default
            .stub()
            .callsFake(query => mockInstanceContainer.apolloInstance.query(query)),
        getInvalidDids: sinon_1.default.stub().resolves(opts.invalidDids),
        getProtocolFees: sinon_1.default.stub().resolves(opts.transactionFee),
        getTransactionArguments: sinon_1.default.stub().returns([]),
        getSecondaryAccounts: sinon_1.default.stub().returns(opts.secondaryAccounts),
        issuedClaims: sinon_1.default.stub().resolves(opts.issuedClaims),
        getIdentity: sinon_1.default.stub().resolves(opts.getIdentity),
        getIdentityClaimsFromChain: sinon_1.default.stub().resolves(opts.getIdentityClaimsFromChain),
        getIdentityClaimsFromMiddleware: sinon_1.default.stub().resolves(opts.getIdentityClaimsFromMiddleware),
        getLatestBlock: sinon_1.default.stub().resolves(opts.latestBlock),
        isMiddlewareEnabled: sinon_1.default.stub().returns(opts.middlewareEnabled),
        isMiddlewareAvailable: sinon_1.default.stub().resolves(opts.middlewareAvailable),
        isArchiveNode: opts.isArchiveNode,
        ss58Format: opts.ss58Format,
        disconnect: sinon_1.default.stub(),
        getDividendDistributionsForAssets: sinon_1.default
            .stub()
            .resolves(opts.getDividendDistributionsForAssets),
        addPair: sinon_1.default.stub().returns(opts.addPair),
        getNetworkVersion: sinon_1.default.stub().resolves(opts.networkVersion),
        supportsSubsidy: sinon_1.default.stub().returns(opts.supportsSubsidy),
    };
    contextInstance.clone = sinon_1.default.stub().returns(contextInstance);
    Object.assign(mockInstanceContainer.contextInstance, contextInstance);
    MockContextClass.create = contextCreateStub.resolves(contextInstance);
}
/**
 * @hidden
 */
function initContext(opts) {
    contextCreateStub = sinon_1.default.stub();
    contextOptions = Object.assign(Object.assign({}, defaultContextOptions), opts);
    configureContext(contextOptions);
}
/**
 * @hidden
 */
function updateQuery(mod) {
    const updateTo = mod || queryModule;
    queryModule = updateTo;
    mockInstanceContainer.apiInstance.query = queryModule;
}
/**
 * @hidden
 *
 * Mock the query module
 */
function initQuery() {
    const mod = {};
    updateQuery(mod);
}
/**
 * @hidden
 */
function updateTx(mod) {
    const updateTo = mod || txModule;
    txModule = updateTo;
    mockInstanceContainer.apiInstance.tx = txModule;
}
/**
 * @hidden
 */
function updateRpc(mod) {
    const updateTo = mod || rpcModule;
    rpcModule = updateTo;
    mockInstanceContainer.apiInstance.rpc = rpcModule;
}
/**
 * @hidden
 */
function updateConsts(mod) {
    const updateTo = mod || constsModule;
    constsModule = updateTo;
    mockInstanceContainer.apiInstance.consts = constsModule;
}
/**
 * @hidden
 */
function updateQueryMulti(stub) {
    const updateTo = stub || queryMultiStub;
    queryMultiStub = updateTo;
    mockInstanceContainer.apiInstance.queryMulti = queryMultiStub;
}
/**
 * @hidden
 *
 * Mock the tx module
 */
function initTx() {
    const mod = {};
    updateTx(mod);
}
/**
 * @hidden
 *
 * Mock the rpc module
 */
function initRpc() {
    const mod = {};
    updateRpc(mod);
}
/**
 * @hidden
 *
 * Mock the consts module
 */
function initConsts() {
    const mod = {};
    updateConsts(mod);
}
/**
 * @hidden
 *
 * Mock queryMulti
 */
function initQueryMulti() {
    const stub = sinon_1.default.stub();
    updateQueryMulti(stub);
}
/**
 * @hidden
 */
function initApi() {
    mockInstanceContainer.apiInstance.registry = 'registry';
    mockInstanceContainer.apiInstance.createType = sinon_1.default.stub();
    mockInstanceContainer.apiInstance.runtimeVersion = {};
    initTx();
    initQuery();
    initRpc();
    initConsts();
    initQueryMulti();
    apiPromiseCreateStub = sinon_1.default.stub();
    MockApiPromiseClass.create = apiPromiseCreateStub.resolves(mockInstanceContainer.apiInstance);
}
/**
 * @hidden
 */
function configureKeyring(opts) {
    const { error, getPair, getPairs, addFromUri, addFromSeed, addFromMnemonic, addPair, encodeAddress, } = opts;
    const err = new Error('Error');
    const keyringInstance = {
        getPair: sinon_1.default.stub().returns(getPair),
        getPairs: sinon_1.default.stub().returns(getPairs),
        addFromSeed: sinon_1.default.stub().returns(addFromSeed),
        addFromUri: sinon_1.default.stub().returns(addFromUri),
        addFromMnemonic: sinon_1.default.stub().returns(addFromMnemonic),
        addPair: sinon_1.default.stub().returns(addPair),
        encodeAddress: sinon_1.default.stub().returns(encodeAddress),
    };
    if (error) {
        keyringInstance.getPair.throws(err);
        keyringInstance.getPairs.throws(err);
        keyringInstance.addFromSeed.throws(err);
        keyringInstance.addFromUri.throws(err);
        keyringInstance.addFromMnemonic.throws(err);
        keyringInstance.encodeAddress.throws(err);
    }
    Object.assign(mockInstanceContainer.keyringInstance, keyringInstance);
    keyringConstructorStub.returns(keyringInstance);
}
/**
 * @hidden
 */
function initKeyring(opts) {
    keyringConstructorStub = sinon_1.default.stub();
    keyringOptions = Object.assign(Object.assign({}, defaultKeyringOptions), opts);
    configureKeyring(keyringOptions);
}
/**
 * @hidden
 *
 * Temporarily change instance mock configuration (calling .reset will go back to the configuration passed in `initMocks`)
 */
function configureMocks(opts) {
    const tempKeyringOptions = Object.assign(Object.assign({}, defaultKeyringOptions), opts === null || opts === void 0 ? void 0 : opts.keyringOptions);
    configureKeyring(tempKeyringOptions);
    const tempContextOptions = Object.assign(Object.assign({}, defaultContextOptions), opts === null || opts === void 0 ? void 0 : opts.contextOptions);
    configureContext(tempContextOptions);
}
exports.configureMocks = configureMocks;
/**
 * @hidden
 * Initialize the factory by adding default all-purpose functionality to the mock manager
 *
 * @param opts.mockContext - if defined, the internal [[Context]] class will also be mocked with custom properties
 */
function initMocks(opts) {
    /*
      NOTE: the idea is to expand this function to mock things as we need them
      and use the methods in the class to fetch/manipulate different parts of the API as required
     */
    // Context
    initContext(opts === null || opts === void 0 ? void 0 : opts.contextOptions);
    // Api
    initApi();
    // Keyring
    initKeyring(opts === null || opts === void 0 ? void 0 : opts.keyringOptions);
    // Apollo
    apolloConstructorStub = sinon_1.default.stub().returns(mockInstanceContainer.apolloInstance);
    // WebSocketAsPromised
    webSocketAsPromisedConstructorStub = sinon_1.default
        .stub()
        .returns(mockInstanceContainer.webSocketAsPromisedInstance);
    txMocksData.clear();
    errorStub = sinon_1.default.stub().throws(new Error('Error'));
}
exports.initMocks = initMocks;
/**
 * @hidden
 * Restore instances to their original state
 */
function cleanup() {
    mockInstanceContainer.apiInstance = createApi();
    mockInstanceContainer.contextInstance = {};
    mockInstanceContainer.keyringInstance = {};
    mockInstanceContainer.apolloInstance = createApolloClient();
    mockInstanceContainer.webSocketAsPromisedInstance = createWebSocketAsPromised();
}
exports.cleanup = cleanup;
/**
 * @hidden
 * Reinitialize mocks
 */
function reset() {
    cleanup();
    initMocks({ contextOptions, keyringOptions });
}
exports.reset = reset;
/**
 * @hidden
 * Create and returns a mocked transaction. Each call will create a new version of the stub
 *
 * @param mod - name of the module
 * @param tx - name of the transaction function
 * @param autoResolve - if set to a status, the transaction will resolve immediately with that status.
 *  If set to false, the transaction lifecycle will be controlled by [[updateTxStatus]]
 */
function createTxStub(mod, tx, opts = {}) {
    let runtimeModule = txModule[mod];
    if (!runtimeModule) {
        runtimeModule = {};
        txModule[mod] = runtimeModule;
    }
    const { autoResolve = MockTxStatus.Succeeded, 
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    gas = exports.createMockBalance(1), meta = { args: [] }, } = opts;
    const transaction = sinon_1.default.stub().returns({
        method: tx,
        hash: tx,
        signAndSend: sinon_1.default.stub().callsFake((_, __, cb) => {
            if (autoResolve === MockTxStatus.Rejected) {
                return Promise.reject(new Error('Cancelled'));
            }
            const unsubCallback = sinon_1.default.stub();
            txMocksData.set(runtimeModule[tx], {
                statusCallback: cb,
                unsubCallback,
                resolved: !!autoResolve,
                status: null,
            });
            if (autoResolve) {
                process.nextTick(() => cb(statusToReceipt(autoResolve)));
            }
            return Promise.resolve(unsubCallback);
        }),
        // eslint-disable-next-line @typescript-eslint/no-use-before-define
        paymentInfo: sinon_1.default.stub().resolves({ partialFee: gas }),
    });
    transaction.section = mod;
    transaction.method = tx;
    transaction.meta = meta;
    runtimeModule[tx] = transaction;
    updateTx();
    const instance = mockInstanceContainer.apiInstance;
    return instance.tx[mod][tx];
}
exports.createTxStub = createTxStub;
/**
 * @hidden
 * Create and return an apollo query stub
 *
 * @param query - apollo document node
 * @param returnValue
 */
function createApolloQueryStub(query, returnData) {
    const instance = mockInstanceContainer.apolloInstance;
    const stub = sinon_1.default.stub();
    stub.withArgs(query).resolves({
        data: returnData,
    });
    instance.query = stub;
    return stub;
}
exports.createApolloQueryStub = createApolloQueryStub;
/**
 * @hidden
 * Create and return an apollo stub for multiple queries
 *
 * @param queries - query and returnData for each stubbed query
 */
function createApolloMultipleQueriesStub(queries) {
    const instance = mockInstanceContainer.apolloInstance;
    const stub = sinon_1.default.stub();
    queries.forEach(q => {
        stub.withArgs(q.query).resolves({
            data: q.returnData,
        });
    });
    instance.query = stub;
    return stub;
}
exports.createApolloMultipleQueriesStub = createApolloMultipleQueriesStub;
/**
 * @hidden
 * Create and return a query stub
 *
 * @param mod - name of the module
 * @param query - name of the query function
 */
function createQueryStub(mod, query, opts) {
    var _a;
    let runtimeModule = queryModule[mod];
    if (!runtimeModule) {
        runtimeModule = {};
        queryModule[mod] = runtimeModule;
    }
    let stub;
    if (!runtimeModule[query]) {
        stub = sinon_1.default.stub();
        stub.entries = sinon_1.default.stub();
        stub.entriesPaged = sinon_1.default.stub();
        stub.at = sinon_1.default.stub();
        stub.multi = sinon_1.default.stub();
        stub.size = sinon_1.default.stub();
        runtimeModule[query] = stub;
        updateQuery();
    }
    else {
        const instance = mockInstanceContainer.apiInstance;
        stub = instance.query[mod][query];
    }
    const entries = (_a = opts === null || opts === void 0 ? void 0 : opts.entries) !== null && _a !== void 0 ? _a : [];
    const entryResults = entries.map(([keys, value], index) => [
        { args: keys, toHex: () => `key${index}` },
        value,
    ]);
    stub.entries.resolves(entryResults);
    stub.entriesPaged.resolves(entryResults);
    if (opts === null || opts === void 0 ? void 0 : opts.multi) {
        stub.multi.resolves(opts.multi);
    }
    if (typeof (opts === null || opts === void 0 ? void 0 : opts.size) !== 'undefined') {
        // eslint-disable-next-line @typescript-eslint/no-use-before-define
        stub.size.resolves(exports.createMockU64(opts.size));
    }
    if (opts === null || opts === void 0 ? void 0 : opts.returnValue) {
        stub.resolves(opts.returnValue);
        stub.at.resolves(opts.returnValue);
    }
    return stub;
}
exports.createQueryStub = createQueryStub;
let count = 0;
/**
 * @hidden
 * Create and return a rpc stub
 *
 * @param mod - name of the module
 * @param rpc - name of the rpc function
 */
function createRpcStub(mod, rpc, opts) {
    const runtimeModule = {};
    rpcModule[mod] = runtimeModule;
    const stub = sinon_1.default.stub();
    runtimeModule[rpc] = stub;
    updateRpc();
    if (opts === null || opts === void 0 ? void 0 : opts.returnValue) {
        stub.resolves(opts.returnValue);
    }
    stub.count = count++;
    return stub;
}
exports.createRpcStub = createRpcStub;
/**
 * @hidden
 * Set a consts mock
 *
 * @param mod - name of the module
 * @param constName - name of the constant
 */
function setConstMock(mod, constName, opts) {
    let runtimeModule = constsModule[mod];
    if (!runtimeModule) {
        runtimeModule = {};
        constsModule[mod] = runtimeModule;
    }
    const returnValue = opts.returnValue;
    if (!runtimeModule[constName]) {
        runtimeModule[constName] = returnValue;
        updateConsts();
    }
    else {
        const instance = mockInstanceContainer.apiInstance;
        instance.consts[mod][constName] = returnValue;
    }
}
exports.setConstMock = setConstMock;
/**
 * @hidden
 */
function getQueryMultiStub() {
    return queryMultiStub;
}
exports.getQueryMultiStub = getQueryMultiStub;
/**
 * @hidden
 * Update the status of an existing mock transaction. Will throw an error if the transaction has already been resolved
 *
 * @param tx - transaction to update
 * @param status - new status
 */
function updateTxStatus(tx, status, failReason) {
    const txMockData = txMocksData.get(tx);
    if (!txMockData) {
        throw new Error('Invalid tx object');
    }
    if (txMockData.resolved) {
        throw new Error('Cannot update status on an already resolved tx');
    }
    if (status === txMockData.status) {
        throw new Error(`Status is already ${status}`);
    }
    if ([MockTxStatus.Aborted, MockTxStatus.Failed, MockTxStatus.Succeeded].includes(status)) {
        txMocksData.set(tx, Object.assign(Object.assign({}, txMockData), { status, resolved: true }));
    }
    txMockData.statusCallback(statusToReceipt(status, failReason));
}
exports.updateTxStatus = updateTxStatus;
/**
 * @hidden
 * Make calls to `Middleware.query` throw an error
 */
function throwOnMiddlewareQuery(err) {
    const instance = mockInstanceContainer.apolloInstance;
    if (err) {
        errorStub.throws(err);
    }
    instance.query = errorStub;
}
exports.throwOnMiddlewareQuery = throwOnMiddlewareQuery;
/**
 * @hidden
 * Make calls to `Context.create` throw an error
 */
function throwOnContextCreation() {
    MockContextClass.create = errorStub;
}
exports.throwOnContextCreation = throwOnContextCreation;
/**
 * @hidden
 * Make calls to `ApiPromise.create` throw an error
 */
function throwOnApiCreation(error) {
    MockApiPromiseClass.create = error ? sinon_1.default.stub().throws(error) : errorStub;
}
exports.throwOnApiCreation = throwOnApiCreation;
/**
 * @hidden
 * Sets the `accountBalance` function in the mocked Context to return the specified amount
 *
 * @param balance - new account balance
 */
function setContextAccountBalance(balance) {
    mockInstanceContainer.contextInstance.accountBalance.returns(balance);
}
exports.setContextAccountBalance = setContextAccountBalance;
/**
 * @hidden
 * Retrieve an instance of the mocked Polkadot API
 */
function getApiInstance() {
    return mockInstanceContainer.apiInstance;
}
exports.getApiInstance = getApiInstance;
/**
 * @hidden
 * Retrieve an instance of the mocked Apollo Client
 */
function getMiddlewareApi() {
    return mockInstanceContainer.apolloInstance;
}
exports.getMiddlewareApi = getMiddlewareApi;
/**
 * @hidden
 * Retrieve the stub of the createType method
 */
function getCreateTypeStub() {
    return mockInstanceContainer.apiInstance.createType;
}
exports.getCreateTypeStub = getCreateTypeStub;
/**
 * @hidden
 * Retrieve an instance of the mocked Context
 */
function getContextInstance(opts) {
    if (opts) {
        configureContext(Object.assign(Object.assign({}, defaultContextOptions), opts));
    }
    return mockInstanceContainer.contextInstance;
}
exports.getContextInstance = getContextInstance;
/**
 * @hidden
 * Retrieve the stub of the `Context.create` method
 */
function getContextCreateStub() {
    return contextCreateStub;
}
exports.getContextCreateStub = getContextCreateStub;
/**
 * @hidden
 * Retrieve an instance of the mocked Keyring
 */
function getKeyringInstance(opts) {
    if (opts) {
        configureKeyring(Object.assign(Object.assign({}, defaultKeyringOptions), opts));
    }
    return mockInstanceContainer.keyringInstance;
}
exports.getKeyringInstance = getKeyringInstance;
/**
 * @hidden
 */
const setRuntimeVersion = (args) => {
    mockInstanceContainer.apiInstance.runtimeVersion = args;
};
exports.setRuntimeVersion = setRuntimeVersion;
/**
 * @hidden
 */
function isCodec(codec) {
    return !!(codec === null || codec === void 0 ? void 0 : codec._isCodec);
}
/**
 * @hidden
 */
function isOption(codec) {
    return typeof (codec === null || codec === void 0 ? void 0 : codec.unwrap) === 'function';
}
/**
 * @hidden
 */
const createMockCodec = (codec, isEmpty) => {
    const clone = lodash_1.cloneDeep(codec);
    clone._isCodec = true;
    clone.isEmpty = isEmpty;
    return clone;
};
/**
 * @hidden
 */
const createMockStringCodec = (value) => createMockCodec({
    toString: () => value,
    eq: (compareValue) => value === compareValue.toString(),
}, value === undefined);
/**
 * @hidden
 */
const createMockU8aCodec = (value, hex) => createMockCodec(hex ? util_1.hexToU8a(value) : util_1.stringToU8a(value), value === undefined);
/**
 * @hidden
 */
const createMockNumberCodec = (value) => createMockCodec({
    toNumber: () => value,
    toString: () => `${value}`,
    isZero: () => value === 0,
}, value === undefined);
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockIdentityId = (did) => {
    if (isCodec(did)) {
        return did;
    }
    return createMockStringCodec(did);
};
exports.createMockIdentityId = createMockIdentityId;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockAgentGroup = (agentGroup) => {
    return createMockEnum(agentGroup);
};
exports.createMockAgentGroup = createMockAgentGroup;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockEcdsaSignature = (signature) => {
    if (isCodec(signature)) {
        return signature;
    }
    return createMockStringCodec(signature);
};
exports.createMockEcdsaSignature = createMockEcdsaSignature;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockEthereumAddress = (address) => {
    if (isCodec(address)) {
        return address;
    }
    return createMockU8aCodec(address);
};
exports.createMockEthereumAddress = createMockEthereumAddress;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockTicker = (ticker) => {
    if (isCodec(ticker)) {
        return ticker;
    }
    return createMockU8aCodec(ticker);
};
exports.createMockTicker = createMockTicker;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockAccountId = (accountId) => createMockStringCodec(accountId);
exports.createMockAccountId = createMockAccountId;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockBalance = (balance) => {
    if (isCodec(balance)) {
        return balance;
    }
    return createMockNumberCodec(balance);
};
exports.createMockBalance = createMockBalance;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockDocumentName = (name) => createMockStringCodec(name);
exports.createMockDocumentName = createMockDocumentName;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockDocumentUri = (uri) => createMockStringCodec(uri);
exports.createMockDocumentUri = createMockDocumentUri;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockDocumentHash = (hash) => {
    if (isCodec(hash)) {
        return hash;
    }
    return createMockEnum(hash);
};
exports.createMockDocumentHash = createMockDocumentHash;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockDocumentType = (name) => createMockStringCodec(name);
exports.createMockDocumentType = createMockDocumentType;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockOption = (wrapped = null) => {
    if (isOption(wrapped)) {
        return wrapped;
    }
    return createMockCodec({
        unwrap: () => wrapped,
        unwrapOr: (val) => wrapped !== null && wrapped !== void 0 ? wrapped : val,
        isNone: !wrapped,
        isSome: !!wrapped,
    }, !wrapped);
};
exports.createMockOption = createMockOption;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockCompact = (wrapped = null) => createMockCodec({
    unwrap: () => wrapped,
    isNone: !wrapped,
    isSome: !!wrapped,
}, !wrapped);
exports.createMockCompact = createMockCompact;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockMoment = (millis) => {
    if (isCodec(millis)) {
        return millis;
    }
    return createMockNumberCodec(millis);
};
exports.createMockMoment = createMockMoment;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockTickerRegistration = (registration) => {
    const { owner, expiry } = registration || {
        owner: exports.createMockIdentityId(),
        expiry: exports.createMockOption(),
    };
    return createMockCodec({
        owner: exports.createMockIdentityId(owner),
        expiry: exports.createMockOption(expiry),
    }, !registration);
};
exports.createMockTickerRegistration = createMockTickerRegistration;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockU8 = (value) => createMockNumberCodec(value);
exports.createMockU8 = createMockU8;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockU32 = (value) => {
    if (isCodec(value)) {
        return value;
    }
    return createMockNumberCodec(value);
};
exports.createMockU32 = createMockU32;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockU64 = (value) => {
    if (isCodec(value)) {
        return value;
    }
    return createMockNumberCodec(value);
};
exports.createMockU64 = createMockU64;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockPermill = (value) => {
    if (isCodec(value)) {
        return value;
    }
    return createMockNumberCodec(value);
};
exports.createMockPermill = createMockPermill;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockBytes = (value) => createMockU8aCodec(value);
exports.createMockBytes = createMockBytes;
/**
 * @hidden
 */
const createMockHash = (value) => {
    if (isCodec(value)) {
        return value;
    }
    return createMockStringCodec(value);
};
exports.createMockHash = createMockHash;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockAssetName = (name) => createMockStringCodec(name);
exports.createMockAssetName = createMockAssetName;
/**
 * @hidden
 */
const createMockPosRatio = (numerator, denominator) => [exports.createMockU32(numerator), exports.createMockU32(denominator)];
exports.createMockPosRatio = createMockPosRatio;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockBool = (value) => {
    if (isCodec(value)) {
        return value;
    }
    return createMockCodec({
        isTrue: value,
        isFalse: !value,
        valueOf: () => value,
    }, !value);
};
exports.createMockBool = createMockBool;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockEnum = (enumValue) => {
    const codec = {};
    if (typeof enumValue === 'string') {
        codec[`is${lodash_1.upperFirst(enumValue)}`] = true;
    }
    else if (typeof enumValue === 'object') {
        const key = Object.keys(enumValue)[0];
        codec[`is${lodash_1.upperFirst(key)}`] = true;
        codec[`as${lodash_1.upperFirst(key)}`] = enumValue[key];
    }
    return createMockCodec(codec, false);
};
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockPortfolioKind = (portfolioKind) => {
    if (isCodec(portfolioKind)) {
        return portfolioKind;
    }
    return createMockEnum(portfolioKind);
};
exports.createMockPortfolioKind = createMockPortfolioKind;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockPortfolioId = (portfolioId) => {
    const { did, kind } = portfolioId || {
        did: exports.createMockIdentityId(),
        kind: exports.createMockPortfolioKind(),
    };
    return createMockCodec({
        did: exports.createMockIdentityId(did),
        kind: exports.createMockPortfolioKind(kind),
    }, !portfolioId);
};
exports.createMockPortfolioId = createMockPortfolioId;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockMovePortfolioItem = (movePortfolioItem) => {
    const item = movePortfolioItem || {
        ticker: exports.createMockTicker(),
        amount: exports.createMockBalance(),
    };
    return createMockCodec(Object.assign({}, item), !movePortfolioItem);
};
exports.createMockMovePortfolioItem = createMockMovePortfolioItem;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockAssetType = (assetType) => {
    return createMockEnum(assetType);
};
exports.createMockAssetType = createMockAssetType;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockTickerRegistrationConfig = (regConfig) => {
    const config = regConfig || {
        max_ticker_length: exports.createMockU8(),
        registration_length: exports.createMockOption(),
    };
    return createMockCodec(Object.assign({}, config), !regConfig);
};
exports.createMockTickerRegistrationConfig = createMockTickerRegistrationConfig;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockSecurityToken = (token) => {
    const st = token || {
        total_supply: exports.createMockBalance(),
        owner_did: exports.createMockIdentityId(),
        divisible: exports.createMockBool(),
        asset_type: exports.createMockAssetType(),
    };
    return createMockCodec(Object.assign({}, st), !token);
};
exports.createMockSecurityToken = createMockSecurityToken;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockDocument = (document) => {
    const doc = document || {
        uri: exports.createMockDocumentUri(),
        content_hash: exports.createMockDocumentHash(),
        name: exports.createMockDocumentName(),
        doc_type: exports.createMockOption(),
        filing_date: exports.createMockOption(),
    };
    return createMockCodec(Object.assign({}, doc), !document);
};
exports.createMockDocument = createMockDocument;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockPalletPermissions = (permissions) => {
    const { pallet_name, dispatchable_names } = permissions || {
        pallet_name: exports.createMockPalletName(),
        dispatchable_names: exports.createMockDispatchableNames(),
    };
    return createMockCodec({
        pallet_name: exports.createMockPalletName(pallet_name),
        dispatchable_names: exports.createMockDispatchableNames(dispatchable_names),
    }, !permissions);
};
exports.createMockPalletPermissions = createMockPalletPermissions;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockAccountData = (accountData) => {
    const { free, reserved, miscFrozen, feeFrozen } = accountData || {
        free: exports.createMockBalance(),
        reserved: exports.createMockBalance(),
        miscFrozen: exports.createMockBalance(),
        feeFrozen: exports.createMockBalance(),
    };
    return createMockCodec({
        free: exports.createMockBalance(free),
        reserved: exports.createMockBalance(reserved),
        miscFrozen: exports.createMockBalance(miscFrozen),
        feeFrozen: exports.createMockBalance(feeFrozen),
    }, !accountData);
};
exports.createMockAccountData = createMockAccountData;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockIndex = (value) => createMockNumberCodec(value);
exports.createMockIndex = createMockIndex;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockRefCount = (value) => createMockNumberCodec(value);
exports.createMockRefCount = createMockRefCount;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockAccountInfo = (accountInfo) => {
    const info = accountInfo || {
        nonce: exports.createMockIndex(),
        refcount: exports.createMockRefCount(),
        data: exports.createMockAccountData(),
    };
    return createMockCodec(Object.assign({}, info), !accountInfo);
};
exports.createMockAccountInfo = createMockAccountInfo;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockSubsidy = (subsidy) => {
    const sub = subsidy || {
        paying_key: exports.createMockAccountId(),
        remaining: exports.createMockBalance(),
    };
    return createMockCodec(Object.assign({}, sub), !subsidy);
};
exports.createMockSubsidy = createMockSubsidy;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockSignatory = (signatory) => {
    return createMockEnum(signatory);
};
exports.createMockSignatory = createMockSignatory;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockAuthorizationType = (authorizationType) => {
    return createMockEnum(authorizationType);
};
exports.createMockAuthorizationType = createMockAuthorizationType;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockU8aFixed = (value, hex) => createMockU8aCodec(value, hex);
exports.createMockU8aFixed = createMockU8aFixed;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockAssetIdentifier = (identifier) => createMockEnum(identifier);
exports.createMockAssetIdentifier = createMockAssetIdentifier;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockFundingRoundName = (roundName) => createMockStringCodec(roundName);
exports.createMockFundingRoundName = createMockFundingRoundName;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockPalletName = (name) => {
    if (isCodec(name)) {
        return name;
    }
    return createMockStringCodec(name);
};
exports.createMockPalletName = createMockPalletName;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockDispatchableName = (name) => {
    if (isCodec(name)) {
        return name;
    }
    return createMockStringCodec(name);
};
exports.createMockDispatchableName = createMockDispatchableName;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockFundraiserName = (name) => createMockStringCodec(name);
exports.createMockFundraiserName = createMockFundraiserName;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockPermissions = (permissions) => {
    const perms = permissions || {
        asset: exports.createMockAssetPermissions(),
        extrinsic: exports.createMockExtrinsicPermissions(),
        portfolio: exports.createMockPortfolioPermissions(),
    };
    return createMockCodec(Object.assign({}, perms), !permissions);
};
exports.createMockPermissions = createMockPermissions;
/**
 * @hidden
 */
const createMockAssetPermissions = (assetPermissions) => {
    return createMockEnum(assetPermissions);
};
exports.createMockAssetPermissions = createMockAssetPermissions;
/**
 * @hidden
 */
const createMockExtrinsicPermissions = (assetPermissions) => {
    return createMockEnum(assetPermissions);
};
exports.createMockExtrinsicPermissions = createMockExtrinsicPermissions;
/**
 * @hidden
 */
const createMockPortfolioPermissions = (assetPermissions) => {
    return createMockEnum(assetPermissions);
};
exports.createMockPortfolioPermissions = createMockPortfolioPermissions;
/**
 * @hidden
 */
const createMockDispatchableNames = (dispatchableNames) => {
    if (isCodec(dispatchableNames)) {
        return dispatchableNames;
    }
    return createMockEnum(dispatchableNames);
};
exports.createMockDispatchableNames = createMockDispatchableNames;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockAuthorizationData = (authorizationData) => {
    if (isCodec(authorizationData)) {
        return authorizationData;
    }
    return createMockEnum(authorizationData);
};
exports.createMockAuthorizationData = createMockAuthorizationData;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockAuthorization = (authorization) => {
    const { authorization_data, authorized_by, expiry, auth_id } = authorization || {
        authorization_data: exports.createMockAuthorizationData(),
        authorized_by: exports.createMockIdentityId(),
        expiry: exports.createMockOption(),
        auth_id: exports.createMockU64(),
    };
    return createMockCodec({
        authorization_data: exports.createMockAuthorizationData(authorization_data),
        authorized_by: exports.createMockIdentityId(authorized_by),
        expiry: exports.createMockOption(expiry),
        auth_id: exports.createMockU64(auth_id),
    }, !authorization);
};
exports.createMockAuthorization = createMockAuthorization;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockEventRecord = (data) => ({
    event: {
        data,
    },
});
exports.createMockEventRecord = createMockEventRecord;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockIEvent = (data) => ({
    data,
});
exports.createMockIEvent = createMockIEvent;
/**
 * @hidden
 */
const createMockCddStatus = (cddStatus) => createMockEnum(cddStatus);
exports.createMockCddStatus = createMockCddStatus;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockCountryCode = (name) => createMockEnum(name);
exports.createMockCountryCode = createMockCountryCode;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockScope = (scope) => createMockEnum(scope);
exports.createMockScope = createMockScope;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockCddId = (cddId) => createMockStringCodec(cddId);
exports.createMockCddId = createMockCddId;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockScopeId = (scopeId) => createMockStringCodec(scopeId);
exports.createMockScopeId = createMockScopeId;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockInvestorZKProofData = (proof) => createMockStringCodec(proof);
exports.createMockInvestorZKProofData = createMockInvestorZKProofData;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockClaim = (claim) => createMockEnum(claim);
exports.createMockClaim = createMockClaim;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockIdentityClaim = (identityClaim) => {
    const identityClaimMock = identityClaim || {
        claim_issuer: exports.createMockIdentityId(),
        issuance_date: exports.createMockMoment(),
        last_update_date: exports.createMockMoment(),
        expiry: exports.createMockOption(),
        claim: exports.createMockClaim(),
    };
    return createMockCodec(Object.assign({}, identityClaimMock), !identityClaimMock);
};
exports.createMockIdentityClaim = createMockIdentityClaim;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockTargetIdentity = (targetIdentity) => createMockEnum(targetIdentity);
exports.createMockTargetIdentity = createMockTargetIdentity;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockConditionType = (conditionType) => {
    if (isCodec(conditionType)) {
        return conditionType;
    }
    return createMockEnum(conditionType);
};
exports.createMockConditionType = createMockConditionType;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockClaimType = (claimType) => createMockEnum(claimType);
exports.createMockClaimType = createMockClaimType;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockClaim1stKey = (claim1stKey) => {
    const claimTypeMock = claim1stKey || {
        target: exports.createMockIdentityId(),
        claim_type: exports.createMockClaimType(),
    };
    return createMockCodec(Object.assign({}, claimTypeMock), !claimTypeMock);
};
exports.createMockClaim1stKey = createMockClaim1stKey;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockTrustedFor = (trustedFor) => createMockEnum(trustedFor);
exports.createMockTrustedFor = createMockTrustedFor;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockTrustedIssuer = (issuer) => {
    const trustedIssuer = issuer || {
        issuer: exports.createMockIdentityId(),
        trusted_for: exports.createMockTrustedFor(),
    };
    return createMockCodec(Object.assign({}, trustedIssuer), !issuer);
};
exports.createMockTrustedIssuer = createMockTrustedIssuer;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockCondition = (condition) => {
    const { condition_type, issuers } = condition || {
        condition_type: exports.createMockConditionType(),
        issuers: [],
    };
    return createMockCodec({
        condition_type: exports.createMockConditionType(condition_type),
        issuers: issuers.map(issuer => exports.createMockTrustedIssuer(issuer)),
    }, !condition);
};
exports.createMockCondition = createMockCondition;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockConditionResult = (conditionResult) => {
    const { condition, result } = conditionResult || {
        condition: exports.createMockCondition(),
        result: exports.createMockBool(),
    };
    return createMockCodec({
        condition: exports.createMockCondition(condition),
        result: exports.createMockBool(result),
    }, !conditionResult);
};
exports.createMockConditionResult = createMockConditionResult;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockComplianceRequirement = (complianceRequirement) => {
    const requirement = complianceRequirement || {
        sender_conditions: [],
        receiver_conditions: [],
        id: exports.createMockU32(),
    };
    return createMockCodec(Object.assign({}, requirement), !complianceRequirement);
};
exports.createMockComplianceRequirement = createMockComplianceRequirement;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockComplianceRequirementResult = (complianceRequirementResult) => {
    const { sender_conditions, receiver_conditions, id, result } = complianceRequirementResult || {
        sender_conditions: [],
        receiver_conditions: [],
        id: exports.createMockU32(),
        result: exports.createMockBool(),
    };
    return createMockCodec({
        sender_conditions: sender_conditions.map(condition => exports.createMockConditionResult(condition)),
        receiver_conditions: receiver_conditions.map(condition => exports.createMockConditionResult(condition)),
        id: exports.createMockU32(id),
        result: exports.createMockBool(result),
    }, !complianceRequirementResult);
};
exports.createMockComplianceRequirementResult = createMockComplianceRequirementResult;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockAssetComplianceResult = (assetComplianceResult) => {
    const { paused, requirements, result } = assetComplianceResult || {
        paused: exports.createMockBool(),
        requirements: [],
        result: exports.createMockBool(),
    };
    return createMockCodec({
        paused: exports.createMockBool(paused),
        requirements: requirements.map(requirement => exports.createMockComplianceRequirementResult(requirement)),
        result: exports.createMockBool(result),
    }, !assetComplianceResult);
};
exports.createMockAssetComplianceResult = createMockAssetComplianceResult;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockDidRecord = (didRecord) => {
    const record = didRecord || {
        roles: [],
        primary_key: exports.createMockAccountId(),
        secondary_items: [],
    };
    return createMockCodec(Object.assign({}, record), !didRecord);
};
exports.createMockDidRecord = createMockDidRecord;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockCanTransferResult = (canTransferResult) => createMockEnum(canTransferResult);
exports.createMockCanTransferResult = createMockCanTransferResult;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockText = (value) => {
    if (isCodec(value)) {
        return value;
    }
    return createMockStringCodec(value);
};
exports.createMockText = createMockText;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockAssetOwnershipRelation = (assetOwnershipRelation) => createMockEnum(assetOwnershipRelation);
exports.createMockAssetOwnershipRelation = createMockAssetOwnershipRelation;
/**
 * @hidden
 */
const createMockProposalState = (proposalState) => {
    return createMockEnum(proposalState);
};
exports.createMockProposalState = createMockProposalState;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockPip = (pip) => {
    const proposal = pip || {
        id: exports.createMockU32(),
        proposal: 'proposal',
        state: exports.createMockProposalState(),
    };
    return createMockCodec(Object.assign({}, proposal), !pip);
};
exports.createMockPip = createMockPip;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockPipsMetadata = (metadata) => {
    const data = metadata || {
        proposer: exports.createMockAccountId(),
        cool_off_until: exports.createMockU32(),
        end: exports.createMockU32(),
    };
    return createMockCodec(Object.assign({}, data), !metadata);
};
exports.createMockPipsMetadata = createMockPipsMetadata;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockSecondaryKey = (secondaryKey) => {
    const key = secondaryKey || {
        signer: exports.createMockSignatory(),
        permissions: exports.createMockPermissions(),
    };
    return createMockCodec(Object.assign({}, key), !secondaryKey);
};
exports.createMockSecondaryKey = createMockSecondaryKey;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockPipId = (id) => exports.createMockU32(new bignumber_js_1.BigNumber(id).toNumber());
exports.createMockPipId = createMockPipId;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockVenueDetails = (details) => createMockStringCodec(details);
exports.createMockVenueDetails = createMockVenueDetails;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockVenueType = (venueType) => {
    return createMockEnum(venueType);
};
exports.createMockVenueType = createMockVenueType;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockVenue = (venue) => {
    const vn = venue || {
        creator: exports.createMockIdentityId(),
        // eslint-disable-next-line @typescript-eslint/naming-convention
        venue_type: exports.createMockVenueType(),
    };
    return createMockCodec(Object.assign({}, vn), !venue);
};
exports.createMockVenue = createMockVenue;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockInstructionStatus = (instructionStatus) => {
    return createMockEnum(instructionStatus);
};
exports.createMockInstructionStatus = createMockInstructionStatus;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockSettlementType = (settlementType) => {
    return createMockEnum(settlementType);
};
exports.createMockSettlementType = createMockSettlementType;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockAffirmationStatus = (authorizationStatus) => {
    return createMockEnum(authorizationStatus);
};
exports.createMockAffirmationStatus = createMockAffirmationStatus;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockInstruction = (instruction) => {
    const data = instruction || {
        instruction_id: exports.createMockU64(),
        venue_id: exports.createMockU64(),
        status: exports.createMockInstructionStatus(),
        settlement_type: exports.createMockSettlementType(),
        created_at: exports.createMockOption(),
        trade_date: exports.createMockOption(),
    };
    return createMockCodec(Object.assign({}, data), !instruction);
};
exports.createMockInstruction = createMockInstruction;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockTransferManager = (transferManager) => {
    if (isCodec(transferManager)) {
        return transferManager;
    }
    return createMockEnum(transferManager);
};
exports.createMockTransferManager = createMockTransferManager;
/**
 * @hidden
 */
const createMockFundraiserTier = (fundraiserTier) => {
    const data = fundraiserTier || {
        total: exports.createMockBalance(),
        price: exports.createMockBalance(),
        remaining: exports.createMockBalance(),
    };
    return createMockCodec(Object.assign({}, data), !fundraiserTier);
};
exports.createMockFundraiserTier = createMockFundraiserTier;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockFundraiserStatus = (fundraiserStatus) => {
    return createMockEnum(fundraiserStatus);
};
exports.createMockFundraiserStatus = createMockFundraiserStatus;
/**
 * @hidden
 */
const createMockFundraiser = (fundraiser) => {
    const data = fundraiser || {
        creator: exports.createMockIdentityId(),
        offering_portfolio: exports.createMockPortfolioId(),
        offering_asset: exports.createMockTicker(),
        raising_portfolio: exports.createMockPortfolioId(),
        raising_asset: exports.createMockTicker(),
        tiers: [],
        venue_id: exports.createMockU64(),
        start: exports.createMockMoment(),
        end: exports.createMockOption(),
        status: exports.createMockFundraiserStatus(),
        minimum_investment: exports.createMockBalance(),
    };
    return createMockCodec(Object.assign({}, data), !fundraiser);
};
exports.createMockFundraiser = createMockFundraiser;
/**
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockPriceTier = (priceTier) => {
    const data = priceTier || {
        total: exports.createMockBalance(),
        price: exports.createMockBalance(),
    };
    return createMockCodec(Object.assign({}, data), !priceTier);
};
exports.createMockPriceTier = createMockPriceTier;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockCalendarUnit = (calendarUnit) => {
    if (isCodec(calendarUnit)) {
        return calendarUnit;
    }
    return createMockEnum(calendarUnit);
};
exports.createMockCalendarUnit = createMockCalendarUnit;
/**
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockCalendarPeriod = (calendarPeriod) => {
    const { unit, amount } = calendarPeriod || {
        unit: exports.createMockCalendarUnit(),
        amount: exports.createMockU64(),
    };
    return createMockCodec({
        unit: exports.createMockCalendarUnit(unit),
        amount: exports.createMockU64(amount),
    }, !calendarPeriod);
};
exports.createMockCalendarPeriod = createMockCalendarPeriod;
/**
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockCheckpointSchedule = (checkpointSchedule) => {
    const { start, period } = checkpointSchedule || {
        start: exports.createMockMoment(),
        period: exports.createMockCalendarPeriod(),
    };
    return createMockCodec({
        start: exports.createMockMoment(start),
        period: exports.createMockCalendarPeriod(period),
    }, !checkpointSchedule);
};
exports.createMockCheckpointSchedule = createMockCheckpointSchedule;
/**
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockStoredSchedule = (storedSchedule) => {
    const { schedule, id, at, remaining } = storedSchedule || {
        schedule: exports.createMockCheckpointSchedule(),
        id: exports.createMockU64(),
        at: exports.createMockMoment(),
        remaining: exports.createMockU32(),
    };
    return createMockCodec({
        schedule: exports.createMockCheckpointSchedule(schedule),
        id: exports.createMockU64(id),
        at: exports.createMockMoment(at),
        remaining: exports.createMockU32(remaining),
    }, !storedSchedule);
};
exports.createMockStoredSchedule = createMockStoredSchedule;
/**
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockScheduleSpec = (scheduleSpec) => {
    const { start, period, remaining } = scheduleSpec || {
        start: exports.createMockOption(),
        period: exports.createMockCalendarPeriod(),
        remaining: exports.createMockU32(),
    };
    return createMockCodec({
        start: exports.createMockOption(start),
        period: exports.createMockCalendarPeriod(period),
        remaining: exports.createMockU32(remaining),
    }, !scheduleSpec);
};
exports.createMockScheduleSpec = createMockScheduleSpec;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockScalar = (scalar) => {
    if (!scalar || typeof scalar === 'string') {
        return createMockStringCodec(scalar);
    }
    else {
        return scalar;
    }
};
exports.createMockScalar = createMockScalar;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockRecordDateSpec = (recordDateSpec) => {
    if (isCodec(recordDateSpec)) {
        return recordDateSpec;
    }
    return createMockEnum(recordDateSpec);
};
exports.createMockRecordDateSpec = createMockRecordDateSpec;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockRistrettoPoint = (ristrettoPoint) => {
    if (!ristrettoPoint || typeof ristrettoPoint === 'string') {
        return createMockStringCodec(ristrettoPoint);
    }
    else {
        return ristrettoPoint;
    }
};
exports.createMockRistrettoPoint = createMockRistrettoPoint;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockCACheckpoint = (caCheckpoint) => {
    if (isCodec(caCheckpoint)) {
        return caCheckpoint;
    }
    return createMockEnum(caCheckpoint);
};
exports.createMockCACheckpoint = createMockCACheckpoint;
/**
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockRecordDate = (recordDate) => {
    const { date, checkpoint } = recordDate || {
        date: exports.createMockMoment(),
        checkpoint: exports.createMockCACheckpoint(),
    };
    return createMockCodec({
        date: exports.createMockMoment(date),
        checkpoint: exports.createMockCACheckpoint(checkpoint),
    }, !recordDate);
};
exports.createMockRecordDate = createMockRecordDate;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockSignature = (signature) => {
    if (!signature || typeof signature === 'string') {
        return createMockStringCodec(signature);
    }
    else {
        return signature;
    }
};
exports.createMockSignature = createMockSignature;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockZkProofData = (zkProofData) => {
    const { challenge_responses, subtract_expressions_res, blinded_scope_did_hash } = zkProofData || {
        challenge_responses: [exports.createMockScalar(), exports.createMockScalar()],
        subtract_expressions_res: exports.createMockRistrettoPoint(),
        blinded_scope_did_hash: exports.createMockRistrettoPoint(),
    };
    return createMockCodec({
        challenge_responses: [
            exports.createMockScalar(challenge_responses[0]),
            exports.createMockScalar(challenge_responses[1]),
        ],
        subtract_expressions_res: exports.createMockRistrettoPoint(subtract_expressions_res),
        blinded_scope_did_hash: exports.createMockRistrettoPoint(blinded_scope_did_hash),
    }, !zkProofData);
};
exports.createMockZkProofData = createMockZkProofData;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockTargetTreatment = (targetTreatment) => {
    if (isCodec(targetTreatment)) {
        return targetTreatment;
    }
    return createMockEnum(targetTreatment);
};
exports.createMockTargetTreatment = createMockTargetTreatment;
/**
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockTargetIdentities = (targetIdentities) => {
    const { identities, treatment } = targetIdentities || {
        identities: [],
        treatment: exports.createMockTargetTreatment(),
    };
    return createMockCodec({
        identities: lodash_1.map(identities, identityId => exports.createMockIdentityId(identityId)),
        treatment: exports.createMockTargetTreatment(treatment),
    }, !targetIdentities);
};
exports.createMockTargetIdentities = createMockTargetIdentities;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockScopeClaimProof = (scopeClaimProof) => {
    const { proof_scope_id_wellformed, proof_scope_id_cdd_id_match, scope_id } = scopeClaimProof || {
        proof_scope_id_wellformed: exports.createMockSignature(),
        proof_scope_id_cdd_id_match: exports.createMockZkProofData(),
        scope_id: exports.createMockRistrettoPoint(),
    };
    return createMockCodec({
        proof_scope_id_wellformed: exports.createMockSignature(proof_scope_id_wellformed),
        proof_scope_id_cdd_id_match: exports.createMockZkProofData(proof_scope_id_cdd_id_match),
        scope_id: exports.createMockRistrettoPoint(scope_id),
    }, !scopeClaimProof);
};
exports.createMockScopeClaimProof = createMockScopeClaimProof;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockCAKind = (caKind) => {
    if (isCodec(caKind)) {
        return caKind;
    }
    return createMockEnum(caKind);
};
exports.createMockCAKind = createMockCAKind;
/**
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockCorporateAction = (corporateAction) => {
    const { kind, decl_date, record_date, targets, default_withholding_tax, withholding_tax } = corporateAction || {
        kind: exports.createMockCAKind(),
        decl_date: exports.createMockMoment(),
        record_date: exports.createMockOption(),
        targets: exports.createMockTargetIdentities(),
        default_withholding_tax: exports.createMockPermill(),
        withholding_tax: [],
    };
    return createMockCodec({
        kind: exports.createMockCAKind(kind),
        decl_date: exports.createMockMoment(decl_date),
        record_date: exports.createMockOption(record_date),
        targets: exports.createMockTargetIdentities(targets),
        default_withholding_tax: exports.createMockPermill(default_withholding_tax),
        withholding_tax: withholding_tax.map(([identityId, tax]) => utils_1.tuple(exports.createMockIdentityId(identityId), exports.createMockPermill(tax))),
    }, !corporateAction);
};
exports.createMockCorporateAction = createMockCorporateAction;
/**
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockCAId = (caId) => {
    const { ticker, local_id } = caId || {
        ticker: exports.createMockTicker(),
        local_id: exports.createMockU64(),
    };
    return createMockCodec({
        ticker: exports.createMockTicker(ticker),
        local_id: exports.createMockU64(local_id),
    }, !caId);
};
exports.createMockCAId = createMockCAId;
/**
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockDistribution = (distribution) => {
    const { from, currency, per_share, amount, remaining, reclaimed, payment_at, expires_at } = distribution || {
        from: exports.createMockPortfolioId(),
        currency: exports.createMockTicker(),
        per_share: exports.createMockBalance(),
        amount: exports.createMockBalance(),
        remaining: exports.createMockBalance(),
        reclaimed: exports.createMockBool(),
        payment_at: exports.createMockMoment(),
        expires_at: exports.createMockOption(),
    };
    return createMockCodec({
        from: exports.createMockPortfolioId(from),
        currency: exports.createMockTicker(currency),
        per_share: exports.createMockBalance(per_share),
        amount: exports.createMockBalance(amount),
        remaining: exports.createMockBalance(remaining),
        reclaimed: exports.createMockBool(reclaimed),
        payment_at: exports.createMockMoment(payment_at),
        expires_at: exports.createMockOption(expires_at),
    }, !distribution);
};
exports.createMockDistribution = createMockDistribution;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockTransferManagerResult = (transferManagerResult) => {
    const { tm, result } = transferManagerResult || {
        tm: exports.createMockTransferManager(),
        result: exports.createMockBool(),
    };
    return createMockCodec({
        tm: exports.createMockTransferManager(tm),
        result: exports.createMockBool(result),
    }, !transferManagerResult);
};
exports.createMockTransferManagerResult = createMockTransferManagerResult;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockPortfolioValidityResult = (portfolioValidityResult) => {
    const { receiver_is_same_portfolio, sender_portfolio_does_not_exist, receiver_portfolio_does_not_exist, sender_insufficient_balance, result, } = portfolioValidityResult || {
        receiver_is_same_portfolio: exports.createMockBool(),
        sender_portfolio_does_not_exist: exports.createMockBool(),
        receiver_portfolio_does_not_exist: exports.createMockBool(),
        sender_insufficient_balance: exports.createMockBool(),
        result: exports.createMockBool(),
    };
    return createMockCodec({
        receiver_is_same_portfolio: exports.createMockBool(receiver_is_same_portfolio),
        sender_portfolio_does_not_exist: exports.createMockBool(sender_portfolio_does_not_exist),
        receiver_portfolio_does_not_exist: exports.createMockBool(receiver_portfolio_does_not_exist),
        sender_insufficient_balance: exports.createMockBool(sender_insufficient_balance),
        result: exports.createMockBool(result),
    }, !portfolioValidityResult);
};
exports.createMockPortfolioValidityResult = createMockPortfolioValidityResult;
/**
 * @hidden
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockGranularCanTransferResult = (granularCanTransferResult) => {
    const { invalid_granularity, self_transfer, invalid_receiver_cdd, invalid_sender_cdd, missing_scope_claim, receiver_custodian_error, sender_custodian_error, sender_insufficient_balance, portfolio_validity_result, asset_frozen, statistics_result, compliance_result, result, } = granularCanTransferResult || {
        invalid_granularity: exports.createMockBool(),
        self_transfer: exports.createMockBool(),
        invalid_receiver_cdd: exports.createMockBool(),
        invalid_sender_cdd: exports.createMockBool(),
        missing_scope_claim: exports.createMockBool(),
        receiver_custodian_error: exports.createMockBool(),
        sender_custodian_error: exports.createMockBool(),
        sender_insufficient_balance: exports.createMockBool(),
        portfolio_validity_result: exports.createMockPortfolioValidityResult(),
        asset_frozen: exports.createMockBool(),
        statistics_result: [],
        compliance_result: exports.createMockAssetComplianceResult(),
        result: exports.createMockBool(),
    };
    return createMockCodec({
        invalid_granularity: exports.createMockBool(invalid_granularity),
        self_transfer: exports.createMockBool(self_transfer),
        invalid_receiver_cdd: exports.createMockBool(invalid_receiver_cdd),
        invalid_sender_cdd: exports.createMockBool(invalid_sender_cdd),
        missing_scope_claim: exports.createMockBool(missing_scope_claim),
        receiver_custodian_error: exports.createMockBool(receiver_custodian_error),
        sender_custodian_error: exports.createMockBool(sender_custodian_error),
        sender_insufficient_balance: exports.createMockBool(sender_insufficient_balance),
        portfolio_validity_result: exports.createMockPortfolioValidityResult(portfolio_validity_result),
        asset_frozen: exports.createMockBool(asset_frozen),
        statistics_result: statistics_result.map(res => exports.createMockTransferManagerResult(res)),
        compliance_result: exports.createMockAssetComplianceResult(compliance_result),
        result: exports.createMockBool(result),
    }, !granularCanTransferResult);
};
exports.createMockGranularCanTransferResult = createMockGranularCanTransferResult;
/**
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockClassicTickerRegistration = (registration) => {
    const { eth_owner, is_created } = registration || {
        eth_owner: exports.createMockEthereumAddress(),
        is_created: exports.createMockBool(),
    };
    return createMockCodec({
        eth_owner: exports.createMockEthereumAddress(eth_owner),
        is_created: exports.createMockBool(is_created),
    }, !registration);
};
exports.createMockClassicTickerRegistration = createMockClassicTickerRegistration;
/**
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockSignedBlock = (signedBlock) => {
    const { block } = signedBlock || {
        block: exports.createMockBlock(),
    };
    return createMockCodec({
        block: exports.createMockBlock(block),
    }, !signedBlock);
};
exports.createMockSignedBlock = createMockSignedBlock;
/**
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockBlock = (block) => {
    const { header } = block || {
        header: exports.createMockHeader(),
    };
    return createMockCodec({
        header: exports.createMockHeader(header),
    }, !block);
};
exports.createMockBlock = createMockBlock;
/**
 * NOTE: `isEmpty` will be set to true if no value is passed
 */
const createMockHeader = (header) => {
    const { parentHash, number, stateRoot, extrinsicsRoot } = header || {
        parentHash: exports.createMockHash(),
        number: exports.createMockCompact(),
        stateRoot: exports.createMockHash(),
        extrinsicsRoot: exports.createMockHash(),
    };
    return createMockCodec({
        parentHash: exports.createMockHash(parentHash),
        number: exports.createMockCompact(number.unwrap()),
        stateRoot: exports.createMockHash(stateRoot),
        extrinsicsRoot: exports.createMockHash(extrinsicsRoot),
    }, !header);
};
exports.createMockHeader = createMockHeader;
//# sourceMappingURL=dataSources.js.map