"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const types_1 = require("../../../polkadot/types");
const sinon_1 = __importDefault(require("sinon"));
const consumeAuthorizationRequests_1 = require("../consumeAuthorizationRequests");
const internal_1 = require("../../../internal");
const mocks_1 = require("../../../testUtils/mocks");
const types_2 = require("../../../types");
const utilsConversionModule = __importStar(require("../../../utils/conversion"));
jest.mock('~/api/entities/SecurityToken', require("../../../testUtils/mocks/entities").mockSecurityTokenModule('~/api/entities/SecurityToken'));
jest.mock('~/api/entities/TickerReservation', require("../../../testUtils/mocks/entities").mockTickerReservationModule('~/api/entities/TickerReservation'));
describe('consumeAuthorizationRequests procedure', () => {
    let mockContext;
    let signerValueToSignatoryStub;
    let numberToU64Stub;
    let booleanToBoolStub;
    let authParams;
    let auths;
    let rawAuthIdentifiers;
    let rawAuthIds;
    let rawFalseBool;
    let acceptAssetOwnershipTransferTransaction;
    let acceptPayingKeyTransaction;
    let acceptPrimaryKeyTransaction;
    let acceptBecomeAgentTransaction;
    let acceptPortfolioCustodyTransaction;
    let acceptTickerTransferTransaction;
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks();
        mocks_1.procedureMockUtils.initMocks();
        mocks_1.entityMockUtils.initMocks();
        signerValueToSignatoryStub = sinon_1.default.stub(utilsConversionModule, 'signerValueToSignatory');
        numberToU64Stub = sinon_1.default.stub(utilsConversionModule, 'numberToU64');
        booleanToBoolStub = sinon_1.default.stub(utilsConversionModule, 'booleanToBool');
        sinon_1.default.stub(utilsConversionModule, 'addressToKey');
        mocks_1.dsMockUtils.createQueryStub('identity', 'authorizations', {
            returnValue: mocks_1.dsMockUtils.createMockOption(mocks_1.dsMockUtils.createMockAuthorization({
                /* eslint-disable @typescript-eslint/naming-convention */
                authorization_data: mocks_1.dsMockUtils.createMockAuthorizationData('RotatePrimaryKey'),
                auth_id: 1,
                authorized_by: 'someDid',
                expiry: mocks_1.dsMockUtils.createMockOption(),
                /* eslint-enable @typescript-eslint/naming-convention */
            })),
        });
    });
    let addBatchTransactionStub;
    beforeEach(() => {
        addBatchTransactionStub = mocks_1.procedureMockUtils.getAddBatchTransactionStub();
        mockContext = mocks_1.dsMockUtils.getContextInstance();
        rawFalseBool = mocks_1.dsMockUtils.createMockBool(false);
        authParams = [
            {
                authId: new bignumber_js_1.default(1),
                expiry: new Date('10/14/3040'),
                target: mocks_1.entityMockUtils.getIdentityInstance({ did: 'targetDid1' }),
                issuer: mocks_1.entityMockUtils.getIdentityInstance({ did: 'issuerDid1' }),
                data: {
                    type: types_2.AuthorizationType.TransferAssetOwnership,
                    value: 'SOME_TICKER1',
                },
            },
            {
                authId: new bignumber_js_1.default(2),
                expiry: null,
                target: mocks_1.entityMockUtils.getAccountInstance({ address: 'targetAddress2' }),
                issuer: mocks_1.entityMockUtils.getIdentityInstance({ did: 'issuerDid2' }),
                data: {
                    type: types_2.AuthorizationType.AddRelayerPayingKey,
                    value: {
                        beneficiary: mocks_1.entityMockUtils.getAccountInstance({ address: 'targetAddress2' }),
                        subsidizer: mocks_1.entityMockUtils.getAccountInstance({ address: 'payingKey' }),
                        allowance: new bignumber_js_1.default(1000),
                    },
                },
            },
            {
                authId: new bignumber_js_1.default(3),
                expiry: null,
                target: mocks_1.entityMockUtils.getAccountInstance({ address: 'targetAddress3' }),
                issuer: mocks_1.entityMockUtils.getIdentityInstance({ did: 'issuerDid3' }),
                data: {
                    type: types_2.AuthorizationType.RotatePrimaryKey,
                },
            },
            {
                authId: new bignumber_js_1.default(4),
                expiry: null,
                target: mocks_1.entityMockUtils.getIdentityInstance({ did: 'targetDid4' }),
                issuer: mocks_1.entityMockUtils.getIdentityInstance({ did: 'issuerDid4' }),
                data: {
                    type: types_2.AuthorizationType.BecomeAgent,
                    value: mocks_1.entityMockUtils.getKnownPermissionGroupInstance(),
                },
            },
            {
                authId: new bignumber_js_1.default(5),
                expiry: null,
                target: mocks_1.entityMockUtils.getIdentityInstance({ did: 'targetDid5' }),
                issuer: mocks_1.entityMockUtils.getIdentityInstance({ did: 'issuerDid5' }),
                data: {
                    type: types_2.AuthorizationType.PortfolioCustody,
                    value: mocks_1.entityMockUtils.getDefaultPortfolioInstance({ did: 'issuerDid5' }),
                },
            },
            {
                authId: new bignumber_js_1.default(6),
                expiry: null,
                target: mocks_1.entityMockUtils.getIdentityInstance({ did: 'targetDid6' }),
                issuer: mocks_1.entityMockUtils.getIdentityInstance({ did: 'issuerDid6' }),
                data: {
                    type: types_2.AuthorizationType.TransferTicker,
                    value: 'SOME_TICKER6',
                },
            },
            {
                authId: new bignumber_js_1.default(7),
                expiry: new Date('10/14/1987'),
                target: mocks_1.entityMockUtils.getIdentityInstance({ did: 'targetDid7' }),
                issuer: mocks_1.entityMockUtils.getIdentityInstance({ did: 'issuerDid7' }),
                data: {
                    type: types_2.AuthorizationType.TransferAssetOwnership,
                    value: 'SOME_TICKER7',
                },
            },
        ];
        auths = [];
        rawAuthIds = [];
        rawAuthIdentifiers = [];
        authParams.forEach(params => {
            const { authId, target } = params;
            const signerValue = utilsConversionModule.signerToSignerValue(target);
            auths.push(new internal_1.AuthorizationRequest(params, mockContext));
            const rawAuthId = mocks_1.dsMockUtils.createMockU64(authId.toNumber());
            rawAuthIds.push([rawAuthId]);
            numberToU64Stub.withArgs(authId, mockContext).returns(rawAuthId);
            const rawSignatory = mocks_1.dsMockUtils.createMockSignatory({
                Identity: mocks_1.dsMockUtils.createMockIdentityId(signerValue.value),
            });
            rawAuthIdentifiers.push([rawSignatory, rawAuthId, rawFalseBool]);
            signerValueToSignatoryStub.withArgs(signerValue, mockContext).returns(rawSignatory);
        });
        booleanToBoolStub.withArgs(false, mockContext).returns(rawFalseBool);
        acceptAssetOwnershipTransferTransaction = mocks_1.dsMockUtils.createTxStub('asset', 'acceptAssetOwnershipTransfer');
        acceptPayingKeyTransaction = mocks_1.dsMockUtils.createTxStub('relayer', 'acceptPayingKey');
        acceptPrimaryKeyTransaction = mocks_1.dsMockUtils.createTxStub('identity', 'acceptPrimaryKey');
        acceptBecomeAgentTransaction = mocks_1.dsMockUtils.createTxStub('externalAgents', 'acceptBecomeAgent');
        acceptPortfolioCustodyTransaction = mocks_1.dsMockUtils.createTxStub('portfolio', 'acceptPortfolioCustody');
        acceptTickerTransferTransaction = mocks_1.dsMockUtils.createTxStub('asset', 'acceptTickerTransfer');
    });
    afterEach(() => {
        mocks_1.entityMockUtils.reset();
        mocks_1.procedureMockUtils.reset();
        mocks_1.dsMockUtils.reset();
    });
    afterAll(() => {
        mocks_1.entityMockUtils.cleanup();
        mocks_1.procedureMockUtils.cleanup();
        mocks_1.dsMockUtils.cleanup();
    });
    test('should add a batch of accept authorization transactions (dependent on the type of auth) to the queue and ignore expired requests', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        yield consumeAuthorizationRequests_1.prepareConsumeAuthorizationRequests.call(proc, {
            accept: true,
            authRequests: auths,
        });
        sinon_1.default.assert.calledWith(addBatchTransactionStub, acceptAssetOwnershipTransferTransaction, {}, [
            rawAuthIds[0],
        ]);
        sinon_1.default.assert.calledWith(addBatchTransactionStub, acceptPayingKeyTransaction, {}, [
            rawAuthIds[1],
        ]);
        sinon_1.default.assert.calledWith(addBatchTransactionStub, acceptPrimaryKeyTransaction, {}, [
            [rawAuthIds[2][0], null],
        ]);
        sinon_1.default.assert.calledWith(addBatchTransactionStub, acceptBecomeAgentTransaction, {}, [
            rawAuthIds[3],
        ]);
        sinon_1.default.assert.calledWith(addBatchTransactionStub, acceptPortfolioCustodyTransaction, {}, [
            rawAuthIds[4],
        ]);
        sinon_1.default.assert.calledWith(addBatchTransactionStub, acceptTickerTransferTransaction, {}, [
            rawAuthIds[5],
        ]);
    }));
    test('should add a batch of remove authorization transactions to the queue and ignore expired requests', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        const transaction = mocks_1.dsMockUtils.createTxStub('identity', 'removeAuthorization');
        yield consumeAuthorizationRequests_1.prepareConsumeAuthorizationRequests.call(proc, {
            accept: false,
            authRequests: auths,
        });
        const authIds = rawAuthIdentifiers.slice(0, -1);
        sinon_1.default.assert.calledWith(addBatchTransactionStub, transaction, {}, authIds);
    }));
    describe('getAuthorization', () => {
        test('should return whether the current Identity or Account is the target of all non-expired requests if trying to accept', () => __awaiter(void 0, void 0, void 0, function* () {
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
            const { did } = yield mockContext.getCurrentIdentity();
            const constructorParams = [
                {
                    authId: new bignumber_js_1.default(1),
                    expiry: null,
                    target: mocks_1.entityMockUtils.getIdentityInstance({ did }),
                    issuer: mocks_1.entityMockUtils.getIdentityInstance({ did: 'issuerDid1' }),
                    data: {
                        type: types_2.AuthorizationType.BecomeAgent,
                    },
                },
                {
                    authId: new bignumber_js_1.default(2),
                    expiry: new Date('10/14/1987'),
                    target: mocks_1.entityMockUtils.getIdentityInstance({ did: 'notTheCurrentIdentity' }),
                    issuer: mocks_1.entityMockUtils.getIdentityInstance({ did: 'issuerDid2' }),
                    data: {
                        type: types_2.AuthorizationType.PortfolioCustody,
                    },
                },
            ];
            const args = {
                accept: true,
                authRequests: constructorParams.map(params => new internal_1.AuthorizationRequest(params, mockContext)),
            };
            const boundFunc = consumeAuthorizationRequests_1.getAuthorization.bind(proc);
            let result = yield boundFunc(args);
            expect(result).toEqual({
                roles: true,
                permissions: {
                    tokens: [],
                    portfolios: [],
                    transactions: [
                        types_1.TxTags.externalAgents.AcceptBecomeAgent,
                        types_1.TxTags.portfolio.AcceptPortfolioCustody,
                    ],
                },
            });
            args.authRequests[0].target = mocks_1.entityMockUtils.getIdentityInstance({
                did: 'notTheCurrentIdentity',
            });
            args.accept = false;
            result = yield boundFunc(args);
            expect(result).toEqual({
                roles: 'Authorization Requests can only be accepted by the target Account/Identity. They can only be rejected by the target Account/Identity or the issuing Identity',
                permissions: {
                    tokens: [],
                    portfolios: [],
                    transactions: [types_1.TxTags.identity.RemoveAuthorization],
                },
            });
            args.authRequests[0].target = mocks_1.entityMockUtils.getAccountInstance({ address: 'someAddress' });
            result = yield boundFunc(args);
            expect(result).toEqual({
                roles: 'Authorization Requests can only be accepted by the target Account/Identity. They can only be rejected by the target Account/Identity or the issuing Identity',
                permissions: {
                    tokens: [],
                    portfolios: [],
                    transactions: [types_1.TxTags.identity.RemoveAuthorization],
                },
            });
        }));
    });
});
//# sourceMappingURL=consumeAuthorizationRequests.js.map