"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 });
/* eslint-disable @typescript-eslint/no-unused-vars */
const BigDecimal_1 = __importDefault(require("../../src/domain/context/shared/BigDecimal"));
const ethers_1 = require("ethers");
const SecurityRole_1 = require("../../src/domain/context/security/SecurityRole");
const BondDetails_1 = require("../../src/domain/context/bond/BondDetails");
const Dividend_1 = require("../../src/domain/context/equity/Dividend");
const VotingRights_1 = require("../../src/domain/context/equity/VotingRights");
const Coupon_1 = require("../../src/domain/context/bond/Coupon");
const ScheduledSnapshot_1 = require("../../src/domain/context/security/ScheduledSnapshot");
const HederaId_1 = require("../../src/domain/context/shared/HederaId");
const SecurityType_1 = require("../../src/domain/context/factory/SecurityType");
const EvmAddress_1 = __importDefault(require("../../src/domain/context/contract/EvmAddress"));
const Constants_1 = require("../../src/core/Constants");
const Injectable_1 = __importDefault(require("../../src/core/injectable/Injectable"));
const config_1 = require("../config");
const RegulationType_1 = require("../../src/domain/context/factory/RegulationType");
const ScheduledBalanceAdjustment_1 = require("../../src/domain/context/equity/ScheduledBalanceAdjustment");
const DividendFor_1 = require("../../src/domain/context/equity/DividendFor");
const VotingFor_1 = require("../../src/domain/context/equity/VotingFor");
const Kyc_1 = require("../../src/domain/context/kyc/Kyc");
const KycAccountData_1 = require("../../src/domain/context/kyc/KycAccountData");
const Clearing_1 = require("../../src/domain/context/security/Clearing");
const Hold_1 = require("../../src/domain/context/security/Hold");
//* Mock console.log() method
global.console.log = jest.fn();
//* Mock isWeb() method
Injectable_1.default.isWeb = jest.fn(() => true);
function hexToDecimal(hexString) {
    if (!/^0x[a-fA-F0-9]+$|^[a-fA-F0-9]+$/.test(hexString)) {
        throw new Error("Invalid hexadecimal input.");
    }
    return parseInt(hexString, 16);
}
function identifiers(accountId) {
    let id;
    let accountEvmAddress;
    if (accountId instanceof HederaId_1.HederaId) {
        id = accountId.toString();
        accountEvmAddress = "0x" + accountId.toHederaAddress().toSolidityAddress();
    }
    else {
        id = "0.0." + hexToDecimal("0x" + accountId.toUpperCase().substring(2));
        accountEvmAddress = accountId.toString();
    }
    return [id, "0x" + accountEvmAddress.toUpperCase().substring(2)];
}
const securityEvmAddress = "0x0000000000000000000000000000000000000001";
const transactionId = "0x0102030405060708010203040506070801020304050607080x0102030405060708";
const HBAR_balances = new Map();
const balances = new Map();
const lockedBalances = new Map();
const heldBalances = new Map();
const clearedBalances = new Map();
const coupons = [];
const couponsFor = new Map();
const dividends = [];
const dividendsFor = new Map();
const votingRights = [];
const votingRightsFor = new Map();
const roles = new Map();
const accounts_with_roles = new Map();
const locksIds = new Map();
const locks = new Map();
const holds = new Map();
const clearings = new Map();
const holdsIds = new Map();
const clearingsIds = new Map();
const lastLockIds = new Map();
const lastHoldIds = new Map();
const lastClearingIds = new Map();
const scheduledBalanceAdjustments = [];
const nonces = new Map();
const kycAccountsData = new Map();
const kycAccountsByStatus = new Map();
let controlList = [];
let issuerList = [];
let externalPausesList = [];
let securityInfo;
let equityInfo;
let bondInfo;
let couponInfo;
/*let factory: EvmAddress;
let resolverAddress: EvmAddress;
let businessLogicKeys: string[];
let diamondOwnerAccount: EvmAddress | undefined;*/
const network = "testnet";
let user_account;
let configVersion;
let configId;
let resolverAddress;
let revocationRegistryAddress;
function grantRole(account, newRole) {
    let r = roles.get(account);
    if (!r)
        r = [newRole];
    else if (false == r.includes(newRole))
        r.push(newRole);
    roles.set(account, r);
    let accounts = accounts_with_roles.get(newRole);
    if (!accounts)
        accounts = [account];
    else if (false == accounts.includes(account))
        accounts.push(account);
    accounts_with_roles.set(newRole, accounts);
}
function revokeRole(account, oldRole) {
    let r = roles.get(account);
    if (r) {
        if (r.includes(oldRole)) {
            r = r.filter((role) => role !== oldRole);
            roles.set(account, r);
            let accounts = accounts_with_roles.get(oldRole);
            if (accounts) {
                accounts = accounts.filter((item) => item !== account);
                accounts_with_roles.set(oldRole, accounts);
            }
        }
    }
}
function increaseHeldBalance(targetId, amount) {
    const account = identifiers(targetId.toString())[1];
    let accountHeldBalance = heldBalances.get(account);
    if (accountHeldBalance) {
        accountHeldBalance = BigDecimal_1.default.fromString(accountHeldBalance).toBigNumber().add(amount.toBigNumber()).toString();
        heldBalances.set(account, accountHeldBalance);
    }
    else
        heldBalances.set(account, amount.toString());
}
function increaseClearedBalance(targetId, amount) {
    const account = identifiers(targetId.toString())[1];
    let accountClearedBalance = clearedBalances.get(account);
    if (accountClearedBalance) {
        accountClearedBalance = BigDecimal_1.default.fromString(accountClearedBalance)
            .toBigNumber()
            .add(amount.toBigNumber())
            .toString();
        clearedBalances.set(account, accountClearedBalance);
    }
    else
        clearedBalances.set(account, amount.toString());
}
function decreaseClearedBalance(targetId, amount) {
    const account = identifiers(targetId.toString())[1];
    let accountClearedBalance = clearedBalances.get(account);
    if (accountClearedBalance) {
        accountClearedBalance = BigDecimal_1.default.fromString(accountClearedBalance)
            .toBigNumber()
            .sub(amount.toBigNumber())
            .toString();
        clearedBalances.set(account, accountClearedBalance);
    }
}
function processClearingOperation(targetId, clearingId, clearingOperationType) {
    const accountClearings = clearings.get("0x" + targetId.toString().toUpperCase().substring(2));
    const clearingEntry = accountClearings?.get(clearingId);
    const clearedAmount = clearingEntry && clearingEntry.length > 0 ? clearingEntry[0].amount : BigDecimal_1.default.fromString("0");
    decreaseClearedBalance(targetId, clearedAmount);
    const currentAccount = new EvmAddress_1.default(identifiers(user_account.id)[1]);
    increaseBalance(currentAccount, clearedAmount);
    const operationMap = clearingsIds.get(currentAccount.toString());
    if (operationMap) {
        const idList = operationMap.get(clearingOperationType);
        if (idList) {
            operationMap.set(clearingOperationType, idList.filter((id) => id !== clearingId));
        }
    }
    return {
        status: "success",
        id: transactionId,
    };
}
function decreaseHeldBalance(targetId, amount) {
    const account = identifiers(targetId.toString())[1];
    let accountHeldBalance = heldBalances.get(account);
    if (accountHeldBalance) {
        accountHeldBalance = BigDecimal_1.default.fromString(accountHeldBalance).toBigNumber().sub(amount.toBigNumber()).toString();
        heldBalances.set(account, accountHeldBalance);
    }
}
function increaseLockedBalance(targetId, amount) {
    const account = identifiers(targetId.toString())[1];
    let accountLockedBalance = lockedBalances.get(account);
    if (accountLockedBalance) {
        accountLockedBalance = BigDecimal_1.default.fromString(accountLockedBalance)
            .toBigNumber()
            .add(amount.toBigNumber())
            .toString();
        lockedBalances.set(account, accountLockedBalance);
    }
    else
        lockedBalances.set(account, amount.toString());
}
function decreaseLockedBalance(targetId, amount) {
    const account = identifiers(targetId.toString())[1];
    let accountLockedBalance = lockedBalances.get(account);
    if (accountLockedBalance) {
        accountLockedBalance = BigDecimal_1.default.fromString(accountLockedBalance)
            .toBigNumber()
            .sub(amount.toBigNumber())
            .toString();
        lockedBalances.set(account, accountLockedBalance);
    }
}
function increaseBalance(targetId, amount) {
    const account = identifiers(targetId.toString())[1];
    let accountBalance = balances.get(account);
    if (accountBalance) {
        accountBalance = BigDecimal_1.default.fromString(accountBalance).toBigNumber().add(amount.toBigNumber()).toString();
        balances.set(account, accountBalance);
    }
    else
        balances.set(account, amount.toString());
}
function decreaseBalance(targetId, amount) {
    const account = identifiers(targetId.toString())[1];
    let accountBalance = balances.get(account);
    if (accountBalance) {
        accountBalance = BigDecimal_1.default.fromString(accountBalance).toBigNumber().sub(amount.toBigNumber()).toString();
        balances.set(account, accountBalance);
    }
}
function createBondMockImplementation(_securityInfo, _bondInfo, _couponInfo, _factory, _resolver, _configId, _configVersion, _compliance, _identityRegistryAddress, _externalPauses, _diamondOwnerAccount) {
    securityInfo = _securityInfo;
    const ids = identifiers(securityEvmAddress);
    securityInfo.diamondAddress = HederaId_1.HederaId.from(ids[0]);
    securityInfo.evmDiamondAddress = new EvmAddress_1.default(ids[1]);
    securityInfo.type = SecurityType_1.SecurityType.BOND;
    securityInfo.regulation = {
        type: _securityInfo.regulationType ?? "",
        subType: _securityInfo.regulationsubType ?? "",
        dealSize: "0",
        accreditedInvestors: "ACCREDITATION REQUIRED",
        maxNonAccreditedInvestors: 0,
        manualInvestorVerification: "VERIFICATION INVESTORS FINANCIAL DOCUMENTS REQUIRED",
        internationalInvestors: "ALLOWED",
        resaleHoldPeriod: "NOT APPLICABLE",
    };
    bondInfo = _bondInfo;
    couponInfo = _couponInfo;
    configVersion = _configVersion;
    configId = _configId;
    resolverAddress = _resolver.toString();
    externalPausesList = _externalPauses?.map((address) => address.toString()) ?? [];
    const diff = bondInfo.maturityDate - couponInfo.firstCouponDate;
    const numberOfCoupons = Math.ceil(diff / couponInfo.couponFrequency);
    for (let i = 0; i < numberOfCoupons; i++) {
        const timeStamp = couponInfo.firstCouponDate + couponInfo.couponFrequency * i;
        const coupon = new Coupon_1.Coupon(timeStamp, timeStamp, couponInfo.couponRate, couponInfo.couponRateDecimals, 0);
        coupons.push(coupon);
    }
    return Promise.resolve({
        status: "success",
        id: transactionId,
        response: {
            bondAddress: securityEvmAddress,
        },
    });
}
const createHold = async (sourceId, expirationDate, amount, escrow, targetId) => {
    const account = `0x${sourceId.toString().toUpperCase().substring(2)}`;
    const accountHolds = holds.get(account) ?? new Map();
    const holdIds = holdsIds.get(account) ?? [];
    const lastHoldId = lastHoldIds.get(account) ?? 0;
    const newLastHoldId = lastHoldId + 1;
    holdIds.push(newLastHoldId);
    holdsIds.set(account, holdIds);
    accountHolds.set(newLastHoldId, [
        new Hold_1.HoldDetails(expirationDate.toBigNumber().toNumber(), amount, escrow.toString(), account, sourceId.toString(), "0x", "0x"),
    ]);
    holds.set(sourceId.toString(), accountHolds);
    increaseHeldBalance(sourceId, amount);
    const currentAccount = new EvmAddress_1.default(identifiers(user_account.id)[1]);
    decreaseBalance(targetId ? sourceId : currentAccount, amount);
    return { status: "success", id: transactionId };
};
const createClearing = async (clearingExpirationDate, amount, clearingOperationType, targetId, escrow, holdExpirationDate) => {
    const currentAccount = new EvmAddress_1.default(identifiers(user_account.id)[1]);
    const target = targetId ? targetId : currentAccount;
    const account = `0x${target.toString().toUpperCase().substring(2)}`;
    const accountClearings = clearings.get(account) ?? new Map();
    const clearingIds = clearingsIds.get(account)?.get(clearingOperationType) ?? [];
    const lastClearingId = lastClearingIds.get(account) ?? 0;
    const newLastClearingId = lastClearingId + 1;
    clearingIds.push(newLastClearingId);
    clearingsIds.set(account, new Map([[clearingOperationType, clearingIds]]));
    let clearing;
    switch (clearingOperationType) {
        case Clearing_1.ClearingOperationType.HoldCreation:
            clearing = new Clearing_1.ClearingHoldCreation(amount, clearingExpirationDate.toBigNumber().toNumber(), "0x", "0x", escrow.toString(), holdExpirationDate.toBigNumber().toNumber(), target.toString(), "0x");
            break;
        case Clearing_1.ClearingOperationType.Redeem:
            clearing = new Clearing_1.ClearingRedeem(amount, clearingExpirationDate.toBigNumber().toNumber(), "0x", "0x");
            break;
        default:
            clearing = new Clearing_1.ClearingTransfer(amount, clearingExpirationDate.toBigNumber().toNumber(), targetId.toString(), "0x", "0x");
            break;
    }
    accountClearings.set(newLastClearingId, [clearing]);
    clearings.set(target.toString(), accountClearings);
    increaseClearedBalance(target, amount);
    decreaseBalance(target, amount);
    return { status: "success", id: transactionId };
};
jest.mock("@port/out/rpc/RPCQueryAdapter", () => {
    const actual = jest.requireActual("@port/out/rpc/RPCQueryAdapter.ts");
    const singletonInstance = new actual.RPCQueryAdapter();
    singletonInstance.init = jest.fn(async (urlRpcProvider, apiKey) => {
        return "mock_environment";
    });
    singletonInstance.connect = jest.fn(() => {
        console.log("Mocked connect method");
        return {}; // Return a mock object as needed
    });
    singletonInstance.balanceOf = jest.fn(async (address, target) => {
        const balance = balances.get("0x" + target.toString().toUpperCase().substring(2));
        if (balance)
            return ethers_1.BigNumber.from(BigDecimal_1.default.fromString(balance, securityInfo.decimals));
        return ethers_1.BigNumber.from(BigDecimal_1.default.fromString("0", securityInfo.decimals));
    });
    singletonInstance.balanceOfByPartition = jest.fn(async (address, target, partitionId) => {
        if (partitionId == "0") {
            const balance = balances.get("0x" + target.toString().toUpperCase().substring(2));
            if (balance)
                return BigDecimal_1.default.fromString(balance, securityInfo.decimals);
            return BigDecimal_1.default.fromString("0", securityInfo.decimals);
        }
        return BigDecimal_1.default.fromString("0", securityInfo.decimals);
    });
    singletonInstance.balanceOfAtSnapshot = jest.fn(async (address, target, snapshotId) => {
        return ethers_1.BigNumber.from(0);
    });
    singletonInstance.balanceOfAtSnapshotByPartition = jest.fn(async (address, target, partitionId, snapshotId) => {
        return ethers_1.BigNumber.from(0);
    });
    singletonInstance.partitionsOf = jest.fn(async (address, targetId) => {
        return ["mock_partition"];
    });
    singletonInstance.partitionsOfAtSnapshot = jest.fn(async (address, targetId, snapshotId) => {
        return ["mock_partition"];
    });
    singletonInstance.totalSupply = jest.fn(async (address) => {
        return ethers_1.BigNumber.from(0);
    });
    singletonInstance.totalSupplyAtSnapshot = jest.fn(async (address, snapshotId) => {
        return ethers_1.BigNumber.from(0);
    });
    singletonInstance.getRolesFor = jest.fn(async (address, target, start, end) => {
        const target_roles = roles.get(identifiers(target.toString())[1]);
        if (!target_roles)
            return [];
        const rolesToReturn = [];
        for (let i = start; i < end; i++) {
            rolesToReturn.push(target_roles[i]);
        }
        return rolesToReturn;
    });
    singletonInstance.getRoleMembers = jest.fn(async (address, role, start, end) => {
        const accounts = accounts_with_roles.get(role);
        if (!accounts)
            return [];
        const roleMembers = [];
        for (let i = start; i < end; i++) {
            roleMembers.push(accounts[i]);
        }
        return roleMembers;
    });
    singletonInstance.getRoleCountFor = jest.fn(async (address, target) => {
        const target_roles = roles.get(identifiers(target.toString())[1]);
        if (!target_roles)
            return 0;
        return target_roles.length;
    });
    singletonInstance.getRoleMemberCount = jest.fn(async (address, role) => {
        const accounts = accounts_with_roles.get(role);
        if (!accounts)
            return 0;
        return accounts.length;
    });
    singletonInstance.hasRole = jest.fn(async (address, target, role) => {
        const target_roles = roles.get(identifiers(target.toString())[1]);
        if (!target_roles)
            return false;
        if (target_roles?.includes(role))
            return true;
        return false;
    });
    singletonInstance.getSecurity = jest.fn(async (address) => {
        return securityInfo;
    });
    singletonInstance.getEquityDetails = jest.fn(async (address) => {
        return equityInfo;
    });
    singletonInstance.getBondDetails = jest.fn(async (address) => {
        return bondInfo;
    });
    singletonInstance.getControlListMembers = jest.fn(async (address, start, end) => {
        const listMembers = [];
        for (let i = start; i < end; i++) {
            listMembers.push(controlList[i]);
        }
        return listMembers;
    });
    singletonInstance.getIssuerListMembers = jest.fn(async (address, start, end) => {
        const issuerListMembers = [];
        for (let i = start; i < end; i++) {
            issuerListMembers.push(issuerList[i]);
        }
        return issuerListMembers;
    });
    singletonInstance.getIssuerListCount = jest.fn(async (address) => {
        return issuerList.length;
    });
    singletonInstance.getRevocationRegistryAddress = jest.fn(async function (security) {
        return revocationRegistryAddress;
    });
    singletonInstance.getControlListCount = jest.fn(async (address) => {
        return controlList.length;
    });
    singletonInstance.getControlListType = jest.fn(async (address) => {
        return securityInfo.isWhiteList;
    });
    singletonInstance.isAccountInControlList = jest.fn(async (address, target) => {
        const account = identifiers(target.toString())[1];
        return controlList.findIndex((item) => item == account) !== -1;
    });
    singletonInstance.getDividendsFor = jest.fn(async (address, target, dividend) => {
        const dividendsBalances = dividendsFor.get(dividend);
        if (!dividendsBalances)
            return new DividendFor_1.DividendFor(BigDecimal_1.default.fromString("0", securityInfo.decimals), securityInfo.decimals);
        const balance = dividendsBalances.get("0x" + target.toString().toUpperCase().substring(2));
        if (balance)
            return new DividendFor_1.DividendFor(BigDecimal_1.default.fromString(balance, securityInfo.decimals), securityInfo.decimals);
        return new DividendFor_1.DividendFor(BigDecimal_1.default.fromString("0", securityInfo.decimals), securityInfo.decimals);
    });
    singletonInstance.getDividends = jest.fn(async (address, dividend) => {
        if (dividend > dividends.length)
            return undefined;
        return dividends[dividend - 1];
    });
    singletonInstance.getDividendsCount = jest.fn(async (address) => {
        return dividends.length;
    });
    singletonInstance.getVotingFor = jest.fn(async (address, target, voting) => {
        const votingBalances = votingRightsFor.get(voting);
        if (!votingBalances)
            return new VotingFor_1.VotingFor(BigDecimal_1.default.fromString("0", securityInfo.decimals), securityInfo.decimals);
        const balance = votingBalances.get("0x" + target.toString().toUpperCase().substring(2));
        if (balance)
            return new VotingFor_1.VotingFor(BigDecimal_1.default.fromString(balance, securityInfo.decimals), securityInfo.decimals);
        return new VotingFor_1.VotingFor(BigDecimal_1.default.fromString("0", securityInfo.decimals), securityInfo.decimals);
    });
    singletonInstance.getVoting = jest.fn(async (address, voting) => {
        if (voting > votingRights.length)
            return undefined;
        return votingRights[voting - 1];
    });
    singletonInstance.getVotingsCount = jest.fn(async (address) => {
        return votingRights.length;
    });
    singletonInstance.getCouponFor = jest.fn(async (address, target, coupon) => {
        const couponsBalances = couponsFor.get(coupon);
        if (!couponsBalances)
            return BigDecimal_1.default.fromString("0", securityInfo.decimals);
        const balance = couponsBalances.get("0x" + target.toString().toUpperCase().substring(2));
        if (balance)
            return BigDecimal_1.default.fromString(balance, securityInfo.decimals);
        return BigDecimal_1.default.fromString("0", securityInfo.decimals);
    });
    singletonInstance.getCouponAmountFor = jest.fn(async (address, target, coupon) => {
        const numerator = "5";
        const denominator = "3";
        const recordDateReached = true;
        return {
            numerator,
            denominator,
            recordDateReached,
        };
    });
    singletonInstance.getCoupon = jest.fn(async (address, coupon) => {
        if (coupon > coupons.length)
            return undefined;
        return coupons[coupon - 1];
    });
    singletonInstance.getCouponCount = jest.fn(async (address) => {
        return coupons.length;
    });
    singletonInstance.getAccountSecurityRelationship = jest.fn(async (address, target) => { });
    singletonInstance.isPaused = jest.fn(async (address) => {
        return securityInfo.paused ?? false;
    });
    singletonInstance.isInternalKycActivated = jest.fn(async (address) => {
        return true;
    });
    singletonInstance.isExternallyGranted = jest.fn(async (address) => {
        return true;
    });
    singletonInstance.canTransferByPartition = jest.fn(async (address, sourceId, targetId, amount, partitionId, data, operatorData) => {
        const operator = user_account.evmAddress;
        if (securityInfo.paused)
            return [false, "0x40", ""];
        if (securityInfo.isWhiteList) {
            if (!(await singletonInstance.isAccountInControlList(address, operator)))
                return [false, "0x41", ""];
        }
        else {
            if (await singletonInstance.isAccountInControlList(address, operator))
                return [false, "0x41", ""];
        }
        if (securityInfo.isWhiteList) {
            if (!(await singletonInstance.isAccountInControlList(address, sourceId)))
                return [false, "0x42", ""];
        }
        else {
            if (await singletonInstance.isAccountInControlList(address, sourceId))
                return [false, "0x42", ""];
        }
        if (securityInfo.isWhiteList) {
            if (!(await singletonInstance.isAccountInControlList(address, targetId)))
                return [false, "0x43", ""];
        }
        else {
            if (await singletonInstance.isAccountInControlList(address, targetId))
                return [false, "0x43", ""];
        }
        if (!sourceId)
            return [false, "0x44", ""];
        if (!targetId)
            return [false, "0x45", ""];
        const balance = await singletonInstance.balanceOfByPartition(address, sourceId, partitionId);
        if (amount.isLowerThan(balance))
            return [false, "0x46", ""];
        if (sourceId.toString().toUpperCase != operator.toString().toUpperCase &&
            !singletonInstance.hasRole(SecurityRole_1.SecurityRole._CONTROLLIST_ROLE)) {
            if (!(singletonInstance.isOperatorForPartition(address, partitionId, operator, sourceId) ||
                singletonInstance.isOperator(address, operator, sourceId)))
                return [false, "0x47", ""];
        }
        if (!balance)
            return [false, "0x48", ""];
        if (!singletonInstance.getKycStatusFor(address, sourceId))
            return [false, "0x50", ""];
        if (!singletonInstance.getKycStatusFor(address, targetId))
            return [false, "0x51", ""];
        if (securityInfo.clearingActive)
            return [false, "0x52", ""];
        return [true, "0x01", ""];
    });
    singletonInstance.canTransfer = jest.fn(async (address, targetId, amount, data) => {
        const operator = user_account.evmAddress;
        if (securityInfo.paused)
            return [false, "0x40", ""];
        if (securityInfo.isWhiteList) {
            if (!(await singletonInstance.isAccountInControlList(address, operator)))
                return [false, "0x42", ""];
        }
        else {
            if (await singletonInstance.isAccountInControlList(address, operator))
                return [false, "0x42", ""];
        }
        if (securityInfo.isWhiteList) {
            if (!(await singletonInstance.isAccountInControlList(address, targetId)))
                return [false, "0x43", ""];
        }
        else {
            if (await singletonInstance.isAccountInControlList(address, targetId))
                return [false, "0x43", ""];
        }
        if (!targetId)
            return [false, "0x45", ""];
        const balance = await singletonInstance.balanceOfByPartition(address, operator);
        if (amount.isLowerThan(balance))
            return [false, "0x46", ""];
        if (!singletonInstance.getKycStatusFor(address, operator))
            return [false, "0x50", ""];
        if (!singletonInstance.getKycStatusFor(address, targetId))
            return [false, "0x51", ""];
        if (securityInfo.clearingActive)
            return [false, "0x52", ""];
        return [true, "0x01", ""];
    });
    singletonInstance.canRedeemByPartition = jest.fn(async (address, sourceId, amount, partitionId, data, operatorData) => {
        const operator = user_account.evmAddress;
        if (securityInfo.paused)
            return [false, "0x40", ""];
        if (securityInfo.isWhiteList) {
            if (!(await singletonInstance.isAccountInControlList(address, operator)))
                return [false, "0x41", ""];
        }
        else {
            if (await singletonInstance.isAccountInControlList(address, operator))
                return [false, "0x41", ""];
        }
        if (securityInfo.isWhiteList) {
            if (!(await singletonInstance.isAccountInControlList(address, sourceId)))
                return [false, "0x42", ""];
        }
        else {
            if (await singletonInstance.isAccountInControlList(address, sourceId))
                return [false, "0x42", ""];
        }
        if (!sourceId)
            return [false, "0x44", ""];
        const balance = await singletonInstance.balanceOfByPartition(address, sourceId, partitionId);
        if (amount.isLowerThan(balance))
            return [false, "0x46", ""];
        if (sourceId.toString().toUpperCase != operator.toString().toUpperCase &&
            !singletonInstance.hasRole(SecurityRole_1.SecurityRole._CONTROLLIST_ROLE)) {
            if (!(singletonInstance.isOperatorForPartition(address, partitionId, operator, sourceId) ||
                singletonInstance.isOperator(address, operator, sourceId)))
                return [false, "0x47", ""];
        }
        if (!balance)
            return [false, "0x48", ""];
        if (!singletonInstance.getKycStatusFor(address, sourceId))
            return [false, "0x50", ""];
        if (securityInfo.clearingActive)
            return [false, "0x52", ""];
        return [true, "0x01", ""];
    });
    singletonInstance.getDocument = jest.fn(async (address, name) => {
        return ["", "", ethers_1.BigNumber.from(0)];
    });
    singletonInstance.getAllDocuments = jest.fn(async (address) => {
        return ["mock_document"];
    });
    singletonInstance.isOperatorForPartition = jest.fn(async (address, partitionId, operator, target) => {
        return true;
    });
    singletonInstance.isOperator = jest.fn(async (address, operator, target) => {
        return true;
    });
    singletonInstance.getScheduledSnapshots = jest.fn(async (address, start, end) => {
        return [new ScheduledSnapshot_1.ScheduledSnapshot(ethers_1.BigNumber.from("43756347647"), "data")];
    });
    singletonInstance.scheduledSnapshotCount = jest.fn(async (address) => {
        return 0;
    });
    singletonInstance.getMaxSupply = jest.fn(async (address) => {
        return securityInfo.maxSupply;
    });
    singletonInstance.getRegulationDetails = jest.fn(async (type, subType, factoryAddress) => {
        return {
            type: RegulationType_1.CastRegulationType.fromNumber(type),
            subType: RegulationType_1.CastRegulationSubType.fromNumber(subType),
            dealSize: "0",
            accreditedInvestors: "ACCREDITATION REQUIRED",
            maxNonAccreditedInvestors: 0,
            manualInvestorVerification: "VERIFICATION INVESTORS FINANCIAL DOCUMENTS REQUIRED",
            internationalInvestors: "ALLOWED",
            resaleHoldPeriod: "NOT APPLICABLE",
        };
    });
    singletonInstance.getLockedBalanceOf = jest.fn(async (address, target) => {
        const lockedBalance = lockedBalances.get("0x" + target.toString().toUpperCase().substring(2));
        if (lockedBalance)
            return ethers_1.BigNumber.from(BigDecimal_1.default.fromString(lockedBalance, securityInfo.decimals));
        return ethers_1.BigNumber.from(BigDecimal_1.default.fromString("0", securityInfo.decimals));
    });
    singletonInstance.getLockCount = jest.fn(async (address, target) => {
        const lockIds = locksIds.get("0x" + target.toString().toUpperCase().substring(2));
        if (lockIds)
            return lockIds.length;
        return 0;
    });
    singletonInstance.getLocksId = jest.fn(async (address, target, start, end) => {
        const lockIds = locksIds.get("0x" + target.toString().toUpperCase().substring(2));
        if (!lockIds)
            return [];
        const returnedLocksId = [];
        for (let i = start; i < end; i++) {
            returnedLocksId.push(ethers_1.BigNumber.from(lockIds[i]));
        }
        return returnedLocksId;
    });
    singletonInstance.getLock = jest.fn(async (address, target, lockId) => {
        const accountLocks = locks.get("0x" + target.toString().toUpperCase().substring(2));
        if (!accountLocks)
            return [ethers_1.BigNumber.from(0), ethers_1.BigNumber.from(0)];
        const accountLock = accountLocks.get(lockId);
        if (!accountLock)
            return [ethers_1.BigNumber.from(0), ethers_1.BigNumber.from(0)];
        return accountLock;
    });
    singletonInstance.getConfigInfo = jest.fn(async (address) => {
        return [resolverAddress, configId, configVersion];
    });
    singletonInstance.getScheduledBalanceAdjustment = jest.fn(async (address, balanceAdjustmentId) => {
        if (balanceAdjustmentId > scheduledBalanceAdjustments.length)
            return undefined;
        return scheduledBalanceAdjustments[balanceAdjustmentId - 1];
    });
    singletonInstance.getScheduledBalanceAdjustmentCount = jest.fn(async function (security) {
        return scheduledBalanceAdjustments.length;
    });
    singletonInstance.getLastAggregatedBalanceAdjustmentFactorFor = jest.fn(async function (security, target) {
        return Math.random();
    });
    singletonInstance.getAggregatedBalanceAdjustmentFactor = jest.fn(async function (security) {
        return Math.random();
    });
    singletonInstance.getLastAggregatedBalanceAdjustmentFactorForByPartition = jest.fn(async function (security, target, partitionId) {
        return Math.random();
    });
    singletonInstance.arePartitionsProtected = jest.fn(async (address) => {
        return securityInfo.arePartitionsProtected ?? false;
    });
    singletonInstance.getNounceFor = jest.fn(async (address, target) => {
        const account = "0x" + target.toString().toUpperCase().substring(2);
        return nonces.get(account) ?? new BigDecimal_1.default("0").toBigNumber();
    });
    singletonInstance.getKycStatusFor = jest.fn(async (address, target) => {
        const account = "0x" + target.toString().toUpperCase().substring(2);
        const kycAccounts = kycAccountsByStatus.get(1) || [];
        return kycAccounts.includes(account) ? 1 : 0;
    });
    singletonInstance.getKycAccountsData = jest.fn(async (address, kycStatus, start, end) => {
        const accounts = kycAccountsByStatus.get(kycStatus) || [];
        const kycDataArray = accounts
            .map((account) => {
            const kycData = kycAccountsData.get(account);
            return kycData
                ? new KycAccountData_1.KycAccountData(account, kycData.validFrom.toString(), kycData.validTo.toString(), kycData.vcId, kycData.issuer, kycData.status)
                : null;
        })
            .filter((data) => data !== null)
            .slice(start, end);
        return kycDataArray;
    });
    singletonInstance.getKycFor = jest.fn(async (address, target) => {
        const account = "0x" + target.toString().toUpperCase().substring(2);
        return kycAccountsData.get(account);
    });
    singletonInstance.getKycAccountsCount = jest.fn(async (address, kycStatus) => {
        const kycAccounts = kycAccountsByStatus.get(1) || [];
        return kycAccounts.length;
    });
    singletonInstance.getHeldAmountFor = jest.fn(async (address, targetId) => {
        const heldBalance = heldBalances.get("0x" + targetId.toString().toUpperCase().substring(2));
        if (heldBalance)
            return heldBalance;
        return 0;
    });
    singletonInstance.getClearedAmountFor = jest.fn(async (address, targetId) => {
        const clearedBalance = clearedBalances.get("0x" + targetId.toString().toUpperCase().substring(2));
        if (clearedBalance)
            return Number(clearedBalance);
        return 0;
    });
    singletonInstance.getClearingCountForByPartition = jest.fn(async (address, partitionId, targetId, clearingOperationType) => {
        const clearingIds = clearingsIds
            .get("0x" + targetId.toString().toUpperCase().substring(2))
            ?.get(clearingOperationType);
        if (clearingIds)
            return clearingIds.length;
        return 0;
    });
    singletonInstance.getClearingsIdForByPartition = jest.fn(async (address, partitionId, target, clearingOperationType, start, end) => {
        const clearingIds = clearingsIds
            .get("0x" + target.toString().toUpperCase().substring(2))
            ?.get(clearingOperationType);
        if (!clearingIds)
            return [];
        return clearingIds;
    });
    singletonInstance.getHoldCountForByPartition = jest.fn(async (address, partitionId, targetId) => {
        const holdIds = holdsIds.get("0x" + targetId.toString().toUpperCase().substring(2));
        if (holdIds)
            return holdIds.length;
        return 0;
    });
    singletonInstance.getHoldsIdForByPartition = jest.fn(async (address, partitionId, target, start, end) => {
        const holdIds = holdsIds.get("0x" + target.toString().toUpperCase().substring(2));
        if (!holdIds)
            return [];
        return holdIds;
    });
    singletonInstance.getHoldForByPartition = jest.fn(async (address, partitionId, targetId, holdId) => {
        const accountHolds = holds.get("0x" + targetId.toString().toUpperCase().substring(2));
        const emptyHold = new Hold_1.HoldDetails(0, new BigDecimal_1.default(ethers_1.BigNumber.from(0)), "", "", "", "", "");
        if (!accountHolds)
            return emptyHold;
        const accountHold = accountHolds.get(holdId);
        if (!accountHold)
            return emptyHold;
        return accountHold[0];
    });
    singletonInstance.isIssuer = jest.fn(async (address, issuer) => {
        const account = identifiers(issuer.toString())[1];
        return issuerList.findIndex((item) => item == account) !== -1;
    });
    singletonInstance.isClearingActivated = jest.fn(async (address) => {
        return securityInfo.clearingActive;
    });
    singletonInstance.getClearingRedeemForByPartition = jest.fn(async (address, partitionId, targetId, clearingId) => {
        const accountClearings = clearings.get("0x" + targetId.toString().toUpperCase().substring(2));
        const emptyClearingRedeem = new Clearing_1.ClearingRedeem(new BigDecimal_1.default(ethers_1.BigNumber.from(0)), 0, "", "");
        if (!accountClearings)
            return emptyClearingRedeem;
        const accountClearingRedeem = accountClearings.get(clearingId);
        if (!accountClearingRedeem)
            return emptyClearingRedeem;
        return accountClearingRedeem[0];
    });
    singletonInstance.getClearingCreateHoldForByPartition = jest.fn(async (address, partitionId, targetId, clearingId) => {
        const accountClearings = clearings.get("0x" + targetId.toString().toUpperCase().substring(2));
        const emptyClearingCreateHold = new Clearing_1.ClearingHoldCreation(new BigDecimal_1.default(ethers_1.BigNumber.from(0)), 0, "", "", "", 0, "", "");
        if (!accountClearings)
            return emptyClearingCreateHold;
        const accountClearingCreateHold = accountClearings.get(clearingId);
        if (!accountClearingCreateHold)
            return emptyClearingCreateHold;
        return accountClearingCreateHold[0];
    });
    singletonInstance.getClearingTransferForByPartition = jest.fn(async (address, partitionId, targetId, clearingId) => {
        const accountClearings = clearings.get("0x" + targetId.toString().toUpperCase().substring(2));
        const emptyClearingTransfer = new Clearing_1.ClearingTransfer(new BigDecimal_1.default(ethers_1.BigNumber.from(0)), 0, "", "", "");
        if (!accountClearings)
            return emptyClearingTransfer;
        const accountClearingTransfer = accountClearings.get(clearingId);
        if (!accountClearingTransfer)
            return emptyClearingTransfer;
        return accountClearingTransfer[0];
    });
    singletonInstance.isExternalPause = jest.fn(async (address, externalPauseAddress) => {
        const account = identifiers(externalPauseAddress.toString())[1];
        return externalPausesList.findIndex((item) => item == account) !== -1;
    });
    singletonInstance.getExternalPausesCount = jest.fn(async (address) => {
        return externalPausesList.length;
    });
    singletonInstance.getExternalPausesMembers = jest.fn(async (address, start, end) => {
        const externalPausesListMembers = [];
        for (let i = start; i < end; i++) {
            externalPausesListMembers.push(externalPausesList[i]);
        }
        return externalPausesListMembers;
    });
    return {
        RPCQueryAdapter: jest.fn(() => singletonInstance),
    };
});
jest.mock("@port/out/rpc/RPCTransactionAdapter", () => {
    const actual = jest.requireActual("@port/out/rpc/RPCTransactionAdapter.ts");
    const singletonInstance = new actual.RPCTransactionAdapter();
    singletonInstance.createEquity = jest.fn(async (_securityInfo, _equityInfo, _factory, _resolver, _configId, _configVersion, _compliance, _identityRegistryAddress, _externalPauses, _diamondOwnerAccount) => {
        securityInfo = _securityInfo;
        const ids = identifiers(securityEvmAddress);
        securityInfo.diamondAddress = HederaId_1.HederaId.from(ids[0]);
        securityInfo.evmDiamondAddress = new EvmAddress_1.default(ids[1]);
        securityInfo.type = SecurityType_1.SecurityType.EQUITY;
        securityInfo.regulation = {
            type: _securityInfo.regulationType ?? "",
            subType: _securityInfo.regulationsubType ?? "",
            dealSize: "0",
            accreditedInvestors: "ACCREDITATION REQUIRED",
            maxNonAccreditedInvestors: 0,
            manualInvestorVerification: "VERIFICATION INVESTORS FINANCIAL DOCUMENTS REQUIRED",
            internationalInvestors: "ALLOWED",
            resaleHoldPeriod: "NOT APPLICABLE",
        };
        equityInfo = _equityInfo;
        configVersion = _configVersion;
        configId = _configId;
        resolverAddress = _resolver.toString();
        externalPausesList = _externalPauses?.map((address) => address.toString()) ?? [];
        return {
            status: "success",
            id: transactionId,
            response: {
                equityAddress: securityEvmAddress,
            },
        };
    });
    singletonInstance.createBond = jest.fn(createBondMockImplementation);
    singletonInstance.init = jest.fn(async () => {
        return network;
    });
    singletonInstance.register = jest.fn(async (account) => {
        user_account = account;
        Injectable_1.default.registerTransactionHandler(singletonInstance);
        return {};
    });
    singletonInstance.stop = jest.fn(async () => {
        return true;
    });
    singletonInstance.controllerTransfer = jest.fn(async (address, sourceId, targetId, amount) => {
        increaseBalance(targetId, amount);
        decreaseBalance(sourceId, amount);
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.controllerRedeem = jest.fn(async (address, sourceId, amount) => {
        decreaseBalance(sourceId, amount);
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.issue = jest.fn(async (security, targetId, amount) => {
        increaseBalance(targetId, amount);
        const totalSupply = securityInfo.totalSupply ? securityInfo.totalSupply : BigDecimal_1.default.fromString("0");
        securityInfo.totalSupply = BigDecimal_1.default.fromString(totalSupply.toBigNumber().add(amount.toBigNumber()).toString());
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.transfer = jest.fn(async (address, targetId, amount) => {
        increaseBalance(targetId, amount);
        const currentAccount = new EvmAddress_1.default(identifiers(user_account.id)[1]);
        decreaseBalance(currentAccount, amount);
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.transferAndLock = jest.fn(async (address, targetId, amount, expirationDate) => {
        const account = "0x" + targetId.toString().toUpperCase().substring(2);
        const accountLocks = locks.get(account);
        const lockIds = locksIds.get(account);
        const lastLockId = lastLockIds.get(account) ?? 0;
        const newLastLockId = lastLockId + 1;
        if (!lockIds)
            locksIds.set(account, [newLastLockId]);
        else {
            lockIds.push(newLastLockId);
            locksIds.set(account, lockIds);
        }
        if (!accountLocks) {
            const newLock = new Map();
            newLock.set(newLastLockId, [expirationDate.toString(), amount.toString()]);
            locks.set(account, newLock);
        }
        else {
            accountLocks.set(newLastLockId, [expirationDate.toString(), amount.toString()]);
            locks.set(account, accountLocks);
        }
        increaseLockedBalance(targetId, amount);
        const currentAccount = new EvmAddress_1.default(identifiers(user_account.id)[1]);
        decreaseBalance(currentAccount, amount);
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.redeem = jest.fn(async (address, amount) => {
        const currentAccount = new EvmAddress_1.default(identifiers(user_account.id)[1]);
        decreaseBalance(currentAccount, amount);
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.addIssuer = jest.fn(async (address, issuerId) => {
        const account = identifiers(issuerId.toString())[1];
        if (issuerList.findIndex((item) => item == account) == -1) {
            issuerList.push(account);
        }
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.removeIssuer = jest.fn(async (address, issuerId) => {
        const account = identifiers(issuerId.toString())[1];
        if (issuerList.findIndex((item) => item == account) !== -1) {
            issuerList = issuerList.filter((item) => item !== account);
        }
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.setRevocationRegistryAddress = jest.fn(async function (security, revocationRegistry) {
        revocationRegistryAddress = revocationRegistry.toString();
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.addToControlList = jest.fn(async (address, targetId) => {
        const account = identifiers(targetId.toString())[1];
        if (controlList.findIndex((item) => item == account) == -1) {
            controlList.push(account);
        }
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.removeFromControlList = jest.fn(async (address, targetId) => {
        const account = identifiers(targetId.toString())[1];
        if (controlList.findIndex((item) => item == account) !== -1) {
            controlList = controlList.filter((item) => item !== account);
        }
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.pause = jest.fn(async () => {
        securityInfo.paused = true;
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.unpause = jest.fn(async () => {
        securityInfo.paused = false;
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.takeSnapshot = jest.fn(async () => {
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.setDividends = jest.fn(async (address, recordDate, executionDate, amount) => {
        const dividend = new Dividend_1.Dividend(amount, amount.decimals, parseInt(recordDate.toString()), parseInt(executionDate.toString()), 0);
        dividends.push(dividend);
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.setVotingRights = jest.fn(async (address, recordDate, data) => {
        const votingRight = new VotingRights_1.VotingRights(parseInt(recordDate.toString()), data, 0);
        votingRights.push(votingRight);
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.setCoupon = jest.fn(async (address, recordDate, executionDate, rate) => {
        const coupon = new Coupon_1.Coupon(parseInt(recordDate.toString()), parseInt(executionDate.toString()), rate, rate.decimals, 0);
        coupons.push(coupon);
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.setDocument = jest.fn(async () => {
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.removeDocument = jest.fn(async () => {
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.authorizeOperator = jest.fn(async () => {
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.revokeOperator = jest.fn(async () => {
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.authorizeOperatorByPartition = jest.fn(async () => {
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.revokeOperatorByPartition = jest.fn(async () => {
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.operatorTransferByPartition = jest.fn(async () => {
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.triggerPendingScheduledSnapshots = jest.fn(async () => {
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.triggerScheduledSnapshots = jest.fn(async () => {
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.setMaxSupply = jest.fn(async (address, amount) => {
        securityInfo.maxSupply = amount;
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.lock = jest.fn(async () => {
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.release = jest.fn(async (address, sourceId, lockIdBd) => {
        const account = "0x" + sourceId.toString().toUpperCase().substring(2);
        const lockId = lockIdBd.toBigNumber().toNumber();
        const accountLocks = locks.get(account);
        let lockIds = locksIds.get(account);
        let amount = BigDecimal_1.default.fromString("0");
        if (accountLocks) {
            const values = accountLocks.get(lockId);
            if (values)
                amount = BigDecimal_1.default.fromString(values[1]);
            accountLocks.set(lockId, ["0", "0"]);
        }
        if (lockIds) {
            lockIds = lockIds.filter((id) => id !== lockId);
            locksIds.set(account, lockIds);
        }
        decreaseLockedBalance(sourceId, amount);
        increaseBalance(sourceId, amount);
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.grantRole = jest.fn(async (address, targetId, role) => {
        const account = identifiers(targetId.toString())[1];
        grantRole(account, role);
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.applyRoles = jest.fn(async (address, targetId, roles, actives) => {
        const account = identifiers(targetId.toString())[1];
        for (let i = 0; i < roles.length; i++) {
            if (actives[i])
                grantRole(account, roles[i]);
            else
                revokeRole(account, roles[i]);
        }
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.revokeRole = jest.fn(async (address, targetId, role) => {
        const account = identifiers(targetId.toString())[1];
        revokeRole(account, role);
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.renounceRole = jest.fn(async () => {
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.hasRole = jest.fn(async () => {
        return { status: "success", data: true };
    });
    singletonInstance.getRolesFor = jest.fn(async () => {
        return { status: "success", data: [] };
    });
    singletonInstance.getRoleMembers = jest.fn(async () => {
        return { status: "success", data: [] };
    });
    singletonInstance.getRoleCountFor = jest.fn(async () => {
        return { status: "success", data: 0 };
    });
    singletonInstance.getRoleMemberCount = jest.fn(async () => {
        return { status: "success", data: 0 };
    });
    singletonInstance.getAccount = jest.fn(() => {
        return user_account;
    });
    singletonInstance.getMirrorNodeAdapter = jest.fn(() => {
        return {};
    });
    singletonInstance.updateResolver = jest.fn(async function (security, _resolver, _configVersion, _configId) {
        configVersion = _configVersion;
        configId = _configId;
        resolverAddress = _resolver.toString();
        return { status: "success", data: [] };
    });
    singletonInstance.updateConfigVersion = jest.fn(async function (security, _configVersion) {
        configVersion = _configVersion;
        return { status: "success", data: [] };
    });
    singletonInstance.updateConfig = jest.fn(async function (security, _configId, _configVersion) {
        configVersion = _configVersion;
        configId = _configId;
        return { status: "success", data: [] };
    });
    singletonInstance.updateMaturityDate = jest.fn(async function (security, _maturityDate) {
        bondInfo = new BondDetails_1.BondDetails(bondInfo.currency, bondInfo.nominalValue, bondInfo.nominalValueDecimals, bondInfo.startingDate, _maturityDate);
        return { status: "success", data: [] };
    });
    singletonInstance.setScheduledBalanceAdjustment = jest.fn(async function (security, _executionDate, _factor, _decimals) {
        const scheduledBalanceAdjustment = new ScheduledBalanceAdjustment_1.ScheduledBalanceAdjustment(parseInt(_executionDate.toString()), parseInt(_factor.toString()), parseInt(_decimals.toString()));
        scheduledBalanceAdjustments.pop();
        scheduledBalanceAdjustments.push(scheduledBalanceAdjustment);
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.protectPartitions = jest.fn(async () => {
        securityInfo.arePartitionsProtected = true;
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.unprotectPartitions = jest.fn(async () => {
        securityInfo.arePartitionsProtected = false;
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.protectedTransferFromByPartition = jest.fn(async (security, partitionId, sourceId, targetId, amount, deadline, nounce, signature) => {
        increaseBalance(targetId, amount);
        decreaseBalance(sourceId, amount);
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.protectedRedeemFromByPartition = jest.fn(async (security, partitionId, sourceId, amount, deadline, nounce, signature) => {
        decreaseBalance(sourceId, amount);
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.protectedTransferAndLockByPartition = jest.fn(async (security, partitionId, amount, sourceId, targetId, expirationDate, deadline, nounce, signature) => {
        const account = "0x" + targetId.toString().toUpperCase().substring(2);
        const accountLocks = locks.get(account);
        const lockIds = locksIds.get(account);
        const lastLockId = lastLockIds.get(account) ?? 0;
        const newLastLockId = lastLockId + 1;
        if (!lockIds)
            locksIds.set(account, [newLastLockId]);
        else {
            lockIds.push(newLastLockId);
            locksIds.set(account, lockIds);
        }
        if (!accountLocks) {
            const newLock = new Map();
            newLock.set(newLastLockId, [expirationDate.toString(), amount.toString()]);
            locks.set(account, newLock);
        }
        else {
            accountLocks.set(newLastLockId, [expirationDate.toString(), amount.toString()]);
            locks.set(account, accountLocks);
        }
        increaseLockedBalance(targetId, amount);
        decreaseBalance(sourceId, amount);
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.grantKyc = jest.fn(async (security, targetId, vcId, validFrom, validTo, issuer) => {
        const account = "0x" + targetId.toString().toUpperCase().substring(2);
        const kycStatus = 1;
        const kycAccounts = kycAccountsByStatus.get(kycStatus) || [];
        if (!kycAccounts.includes(account)) {
            kycAccounts.push(account);
            kycAccountsByStatus.set(kycStatus, kycAccounts);
            kycAccountsData.set(account, new Kyc_1.Kyc(validFrom.toString(), validTo.toString(), vcId, issuer.toString(), kycStatus));
        }
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.revokeKyc = jest.fn(async (security, targetId) => {
        const account = "0x" + targetId.toString().toUpperCase().substring(2);
        const kycStatus = 1;
        let kycAccounts = kycAccountsByStatus.get(kycStatus) || [];
        if (kycAccounts.includes(account)) {
            kycAccounts = kycAccounts.filter((kycAccount) => kycAccount !== account);
            kycAccountsByStatus.set(kycStatus, kycAccounts.length > 0 ? kycAccounts : []);
            kycAccountsData.delete(account);
            const revokedStatus = 0;
            const revokedAccounts = kycAccountsByStatus.get(revokedStatus) || [];
            if (!revokedAccounts.includes(account)) {
                revokedAccounts.push(account);
                kycAccountsByStatus.set(revokedStatus, revokedAccounts);
            }
        }
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.createHoldByPartition = jest.fn(async (address, partitionId, escrow, amount, targetId, expirationDate) => createHold(targetId, expirationDate, amount, escrow));
    singletonInstance.protectedCreateHoldByPartition = jest.fn(async (security, partitionId, amount, escrow, sourceId, targetId, expirationDate, deadline, nonce, signature) => createHold(sourceId, expirationDate, amount, escrow, targetId));
    singletonInstance.releaseHoldByPartition = jest.fn(async (security, partitionId, holdId, targetId, amount) => {
        const accountHolds = holds.get("0x" + targetId.toString().toUpperCase().substring(2));
        const holdEntry = accountHolds?.get(holdId);
        const heldAmount = holdEntry && holdEntry.length > 0 ? holdEntry[0].amount : BigDecimal_1.default.fromString("0");
        decreaseHeldBalance(targetId, heldAmount);
        const currentAccount = new EvmAddress_1.default(identifiers(user_account.id)[1]);
        increaseBalance(currentAccount, heldAmount);
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.executeHoldByPartition = jest.fn(async (security, sourceId, targetId, amount, partitionId, holdId) => {
        decreaseHeldBalance(sourceId, amount);
        increaseBalance(targetId, amount);
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.clearingCreateHoldByPartition = jest.fn(async (address, partitionId, escrow, amount, targetId, clearingExpirationDate, holdExpirationDate) => createClearing(clearingExpirationDate, amount, Clearing_1.ClearingOperationType.HoldCreation, targetId, escrow, holdExpirationDate));
    singletonInstance.operatorClearingCreateHoldByPartition = jest.fn(async (address, partitionId, escrow, amount, sourceId, targetId, clearingExpirationDate, holdExpirationDate) => createClearing(clearingExpirationDate, amount, Clearing_1.ClearingOperationType.HoldCreation, targetId, escrow, holdExpirationDate));
    singletonInstance.protectedClearingCreateHoldByPartition = jest.fn(async (address, partitionId, amount, escrow, sourceId, targetId, clearingExpirationDate, holdExpirationDate, deadline, nonce, signature) => createClearing(clearingExpirationDate, amount, Clearing_1.ClearingOperationType.HoldCreation, sourceId, escrow, holdExpirationDate));
    singletonInstance.clearingRedeemByPartition = jest.fn(async (address, partitionId, amount, expirationDate) => createClearing(expirationDate, amount, Clearing_1.ClearingOperationType.Redeem));
    singletonInstance.operatorClearingRedeemByPartition = jest.fn(async (address, partitionId, amount, sourceId, expirationDate) => createClearing(expirationDate, amount, Clearing_1.ClearingOperationType.Redeem));
    singletonInstance.protectedClearingRedeemByPartition = jest.fn(async (address, partitionId, amount, sourceId, expirationDate, deadline, nonce, signature) => createClearing(expirationDate, amount, Clearing_1.ClearingOperationType.Redeem, sourceId));
    singletonInstance.clearingTransferByPartition = jest.fn(async (address, partitionId, amount, targetId, expirationDate) => createClearing(expirationDate, amount, Clearing_1.ClearingOperationType.Transfer, targetId));
    singletonInstance.operatorClearingTransferByPartition = jest.fn(async (address, partitionId, amount, sourceId, targetId, expirationDate) => createClearing(expirationDate, amount, Clearing_1.ClearingOperationType.Transfer, targetId));
    singletonInstance.protectedClearingTransferByPartition = jest.fn(async (address, partitionId, amount, sourceId, targetId, expirationDate, deadline, nonce, signature) => createClearing(expirationDate, amount, Clearing_1.ClearingOperationType.Transfer, sourceId));
    singletonInstance.activateClearing = jest.fn(async (address) => {
        securityInfo.clearingActive = true;
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.deactivateClearing = jest.fn(async (address) => {
        securityInfo.clearingActive = false;
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.cancelClearingOperationByPartition = jest.fn(async (security, partitionId, targetId, clearingId, clearingOperationType) => processClearingOperation(targetId, clearingId, clearingOperationType));
    singletonInstance.reclaimClearingOperationByPartition = jest.fn(async (security, partitionId, targetId, clearingId, clearingOperationType) => processClearingOperation(targetId, clearingId, clearingOperationType));
    singletonInstance.approveClearingOperationByPartition = jest.fn(async (security, partitionId, targetId, clearingId, clearingOperationType) => processClearingOperation(targetId, clearingId, clearingOperationType));
    singletonInstance.updateExternalPauses = jest.fn(async (address, externalPausesAddresses) => {
        externalPausesAddresses.forEach((externalPauseAddress) => {
            const account = identifiers(externalPauseAddress.toString())[1];
            if (externalPausesList.findIndex((item) => item == account) == -1) {
                externalPausesList.push(account);
            }
        });
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.addExternalPause = jest.fn(async (address, externalPauseAddress) => {
        const account = identifiers(externalPauseAddress.toString())[1];
        if (externalPausesList.findIndex((item) => item == account) == -1) {
            externalPausesList.push(account);
        }
        return {
            status: "success",
            id: transactionId,
        };
    });
    singletonInstance.removeExternalPause = jest.fn(async (address, externalPauseAddress) => {
        const account = identifiers(externalPauseAddress.toString())[1];
        if (externalPausesList.findIndex((item) => item == account) !== -1) {
            externalPausesList = externalPausesList.filter((item) => item !== account);
        }
        return {
            status: "success",
            id: transactionId,
        };
    });
    return {
        RPCTransactionAdapter: jest.fn(() => singletonInstance),
    };
});
jest.mock("@port/out/hs/hts/custodial/DFNSTransactionAdapter", () => {
    const actual = jest.requireActual("@port/out/hs/hts/custodial/DFNSTransactionAdapter.ts");
    const singletonInstance = new actual.DFNSTransactionAdapter();
    singletonInstance.init = jest.fn(async () => {
        return network;
    });
    return {
        DFNSTransactionAdapter: jest.fn(() => singletonInstance),
    };
});
jest.mock("@port/out/hs/hts/custodial/FireblocksTransactionAdapter", () => {
    const actual = jest.requireActual("@port/out/hs/hts/custodial/FireblocksTransactionAdapter.ts");
    const singletonInstance = new actual.FireblocksTransactionAdapter();
    singletonInstance.init = jest.fn(async () => {
        return network;
    });
    return {
        FireblocksTransactionAdapter: jest.fn(() => singletonInstance),
    };
});
jest.mock("@port/out/hs/hts/custodial/AWSKMSTransactionAdapter", () => {
    const actual = jest.requireActual("@port/out/hs/hts/custodial/AWSKMSTransactionAdapter.ts");
    const singletonInstance = new actual.AWSKMSTransactionAdapter();
    singletonInstance.init = jest.fn(async () => {
        return network;
    });
    return {
        AWSKMSTransactionAdapter: jest.fn(() => singletonInstance),
    };
});
jest.mock("@port/out/hs/hts/custodial/CustodialTransactionAdapter", () => {
    const actual = jest.requireActual("@port/out/hs/hts/custodial/CustodialTransactionAdapter.ts");
    const singletonInstance = new actual.CustodialTransactionAdapter();
    singletonInstance.register = jest.fn(async (settings) => {
        Injectable_1.default.registerTransactionHandler(singletonInstance);
        return {};
    });
    return {
        CustodialTransactionAdapter: jest.fn(() => singletonInstance),
    };
});
jest.mock("@port/out/hs/HederaTransactionAdapter", () => {
    const actual = jest.requireActual("@port/out/hs/HederaTransactionAdapter.ts");
    const singletonInstance = new actual.HederaTransactionAdapter();
    singletonInstance.createBond = jest.fn(createBondMockImplementation);
    singletonInstance.setupDisconnectEventHandler = jest.fn(async () => {
        return true;
    });
    return {
        HederaTransactionAdapter: jest.fn(() => singletonInstance),
    };
});
jest.mock("@port/out/mirror/MirrorNodeAdapter", () => {
    const actual = jest.requireActual("@port/out/mirror/MirrorNodeAdapter.ts");
    const MirrorNodeAdapterMock = new actual.MirrorNodeAdapter();
    MirrorNodeAdapterMock.set = jest.fn().mockResolvedValue("mocked set");
    MirrorNodeAdapterMock.getAccountInfo = jest.fn((accountId) => {
        const ids = identifiers(accountId);
        const response = {
            id: HederaId_1.HederaId.from(ids[0]),
            evmAddress: ids[1],
            alias: "anything",
            publicKey: config_1.CLIENT_PUBLIC_KEY_ECDSA,
        };
        return response;
    });
    MirrorNodeAdapterMock.getContractInfo = jest.fn((contractEvmAddress) => {
        let accountId;
        if (contractEvmAddress.toString().indexOf(".") !== -1) {
            accountId = HederaId_1.HederaId.from(contractEvmAddress);
        }
        else {
            accountId = contractEvmAddress;
        }
        const ids = identifiers(accountId);
        const response = {
            id: ids[0],
            evmAddress: ids[1],
        };
        return response;
    });
    MirrorNodeAdapterMock.getTransactionResult = jest.fn((transactionId) => {
        const response = {
            result: "resultMessage",
        };
        return response;
    });
    MirrorNodeAdapterMock.getTransactionFinalError = jest.fn((transactionId) => {
        const response = {
            result: "resultMessage",
        };
        return response;
    });
    MirrorNodeAdapterMock.accountToEvmAddress = jest.fn((accountId) => {
        const ids = identifiers(HederaId_1.HederaId.from(accountId));
        return ids[1];
    });
    MirrorNodeAdapterMock.getHBARBalance = jest.fn((accountId) => {
        const balance = HBAR_balances.get(identifiers(accountId)[1]);
        if (balance)
            return BigDecimal_1.default.fromString(balance, Constants_1.HBAR_DECIMALS);
        return BigDecimal_1.default.fromString("0", Constants_1.HBAR_DECIMALS);
    });
    MirrorNodeAdapterMock.getContractResults = jest.fn(async (transactionId, numberOfResultItems, timeout = 15, requestInterval = 2) => {
        return ["123", "1"];
    });
    return {
        MirrorNodeAdapter: jest.fn(() => MirrorNodeAdapterMock),
    };
});
