"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const sinon_1 = __importDefault(require("sinon"));
const internal_1 = require("../../../../internal");
const queries_1 = require("../../../../middleware/queries");
const types_1 = require("../../../../middleware/types");
const mocks_1 = require("../../../../testUtils/mocks");
const types_2 = require("../../../../types");
const internal_2 = require("../../../../types/internal");
const utils_1 = require("../../../../types/utils");
const utilsConversionModule = __importStar(require("../../../../utils/conversion"));
const utilsInternalModule = __importStar(require("../../../../utils/internal"));
jest.mock('~/api/entities/Identity', require("../../../../testUtils/mocks/entities").mockIdentityModule('~/api/entities/Identity'));
jest.mock('~/api/entities/Asset', require("../../../../testUtils/mocks/entities").mockAssetModule('~/api/entities/Asset'));
jest.mock('~/api/entities/Venue', require("../../../../testUtils/mocks/entities").mockVenueModule('~/api/entities/Venue'));
jest.mock('~/base/Procedure', require("../../../../testUtils/mocks/procedure").mockProcedureModule('~/base/Procedure'));
describe('Instruction class', () => {
    let context;
    let instruction;
    let id;
    let rawId;
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks();
        mocks_1.entityMockUtils.initMocks();
        mocks_1.procedureMockUtils.initMocks();
        id = new bignumber_js_1.default(1);
        rawId = mocks_1.dsMockUtils.createMockU64(id);
    });
    beforeEach(() => {
        context = mocks_1.dsMockUtils.getContextInstance();
        instruction = new internal_1.Instruction({ id }, context);
    });
    afterEach(() => {
        mocks_1.dsMockUtils.reset();
        mocks_1.entityMockUtils.reset();
        mocks_1.procedureMockUtils.reset();
    });
    afterAll(() => {
        mocks_1.dsMockUtils.cleanup();
        mocks_1.procedureMockUtils.cleanup();
    });
    test('should extend Entity', () => {
        expect(internal_1.Instruction.prototype instanceof internal_1.Entity).toBe(true);
    });
    describe('method: isUniqueIdentifiers', () => {
        test('should return true if the object conforms to the interface', () => {
            expect(internal_1.Instruction.isUniqueIdentifiers({ id: new bignumber_js_1.default(1) })).toBe(true);
            expect(internal_1.Instruction.isUniqueIdentifiers({})).toBe(false);
            expect(internal_1.Instruction.isUniqueIdentifiers({ id: 3 })).toBe(false);
        });
    });
    describe('method: isExecuted', () => {
        afterAll(() => {
            sinon_1.default.restore();
        });
        let bigNumberToU64Stub;
        let instructionCounterStub;
        beforeAll(() => {
            bigNumberToU64Stub = sinon_1.default.stub(utilsConversionModule, 'bigNumberToU64');
        });
        beforeEach(() => {
            instructionCounterStub = mocks_1.dsMockUtils.createQueryStub('settlement', 'instructionCounter', {
                returnValue: mocks_1.dsMockUtils.createMockU64(new bignumber_js_1.default(1000)),
            });
            bigNumberToU64Stub.withArgs(id, context).returns(rawId);
        });
        test('should return whether the instruction is executed', () => __awaiter(void 0, void 0, void 0, function* () {
            const status = internal_2.InstructionStatus.Unknown;
            const createdAt = new Date('10/14/1987');
            const tradeDate = new Date('11/17/1987');
            const valueDate = new Date('11/17/1987');
            const venueId = new bignumber_js_1.default(1);
            const type = types_2.InstructionType.SettleOnAffirmation;
            const owner = 'someDid';
            mocks_1.entityMockUtils.configureMocks({ identityOptions: { did: owner } });
            const queryResult = mocks_1.dsMockUtils.createMockInstruction({
                /* eslint-disable @typescript-eslint/naming-convention */
                instruction_id: mocks_1.dsMockUtils.createMockU64(new bignumber_js_1.default(1)),
                status: mocks_1.dsMockUtils.createMockInstructionStatus(status),
                venue_id: mocks_1.dsMockUtils.createMockU64(venueId),
                created_at: mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockMoment(new bignumber_js_1.default(createdAt.getTime()))),
                trade_date: mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockMoment(new bignumber_js_1.default(tradeDate.getTime()))),
                value_date: mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockMoment(new bignumber_js_1.default(valueDate.getTime()))),
                settlement_type: mocks_1.dsMockUtils.createMockSettlementType(type),
                /* eslint-enable @typescript-eslint/naming-convention */
            });
            const instructionDetailsStub = mocks_1.dsMockUtils
                .createQueryStub('settlement', 'instructionDetails')
                .withArgs(rawId)
                .resolves(queryResult);
            let result = yield instruction.isExecuted();
            expect(result).toBe(true);
            instructionCounterStub.resolves(mocks_1.dsMockUtils.createMockU64(new bignumber_js_1.default(0)));
            result = yield instruction.isExecuted();
            expect(result).toBe(false);
            instructionDetailsStub.resolves(mocks_1.dsMockUtils.createMockInstruction(Object.assign(Object.assign({}, queryResult), { status: mocks_1.dsMockUtils.createMockInstructionStatus('Unknown') })));
            result = yield instruction.isExecuted();
            expect(result).toBe(false);
        }));
    });
    describe('method: isPending', () => {
        afterAll(() => {
            sinon_1.default.restore();
        });
        let bigNumberToU64Stub;
        beforeAll(() => {
            bigNumberToU64Stub = sinon_1.default.stub(utilsConversionModule, 'bigNumberToU64');
        });
        beforeEach(() => {
            bigNumberToU64Stub.withArgs(id, context).returns(rawId);
        });
        test('should return whether the instruction is pending', () => __awaiter(void 0, void 0, void 0, function* () {
            const status = types_2.InstructionStatus.Pending;
            const createdAt = new Date('10/14/1987');
            const tradeDate = new Date('11/17/1987');
            const valueDate = new Date('11/17/1987');
            const venueId = new bignumber_js_1.default(1);
            const type = types_2.InstructionType.SettleOnAffirmation;
            const owner = 'someDid';
            mocks_1.entityMockUtils.configureMocks({ identityOptions: { did: owner } });
            const queryResult = mocks_1.dsMockUtils.createMockInstruction({
                /* eslint-disable @typescript-eslint/naming-convention */
                instruction_id: mocks_1.dsMockUtils.createMockU64(new bignumber_js_1.default(1)),
                status: mocks_1.dsMockUtils.createMockInstructionStatus(status),
                venue_id: mocks_1.dsMockUtils.createMockU64(venueId),
                created_at: mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockMoment(new bignumber_js_1.default(createdAt.getTime()))),
                trade_date: mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockMoment(new bignumber_js_1.default(tradeDate.getTime()))),
                value_date: mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockMoment(new bignumber_js_1.default(valueDate.getTime()))),
                settlement_type: mocks_1.dsMockUtils.createMockSettlementType(type),
                /* eslint-enable @typescript-eslint/naming-convention */
            });
            const instructionDetailsStub = mocks_1.dsMockUtils
                .createQueryStub('settlement', 'instructionDetails')
                .withArgs(rawId)
                .resolves(queryResult);
            let result = yield instruction.isPending();
            expect(result).toBe(true);
            instructionDetailsStub.resolves(mocks_1.dsMockUtils.createMockInstruction(Object.assign(Object.assign({}, queryResult), { status: mocks_1.dsMockUtils.createMockInstructionStatus('Unknown') })));
            result = yield instruction.isPending();
            expect(result).toBe(false);
        }));
    });
    describe('method: exists', () => {
        afterAll(() => {
            sinon_1.default.restore();
        });
        let bigNumberToU64Stub;
        beforeAll(() => {
            bigNumberToU64Stub = sinon_1.default.stub(utilsConversionModule, 'bigNumberToU64');
        });
        beforeEach(() => {
            bigNumberToU64Stub.withArgs(id, context).returns(rawId);
        });
        test('should return whether the instruction exists', () => __awaiter(void 0, void 0, void 0, function* () {
            const owner = 'someDid';
            mocks_1.entityMockUtils.configureMocks({ identityOptions: { did: owner } });
            const instructionCounterStub = mocks_1.dsMockUtils
                .createQueryStub('settlement', 'instructionCounter')
                .resolves(mocks_1.dsMockUtils.createMockU64(new bignumber_js_1.default(10)));
            let result = yield instruction.exists();
            expect(result).toBe(true);
            instructionCounterStub.resolves(mocks_1.dsMockUtils.createMockU64(new bignumber_js_1.default(0)));
            result = yield instruction.exists();
            expect(result).toBe(false);
        }));
    });
    describe('method: details', () => {
        afterAll(() => {
            sinon_1.default.restore();
        });
        let bigNumberToU64Stub;
        beforeAll(() => {
            bigNumberToU64Stub = sinon_1.default.stub(utilsConversionModule, 'bigNumberToU64');
        });
        beforeEach(() => {
            bigNumberToU64Stub.withArgs(id, context).returns(rawId);
        });
        test('should return the Instruction details', () => __awaiter(void 0, void 0, void 0, function* () {
            let status = types_2.InstructionStatus.Pending;
            const createdAt = new Date('10/14/1987');
            const tradeDate = new Date('11/17/1987');
            const valueDate = new Date('11/17/1987');
            const venueId = new bignumber_js_1.default(1);
            let type = types_2.InstructionType.SettleOnAffirmation;
            const owner = 'someDid';
            mocks_1.entityMockUtils.configureMocks({ identityOptions: { did: owner } });
            const queryResult = mocks_1.dsMockUtils.createMockInstruction({
                /* eslint-disable @typescript-eslint/naming-convention */
                instruction_id: mocks_1.dsMockUtils.createMockU64(new bignumber_js_1.default(1)),
                status: mocks_1.dsMockUtils.createMockInstructionStatus(status),
                venue_id: mocks_1.dsMockUtils.createMockU64(venueId),
                created_at: mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockMoment(new bignumber_js_1.default(createdAt.getTime()))),
                trade_date: mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockMoment(new bignumber_js_1.default(tradeDate.getTime()))),
                value_date: mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockMoment(new bignumber_js_1.default(valueDate.getTime()))),
                settlement_type: mocks_1.dsMockUtils.createMockSettlementType(type),
                /* eslint-enable @typescript-eslint/naming-convention */
            });
            const instructionDetailsStub = mocks_1.dsMockUtils
                .createQueryStub('settlement', 'instructionDetails')
                // .withArgs(rawId)
                .resolves(queryResult);
            let result = yield instruction.details();
            expect(result).toMatchObject({
                status,
                createdAt,
                tradeDate,
                valueDate,
                type,
            });
            expect(result.venue.id).toEqual(venueId);
            type = types_2.InstructionType.SettleOnBlock;
            const endBlock = new bignumber_js_1.default(100);
            instructionDetailsStub.resolves(mocks_1.dsMockUtils.createMockInstruction(Object.assign(Object.assign({}, queryResult), { 
                /* eslint-disable @typescript-eslint/naming-convention */
                trade_date: mocks_1.dsMockUtils.createMockOption(), value_date: mocks_1.dsMockUtils.createMockOption(), settlement_type: mocks_1.dsMockUtils.createMockSettlementType({
                    SettleOnBlock: mocks_1.dsMockUtils.createMockU32(endBlock),
                }) })));
            result = yield instruction.details();
            expect(result).toMatchObject({
                status,
                createdAt,
                tradeDate: null,
                valueDate: null,
                type,
                endBlock,
            });
            expect(result.venue.id).toEqual(venueId);
            status = types_2.InstructionStatus.Failed;
            type = types_2.InstructionType.SettleOnAffirmation;
            instructionDetailsStub.resolves(mocks_1.dsMockUtils.createMockInstruction(Object.assign(Object.assign({}, queryResult), { status: mocks_1.dsMockUtils.createMockInstructionStatus(status) })));
            result = yield instruction.details();
            expect(result).toMatchObject({
                status,
                createdAt,
                tradeDate,
                valueDate,
                type,
            });
            expect(result.venue.id).toEqual(venueId);
        }));
        test('should throw an error if the Instruction is not pending', () => {
            mocks_1.dsMockUtils
                .createQueryStub('settlement', 'instructionDetails')
                .withArgs(rawId)
                .resolves(mocks_1.dsMockUtils.createMockInstruction({
                /* eslint-disable @typescript-eslint/naming-convention */
                instruction_id: mocks_1.dsMockUtils.createMockU64(new bignumber_js_1.default(1)),
                status: mocks_1.dsMockUtils.createMockInstructionStatus('Unknown'),
                venue_id: mocks_1.dsMockUtils.createMockU64(new bignumber_js_1.default(1)),
                created_at: mocks_1.dsMockUtils.createMockOption(),
                trade_date: mocks_1.dsMockUtils.createMockOption(),
                value_date: mocks_1.dsMockUtils.createMockOption(),
                settlement_type: mocks_1.dsMockUtils.createMockSettlementType(),
                /* eslint-enable @typescript-eslint/naming-convention */
            }));
            return expect(instruction.details()).rejects.toThrow('Instruction has already been executed/rejected and it was purged from chain');
        });
    });
    describe('method: getAffirmations', () => {
        const did = 'someDid';
        const status = types_2.AffirmationStatus.Affirmed;
        let rawStorageKey;
        let instructionDetailsStub;
        afterAll(() => {
            sinon_1.default.restore();
        });
        beforeAll(() => {
            rawStorageKey = [
                utils_1.tuple(mocks_1.dsMockUtils.createMockU64(), mocks_1.dsMockUtils.createMockPortfolioId({
                    did: mocks_1.dsMockUtils.createMockIdentityId(did),
                    kind: mocks_1.dsMockUtils.createMockPortfolioKind('Default'),
                })),
            ];
            const authsReceivedEntries = rawStorageKey.map(([instructionId, portfolioId]) => utils_1.tuple({
                args: [instructionId, portfolioId],
            }, mocks_1.dsMockUtils.createMockAffirmationStatus(types_2.AffirmationStatus.Affirmed)));
            sinon_1.default
                .stub(utilsInternalModule, 'requestPaginated')
                .resolves({ entries: authsReceivedEntries, lastKey: null });
            sinon_1.default.stub(utilsConversionModule, 'identityIdToString').returns(did);
            sinon_1.default.stub(utilsConversionModule, 'meshAffirmationStatusToAffirmationStatus').returns(status);
        });
        beforeEach(() => {
            mocks_1.dsMockUtils.createQueryStub('settlement', 'instructionCounter', {
                returnValue: mocks_1.dsMockUtils.createMockU64(new bignumber_js_1.default(1000)),
            });
            instructionDetailsStub = mocks_1.dsMockUtils.createQueryStub('settlement', 'instructionDetails', {
                returnValue: mocks_1.dsMockUtils.createMockInstruction({
                    /* eslint-disable @typescript-eslint/naming-convention */
                    instruction_id: mocks_1.dsMockUtils.createMockU64(new bignumber_js_1.default(1)),
                    venue_id: mocks_1.dsMockUtils.createMockU64(new bignumber_js_1.default(1)),
                    status: mocks_1.dsMockUtils.createMockInstructionStatus('Pending'),
                    settlement_type: mocks_1.dsMockUtils.createMockSettlementType('SettleOnAffirmation'),
                    created_at: mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockMoment(new bignumber_js_1.default(new Date('10/14/1987').getTime()))),
                    trade_date: mocks_1.dsMockUtils.createMockOption(),
                    value_date: mocks_1.dsMockUtils.createMockOption(),
                    /* eslint-enable @typescript-eslint/naming-convention */
                }),
            });
            mocks_1.dsMockUtils.createQueryStub('settlement', 'affirmsReceived');
        });
        test('should throw an error if the instruction is not pending', () => {
            instructionDetailsStub.resolves(mocks_1.dsMockUtils.createMockInstruction({
                /* eslint-disable @typescript-eslint/naming-convention */
                instruction_id: mocks_1.dsMockUtils.createMockU64(new bignumber_js_1.default(1)),
                venue_id: mocks_1.dsMockUtils.createMockU64(),
                status: mocks_1.dsMockUtils.createMockInstructionStatus('Unknown'),
                settlement_type: mocks_1.dsMockUtils.createMockSettlementType(),
                created_at: mocks_1.dsMockUtils.createMockOption(),
                trade_date: mocks_1.dsMockUtils.createMockOption(),
                value_date: mocks_1.dsMockUtils.createMockOption(),
                /* eslint-enable @typescript-eslint/naming-convention */
            }));
            return expect(instruction.getAffirmations()).rejects.toThrow('Instruction has already been executed/rejected and it was purged from chain');
        });
        test('should return a list of Affirmation Statuses', () => __awaiter(void 0, void 0, void 0, function* () {
            const { data } = yield instruction.getAffirmations();
            expect(data).toHaveLength(1);
            expect(data[0].identity.did).toEqual(did);
            expect(data[0].status).toEqual(status);
        }));
    });
    describe('method: getLegs', () => {
        let instructionDetailsStub;
        afterAll(() => {
            sinon_1.default.restore();
        });
        let bigNumberToU64Stub;
        beforeAll(() => {
            bigNumberToU64Stub = sinon_1.default.stub(utilsConversionModule, 'bigNumberToU64');
        });
        beforeEach(() => {
            mocks_1.dsMockUtils.createQueryStub('settlement', 'instructionCounter', {
                returnValue: mocks_1.dsMockUtils.createMockU64(new bignumber_js_1.default(1000)),
            });
            bigNumberToU64Stub.withArgs(id, context).returns(rawId);
            mocks_1.dsMockUtils.createQueryStub('settlement', 'instructionLegs');
            instructionDetailsStub = mocks_1.dsMockUtils.createQueryStub('settlement', 'instructionDetails', {
                returnValue: mocks_1.dsMockUtils.createMockInstruction({
                    /* eslint-disable @typescript-eslint/naming-convention */
                    instruction_id: mocks_1.dsMockUtils.createMockU64(new bignumber_js_1.default(1)),
                    venue_id: mocks_1.dsMockUtils.createMockU64(new bignumber_js_1.default(1)),
                    status: mocks_1.dsMockUtils.createMockInstructionStatus('Pending'),
                    settlement_type: mocks_1.dsMockUtils.createMockSettlementType('SettleOnAffirmation'),
                    created_at: mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockMoment(new bignumber_js_1.default(new Date('10/14/1987').getTime()))),
                    trade_date: mocks_1.dsMockUtils.createMockOption(),
                    value_date: mocks_1.dsMockUtils.createMockOption(),
                    /* eslint-enable @typescript-eslint/naming-convention */
                }),
            });
        });
        test("should return the instruction's legs", () => __awaiter(void 0, void 0, void 0, function* () {
            const fromDid = 'fromDid';
            const toDid = 'toDid';
            const ticker = 'SOME_TICKER';
            const amount = new bignumber_js_1.default(1000);
            mocks_1.entityMockUtils.configureMocks({ assetOptions: { ticker } });
            const entries = [
                utils_1.tuple(['instructionId', 'legId'], {
                    from: mocks_1.dsMockUtils.createMockPortfolioId({
                        did: mocks_1.dsMockUtils.createMockIdentityId(fromDid),
                        kind: mocks_1.dsMockUtils.createMockPortfolioKind('Default'),
                    }),
                    to: mocks_1.dsMockUtils.createMockPortfolioId({
                        did: mocks_1.dsMockUtils.createMockIdentityId(toDid),
                        kind: mocks_1.dsMockUtils.createMockPortfolioKind('Default'),
                    }),
                    asset: mocks_1.dsMockUtils.createMockTicker(ticker),
                    amount: mocks_1.dsMockUtils.createMockBalance(amount.shiftedBy(6)),
                }),
            ];
            sinon_1.default.stub(utilsInternalModule, 'requestPaginated').resolves({ entries, lastKey: null });
            const { data: leg } = yield instruction.getLegs();
            expect(leg[0].amount).toEqual(amount);
            expect(leg[0].asset.ticker).toBe(ticker);
            expect(leg[0].from.owner.did).toBe(fromDid);
            expect(leg[0].to.owner.did).toBe(toDid);
        }));
        test('should throw an error if the instruction is not pending', () => {
            instructionDetailsStub.resolves(mocks_1.dsMockUtils.createMockInstruction({
                /* eslint-disable @typescript-eslint/naming-convention */
                instruction_id: mocks_1.dsMockUtils.createMockU64(new bignumber_js_1.default(1)),
                venue_id: mocks_1.dsMockUtils.createMockU64(),
                status: mocks_1.dsMockUtils.createMockInstructionStatus('Unknown'),
                settlement_type: mocks_1.dsMockUtils.createMockSettlementType(),
                created_at: mocks_1.dsMockUtils.createMockOption(),
                trade_date: mocks_1.dsMockUtils.createMockOption(),
                value_date: mocks_1.dsMockUtils.createMockOption(),
                /* eslint-enable @typescript-eslint/naming-convention */
            }));
            return expect(instruction.getLegs()).rejects.toThrow('Instruction has already been executed/rejected and it was purged from chain');
        });
    });
    describe('method: reject', () => {
        afterAll(() => {
            sinon_1.default.restore();
        });
        test('should prepare the procedure and return the resulting transaction queue', () => __awaiter(void 0, void 0, void 0, function* () {
            const expectedQueue = 'someQueue';
            mocks_1.procedureMockUtils
                .getPrepareStub()
                .withArgs({
                args: { id, operation: internal_2.InstructionAffirmationOperation.Reject },
                transformer: undefined,
            }, context)
                .resolves(expectedQueue);
            const queue = yield instruction.reject();
            expect(queue).toBe(expectedQueue);
        }));
    });
    describe('method: affirm', () => {
        afterAll(() => {
            sinon_1.default.restore();
        });
        test('should prepare the procedure and return the resulting transaction queue', () => __awaiter(void 0, void 0, void 0, function* () {
            const expectedQueue = 'someQueue';
            mocks_1.procedureMockUtils
                .getPrepareStub()
                .withArgs({
                args: { id, operation: internal_2.InstructionAffirmationOperation.Affirm },
                transformer: undefined,
            }, context)
                .resolves(expectedQueue);
            const queue = yield instruction.affirm();
            expect(queue).toBe(expectedQueue);
        }));
    });
    describe('method: withdraw', () => {
        afterAll(() => {
            sinon_1.default.restore();
        });
        test('should prepare the procedure and return the resulting transaction queue', () => __awaiter(void 0, void 0, void 0, function* () {
            const expectedQueue = 'someQueue';
            mocks_1.procedureMockUtils
                .getPrepareStub()
                .withArgs({
                args: { id, operation: internal_2.InstructionAffirmationOperation.Withdraw },
                transformer: undefined,
            }, context)
                .resolves(expectedQueue);
            const queue = yield instruction.withdraw();
            expect(queue).toBe(expectedQueue);
        }));
    });
    describe('method: reschedule', () => {
        afterAll(() => {
            sinon_1.default.restore();
        });
        test('should prepare the procedure and return the resulting transaction queue', () => __awaiter(void 0, void 0, void 0, function* () {
            const expectedQueue = 'someQueue';
            mocks_1.procedureMockUtils
                .getPrepareStub()
                .withArgs({
                args: { id },
                transformer: undefined,
            }, context)
                .resolves(expectedQueue);
            const queue = yield instruction.reschedule();
            expect(queue).toBe(expectedQueue);
        }));
    });
    describe('method: getStatus', () => {
        afterAll(() => {
            sinon_1.default.restore();
        });
        let bigNumberToU64Stub;
        beforeAll(() => {
            bigNumberToU64Stub = sinon_1.default.stub(utilsConversionModule, 'bigNumberToU64');
        });
        beforeEach(() => {
            bigNumberToU64Stub.withArgs(id, context).returns(rawId);
        });
        test('should return Pending Instruction status', () => __awaiter(void 0, void 0, void 0, function* () {
            const queryResult = mocks_1.dsMockUtils.createMockInstruction({
                /* eslint-disable @typescript-eslint/naming-convention */
                instruction_id: mocks_1.dsMockUtils.createMockU64(new bignumber_js_1.default(1)),
                status: mocks_1.dsMockUtils.createMockInstructionStatus(internal_2.InstructionStatus.Pending),
                venue_id: mocks_1.dsMockUtils.createMockU64(),
                created_at: mocks_1.dsMockUtils.createMockOption(),
                trade_date: mocks_1.dsMockUtils.createMockOption(),
                value_date: mocks_1.dsMockUtils.createMockOption(),
                settlement_type: mocks_1.dsMockUtils.createMockSettlementType(),
                /* eslint-enable @typescript-eslint/naming-convention */
            });
            mocks_1.dsMockUtils
                .createQueryStub('settlement', 'instructionDetails')
                .withArgs(rawId)
                .resolves(queryResult);
            const result = yield instruction.getStatus();
            expect(result).toMatchObject({
                status: types_2.InstructionStatus.Pending,
            });
        }));
        test('should return Executed Instruction status', () => __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 fakeQueryResult = {
                /* eslint-disable @typescript-eslint/naming-convention */
                block_id: blockNumber.toNumber(),
                block: { datetime: blockDate },
                event_idx: eventIdx.toNumber(),
                /* eslint-enable @typescript-eslint/naming-convention */
            };
            const fakeEventIdentifierResult = { blockNumber, blockDate, eventIndex: eventIdx };
            const queryVariables = {
                moduleId: types_1.ModuleIdEnum.Settlement,
                eventId: types_1.EventIdEnum.InstructionExecuted,
                eventArg1: id.toString(),
            };
            // Should return Pending status
            const queryResult = mocks_1.dsMockUtils.createMockInstruction({
                /* eslint-disable @typescript-eslint/naming-convention */
                instruction_id: mocks_1.dsMockUtils.createMockU64(new bignumber_js_1.default(1)),
                status: mocks_1.dsMockUtils.createMockInstructionStatus(internal_2.InstructionStatus.Unknown),
                venue_id: mocks_1.dsMockUtils.createMockU64(),
                created_at: mocks_1.dsMockUtils.createMockOption(),
                trade_date: mocks_1.dsMockUtils.createMockOption(),
                value_date: mocks_1.dsMockUtils.createMockOption(),
                settlement_type: mocks_1.dsMockUtils.createMockSettlementType(),
                /* eslint-enable @typescript-eslint/naming-convention */
            });
            mocks_1.dsMockUtils
                .createQueryStub('settlement', 'instructionDetails')
                .withArgs(rawId)
                .resolves(queryResult);
            mocks_1.dsMockUtils.createApolloQueryStub(queries_1.eventByIndexedArgs(queryVariables), {
                eventByIndexedArgs: fakeQueryResult,
            });
            const result = yield instruction.getStatus();
            expect(result).toMatchObject({
                status: types_2.InstructionStatus.Executed,
                eventIdentifier: fakeEventIdentifierResult,
            });
        }));
        test('should return Failed Instruction status', () => __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 fakeQueryResult = {
                /* eslint-disable @typescript-eslint/naming-convention */
                block_id: blockNumber.toNumber(),
                block: { datetime: blockDate },
                event_idx: eventIdx.toNumber(),
                /* eslint-enable @typescript-eslint/naming-convention */
            };
            const fakeEventIdentifierResult = { blockNumber, blockDate, eventIndex: eventIdx };
            const queryVariables = {
                moduleId: types_1.ModuleIdEnum.Settlement,
                eventId: types_1.EventIdEnum.InstructionExecuted,
                eventArg1: id.toString(),
            };
            // Should return Pending status
            const queryResult = mocks_1.dsMockUtils.createMockInstruction({
                /* eslint-disable @typescript-eslint/naming-convention */
                instruction_id: mocks_1.dsMockUtils.createMockU64(new bignumber_js_1.default(1)),
                status: mocks_1.dsMockUtils.createMockInstructionStatus(internal_2.InstructionStatus.Unknown),
                venue_id: mocks_1.dsMockUtils.createMockU64(),
                created_at: mocks_1.dsMockUtils.createMockOption(),
                trade_date: mocks_1.dsMockUtils.createMockOption(),
                value_date: mocks_1.dsMockUtils.createMockOption(),
                settlement_type: mocks_1.dsMockUtils.createMockSettlementType(),
                /* eslint-enable @typescript-eslint/naming-convention */
            });
            mocks_1.dsMockUtils
                .createQueryStub('settlement', 'instructionDetails')
                .withArgs(rawId)
                .resolves(queryResult);
            mocks_1.dsMockUtils.createApolloMultipleQueriesStub([
                {
                    query: queries_1.eventByIndexedArgs(queryVariables),
                    returnData: {
                        eventByIndexedArgs: null,
                    },
                },
                {
                    query: queries_1.eventByIndexedArgs(Object.assign(Object.assign({}, queryVariables), { eventId: types_1.EventIdEnum.InstructionFailed })),
                    returnData: {
                        eventByIndexedArgs: fakeQueryResult,
                    },
                },
            ]);
            const result = yield instruction.getStatus();
            expect(result).toMatchObject({
                status: types_2.InstructionStatus.Failed,
                eventIdentifier: fakeEventIdentifierResult,
            });
        }));
        test("should throw an error if Instruction status couldn't be determied", () => __awaiter(void 0, void 0, void 0, function* () {
            const queryVariables = {
                moduleId: types_1.ModuleIdEnum.Settlement,
                eventId: types_1.EventIdEnum.InstructionExecuted,
                eventArg1: id.toString(),
            };
            // Should return Pending status
            const queryResult = mocks_1.dsMockUtils.createMockInstruction({
                /* eslint-disable @typescript-eslint/naming-convention */
                instruction_id: mocks_1.dsMockUtils.createMockU64(new bignumber_js_1.default(1)),
                status: mocks_1.dsMockUtils.createMockInstructionStatus(internal_2.InstructionStatus.Unknown),
                venue_id: mocks_1.dsMockUtils.createMockU64(),
                created_at: mocks_1.dsMockUtils.createMockOption(),
                trade_date: mocks_1.dsMockUtils.createMockOption(),
                value_date: mocks_1.dsMockUtils.createMockOption(),
                settlement_type: mocks_1.dsMockUtils.createMockSettlementType(),
                /* eslint-enable @typescript-eslint/naming-convention */
            });
            mocks_1.dsMockUtils
                .createQueryStub('settlement', 'instructionDetails')
                .withArgs(rawId)
                .resolves(queryResult);
            mocks_1.dsMockUtils.createApolloMultipleQueriesStub([
                {
                    query: queries_1.eventByIndexedArgs(queryVariables),
                    returnData: {
                        eventByIndexedArgs: null,
                    },
                },
                {
                    query: queries_1.eventByIndexedArgs(Object.assign(Object.assign({}, queryVariables), { eventId: types_1.EventIdEnum.InstructionFailed })),
                    returnData: {
                        eventByIndexedArgs: null,
                    },
                },
            ]);
            return expect(instruction.getStatus()).rejects.toThrow("It isn't possible to determine the current status of this Instruction");
        }));
    });
    describe('method: toJson', () => {
        test('should return a human readable version of the entity', () => {
            expect(instruction.toJson()).toBe('1');
        });
    });
});
//# sourceMappingURL=index.js.map