"use strict";
/*
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

*/
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const ValidationService_1 = __importDefault(require("./ValidationService"));
const Injectable_1 = __importDefault(require("../../../core/injectable/Injectable"));
const ts_jest_1 = require("@golevelup/ts-jest");
const DataFixture_1 = require("../../../../__tests__/fixtures/shared/DataFixture");
const AccountNotKycd_1 = require("../../../domain/context/security/error/operations/AccountNotKycd");
const UnlistedKycIssuer_1 = require("../../../domain/context/security/error/operations/UnlistedKycIssuer");
const ClearingDeactivated_1 = require("../../../domain/context/security/error/operations/ClearingDeactivated");
const ClearingActivated_1 = require("../../../domain/context/security/error/operations/ClearingActivated");
const AccountIsNotOperator_1 = require("../../../domain/context/security/error/operations/AccountIsNotOperator");
const NotGrantedRole_1 = require("../../../domain/context/security/error/operations/NotGrantedRole");
const SecurityPaused_1 = require("../../../domain/context/security/error/operations/SecurityPaused");
const SecurityFixture_1 = require("../../../../__tests__/fixtures/shared/SecurityFixture");
const Security_1 = require("../../../domain/context/security/Security");
const PartitionsUnprotected_1 = require("../../../domain/context/security/error/operations/PartitionsUnprotected");
const PartitionsProtected_1 = require("../../../domain/context/security/error/operations/PartitionsProtected");
const CanTransferByPartitionQuery_1 = require("../../usecase/query/security/canTransferByPartition/CanTransferByPartitionQuery");
const ContractsErrorMapper_1 = require("../../../domain/context/security/error/operations/contractsErrorsMapper/ContractsErrorMapper");
const CanRedeemByPartitionQuery_1 = require("../../usecase/query/security/canRedeemByPartition/CanRedeemByPartitionQuery");
const GetMaxSupplyByPartitionQuery_1 = require("../../usecase/query/security/cap/getMaxSupplyByPartition/GetMaxSupplyByPartitionQuery");
const GetTotalSupplyByPartitionQuery_1 = require("../../usecase/query/security/cap/getTotalSupplyByPartition/GetTotalSupplyByPartitionQuery");
const MaxSupplyByPartitionReached_1 = require("../../../domain/context/security/error/operations/MaxSupplyByPartitionReached");
const GetMaxSupplyQuery_1 = require("../../usecase/query/security/cap/getMaxSupply/GetMaxSupplyQuery");
const MaxSupplyReached_1 = require("../../../domain/context/security/error/operations/MaxSupplyReached");
const CheckNums_1 = __importDefault(require("../../../core/checks/numbers/CheckNums"));
const DecimalsOverRange_1 = require("../../../domain/context/security/error/operations/DecimalsOverRange");
const GetNounceQuery_1 = require("../../usecase/query/security/protectedPartitions/getNounce/GetNounceQuery");
const NounceAlreadyUsed_1 = require("../../../domain/context/security/error/operations/NounceAlreadyUsed");
const IsInControlListQuery_1 = require("../../usecase/query/account/controlList/IsInControlListQuery");
const AccountAlreadyInControlList_1 = require("../../../domain/context/security/error/operations/AccountAlreadyInControlList");
const AccountNotInControlList_1 = require("../../../domain/context/security/error/operations/AccountNotInControlList");
const IsIssuerQuery_1 = require("../../usecase/query/security/ssi/isIssuer/IsIssuerQuery");
const AccountAlreadyIsAnIssuer_1 = require("../../../domain/context/security/error/operations/AccountAlreadyIsAnIssuer");
const BigDecimal_1 = __importDefault(require("../../../domain/context/shared/BigDecimal"));
const GetHoldForByPartitionQuery_1 = require("../../usecase/query/security/hold/getHoldForByPartition/GetHoldForByPartitionQuery");
const InsufficientHoldBalance_1 = require("../../../domain/context/security/error/operations/InsufficientHoldBalance");
const BalanceOfQuery_1 = require("../../usecase/query/security/balanceof/BalanceOfQuery");
const InsufficientBalance_1 = require("../../../domain/context/security/error/operations/InsufficientBalance");
const SecurityControlListType_1 = require("../../../domain/context/security/SecurityControlListType");
const GetControlListTypeQuery_1 = require("../../usecase/query/security/controlList/getControlListType/GetControlListTypeQuery");
const GetControlListCountQuery_1 = require("../../usecase/query/security/controlList/getControlListCount/GetControlListCountQuery");
const GetControlListMembersQuery_1 = require("../../usecase/query/security/controlList/getControlListMembers/GetControlListMembersQuery");
const AccountNotInWhiteList_1 = require("../../../domain/context/security/error/operations/AccountNotInWhiteList");
const GetKycStatusForQuery_1 = require("../../usecase/query/security/kyc/getKycStatusFor/GetKycStatusForQuery");
const IsClearingActivatedQuery_1 = require("../../usecase/query/security/clearing/isClearingActivated/IsClearingActivatedQuery");
const IsOperatorQuery_1 = require("../../usecase/query/security/operator/isOperator/IsOperatorQuery");
const IsOperatorForPartitionQuery_1 = require("../../usecase/query/security/operator/isOperatorForPartition/IsOperatorForPartitionQuery");
const HasRoleQuery_1 = require("../../usecase/query/security/roles/hasRole/HasRoleQuery");
const IsPausedQuery_1 = require("../../usecase/query/security/isPaused/IsPausedQuery");
const SecurityUnPaused_1 = require("../../../domain/context/security/error/operations/SecurityUnPaused");
const Constants_1 = require("../../../core/Constants");
const NotAllowedInMultiPartition_1 = require("../../../domain/context/security/error/operations/NotAllowedInMultiPartition");
const OnlyDefaultPartitionAllowed_1 = require("../../../domain/context/security/error/operations/OnlyDefaultPartitionAllowed");
const NotIssuable_1 = require("../../../domain/context/security/error/operations/NotIssuable");
const Terminal3_1 = require("../../../domain/context/kyc/Terminal3");
const InvalidVcHolder_1 = require("../../../domain/context/security/error/operations/InvalidVcHolder");
const EvmAddress_1 = __importDefault(require("../../../domain/context/contract/EvmAddress"));
const GetBondDetailsQuery_1 = require("../../usecase/query/bond/get/getBondDetails/GetBondDetailsQuery");
const OperationNotAllowed_1 = require("../../../domain/context/security/error/operations/OperationNotAllowed");
const Kyc_1 = require("../../../domain/context/kyc/Kyc");
const IsInternalKycActivatedQuery_1 = require("../../usecase/query/security/kyc/isInternalKycActivated/IsInternalKycActivatedQuery");
const IsExternallyGrantedQuery_1 = require("../../usecase/query/security/externalKycLists/isExternallyGranted/IsExternallyGrantedQuery");
const IsProceedRecipientQuery_1 = require("../../usecase/query/security/proceedRecipient/isProceedRecipient/IsProceedRecipientQuery");
const AccountIsNotProceedRecipient_1 = require("../../../domain/context/security/error/operations/AccountIsNotProceedRecipient");
const AccountIsProceedRecipient_1 = require("../../../domain/context/security/error/operations/AccountIsProceedRecipient");
describe('ValidationService', () => {
    let service;
    const queryBusMock = (0, ts_jest_1.createMock)();
    const securityId = DataFixture_1.HederaIdPropsFixture.create();
    const issuerId = DataFixture_1.HederaIdPropsFixture.create();
    const operatorId = DataFixture_1.HederaIdPropsFixture.create();
    const targetId = DataFixture_1.HederaIdPropsFixture.create();
    const targetEvmAddress = new EvmAddress_1.default(DataFixture_1.EvmAddressPropsFixture.create().value);
    const firstAddress = DataFixture_1.HederaIdPropsFixture.create();
    const secondAddress = DataFixture_1.HederaIdPropsFixture.create();
    const partitionId = DataFixture_1.PartitionIdFixture.create();
    const nonDefaultPartitionId = DataFixture_1.NonDefaultPartitionIdFixture.create();
    const role = DataFixture_1.RoleFixture.create();
    const amount = DataFixture_1.AmountFixture.create();
    const sourceId = DataFixture_1.HederaIdPropsFixture.create();
    const holdId = 1;
    beforeEach(() => {
        service = new ValidationService_1.default();
        jest.spyOn(Injectable_1.default, 'resolve').mockReturnValue(queryBusMock);
    });
    afterEach(() => {
        jest.resetAllMocks();
    });
    describe('checkIssuer', () => {
        it('should return void when issuer is valid', async () => {
            queryBusMock.execute.mockResolvedValue({ payload: true });
            await expect(service.checkIssuer(securityId.value, issuerId.value)).resolves.toBeUndefined();
            expect(queryBusMock.execute).toHaveBeenCalledWith(new IsIssuerQuery_1.IsIssuerQuery(securityId.value, issuerId.value));
        });
        it('should throw UnlistedKycIssuer when issuer is invalid', async () => {
            queryBusMock.execute.mockResolvedValue({ payload: false });
            await expect(service.checkIssuer(securityId.value, issuerId.value)).rejects.toThrow(UnlistedKycIssuer_1.UnlistedKycIssuer);
        });
    });
    describe('checkKycAddresses', () => {
        it('should return void when internal/external all addresses are Granted', async () => {
            queryBusMock.execute
                .mockResolvedValueOnce({ payload: true })
                .mockResolvedValueOnce({ payload: 1 })
                .mockResolvedValueOnce({ payload: true })
                .mockResolvedValueOnce({ payload: 1 })
                .mockResolvedValueOnce({ payload: true });
            await expect(service.checkKycAddresses(securityId.value, [firstAddress.value, secondAddress.value], Kyc_1.KycStatus.GRANTED)).resolves.toBeUndefined();
            expect(queryBusMock.execute).toHaveBeenCalledTimes(5);
            expect(queryBusMock.execute).toHaveBeenNthCalledWith(1, new IsInternalKycActivatedQuery_1.IsInternalKycActivatedQuery(securityId.value));
            expect(queryBusMock.execute).toHaveBeenNthCalledWith(2, new GetKycStatusForQuery_1.GetKycStatusForQuery(securityId.value, firstAddress.value));
            expect(queryBusMock.execute).toHaveBeenNthCalledWith(3, new IsExternallyGrantedQuery_1.IsExternallyGrantedQuery(securityId.value, Kyc_1.KycStatus.GRANTED, firstAddress.value));
            expect(queryBusMock.execute).toHaveBeenNthCalledWith(4, new GetKycStatusForQuery_1.GetKycStatusForQuery(securityId.value, secondAddress.value));
            expect(queryBusMock.execute).toHaveBeenNthCalledWith(5, new IsExternallyGrantedQuery_1.IsExternallyGrantedQuery(securityId.value, Kyc_1.KycStatus.GRANTED, secondAddress.value));
        });
        it('should throw AccountNotKycd when internal validation is false', async () => {
            queryBusMock.execute
                .mockResolvedValueOnce({ payload: true })
                .mockResolvedValueOnce({ payload: 0 });
            await expect(service.checkKycAddresses(securityId.value, [firstAddress.value], Kyc_1.KycStatus.GRANTED)).rejects.toThrow(AccountNotKycd_1.AccountNotKycd);
        });
        it('should throw AccountNotKycd when external validation is false', async () => {
            queryBusMock.execute
                .mockResolvedValueOnce({ payload: true })
                .mockResolvedValueOnce({ payload: 1 })
                .mockResolvedValueOnce({ payload: false });
            await expect(service.checkKycAddresses(securityId.value, [firstAddress.value], Kyc_1.KycStatus.GRANTED)).rejects.toThrow(AccountNotKycd_1.AccountNotKycd);
        });
    });
    describe('checkClearingActivated', () => {
        it('should return void when clearing is activated', async () => {
            queryBusMock.execute.mockResolvedValue({ payload: true });
            await expect(service.checkClearingActivated(securityId.value)).resolves.toBeUndefined();
            expect(queryBusMock.execute).toHaveBeenCalledWith(new IsClearingActivatedQuery_1.IsClearingActivatedQuery(securityId.value));
        });
        it('should throw ClearingDeactivated when clearing is not activated', async () => {
            queryBusMock.execute.mockResolvedValue({ payload: false });
            await expect(service.checkClearingActivated(securityId.value)).rejects.toThrow(ClearingDeactivated_1.ClearingDeactivated);
        });
    });
    describe('checkClearingDeactivated', () => {
        it('should return void when clearing is deactivated', async () => {
            queryBusMock.execute.mockResolvedValue({ payload: false });
            await expect(service.checkClearingDeactivated(securityId.value)).resolves.toBeUndefined();
            expect(queryBusMock.execute).toHaveBeenCalledWith(new IsClearingActivatedQuery_1.IsClearingActivatedQuery(securityId.value));
        });
        it('should throw ClearingActivated when clearing is activated', async () => {
            queryBusMock.execute.mockResolvedValue({ payload: true });
            await expect(service.checkClearingDeactivated(securityId.value)).rejects.toThrow(ClearingActivated_1.ClearingActivated);
        });
    });
    describe('checkOperator', () => {
        it('should return void when operator is valid via IsOperatorQuery', async () => {
            queryBusMock.execute
                .mockResolvedValueOnce({ payload: true })
                .mockResolvedValueOnce({ payload: false });
            await expect(service.checkOperator(securityId.value, partitionId.value, operatorId.value, targetId.value)).resolves.toBeUndefined();
            expect(queryBusMock.execute).toHaveBeenCalledTimes(1);
            expect(queryBusMock.execute).toHaveBeenCalledWith(new IsOperatorQuery_1.IsOperatorQuery(securityId.value, operatorId.value, targetId.value));
        });
        it('should return void when operator is valid via IsOperatorForPartitionQuery', async () => {
            queryBusMock.execute
                .mockResolvedValueOnce({ payload: false })
                .mockResolvedValueOnce({ payload: true });
            await expect(service.checkOperator(securityId.value, partitionId.value, operatorId.value, targetId.value)).resolves.toBeUndefined();
            expect(queryBusMock.execute).toHaveBeenCalledTimes(2);
            expect(queryBusMock.execute).toHaveBeenNthCalledWith(1, new IsOperatorQuery_1.IsOperatorQuery(securityId.value, operatorId.value, targetId.value));
            expect(queryBusMock.execute).toHaveBeenNthCalledWith(2, new IsOperatorForPartitionQuery_1.IsOperatorForPartitionQuery(securityId.value, partitionId.value, operatorId.value, targetId.value));
        });
        it('should throw AccountIsNotOperator when neither query validates', async () => {
            queryBusMock.execute
                .mockResolvedValueOnce({ payload: false })
                .mockResolvedValueOnce({ payload: false });
            await expect(service.checkOperator(securityId.value, partitionId.value, operatorId.value, targetId.value)).rejects.toThrow(AccountIsNotOperator_1.AccountIsNotOperator);
        });
    });
    describe('checkRole', () => {
        it('should return void when role is valid via HasRoleQuery', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: true });
            await expect(service.checkRole(role.value, targetId.value, securityId.value)).resolves.toBeUndefined();
            expect(queryBusMock.execute).toHaveBeenCalledTimes(1);
            expect(queryBusMock.execute).toHaveBeenCalledWith(new HasRoleQuery_1.HasRoleQuery(role.value, targetId.value, securityId.value));
        });
        it('should throw NotGrantedRole when role is not granted', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: false });
            await expect(service.checkRole(role.value, targetId.value, securityId.value)).rejects.toThrow(NotGrantedRole_1.NotGrantedRole);
        });
    });
    describe('checkAnyRole', () => {
        it('should return void when any role is valid via HasRoleQuery', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: true });
            await expect(service.checkAnyRole([role.value, role.value], targetId.value, securityId.value)).resolves.toBeUndefined();
            expect(queryBusMock.execute).toHaveBeenCalledTimes(2);
            expect(queryBusMock.execute).toHaveBeenCalledWith(new HasRoleQuery_1.HasRoleQuery(role.value, targetId.value, securityId.value));
        });
        it('should throw NotGrantedRole when no role is not granted', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: false });
            await expect(service.checkAnyRole([role.value], targetId.value, securityId.value)).rejects.toThrow(NotGrantedRole_1.NotGrantedRole);
        });
    });
    describe('checkPause', () => {
        it('should return void when pause via IsPausedQuery', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: false });
            await expect(service.checkPause(securityId.value)).resolves.toBeUndefined();
            expect(queryBusMock.execute).toHaveBeenCalledTimes(1);
            expect(queryBusMock.execute).toHaveBeenCalledWith(new IsPausedQuery_1.IsPausedQuery(securityId.value));
        });
        it('should throw SecurityPaused when security is paused', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: true });
            await expect(service.checkPause(securityId.value)).rejects.toThrow(SecurityPaused_1.SecurityPaused);
        });
    });
    describe('checkUnpause', () => {
        it('should return void when pause via IsPausedQuery', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: true });
            await expect(service.checkUnpause(securityId.value)).resolves.toBeUndefined();
            expect(queryBusMock.execute).toHaveBeenCalledTimes(1);
            expect(queryBusMock.execute).toHaveBeenCalledWith(new IsPausedQuery_1.IsPausedQuery(securityId.value));
        });
        it('should throw SecurityUnPaused when security is paused', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: false });
            await expect(service.checkUnpause(securityId.value)).rejects.toThrow(SecurityUnPaused_1.SecurityUnPaused);
        });
    });
    describe('checkProtectedPartitions', () => {
        it('should work successfully', async () => {
            const security = new Security_1.Security(SecurityFixture_1.SecurityPropsFixture.create({ arePartitionsProtected: true }));
            await expect(service.checkProtectedPartitions(security)).resolves.toBeUndefined();
        });
        it('should throw PartitionsUnProtected when security is unprotected', async () => {
            const security = new Security_1.Security(SecurityFixture_1.SecurityPropsFixture.create({ arePartitionsProtected: false }));
            await expect(service.checkProtectedPartitions(security)).rejects.toThrow(PartitionsUnprotected_1.PartitionsUnProtected);
        });
    });
    describe('checkUnprotectedPartitions', () => {
        it('should work successfully', async () => {
            const security = new Security_1.Security(SecurityFixture_1.SecurityPropsFixture.create({ arePartitionsProtected: false }));
            await expect(service.checkUnprotectedPartitions(security)).resolves.toBeUndefined();
        });
        it('should throw PartitionsProtected when security is protected', async () => {
            const security = new Security_1.Security(SecurityFixture_1.SecurityPropsFixture.create({ arePartitionsProtected: true }));
            await expect(service.checkUnprotectedPartitions(security)).rejects.toThrow(PartitionsProtected_1.PartitionsProtected);
        });
    });
    describe('checkCanTransfer', () => {
        it('should work when transfer is possible', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: ['0x01', 'test'] });
            await expect(service.checkCanTransfer(securityId.value, targetId.value, amount.value.toString(), operatorId.value, sourceId.value, partitionId.value)).resolves.toBeUndefined();
            expect(queryBusMock.execute).toHaveBeenCalledWith(new CanTransferByPartitionQuery_1.CanTransferByPartitionQuery(securityId.value, sourceId.value, targetId.value, partitionId.value, amount.value.toString()));
            expect(queryBusMock.execute).toHaveBeenCalledTimes(1);
        });
        it('should throw error when transfer fails', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: '0x00' });
            jest.spyOn(ContractsErrorMapper_1.ContractsErrorMapper, 'mapError').mockImplementation(() => {
                throw new Error('Transfer failed');
            });
            await expect(service.checkCanTransfer(securityId.value, targetId.value, amount.value.toString(), operatorId.value, sourceId.value, partitionId.value)).rejects.toThrow('Transfer failed');
        });
    });
    describe('checkCanRedeem', () => {
        it('should work when redeem', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: ['0x01', 'test'] });
            await expect(service.checkCanRedeem(securityId.value, sourceId.value, amount.value.toString(), partitionId.value)).resolves.toBeUndefined();
            expect(queryBusMock.execute).toHaveBeenCalledWith(new CanRedeemByPartitionQuery_1.CanRedeemByPartitionQuery(securityId.value, sourceId.value, partitionId.value, amount.value.toString()));
            expect(queryBusMock.execute).toHaveBeenCalledTimes(1);
        });
        it('should throw error when redeem fails', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: '0x00' });
            jest.spyOn(ContractsErrorMapper_1.ContractsErrorMapper, 'mapError').mockImplementation(() => {
                throw new Error('Transfer failed');
            });
            await expect(service.checkCanRedeem(securityId.value, sourceId.value, partitionId.value, amount.value.toString())).rejects.toThrow('Transfer failed');
        });
    });
    describe('checkMaxSupply', () => {
        it('should work when max supply not exceeded with partitionId', async () => {
            const security = new Security_1.Security(SecurityFixture_1.SecurityPropsFixture.create());
            queryBusMock.execute
                .mockResolvedValueOnce({ payload: amount.value })
                .mockResolvedValueOnce({
                payload: BigDecimal_1.default.fromString((BigInt(amount.value.toString()) - BigInt(10000)).toString()),
            })
                .mockResolvedValueOnce({
                payload: BigDecimal_1.default.fromString((BigInt(security.totalSupply.value.toString()) + BigInt(10000)).toString()),
            });
            await expect(service.checkMaxSupply(securityId.value, BigDecimal_1.default.fromString('1'), security, partitionId.value)).resolves.toBeUndefined();
            expect(queryBusMock.execute).toHaveBeenCalledTimes(3);
            expect(queryBusMock.execute).toHaveBeenNthCalledWith(1, new GetMaxSupplyByPartitionQuery_1.GetMaxSupplyByPartitionQuery(securityId.value, partitionId.value));
            expect(queryBusMock.execute).toHaveBeenNthCalledWith(2, new GetTotalSupplyByPartitionQuery_1.GetTotalSupplyByPartitionQuery(securityId.value, partitionId.value));
            expect(queryBusMock.execute).toHaveBeenNthCalledWith(3, new GetMaxSupplyQuery_1.GetMaxSupplyQuery(securityId.value));
        });
        it('should work when max supply not exceeded without partitionId', async () => {
            const security = new Security_1.Security(SecurityFixture_1.SecurityPropsFixture.create());
            queryBusMock.execute.mockResolvedValueOnce({
                payload: BigDecimal_1.default.fromString((BigInt(security.totalSupply.value.toString()) +
                    BigInt(amount.value.toString())).toString()),
            });
            await service.checkMaxSupply(securityId.value, amount.value, security);
            expect(queryBusMock.execute).toHaveBeenCalledTimes(1);
            expect(queryBusMock.execute).toHaveBeenCalledWith(new GetMaxSupplyQuery_1.GetMaxSupplyQuery(securityId.value));
        });
        it('should throw MaxSupplyByPartitionReached when partition limit exceeded', async () => {
            const security = new Security_1.Security(SecurityFixture_1.SecurityPropsFixture.create());
            queryBusMock.execute
                .mockResolvedValueOnce({ payload: amount.value })
                .mockResolvedValueOnce({ payload: amount.value });
            await expect(service.checkMaxSupply(securityId.value, amount.value, security, partitionId.value)).rejects.toThrow(MaxSupplyByPartitionReached_1.MaxSupplyByPartitionReached);
        });
        it('should throw MaxSupplyReached when limit exceeded', async () => {
            const security = new Security_1.Security(SecurityFixture_1.SecurityPropsFixture.create());
            queryBusMock.execute.mockResolvedValueOnce({ payload: amount.value });
            await expect(service.checkMaxSupply(securityId.value, amount.value, security)).rejects.toThrow(MaxSupplyReached_1.MaxSupplyReached);
        });
    });
    describe('checkDecimals', () => {
        const security = new Security_1.Security(SecurityFixture_1.SecurityPropsFixture.create());
        it('should return void when decimals are within range', async () => {
            jest.spyOn(CheckNums_1.default, 'hasMoreDecimals').mockReturnValue(false);
            await expect(service.checkDecimals(security, amount.value.toString())).resolves.toBeUndefined();
            expect(CheckNums_1.default.hasMoreDecimals).toHaveBeenCalledWith(amount.value.toString(), security.decimals);
        });
        it('should throw DecimalsOverRange when too many decimals', async () => {
            jest.spyOn(CheckNums_1.default, 'hasMoreDecimals').mockReturnValue(true);
            await expect(service.checkDecimals(security, amount.value.toString())).rejects.toThrow(DecimalsOverRange_1.DecimalsOverRange);
            expect(CheckNums_1.default.hasMoreDecimals).toHaveBeenCalledWith(amount.value.toString(), security.decimals);
        });
    });
    describe('checkProtectedPartitionRole', () => {
        it('should return void when role check passes', async () => {
            const checkRoleSpy = jest
                .spyOn(service, 'checkRole')
                .mockResolvedValue(undefined);
            await expect(service.checkProtectedPartitionRole(partitionId.value, targetId.value, securityId.value)).resolves.toBeUndefined();
            expect(checkRoleSpy).toHaveBeenCalledWith(expect.any(String), targetId.value, securityId.value);
        });
    });
    describe('checkValidNounce', () => {
        const nonce = 5;
        it('should return void when nounce is valid', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: 4 });
            await expect(service.checkValidNounce(securityId.value, targetId.value, nonce)).resolves.toBeUndefined();
            expect(queryBusMock.execute).toHaveBeenCalledWith(new GetNounceQuery_1.GetNounceQuery(securityId.value, targetId.value));
            expect(queryBusMock.execute).toHaveBeenCalledTimes(1);
        });
        it('should throw NounceAlreadyUsed when nounce is equal to nextNounce', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: 5 });
            await expect(service.checkValidNounce(securityId.value, targetId.value, nonce)).rejects.toThrow(NounceAlreadyUsed_1.NounceAlreadyUsed);
        });
        it('should throw NounceAlreadyUsed when nounce is less than nextNounce', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: 6 });
            await expect(service.checkValidNounce(securityId.value, targetId.value, nonce)).rejects.toThrow(NounceAlreadyUsed_1.NounceAlreadyUsed);
        });
    });
    describe('checkAccountInControlList', () => {
        it('should return void when adding and account is not in control list', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: false });
            await expect(service.checkAccountInControlList(securityId.value, targetId.value, true)).resolves.toBeUndefined();
            expect(queryBusMock.execute).toHaveBeenCalledWith(new IsInControlListQuery_1.IsInControlListQuery(securityId.value, targetId.value));
            expect(queryBusMock.execute).toHaveBeenCalledTimes(1);
        });
        it('should return void when removing and account is in control list', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: true });
            await expect(service.checkAccountInControlList(securityId.value, targetId.value, false)).resolves.toBeUndefined();
            expect(queryBusMock.execute).toHaveBeenCalledWith(new IsInControlListQuery_1.IsInControlListQuery(securityId.value, targetId.value));
        });
        it('should throw AccountAlreadyInControlList when adding and account exists', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: true });
            await expect(service.checkAccountInControlList(securityId.value, targetId.value, true)).rejects.toThrow(AccountAlreadyInControlList_1.AccountAlreadyInControlList);
        });
        it('should throw AccountNotInControlList when removing and account not found', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: false });
            await expect(service.checkAccountInControlList(securityId.value, targetId.value, false)).rejects.toThrow(AccountNotInControlList_1.AccountNotInControlList);
        });
    });
    describe('checkAccountInIssuersList', () => {
        it('should return void when adding and account is not an issuer', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: false });
            await expect(service.checkAccountInIssuersList(securityId.value, targetId.value, true)).resolves.toBeUndefined();
            expect(queryBusMock.execute).toHaveBeenCalledWith(new IsIssuerQuery_1.IsIssuerQuery(securityId.value, targetId.value));
            expect(queryBusMock.execute).toHaveBeenCalledTimes(1);
        });
        it('should return void when removing and account is an issuer', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: true });
            await expect(service.checkAccountInIssuersList(securityId.value, targetId.value, false)).resolves.toBeUndefined();
            expect(queryBusMock.execute).toHaveBeenCalledWith(new IsIssuerQuery_1.IsIssuerQuery(securityId.value, targetId.value));
        });
        it('should throw AccountIsAlreadyAnIssuer when adding and account exists', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: true });
            await expect(service.checkAccountInIssuersList(securityId.value, targetId.value, true)).rejects.toThrow(AccountAlreadyIsAnIssuer_1.AccountIsAlreadyAnIssuer);
        });
        it('should throw UnlistedKycIssuer when removing and account not found', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: false });
            await expect(service.checkAccountInIssuersList(securityId.value, targetId.value, false)).rejects.toThrow(UnlistedKycIssuer_1.UnlistedKycIssuer);
        });
    });
    describe('checkHoldBalance', () => {
        it('should return void when hold balance is sufficient', async () => {
            queryBusMock.execute.mockResolvedValueOnce({
                payload: {
                    amount: new BigDecimal_1.default((BigInt(amount.value.toString()) + BigInt(150)).toString()),
                },
            });
            await expect(service.checkHoldBalance(securityId.value, partitionId.value, sourceId.value, holdId, amount.value)).resolves.toBeUndefined();
            expect(queryBusMock.execute).toHaveBeenCalledWith(new GetHoldForByPartitionQuery_1.GetHoldForByPartitionQuery(securityId.value, partitionId.value, sourceId.value, holdId));
            expect(queryBusMock.execute).toHaveBeenCalledTimes(1);
        });
        it('should throw InsufficientHoldBalance when balance is too low', async () => {
            queryBusMock.execute.mockResolvedValueOnce({
                payload: {
                    amount: BigDecimal_1.default.fromString((BigInt(amount.value.toString()) - BigInt(150)).toString()),
                },
            });
            await expect(service.checkHoldBalance(securityId.value, partitionId.value, sourceId.value, holdId, amount.value)).rejects.toThrow(InsufficientHoldBalance_1.InsufficientHoldBalance);
        });
    });
    describe('checkBalance', () => {
        it('should return void when balance is sufficient', async () => {
            queryBusMock.execute.mockResolvedValueOnce({
                payload: BigDecimal_1.default.fromString((BigInt(amount.value.toString()) + BigInt(amount.value.toString())).toString()),
            });
            await expect(service.checkBalance(securityId.value, targetId.value, amount.value)).resolves.toBeUndefined();
            expect(queryBusMock.execute).toHaveBeenCalledWith(new BalanceOfQuery_1.BalanceOfQuery(securityId.value, targetId.value));
        });
        it('should throw InsufficientBalance when balance is too low', async () => {
            queryBusMock.execute.mockResolvedValueOnce({
                payload: BigDecimal_1.default.fromString((BigInt(amount.value.toString()) - BigInt(amount.value.toString())).toString()),
            });
            await expect(service.checkBalance(securityId.value, targetId.value, amount.value)).rejects.toThrow(InsufficientBalance_1.InsufficientBalance);
        });
    });
    describe('checkControlList', () => {
        it('should return true for whitelist when user is in list', async () => {
            queryBusMock.execute
                .mockResolvedValueOnce({ payload: SecurityControlListType_1.SecurityControlListType.WHITELIST })
                .mockResolvedValueOnce({ payload: 2 })
                .mockResolvedValueOnce({
                payload: [sourceId.value, targetId.value],
            });
            await expect(service.checkControlList(securityId.value, sourceId.value, targetId.value)).resolves.toBeUndefined();
            expect(queryBusMock.execute).toHaveBeenCalledTimes(3);
            expect(queryBusMock.execute).toHaveBeenNthCalledWith(1, new GetControlListTypeQuery_1.GetControlListTypeQuery(securityId.value));
            expect(queryBusMock.execute).toHaveBeenNthCalledWith(2, new GetControlListCountQuery_1.GetControlListCountQuery(securityId.value));
            expect(queryBusMock.execute).toHaveBeenNthCalledWith(3, new GetControlListMembersQuery_1.GetControlListMembersQuery(securityId.value, 0, 2));
        });
        it('should throw AccountNotInWhiteList when user not in whitelist', async () => {
            queryBusMock.execute
                .mockResolvedValueOnce({ payload: SecurityControlListType_1.SecurityControlListType.WHITELIST })
                .mockResolvedValueOnce({ payload: 1 })
                .mockResolvedValueOnce({ payload: ['0xOTHER'] });
            await expect(service.checkControlList(securityId.value, sourceId.value)).rejects.toThrow(AccountNotInWhiteList_1.AccountNotInWhiteList);
        });
    });
    describe('checkMultiPartition', () => {
        const securityMulti = new Security_1.Security(SecurityFixture_1.SecurityPropsFixture.create({ isMultiPartition: true }));
        const securitySingle = new Security_1.Security(SecurityFixture_1.SecurityPropsFixture.create({ isMultiPartition: false }));
        it('should resolve void when no partitionId and single partition', async () => {
            await expect(service.checkMultiPartition(securitySingle)).resolves.toBeUndefined();
        });
        it('should resolve void when partitionId matches default and single partition', async () => {
            await expect(service.checkMultiPartition(securitySingle, Constants_1._PARTITION_ID_1)).resolves.toBeUndefined();
        });
        it('should resolve void when partitionId provided and multi-partition', async () => {
            await expect(service.checkMultiPartition(securityMulti, partitionId.value)).resolves.toBeUndefined();
        });
        it('should throw NotAllowedInMultiPartition when no partitionId and multi-partition', async () => {
            await expect(service.checkMultiPartition(securityMulti)).rejects.toThrow(NotAllowedInMultiPartition_1.NotAllowedInMultiPartition);
        });
        it('should throw OnlyDefaultPartitionAllowed when non-default partitionId and single partition', async () => {
            await expect(service.checkMultiPartition(securitySingle, nonDefaultPartitionId.value)).rejects.toThrow(OnlyDefaultPartitionAllowed_1.OnlyDefaultPartitionAllowed);
        });
    });
    describe('checkIssuable', () => {
        it('should resolve void when security is issuable', async () => {
            const security = new Security_1.Security(SecurityFixture_1.SecurityPropsFixture.create({ isIssuable: true }));
            await expect(service.checkIssuable(security)).resolves.toBeUndefined();
        });
        it('should throw NotIssuable when security is not issuable', async () => {
            const security = new Security_1.Security(SecurityFixture_1.SecurityPropsFixture.create({ isIssuable: false }));
            await expect(service.checkIssuable(security)).rejects.toThrow(NotIssuable_1.NotIssuable);
        });
    });
    describe('checkValidVc', () => {
        const signedCredential = {};
        beforeEach(() => {
            jest.spyOn(Terminal3_1.Terminal3Vc, 'extractIssuer').mockReturnValue(issuerId.value);
            jest
                .spyOn(Terminal3_1.Terminal3Vc, 'checkValidDates')
                .mockReturnValue(signedCredential);
            jest
                .spyOn(Terminal3_1.Terminal3Vc, 'extractHolder')
                .mockReturnValue(targetEvmAddress.value.toString());
        });
        it('should return issuer and credential when valid', async () => {
            const checkIssuerSpy = jest
                .spyOn(service, 'checkIssuer')
                .mockResolvedValue(undefined);
            const result = await service.checkValidVc(signedCredential, targetEvmAddress, securityId.value);
            expect(result).toEqual([issuerId.value, signedCredential]);
            expect(Terminal3_1.Terminal3Vc.extractIssuer).toHaveBeenCalledWith(signedCredential);
            expect(Terminal3_1.Terminal3Vc.checkValidDates).toHaveBeenCalledWith(signedCredential);
            expect(Terminal3_1.Terminal3Vc.extractHolder).toHaveBeenCalledWith(signedCredential);
            expect(checkIssuerSpy).toHaveBeenCalledWith(securityId.value, issuerId.value);
        });
        it('should throw InvalidVcHolder when holder mismatch', async () => {
            jest
                .spyOn(Terminal3_1.Terminal3Vc, 'extractHolder')
                .mockReturnValue(sourceId.value + '1');
            await expect(service.checkValidVc(signedCredential, targetEvmAddress, securityId.value)).rejects.toThrow(InvalidVcHolder_1.InvalidVcHolder);
        });
    });
    describe('checkMaturityDate', () => {
        const currentTime = new Date().getTime();
        it('should resolve void when new maturity date is later', async () => {
            queryBusMock.execute.mockResolvedValueOnce({
                bond: { maturityDate: currentTime },
            });
            await expect(service.checkMaturityDate(securityId.value, (currentTime + 1000).toString())).resolves.toBeUndefined();
            expect(queryBusMock.execute).toHaveBeenCalledWith(new GetBondDetailsQuery_1.GetBondDetailsQuery(securityId.value));
        });
        it('should throw OperationNotAllowed when date is earlier', async () => {
            queryBusMock.execute.mockResolvedValueOnce({
                bond: { maturityDate: currentTime },
            });
            await expect(service.checkMaturityDate(securityId.value, (currentTime - 1000).toString())).rejects.toThrow(OperationNotAllowed_1.OperationNotAllowed);
        });
        it('should throw OperationNotAllowed when date is equal', async () => {
            queryBusMock.execute.mockResolvedValueOnce({
                bond: { maturityDate: currentTime },
            });
            await expect(service.checkMaturityDate(securityId.value, currentTime.toString())).rejects.toThrow(OperationNotAllowed_1.OperationNotAllowed);
        });
    });
    describe('checkIsProceedRecipient', () => {
        it('should resolve successfully when address is a proceed recipient', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: true });
            const res = await service.checkIsProceedRecipient(securityId.value, targetId.value);
            expect(res).toBe(true);
            expect(queryBusMock.execute).toHaveBeenCalledWith(new IsProceedRecipientQuery_1.IsProceedRecipientQuery(securityId.value, targetId.value));
        });
        it('should throw AccountIsNotProceedRecipient when security is not issuable', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: false });
            await expect(service.checkIsProceedRecipient(securityId.value, targetId.value)).rejects.toThrow(AccountIsNotProceedRecipient_1.AccountIsNotProceedRecipient);
        });
    });
    describe('checkIsNotProceedRecipient', () => {
        it('should resolve successfully when address is not a proceed recipient', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: false });
            const res = await service.checkIsNotProceedRecipient(securityId.value, targetId.value);
            expect(res).toBe(true);
            expect(queryBusMock.execute).toHaveBeenCalledWith(new IsProceedRecipientQuery_1.IsProceedRecipientQuery(securityId.value, targetId.value));
        });
        it('should throw AccountIsProceedRecipient when security is not issuable', async () => {
            queryBusMock.execute.mockResolvedValueOnce({ payload: true });
            await expect(service.checkIsNotProceedRecipient(securityId.value, targetId.value)).rejects.toThrow(AccountIsProceedRecipient_1.AccountIsProceedRecipient);
        });
    });
});
