/*
                                 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.

*/
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-non-null-asserted-optional-chain */
/* eslint-disable @typescript-eslint/no-non-null-assertion */
/* eslint-disable no-case-declarations */
import { ContractCreateTransaction, ContractExecuteTransaction, ContractFunctionParameters, } from '@hashgraph/sdk';
import { AccessControlFacet__factory, Bond__factory, BondUSAFacet__factory, CapFacet__factory, ControlListFacet__factory, DiamondFacet__factory, EquityUSAFacet__factory, ERC1643Facet__factory, Factory__factory, LockFacet__factory, ScheduledCrossOrderedTasksFacet__factory, SnapshotsFacet__factory, TransferAndLockFacet__factory, SsiManagementFacet__factory, KycFacet__factory, ClearingTransferFacet__factory, ClearingRedeemFacet__factory, ClearingHoldCreationFacet__factory, ClearingActionsFacet__factory, ExternalPauseManagementFacet__factory, MockedExternalPause__factory, ExternalControlListManagementFacet__factory, MockedBlacklist__factory, MockedWhitelist__factory, ExternalKycListManagementFacet__factory, MockedExternalKycList__factory, FreezeFacet__factory, ERC1410TokenHolderFacet__factory, ERC1410ManagementFacet__factory, HoldTokenHolderFacet__factory, HoldManagementFacet__factory, ERC3643ManagementFacet__factory, ERC3643OperationsFacet__factory, ERC3643BatchFacet__factory, TREXFactoryAts__factory, ProceedRecipientsFacet__factory, ERC1410IssuerFacet__factory, } from '@hashgraph/asset-tokenization-contracts';
import { _PARTITION_ID_1, EVM_ZERO_ADDRESS, GAS } from '../../../core/Constants';
import TransactionAdapter from '../TransactionAdapter';
import { SigningError } from '../error/SigningError';
import LogService from '../../../app/service/log/LogService';
import { FactoryBondToken, FactoryEquityToken, FactoryRegulationData, } from '../../../domain/context/factory/FactorySecurityToken';
import { CastRegulationSubType, CastRegulationType, } from '../../../domain/context/factory/RegulationType';
import { SecurityRole } from '../../../domain/context/security/SecurityRole';
import { BondDetailsData } from '../../../domain/context/factory/BondDetailsData';
import { CastDividendType } from '../../../domain/context/equity/DividendType';
import { CastClearingOperationType, } from '../../../domain/context/security/Clearing';
import { MissingRegulationSubType } from '../../../domain/context/factory/error/MissingRegulationSubType';
import { MissingRegulationType } from '../../../domain/context/factory/error/MissingRegulationType';
import { Contract } from 'ethers';
export class HederaTransactionAdapter extends TransactionAdapter {
    constructor(mirrorNodeAdapter, networkService) {
        super();
        this.mirrorNodeAdapter = mirrorNodeAdapter;
        this.networkService = networkService;
    }
    async executeWithArgs(contractInstance, functionName, contractId, gas, args) {
        const encodedHex = contractInstance.interface.encodeFunctionData(functionName, args);
        const encoded = new Uint8Array(Buffer.from(encodedHex.slice(2), 'hex'));
        return this.buildAndSendTransaction(contractId, gas, (tx) => {
            tx.setFunctionParameters(encoded);
        });
    }
    async executeWithParams(contractId, gas, functionName, functionParameters) {
        return this.buildAndSendTransaction(contractId, gas, (tx) => {
            tx.setFunction(functionName, functionParameters);
        });
    }
    async buildAndSendTransaction(contractId, gas, setup) {
        const tx = new ContractExecuteTransaction()
            .setContractId(contractId)
            .setGas(gas);
        setup(tx);
        return this.signAndSendTransaction(tx);
    }
    // * Operations NOT Smart Contract related
    setMirrorNodes(mirrorNodes) {
        if (mirrorNodes)
            this.mirrorNodes = mirrorNodes;
    }
    setJsonRpcRelays(jsonRpcRelays) {
        if (jsonRpcRelays)
            this.jsonRpcRelays = jsonRpcRelays;
    }
    setFactories(factories) {
        if (factories)
            this.factories = factories;
    }
    setResolvers(resolvers) {
        if (resolvers)
            this.resolvers = resolvers;
    }
    setBusinessLogicKeysCommon(businessLogicKeys) {
        if (businessLogicKeys)
            this.businessLogicKeysCommon = businessLogicKeys;
    }
    setBusinessLogicKeysEquity(businessLogicKeys) {
        if (businessLogicKeys)
            this.businessLogicKeysEquity = businessLogicKeys;
    }
    setBusinessLogicKeysBond(businessLogicKeys) {
        if (businessLogicKeys)
            this.businessLogicKeysBond = businessLogicKeys;
    }
    async createEquity(securityInfo, equityInfo, factory, resolver, configId, configVersion, compliance, identityRegistryAddress, externalPauses, externalControlLists, externalKycLists, diamondOwnerAccount, factoryId) {
        try {
            if (!securityInfo.regulationType) {
                throw new MissingRegulationType();
            }
            if (!securityInfo.regulationsubType) {
                throw new MissingRegulationSubType();
            }
            const rbacAdmin = {
                role: SecurityRole._DEFAULT_ADMIN_ROLE,
                members: [diamondOwnerAccount.toString()],
            };
            const rbacs = [rbacAdmin];
            const erc20MetadataInfo = {
                name: securityInfo.name,
                symbol: securityInfo.symbol,
                isin: securityInfo.isin,
                decimals: securityInfo.decimals,
            };
            const resolverProxyConfiguration = {
                key: configId,
                version: configVersion,
            };
            const security = {
                arePartitionsProtected: securityInfo.arePartitionsProtected,
                isMultiPartition: securityInfo.isMultiPartition,
                resolver: resolver.toString(),
                resolverProxyConfiguration: resolverProxyConfiguration,
                rbacs: rbacs,
                isControllable: securityInfo.isControllable,
                isWhiteList: securityInfo.isWhiteList,
                maxSupply: securityInfo.maxSupply
                    ? securityInfo.maxSupply.toString()
                    : '0',
                erc20VotesActivated: securityInfo.erc20VotesActivated,
                erc20MetadataInfo: erc20MetadataInfo,
                clearingActive: securityInfo.clearingActive,
                internalKycActivated: securityInfo.internalKycActivated,
                externalPauses: externalPauses?.map((address) => address.toString()) ?? [],
                externalControlLists: externalControlLists?.map((address) => address.toString()) ?? [],
                externalKycLists: externalKycLists?.map((address) => address.toString()) ?? [],
                compliance: compliance.toString(),
                identityRegistry: identityRegistryAddress?.toString(),
            };
            const equityDetails = {
                votingRight: equityInfo.votingRight,
                informationRight: equityInfo.informationRight,
                liquidationRight: equityInfo.liquidationRight,
                subscriptionRight: equityInfo.subscriptionRight,
                conversionRight: equityInfo.conversionRight,
                redemptionRight: equityInfo.redemptionRight,
                putRight: equityInfo.putRight,
                dividendRight: CastDividendType.toNumber(equityInfo.dividendRight),
                currency: equityInfo.currency,
                nominalValue: equityInfo.nominalValue.toString(),
                nominalValueDecimals: equityInfo.nominalValueDecimals,
            };
            const securityTokenToCreate = new FactoryEquityToken(security, equityDetails);
            const additionalSecurityData = {
                countriesControlListType: securityInfo.isCountryControlListWhiteList,
                listOfCountries: securityInfo.countries ?? '',
                info: securityInfo.info ?? '',
            };
            const factoryRegulationData = new FactoryRegulationData(CastRegulationType.toNumber(securityInfo.regulationType), CastRegulationSubType.toNumber(securityInfo.regulationsubType), additionalSecurityData);
            LogService.logTrace(`Deploying equity: ${{
                security: securityTokenToCreate,
            }}`);
            return this.executeWithArgs(new Factory__factory().attach(factory.toString()), 'deployEquity', factoryId, GAS.CREATE_EQUITY_ST, [securityTokenToCreate, factoryRegulationData]);
        }
        catch (error) {
            LogService.logError(error);
            throw new SigningError(`Unexpected error in HederaTransactionAdapter create operation : ${error}`);
        }
    }
    async createBond(securityInfo, bondInfo, factory, resolver, configId, configVersion, compliance, identityRegistry, externalPauses, externalControlLists, externalKycLists, diamondOwnerAccount, proceedRecipients = [], proceedRecipientsData = [], factoryId) {
        try {
            if (!securityInfo.regulationType) {
                throw new MissingRegulationType();
            }
            if (!securityInfo.regulationsubType) {
                throw new MissingRegulationSubType();
            }
            const rbacAdmin = {
                role: SecurityRole._DEFAULT_ADMIN_ROLE,
                members: [diamondOwnerAccount.toString()],
            };
            const rbacs = [rbacAdmin];
            const erc20MetadataInfo = {
                name: securityInfo.name,
                symbol: securityInfo.symbol,
                isin: securityInfo.isin,
                decimals: securityInfo.decimals,
            };
            const resolverProxyConfiguration = {
                key: configId,
                version: configVersion,
            };
            const security = {
                arePartitionsProtected: securityInfo.arePartitionsProtected,
                isMultiPartition: securityInfo.isMultiPartition,
                resolver: resolver.toString(),
                resolverProxyConfiguration: resolverProxyConfiguration,
                rbacs: rbacs,
                isControllable: securityInfo.isControllable,
                isWhiteList: securityInfo.isWhiteList,
                maxSupply: securityInfo.maxSupply
                    ? securityInfo.maxSupply.toString()
                    : '0',
                erc20VotesActivated: securityInfo.erc20VotesActivated,
                erc20MetadataInfo: erc20MetadataInfo,
                clearingActive: securityInfo.clearingActive,
                internalKycActivated: securityInfo.internalKycActivated,
                externalPauses: externalPauses?.map((address) => address.toString()) ?? [],
                externalControlLists: externalControlLists?.map((address) => address.toString()) ?? [],
                externalKycLists: externalKycLists?.map((address) => address.toString()) ?? [],
                compliance: compliance.toString(),
                identityRegistry: identityRegistry.toString(),
            };
            const bondDetails = new BondDetailsData(bondInfo.currency, bondInfo.nominalValue.toString(), bondInfo.nominalValueDecimals, bondInfo.startingDate.toString(), bondInfo.maturityDate.toString());
            const securityTokenToCreate = new FactoryBondToken(security, bondDetails, proceedRecipients.map((addr) => addr.toString()), proceedRecipientsData.map((data) => (data == '' ? '0x' : data)));
            const additionalSecurityData = {
                countriesControlListType: securityInfo.isCountryControlListWhiteList,
                listOfCountries: securityInfo.countries ?? '',
                info: securityInfo.info ?? '',
            };
            const factoryRegulationData = new FactoryRegulationData(CastRegulationType.toNumber(securityInfo.regulationType), CastRegulationSubType.toNumber(securityInfo.regulationsubType), additionalSecurityData);
            LogService.logTrace(`Deploying bond: ${{
                security: securityTokenToCreate,
            }}`);
            return this.executeWithArgs(new Factory__factory().attach(factory.toString()), 'deployBond', factoryId, GAS.CREATE_BOND_ST, [securityTokenToCreate, factoryRegulationData]);
        }
        catch (error) {
            LogService.logError(error);
            throw new SigningError(`Unexpected error in HederaTransactionAdapter create operation : ${error}`);
        }
    }
    async transfer(security, targetId, amount, securityId) {
        LogService.logTrace(`Transfering ${amount} securities to account ${targetId.toString()}`);
        const basicTransferInfo = {
            to: targetId.toString(),
            value: amount.toHexString(),
        };
        return this.executeWithArgs(new ERC1410TokenHolderFacet__factory().attach(security.toString()), 'transferByPartition', securityId, GAS.TRANSFER, [_PARTITION_ID_1, basicTransferInfo, '0x']);
    }
    async transferAndLock(security, targetId, amount, expirationDate, securityId) {
        LogService.logTrace(`Transfering ${amount} securities to account ${targetId.toString()} and locking them until ${expirationDate.toString()}`);
        return this.executeWithArgs(new TransferAndLockFacet__factory().attach(security.toString()), 'transferAndLockByPartition', securityId, GAS.TRANSFER_AND_LOCK, [
            _PARTITION_ID_1,
            targetId.toString(),
            amount.toHexString(),
            '0x',
            expirationDate.toHexString(),
        ]);
    }
    async redeem(security, amount, securityId) {
        LogService.logTrace(`Redeeming ${amount} securities from account ${security.toString()}`);
        return this.executeWithArgs(new ERC1410TokenHolderFacet__factory().attach(security.toString()), 'redeemByPartition', securityId, GAS.REDEEM, [_PARTITION_ID_1, amount.toHexString(), '0x']);
    }
    async burn(security, source, amount, securityId) {
        LogService.logTrace(`Burning ${amount} securities from account ${source.toString()}`);
        return this.executeWithArgs(new ERC3643OperationsFacet__factory().attach(security.toString()), 'burn', securityId, GAS.BURN, [source.toString(), amount.toHexString()]);
    }
    async pause(security, securityId) {
        LogService.logTrace(`Pausing security: ${security.toString()}`);
        return this.executeWithParams(securityId, GAS.PAUSE, 'pause', new ContractFunctionParameters());
    }
    async unpause(security, securityId) {
        LogService.logTrace(`Unpausing security: ${security.toString()}`);
        return this.executeWithParams(securityId, GAS.PAUSE, 'unpause', new ContractFunctionParameters());
    }
    async grantRole(security, targetId, role, securityId) {
        LogService.logTrace(`Granting role ${role.toString()} to account: ${targetId.toString()}`);
        const contract = new Contract(security.toString(), AccessControlFacet__factory.abi);
        return this.executeWithArgs(contract, 'grantRole', securityId, GAS.GRANT_ROLES, [role, targetId.toString()]);
    }
    async applyRoles(security, targetId, roles, actives, securityId) {
        let gas = roles.length * GAS.GRANT_ROLES;
        gas = gas > GAS.MAX_ROLES ? GAS.MAX_ROLES : gas;
        const contract = new Contract(security.toString(), AccessControlFacet__factory.abi);
        return this.executeWithArgs(contract, 'applyRoles', securityId, gas, [
            roles,
            actives,
            targetId.toString(),
        ]);
    }
    async revokeRole(security, targetId, role, securityId) {
        LogService.logTrace(`Revoking role ${role.toString()} to account: ${targetId.toString()}`);
        const contract = new Contract(security.toString(), AccessControlFacet__factory.abi);
        return this.executeWithArgs(contract, 'revokeRole', securityId, GAS.GRANT_ROLES, [role, targetId.toString()]);
    }
    async renounceRole(security, role, securityId) {
        LogService.logTrace(`Renounce role ${role.toString()}`);
        const contract = new Contract(security.toString(), AccessControlFacet__factory.abi);
        return this.executeWithArgs(contract, 'renounceRole', securityId, GAS.RENOUNCE_ROLES, [role]);
    }
    async issue(security, targetId, amount, securityId) {
        LogService.logTrace(`Issue ${amount} ${security} to account: ${targetId.toString()}`);
        const issueData = {
            partition: _PARTITION_ID_1,
            tokenHolder: targetId.toString(),
            value: amount.toHexString(),
            data: '0x',
        };
        return this.executeWithArgs(new ERC1410IssuerFacet__factory().attach(security.toString()), 'issueByPartition', securityId, GAS.ISSUE, [issueData]);
    }
    async mint(security, target, amount, securityId) {
        LogService.logTrace(`Minting ${amount} ${security} to account: ${target.toString()}`);
        return this.executeWithArgs(new ERC3643OperationsFacet__factory().attach(security.toString()), 'mint', securityId, GAS.MINT, [target.toString(), amount.toHexString()]);
    }
    async addToControlList(security, targetId, securityId) {
        LogService.logTrace(`Adding account ${targetId.toString()} to a control list`);
        return this.executeWithArgs(new ControlListFacet__factory().attach(security.toString()), 'addToControlList', securityId, GAS.ADD_TO_CONTROL_LIST, [targetId.toString()]);
    }
    async removeFromControlList(security, targetId, securityId) {
        LogService.logTrace(`Removing account ${targetId.toString()} from a control list`);
        return this.executeWithArgs(new ControlListFacet__factory().attach(security.toString()), 'removeFromControlList', securityId, GAS.REMOVE_FROM_CONTROL_LIST, [targetId.toString()]);
    }
    protectedTransferAndLockByPartition(security, partitionId, amount, sourceId, targetId, expirationDate, deadline, nounce, signature, securityId) {
        LogService.logTrace(`Protected Transfering ${amount} securities from account ${sourceId.toString()} to account ${targetId.toString()} and locking them until ${expirationDate.toString()}`);
        const transferAndLockData = {
            from: sourceId.toString(),
            to: targetId.toString(),
            amount: amount.toBigNumber(),
            data: '0x',
            expirationTimestamp: expirationDate.toBigNumber(),
        };
        return this.executeWithArgs(new TransferAndLockFacet__factory().attach(security.toString()), 'protectedTransferAndLockByPartition', securityId, GAS.PROTECTED_TRANSFER_AND_LOCK, [
            partitionId,
            transferAndLockData,
            deadline.toBigNumber(),
            nounce.toBigNumber(),
            signature,
        ]);
    }
    async controllerTransfer(security, sourceId, targetId, amount, securityId) {
        LogService.logTrace(`Controller transfer ${amount} tokens from account ${sourceId.toString()} to account ${targetId.toString()}`);
        return this.executeWithArgs(new ERC1410ManagementFacet__factory().attach(security.toString()), 'controllerTransferByPartition', securityId, GAS.CONTROLLER_TRANSFER, [
            _PARTITION_ID_1,
            sourceId.toString(),
            targetId.toString(),
            amount.toHexString(),
            '0x',
            '0x',
        ]);
    }
    async forcedTransfer(security, source, target, amount, securityId) {
        LogService.logTrace(`Forced transfer ${amount} tokens from account ${source.toString()} to account ${target.toString()}`);
        return this.executeWithArgs(new ERC3643OperationsFacet__factory().attach(security.toString()), 'forcedTransfer', securityId, GAS.FORCED_TRANSFER, [source.toString(), target.toString(), amount.toHexString()]);
    }
    async controllerRedeem(security, sourceId, amount, securityId) {
        LogService.logTrace(`Force redeem ${amount} tokens from account ${sourceId.toString()}`);
        return this.executeWithArgs(new ERC1410ManagementFacet__factory().attach(security.toString()), 'controllerRedeemByPartition', securityId, GAS.CONTROLLER_REDEEM, [_PARTITION_ID_1, sourceId.toString(), amount.toHexString(), '0x', '0x']);
    }
    async setDividends(security, recordDate, executionDate, amount, securityId) {
        LogService.logTrace(`equity: ${security} ,
      recordDate :${recordDate} , 
      executionDate: ${executionDate},
      amount : ${amount}  `);
        const dividend = {
            recordDate: recordDate.toHexString(),
            executionDate: executionDate.toHexString(),
            amount: amount.toHexString(),
            amountDecimals: amount.decimals,
        };
        return this.executeWithArgs(new EquityUSAFacet__factory().attach(security.toString()), 'setDividends', securityId, GAS.SET_DIVIDENDS, [dividend]);
    }
    async setVotingRights(security, recordDate, data, securityId) {
        LogService.logTrace(`equity: ${security} ,
      recordDate :${recordDate} , `);
        const voting = {
            recordDate: recordDate.toHexString(),
            data: data,
        };
        return this.executeWithArgs(new EquityUSAFacet__factory().attach(security.toString()), 'setVoting', securityId, GAS.SET_VOTING_RIGHTS, [voting]);
    }
    async setCoupon(security, recordDate, executionDate, rate, period, securityId) {
        LogService.logTrace(`bond: ${security} ,
      recordDate :${recordDate} , 
      executionDate: ${executionDate},
      rate : ${rate},
      period: ${period}`);
        const coupon = {
            recordDate: recordDate.toHexString(),
            executionDate: executionDate.toHexString(),
            rate: rate.toHexString(),
            rateDecimals: rate.decimals,
            period: period.toHexString(),
        };
        return this.executeWithArgs(new BondUSAFacet__factory().attach(security.toString()), 'setCoupon', securityId, GAS.SET_COUPON, [coupon]);
    }
    async takeSnapshot(security, securityId) {
        LogService.logTrace(`Take snapshot of: ${security.toString()}`);
        return this.executeWithArgs(new SnapshotsFacet__factory().attach(security.toString()), 'takeSnapshot', securityId, GAS.TAKE_SNAPSHOT, []);
    }
    async setDocument(security, name, uri, hash, securityId) {
        LogService.logTrace(`Setting document: ${name}, with ${uri}, and hash ${hash} for security ${security.toString()}`);
        return this.executeWithArgs(new ERC1643Facet__factory().attach(security.toString()), 'setDocument', securityId, GAS.SET_DOCUMENT, [name, uri, hash]);
    }
    async removeDocument(security, name, securityId) {
        LogService.logTrace(`Removing document: ${name} for security ${security.toString()}`);
        return this.executeWithArgs(new ERC1643Facet__factory().attach(security.toString()), 'removeDocument', securityId, GAS.REMOVE_DOCUMENT, [name]);
    }
    async authorizeOperator(security, targetId, securityId) {
        LogService.logTrace(`authorizing operator: ${targetId.toString()} for security ${security.toString()}`);
        return this.executeWithArgs(new ERC1410TokenHolderFacet__factory().attach(security.toString()), 'authorizeOperator', securityId, GAS.AUTHORIZE_OPERATOR, [targetId.toString()]);
    }
    async revokeOperator(security, targetId, securityId) {
        LogService.logTrace(`revoking operator: ${targetId.toString()} for security ${security.toString()}`);
        return this.executeWithArgs(new ERC1410TokenHolderFacet__factory().attach(security.toString()), 'revokeOperator', securityId, GAS.REVOKE_OPERATOR, [targetId.toString()]);
    }
    async authorizeOperatorByPartition(security, targetId, partitionId, securityId) {
        LogService.logTrace(`authorizing operator: ${targetId.toString()} for security ${security.toString()} and partition ${partitionId}`);
        return this.executeWithArgs(new ERC1410TokenHolderFacet__factory().attach(security.toString()), 'authorizeOperatorByPartition', securityId, GAS.AUTHORIZE_OPERATOR, [partitionId, targetId.toString()]);
    }
    async revokeOperatorByPartition(security, targetId, partitionId, securityId) {
        LogService.logTrace(`revoking operator: ${targetId.toString()} for security ${security.toString()} and partition ${partitionId}`);
        return this.executeWithArgs(new ERC1410TokenHolderFacet__factory().attach(security.toString()), 'revokeOperatorByPartition', securityId, GAS.REVOKE_OPERATOR, [partitionId, targetId.toString()]);
    }
    async operatorTransferByPartition(security, sourceId, targetId, amount, partitionId, securityId) {
        LogService.logTrace(`Transfering ${amount} securities to account ${targetId.toString()} from account ${sourceId.toString()} on partition ${partitionId}`);
        const operatorTransferData = {
            partition: partitionId,
            from: sourceId.toString(),
            to: targetId.toString(),
            value: amount.toHexString(),
            data: '0x',
            operatorData: '0x',
        };
        return this.executeWithArgs(new ERC1410ManagementFacet__factory().attach(security.toString()), 'operatorTransferByPartition', securityId, GAS.TRANSFER_OPERATOR, [operatorTransferData]);
    }
    async setMaxSupply(security, maxSupply, securityId) {
        LogService.logTrace(`Setting max supply ${maxSupply} for security ${security.toString()}`);
        return this.executeWithArgs(new CapFacet__factory().attach(security.toString()), 'setMaxSupply', securityId, GAS.SET_MAX_SUPPLY, [maxSupply.toHexString()]);
    }
    async triggerPendingScheduledSnapshots(security, securityId) {
        LogService.logTrace(`Triggering pending scheduled snapshots for ${security.toString()}`);
        return this.executeWithArgs(new ScheduledCrossOrderedTasksFacet__factory().attach(security.toString()), 'triggerPendingScheduledCrossOrderedTasks', securityId, GAS.TRIGGER_PENDING_SCHEDULED_SNAPSHOTS, []);
    }
    async triggerScheduledSnapshots(security, max, securityId) {
        LogService.logTrace(`Triggering up to ${max.toString()} pending scheduled snapshots for ${security.toString()}`);
        return this.executeWithArgs(new ScheduledCrossOrderedTasksFacet__factory().attach(security.toString()), 'triggerScheduledCrossOrderedTasks', securityId, GAS.TRIGGER_PENDING_SCHEDULED_SNAPSHOTS, [max.toHexString()]);
    }
    async lock(security, sourceId, amount, expirationDate, securityId) {
        LogService.logTrace(`Locking ${amount} tokens from account ${sourceId.toString()} until ${expirationDate}`);
        return this.executeWithArgs(new LockFacet__factory().attach(security.toString()), 'lockByPartition', securityId, GAS.LOCK, [
            _PARTITION_ID_1,
            amount.toHexString(),
            sourceId.toString(),
            expirationDate.toHexString(),
        ]);
    }
    async release(security, sourceId, lockId, securityId) {
        LogService.logTrace(`Releasing lock ${lockId} from account ${sourceId.toString()}`);
        return this.executeWithArgs(new LockFacet__factory().attach(security.toString()), 'releaseByPartition', securityId, GAS.RELEASE, [_PARTITION_ID_1, lockId.toHexString(), sourceId.toString()]);
    }
    async updateConfigVersion(security, configVersion, securityId) {
        LogService.logTrace(`Updating config version`);
        return this.executeWithArgs(new DiamondFacet__factory().attach(security.toString()), 'updateConfigVersion', securityId, GAS.UPDATE_CONFIG_VERSION, [configVersion]);
    }
    async updateConfig(security, configId, configVersion, securityId) {
        LogService.logTrace(`Updating config`);
        return this.executeWithArgs(new DiamondFacet__factory().attach(security.toString()), 'updateConfig', securityId, GAS.UPDATE_CONFIG, [configId, configVersion]);
    }
    async updateResolver(security, resolver, configVersion, configId, securityId) {
        LogService.logTrace(`Updating Resolver`);
        return this.executeWithArgs(new DiamondFacet__factory().attach(security.toString()), 'updateResolver', securityId, GAS.UPDATE_RESOLVER, [resolver.toString(), configId, configVersion]);
    }
    async updateMaturityDate(security, maturityDate, securityId) {
        LogService.logTrace(`Updating bond maturity date ${maturityDate} for security ${security.toString()}`);
        const contract = new Contract(security.toString(), Bond__factory.abi);
        return this.executeWithArgs(contract, 'updateMaturityDate', securityId, GAS.UPDATE_MATURITY_DATE, [maturityDate]);
    }
    async setScheduledBalanceAdjustment(security, executionDate, factor, decimals, securityId) {
        LogService.logTrace(`equity: ${security} ,
      executionDate :${executionDate} , 
      factor: ${factor},
      decimals : ${decimals}  `);
        const scheduleBalanceAdjustment = {
            executionDate: executionDate.toHexString(),
            factor: factor.toHexString(),
            decimals: decimals.toHexString(),
        };
        return this.executeWithArgs(new EquityUSAFacet__factory().attach(security.toString()), 'setScheduledBalanceAdjustment', securityId, GAS.SET_SCHEDULED_BALANCE_ADJUSTMENT, [scheduleBalanceAdjustment]);
    }
    async protectPartitions(security, securityId) {
        LogService.logTrace(`Protecting Partitions for security: ${security.toString()}`);
        return this.executeWithParams(securityId, GAS.PROTECT_PARTITION, 'protectPartitions', new ContractFunctionParameters());
    }
    async unprotectPartitions(security, securityId) {
        LogService.logTrace(`Unprotecting Partitions for security: ${security.toString()}`);
        return this.executeWithParams(securityId, GAS.UNPROTECT_PARTITION, 'unprotectPartitions', new ContractFunctionParameters());
    }
    async protectedRedeemFromByPartition(security, partitionId, sourceId, amount, deadline, nounce, signature, securityId) {
        LogService.logTrace(`Protected Redeeming ${amount} securities from account ${sourceId.toString()}`);
        return this.executeWithArgs(new ERC1410ManagementFacet__factory().attach(security.toString()), 'protectedRedeemFromByPartition', securityId, GAS.PROTECTED_REDEEM, [
            partitionId,
            sourceId.toString(),
            amount.toBigNumber(),
            deadline.toBigNumber(),
            nounce.toBigNumber(),
            signature,
        ]);
    }
    async protectedTransferFromByPartition(security, partitionId, sourceId, targetId, amount, deadline, nounce, signature, securityId) {
        LogService.logTrace(`Protected Transfering ${amount} securities from account ${sourceId.toString()} to account ${targetId.toString()}`);
        return this.executeWithArgs(new ERC1410ManagementFacet__factory().attach(security.toString()), 'protectedTransferFromByPartition', securityId, GAS.PROTECTED_TRANSFER, [
            partitionId,
            sourceId.toString(),
            targetId.toString(),
            amount.toBigNumber(),
            deadline.toBigNumber(),
            nounce.toBigNumber(),
            signature,
        ]);
    }
    async protectedTransferAndLock(security, amount, sourceId, targetId, expirationDate, deadline, nounce, signature, securityId) {
        LogService.logTrace(`Protected Transfering ${amount} securities from account ${sourceId.toString()} to account ${targetId.toString()} and locking them until ${expirationDate.toString()}`);
        const transferAndLockData = {
            from: sourceId.toString(),
            to: targetId.toString(),
            amount: amount.toBigNumber(),
            data: '0x',
            expirationTimestamp: expirationDate.toBigNumber(),
        };
        return this.executeWithArgs(new TransferAndLockFacet__factory().attach(security.toString()), 'protectedTransferAndLock', securityId, GAS.PROTECTED_TRANSFER_AND_LOCK, [
            transferAndLockData,
            deadline.toBigNumber(),
            nounce.toBigNumber(),
            signature,
        ]);
    }
    async createHoldByPartition(security, partitionId, escrowId, amount, targetId, expirationDate, securityId) {
        LogService.logTrace(`Holding ${amount} tokens from account ${targetId.toString()} until ${expirationDate} with escrow ${escrowId}`);
        const hold = {
            amount: amount.toBigNumber(),
            expirationTimestamp: expirationDate.toBigNumber(),
            escrow: escrowId.toString(),
            to: targetId.toString(),
            data: '0x',
        };
        return this.executeWithArgs(new HoldTokenHolderFacet__factory().attach(security.toString()), 'createHoldByPartition', securityId, GAS.CREATE_HOLD, [partitionId, hold]);
    }
    async createHoldFromByPartition(security, partitionId, escrowId, amount, sourceId, targetId, expirationDate, securityId) {
        LogService.logTrace(`Holding ${amount} tokens from account ${sourceId.toString()} until ${expirationDate} with escrow ${escrowId}`);
        const hold = {
            amount: amount.toBigNumber(),
            expirationTimestamp: expirationDate.toBigNumber(),
            escrow: escrowId.toString(),
            to: targetId.toString(),
            data: '0x',
        };
        return this.executeWithArgs(new HoldTokenHolderFacet__factory().attach(security.toString()), 'createHoldFromByPartition', securityId, GAS.CREATE_HOLD_FROM, [partitionId, sourceId.toString(), hold, '0x']);
    }
    async controllerCreateHoldByPartition(security, partitionId, escrowId, amount, sourceId, targetId, expirationDate, securityId) {
        LogService.logTrace(`Controller Holding ${amount} tokens from account ${sourceId.toString()} until ${expirationDate} with escrow ${escrowId}`);
        const hold = {
            amount: amount.toBigNumber(),
            expirationTimestamp: expirationDate.toBigNumber(),
            escrow: escrowId.toString(),
            to: targetId.toString(),
            data: '0x',
        };
        return this.executeWithArgs(new HoldManagementFacet__factory().attach(security.toString()), 'controllerCreateHoldByPartition', securityId, GAS.CONTROLLER_CREATE_HOLD, [partitionId, sourceId.toString(), hold, '0x']);
    }
    async protectedCreateHoldByPartition(security, partitionId, amount, escrowId, sourceId, targetId, expirationDate, deadline, nonce, signature, securityId) {
        LogService.logTrace(`Protected Holding ${amount} tokens from account ${sourceId.toString()} until ${expirationDate} with escrow ${escrowId}`);
        const hold = {
            amount: amount.toBigNumber(),
            expirationTimestamp: expirationDate.toBigNumber(),
            escrow: escrowId.toString(),
            to: targetId.toString(),
            data: '0x',
        };
        const protectedHold = {
            hold: hold,
            deadline: deadline.toBigNumber(),
            nonce: nonce.toBigNumber(),
        };
        return this.executeWithArgs(new HoldManagementFacet__factory().attach(security.toString()), 'protectedCreateHoldByPartition', securityId, GAS.PROTECTED_CREATE_HOLD, [partitionId, sourceId.toString(), protectedHold, signature]);
    }
    async releaseHoldByPartition(security, partitionId, holdId, targetId, amount, securityId) {
        LogService.logTrace(`Releasing hold amount ${amount} from account ${targetId.toString()}}`);
        const holdIdentifier = {
            partition: partitionId,
            tokenHolder: targetId.toString(),
            holdId,
        };
        return this.executeWithArgs(new HoldTokenHolderFacet__factory().attach(security.toString()), 'releaseHoldByPartition', securityId, GAS.RELEASE_HOLD, [holdIdentifier, amount.toBigNumber()]);
    }
    async reclaimHoldByPartition(security, partitionId, holdId, targetId, securityId) {
        LogService.logTrace(`Reclaiming hold from account ${targetId.toString()}}`);
        const holdIdentifier = {
            partition: partitionId,
            tokenHolder: targetId.toString(),
            holdId,
        };
        return this.executeWithArgs(new HoldTokenHolderFacet__factory().attach(security.toString()), 'reclaimHoldByPartition', securityId, GAS.RECLAIM_HOLD, [holdIdentifier]);
    }
    async executeHoldByPartition(security, sourceId, targetId, amount, partitionId, holdId, securityId) {
        LogService.logTrace(`Executing hold with Id ${holdId} from account ${sourceId.toString()} to account ${targetId.toString()}`);
        const holdIdentifier = {
            partition: partitionId,
            tokenHolder: sourceId.toString(),
            holdId,
        };
        return this.executeWithArgs(new HoldTokenHolderFacet__factory().attach(security.toString()), 'executeHoldByPartition', securityId, GAS.EXECUTE_HOLD_BY_PARTITION, [holdIdentifier, targetId.toString(), amount.toBigNumber()]);
    }
    async addIssuer(security, issuer, securityId) {
        LogService.logTrace(`Adding issuer ${issuer}`);
        return this.executeWithArgs(new SsiManagementFacet__factory().attach(security.toString()), 'addIssuer', securityId, GAS.ADD_ISSUER, [issuer.toString()]);
    }
    async setRevocationRegistryAddress(security, revocationRegistry, securityId) {
        LogService.logTrace(`Setting revocation registry address ${revocationRegistry}`);
        return this.executeWithArgs(new SsiManagementFacet__factory().attach(security.toString()), 'setRevocationRegistryAddress', securityId, GAS.SET_REVOCATION_REGISTRY, [revocationRegistry.toString()]);
    }
    async removeIssuer(security, issuer, securityId) {
        LogService.logTrace(`Removing issuer ${issuer}`);
        return this.executeWithArgs(new SsiManagementFacet__factory().attach(security.toString()), 'removeIssuer', securityId, GAS.REMOVE_ISSUER, [issuer.toString()]);
    }
    async grantKyc(security, targetId, vcBase64, validFrom, validTo, issuer, securityId) {
        LogService.logTrace(`Granting KYC from issuer ${issuer.toString()} to address ${targetId.toString()} with VC ${vcBase64}`);
        return this.executeWithArgs(new KycFacet__factory().attach(security.toString()), 'grantKyc', securityId, GAS.GRANT_KYC, [
            targetId.toString(),
            vcBase64,
            validFrom.toBigNumber(),
            validTo.toBigNumber(),
            issuer.toString(),
        ]);
    }
    async revokeKyc(security, targetId, securityId) {
        LogService.logTrace(`Revoking KYC to address ${targetId.toString()}`);
        return this.executeWithArgs(new KycFacet__factory().attach(security.toString()), 'revokeKyc', securityId, GAS.REVOKE_KYC, [targetId.toString()]);
    }
    async activateClearing(security, securityId) {
        LogService.logTrace(`Activate Clearing to address ${security.toString()}`);
        return this.executeWithParams(securityId, GAS.ACTIVATE_CLEARING, 'activateClearing', new ContractFunctionParameters());
    }
    async deactivateClearing(security, securityId) {
        LogService.logTrace(`Deactivate Clearing to address ${security.toString()}`);
        return this.executeWithParams(securityId, GAS.DEACTIVATE_CLEARING, 'deactivateClearing', new ContractFunctionParameters());
    }
    async clearingTransferByPartition(security, partitionId, amount, targetId, expirationDate, securityId) {
        LogService.logTrace(`Clearing Transfer By Partition to address ${security.toString()}`);
        const clearingOperation = {
            partition: partitionId,
            expirationTimestamp: expirationDate.toBigNumber(),
            data: '0x',
        };
        return this.executeWithArgs(new ClearingTransferFacet__factory().attach(security.toString()), 'clearingTransferByPartition', securityId, GAS.CLEARING_TRANSFER_BY_PARTITION, [clearingOperation, amount.toBigNumber(), targetId.toString()]);
    }
    async clearingTransferFromByPartition(security, partitionId, amount, sourceId, targetId, expirationDate, securityId) {
        LogService.logTrace(`Clearing Transfer From By Partition to address ${security.toString()}`);
        const clearingOperationFrom = {
            clearingOperation: {
                partition: partitionId,
                expirationTimestamp: expirationDate.toBigNumber(),
                data: '0x',
            },
            from: sourceId.toString(),
            operatorData: '0x',
        };
        return this.executeWithArgs(new ClearingTransferFacet__factory().attach(security.toString()), 'clearingTransferFromByPartition', securityId, GAS.CLEARING_TRANSFER_FROM_BY_PARTITION, [clearingOperationFrom, amount.toBigNumber(), targetId.toString()]);
    }
    async protectedClearingTransferByPartition(security, partitionId, amount, sourceId, targetId, expirationDate, deadline, nonce, signature, securityId) {
        LogService.logTrace(`Protected Clearing Transfer By Partition to address ${security.toString()}`);
        const protectedClearingOperation = {
            clearingOperation: {
                partition: partitionId,
                expirationTimestamp: expirationDate.toBigNumber(),
                data: '0x',
            },
            from: sourceId.toString(),
            deadline: deadline.toBigNumber(),
            nonce: nonce.toBigNumber(),
        };
        return this.executeWithArgs(new ClearingTransferFacet__factory().attach(security.toString()), 'protectedClearingTransferByPartition', securityId, GAS.PROTECTED_CLEARING_TRANSFER_BY_PARTITION, [
            protectedClearingOperation,
            amount.toBigNumber(),
            targetId.toString(),
            signature,
        ]);
    }
    async approveClearingOperationByPartition(security, partitionId, targetId, clearingId, clearingOperationType, securityId) {
        LogService.logTrace(`Approve Clearing Operation By Partition to address ${security.toString()}`);
        const clearingOperationIdentifier = {
            partition: partitionId,
            tokenHolder: targetId.toString(),
            clearingOperationType: CastClearingOperationType.toNumber(clearingOperationType),
            clearingId: clearingId,
        };
        return this.executeWithArgs(new ClearingActionsFacet__factory().attach(security.toString()), 'approveClearingOperationByPartition', securityId, GAS.APPROVE_CLEARING_TRANSFER_BY_PARTITION, [clearingOperationIdentifier]);
    }
    async cancelClearingOperationByPartition(security, partitionId, targetId, clearingId, clearingOperationType, securityId) {
        LogService.logTrace(`Cancel Clearing Operation By Partition to address ${security.toString()}`);
        const clearingOperationIdentifier = {
            partition: partitionId,
            tokenHolder: targetId.toString(),
            clearingOperationType: CastClearingOperationType.toNumber(clearingOperationType),
            clearingId: clearingId,
        };
        return this.executeWithArgs(new ClearingActionsFacet__factory().attach(security.toString()), 'cancelClearingOperationByPartition', securityId, GAS.CANCEL_CLEARING_TRANSFER_BY_PARTITION, [clearingOperationIdentifier]);
    }
    async reclaimClearingOperationByPartition(security, partitionId, targetId, clearingId, clearingOperationType, securityId) {
        LogService.logTrace(`Reclaim Clearing Operation By Partition to address ${security.toString()}`);
        const clearingOperationIdentifier = {
            partition: partitionId,
            tokenHolder: targetId.toString(),
            clearingOperationType: CastClearingOperationType.toNumber(clearingOperationType),
            clearingId: clearingId,
        };
        return this.executeWithArgs(new ClearingActionsFacet__factory().attach(security.toString()), 'reclaimClearingOperationByPartition', securityId, GAS.RECLAIM_CLEARING_TRANSFER_BY_PARTITION, [clearingOperationIdentifier]);
    }
    async clearingRedeemByPartition(security, partitionId, amount, expirationDate, securityId) {
        LogService.logTrace(`Clearing Redeem By Partition to address ${security.toString()}`);
        const clearingOperation = {
            partition: partitionId,
            expirationTimestamp: expirationDate.toBigNumber(),
            data: '0x',
        };
        return this.executeWithArgs(new ClearingRedeemFacet__factory().attach(security.toString()), 'clearingRedeemByPartition', securityId, GAS.CLEARING_REDEEM_BY_PARTITION, [clearingOperation, amount.toBigNumber()]);
    }
    async clearingRedeemFromByPartition(security, partitionId, amount, sourceId, expirationDate, securityId) {
        LogService.logTrace(`Clearing Redeem From By Partition to address ${security.toString()}`);
        const clearingOperationFrom = {
            clearingOperation: {
                partition: partitionId,
                expirationTimestamp: expirationDate.toBigNumber(),
                data: '0x',
            },
            from: sourceId.toString(),
            operatorData: '0x',
        };
        return this.executeWithArgs(new ClearingRedeemFacet__factory().attach(security.toString()), 'clearingRedeemFromByPartition', securityId, GAS.CLEARING_REDEEM_FROM_BY_PARTITION, [clearingOperationFrom, amount.toBigNumber()]);
    }
    async protectedClearingRedeemByPartition(security, partitionId, amount, sourceId, expirationDate, deadline, nonce, signature, securityId) {
        LogService.logTrace(`Protected Clearing Redeem By Partition to address ${security.toString()}`);
        const protectedClearingOperation = {
            clearingOperation: {
                partition: partitionId,
                expirationTimestamp: expirationDate.toBigNumber(),
                data: '0x',
            },
            from: sourceId.toString(),
            deadline: deadline.toBigNumber(),
            nonce: nonce.toBigNumber(),
        };
        return this.executeWithArgs(new ClearingRedeemFacet__factory().attach(security.toString()), 'protectedClearingRedeemByPartition', securityId, GAS.PROTECTED_CLEARING_REDEEM_BY_PARTITION, [protectedClearingOperation, amount.toBigNumber(), signature]);
    }
    async clearingCreateHoldByPartition(security, partitionId, escrowId, amount, targetId, clearingExpirationDate, holdExpirationDate, securityId) {
        LogService.logTrace(`Clearing Create Hold By Partition to address ${security.toString()}`);
        const clearingOperation = {
            partition: partitionId,
            expirationTimestamp: clearingExpirationDate.toBigNumber(),
            data: '0x',
        };
        const hold = {
            amount: amount.toBigNumber(),
            expirationTimestamp: holdExpirationDate.toBigNumber(),
            escrow: escrowId.toString(),
            to: targetId.toString(),
            data: '0x',
        };
        return this.executeWithArgs(new ClearingHoldCreationFacet__factory().attach(security.toString()), 'clearingCreateHoldByPartition', securityId, GAS.CLEARING_CREATE_HOLD_BY_PARTITION, [clearingOperation, hold]);
    }
    async clearingCreateHoldFromByPartition(security, partitionId, escrowId, amount, sourceId, targetId, clearingExpirationDate, holdExpirationDate, securityId) {
        LogService.logTrace(`Clearing Create Hold From By Partition to address ${security.toString()}`);
        const clearingOperationFrom = {
            clearingOperation: {
                partition: partitionId,
                expirationTimestamp: clearingExpirationDate.toBigNumber(),
                data: '0x',
            },
            from: sourceId.toString(),
            operatorData: '0x',
        };
        const hold = {
            amount: amount.toBigNumber(),
            expirationTimestamp: holdExpirationDate.toBigNumber(),
            escrow: escrowId.toString(),
            to: targetId.toString(),
            data: '0x',
        };
        return this.executeWithArgs(new ClearingHoldCreationFacet__factory().attach(security.toString()), 'clearingCreateHoldFromByPartition', securityId, GAS.CLEARING_CREATE_HOLD_FROM_BY_PARTITION, [clearingOperationFrom, hold]);
    }
    async protectedClearingCreateHoldByPartition(security, partitionId, amount, escrowId, sourceId, targetId, clearingExpirationDate, holdExpirationDate, deadline, nonce, signature, securityId) {
        LogService.logTrace(`Protected Clearing Create Hold By Partition to address ${security.toString()}`);
        const protectedClearingOperation = {
            clearingOperation: {
                partition: partitionId,
                expirationTimestamp: clearingExpirationDate.toBigNumber(),
                data: '0x',
            },
            from: sourceId.toString(),
            deadline: deadline.toBigNumber(),
            nonce: nonce.toBigNumber(),
        };
        const hold = {
            amount: amount.toBigNumber(),
            expirationTimestamp: holdExpirationDate.toBigNumber(),
            escrow: escrowId.toString(),
            to: targetId.toString(),
            data: '0x',
        };
        return this.executeWithArgs(new ClearingHoldCreationFacet__factory().attach(security.toString()), 'protectedClearingCreateHoldByPartition', securityId, GAS.PROTECTED_CLEARING_CREATE_HOLD_BY_PARTITION, [protectedClearingOperation, hold, signature]);
    }
    async operatorClearingCreateHoldByPartition(security, partitionId, escrowId, amount, sourceId, targetId, clearingExpirationDate, holdExpirationDate, securityId) {
        LogService.logTrace(`Operator Clearing Create Hold By Partition to address ${security.toString()}`);
        const clearingOperationFrom = {
            clearingOperation: {
                partition: partitionId,
                expirationTimestamp: clearingExpirationDate.toBigNumber(),
                data: '0x',
            },
            from: sourceId.toString(),
            operatorData: '0x',
        };
        const hold = {
            amount: amount.toBigNumber(),
            expirationTimestamp: holdExpirationDate.toBigNumber(),
            escrow: escrowId.toString(),
            to: targetId.toString(),
            data: '0x',
        };
        return this.executeWithArgs(new ClearingHoldCreationFacet__factory().attach(security.toString()), 'operatorClearingCreateHoldByPartition', securityId, GAS.OPERATOR_CLEARING_CREATE_HOLD_BY_PARTITION, [clearingOperationFrom, hold]);
    }
    async operatorClearingRedeemByPartition(security, partitionId, amount, sourceId, expirationDate, securityId) {
        LogService.logTrace(`Operator Clearing Redeem By Partition to address ${security.toString()}`);
        const clearingOperationFrom = {
            clearingOperation: {
                partition: partitionId,
                expirationTimestamp: expirationDate.toBigNumber(),
                data: '0x',
            },
            from: sourceId.toString(),
            operatorData: '0x',
        };
        return this.executeWithArgs(new ClearingRedeemFacet__factory().attach(security.toString()), 'operatorClearingRedeemByPartition', securityId, GAS.OPERATOR_CLEARING_REDEEM_BY_PARTITION, [clearingOperationFrom, amount.toBigNumber()]);
    }
    async operatorClearingTransferByPartition(security, partitionId, amount, sourceId, targetId, expirationDate, securityId) {
        LogService.logTrace(`Operator Clearing Transfer By Partition to address ${security.toString()}`);
        const clearingOperationFrom = {
            clearingOperation: {
                partition: partitionId,
                expirationTimestamp: expirationDate.toBigNumber(),
                data: '0x',
            },
            from: sourceId.toString(),
            operatorData: '0x',
        };
        return this.executeWithArgs(new ClearingTransferFacet__factory().attach(security.toString()), 'operatorClearingTransferByPartition', securityId, GAS.OPERATOR_CLEARING_TRANSFER_BY_PARTITION, [clearingOperationFrom, amount.toBigNumber(), targetId.toString()]);
    }
    async updateExternalPauses(security, externalPausesAddresses, actives, securityId) {
        LogService.logTrace(`Updating External Pauses for security ${security.toString()}`);
        return this.executeWithArgs(new ExternalPauseManagementFacet__factory().attach(security.toString()), 'updateExternalPauses', securityId, GAS.UPDATE_EXTERNAL_PAUSES, [externalPausesAddresses.map((address) => address.toString()), actives]);
    }
    async addExternalPause(security, externalPauseAddress, securityId) {
        LogService.logTrace(`Adding External Pause for security ${security.toString()}`);
        return this.executeWithArgs(new ExternalPauseManagementFacet__factory().attach(security.toString()), 'addExternalPause', securityId, GAS.ADD_EXTERNAL_PAUSE, [externalPauseAddress.toString()]);
    }
    async removeExternalPause(security, externalPauseAddress, securityId) {
        LogService.logTrace(`Removing External Pause for security ${security.toString()}`);
        return this.executeWithArgs(new ExternalPauseManagementFacet__factory().attach(security.toString()), 'removeExternalPause', securityId, GAS.REMOVE_EXTERNAL_PAUSE, [externalPauseAddress.toString()]);
    }
    async setPausedMock(contract, paused, contractId) {
        LogService.logTrace(`Setting paused to external pause mock contract ${contract.toString()}`);
        return this.executeWithArgs(new MockedExternalPause__factory().attach(contract.toString()), 'setPaused', contractId, GAS.SET_PAUSED_MOCK, [paused]);
    }
    async createExternalPauseMock() {
        LogService.logTrace(`Deploying External Pause Mock contract`);
        const bytecodeHex = MockedExternalPause__factory.bytecode.startsWith('0x')
            ? MockedExternalPause__factory.bytecode.slice(2)
            : MockedExternalPause__factory.bytecode;
        const bytecode = Uint8Array.from(Buffer.from(bytecodeHex, 'hex'));
        const contractCreate = new ContractCreateTransaction()
            .setBytecode(bytecode)
            .setGas(GAS.CREATE_EXTERNAL_PAUSE_MOCK);
        //TODO: Review signandsend
        return this.signAndSendTransaction(contractCreate);
    }
    async updateExternalControlLists(security, externalControlListsAddresses, actives, securityId) {
        LogService.logTrace(`Updating External Control Lists for security ${security.toString()}`);
        return this.executeWithArgs(new ExternalControlListManagementFacet__factory().attach(security.toString()), 'updateExternalControlLists', securityId, GAS.UPDATE_EXTERNAL_CONTROL_LISTS, [
            externalControlListsAddresses.map((address) => address.toString()),
            actives,
        ]);
    }
    async addExternalControlList(security, externalControlListAddress, securityId) {
        LogService.logTrace(`Adding External Control Lists for security ${security.toString()}`);
        return this.executeWithArgs(new ExternalControlListManagementFacet__factory().attach(security.toString()), 'addExternalControlList', securityId, GAS.ADD_EXTERNAL_CONTROL_LIST, [externalControlListAddress.toString()]);
    }
    async removeExternalControlList(security, externalControlListAddress, securityId) {
        LogService.logTrace(`Removing External Control Lists for security ${security.toString()}`);
        return this.executeWithArgs(new ExternalControlListManagementFacet__factory().attach(security.toString()), 'removeExternalControlList', securityId, GAS.REMOVE_EXTERNAL_CONTROL_LIST, [externalControlListAddress.toString()]);
    }
    async addToBlackListMock(contract, targetId, contractId) {
        LogService.logTrace(`Adding address ${targetId.toString()} to external Control black List mock ${contract.toString()}`);
        return this.executeWithArgs(new MockedBlacklist__factory().attach(contract.toString()), 'addToBlacklist', contractId, GAS.ADD_TO_BLACK_LIST_MOCK, [targetId.toString()]);
    }
    async addToWhiteListMock(contract, targetId, contractId) {
        LogService.logTrace(`Adding address ${targetId.toString()} to external Control white List mock ${contract.toString()}`);
        return this.executeWithArgs(new MockedWhitelist__factory().attach(contract.toString()), 'addToWhitelist', contractId, GAS.ADD_TO_WHITE_LIST_MOCK, [targetId.toString()]);
    }
    async removeFromBlackListMock(contract, targetId, contractId) {
        LogService.logTrace(`Removing address ${targetId.toString()} from external Control black List mock ${contract.toString()}`);
        return this.executeWithArgs(new MockedBlacklist__factory().attach(contract.toString()), 'removeFromBlacklist', contractId, GAS.REMOVE_FROM_BLACK_LIST_MOCK, [targetId.toString()]);
    }
    async removeFromWhiteListMock(contract, targetId, contractId) {
        LogService.logTrace(`Removing address ${targetId.toString()} from external Control white List mock ${contract.toString()}`);
        return this.executeWithArgs(new MockedWhitelist__factory().attach(contract.toString()), 'removeFromWhitelist', contractId, GAS.REMOVE_FROM_WHITE_LIST_MOCK, [targetId.toString()]);
    }
    async createExternalBlackListMock() {
        LogService.logTrace(`Deploying External Control Black List Mock contract`);
        const bytecodeHex = MockedBlacklist__factory.bytecode.startsWith('0x')
            ? MockedBlacklist__factory.bytecode.slice(2)
            : MockedBlacklist__factory.bytecode;
        const bytecode = Uint8Array.from(Buffer.from(bytecodeHex, 'hex'));
        const contractCreate = new ContractCreateTransaction()
            .setBytecode(bytecode)
            .setGas(GAS.CREATE_EXTERNAL_BLACK_LIST_MOCK);
        return this.signAndSendTransaction(contractCreate);
    }
    async createExternalWhiteListMock() {
        LogService.logTrace(`Deploying External Control White List Mock contract`);
        const bytecodeHex = MockedWhitelist__factory.bytecode.startsWith('0x')
            ? MockedWhitelist__factory.bytecode.slice(2)
            : MockedWhitelist__factory.bytecode;
        const bytecode = Uint8Array.from(Buffer.from(bytecodeHex, 'hex'));
        const contractCreate = new ContractCreateTransaction()
            .setBytecode(bytecode)
            .setGas(GAS.CREATE_EXTERNAL_WHITE_LIST_MOCK);
        return this.signAndSendTransaction(contractCreate);
    }
    async updateExternalKycLists(security, externalKycListsAddresses, actives, securityId) {
        LogService.logTrace(`Updating External Kyc Lists for security ${security.toString()}`);
        return this.executeWithArgs(new ExternalKycListManagementFacet__factory().attach(security.toString()), 'updateExternalKycLists', securityId, GAS.UPDATE_EXTERNAL_KYC_LISTS, [externalKycListsAddresses.map((address) => address.toString()), actives]);
    }
    async addExternalKycList(security, externalKycListAddress, securityId) {
        LogService.logTrace(`Adding External kyc Lists for security ${security.toString()}`);
        return this.executeWithArgs(new ExternalKycListManagementFacet__factory().attach(security.toString()), 'addExternalKycList', securityId, GAS.ADD_EXTERNAL_KYC_LIST, [externalKycListAddress.toString()]);
    }
    async removeExternalKycList(security, externalKycListAddress, securityId) {
        LogService.logTrace(`Removing External kyc Lists for security ${security.toString()}`);
        return this.executeWithArgs(new ExternalKycListManagementFacet__factory().attach(security.toString()), 'removeExternalKycList', securityId, GAS.REMOVE_EXTERNAL_KYC_LIST, [externalKycListAddress.toString()]);
    }
    async grantKycMock(contract, targetId, contractId) {
        LogService.logTrace(`Grant kyc address ${targetId.toString()} to external kyc mock ${contract.toString()}`);
        return this.executeWithArgs(new MockedExternalKycList__factory().attach(contract.toString()), 'grantKyc', contractId, GAS.GRANT_KYC_MOCK, [targetId.toString()]);
    }
    async revokeKycMock(contract, targetId, contractId) {
        LogService.logTrace(`Revoke kyc address ${targetId.toString()} to external kyc mock ${contract.toString()}`);
        return this.executeWithArgs(new MockedExternalKycList__factory().attach(contract.toString()), 'revokeKyc', contractId, GAS.REVOKE_KYC_MOCK, [targetId.toString()]);
    }
    async createExternalKycListMock() {
        LogService.logTrace(`Deploying External Kyc List List Mock contract`);
        const bytecodeHex = MockedExternalKycList__factory.bytecode.startsWith('0x')
            ? MockedExternalKycList__factory.bytecode.slice(2)
            : MockedExternalKycList__factory.bytecode;
        const bytecode = Uint8Array.from(Buffer.from(bytecodeHex, 'hex'));
        const contractCreate = new ContractCreateTransaction()
            .setBytecode(bytecode)
            .setGas(GAS.CREATE_EXTERNAL_KYC_LIST_MOCK);
        return this.signAndSendTransaction(contractCreate);
    }
    async activateInternalKyc(security, securityId) {
        LogService.logTrace(`Activate Internal Kyc to address ${security.toString()}`);
        return this.executeWithParams(securityId, GAS.ACTIVATE_INTERNAL_KYC, 'activateInternalKyc', new ContractFunctionParameters());
    }
    async deactivateInternalKyc(security, securityId) {
        LogService.logTrace(`Deactivate Internal Kyc to address ${security.toString()}`);
        return this.executeWithParams(securityId, GAS.DEACTIVATE_INTERNAL_KYC, 'deactivateInternalKyc', new ContractFunctionParameters());
    }
    async setName(security, name, securityId) {
        LogService.logTrace(`Setting name to ${security.toString()}`);
        return this.executeWithArgs(new ERC3643ManagementFacet__factory().attach(security.toString()), 'setName', securityId, GAS.SET_NAME, [name]);
    }
    async setSymbol(security, symbol, securityId) {
        LogService.logTrace(`Setting symbol to ${security.toString()}`);
        return this.executeWithArgs(new ERC3643ManagementFacet__factory().attach(security.toString()), 'setSymbol', securityId, GAS.SET_SYMBOL, [symbol]);
    }
    async setOnchainID(security, onchainID, securityId) {
        LogService.logTrace(`Setting onchainID to ${security.toString()}`);
        return this.executeWithArgs(new ERC3643ManagementFacet__factory().attach(security.toString()), 'setOnchainID', securityId, GAS.SET_ONCHAIN_ID, [onchainID.toString()]);
    }
    async setIdentityRegistry(security, identityRegistry, securityId) {
        LogService.logTrace(`Setting identity registry to ${security.toString()}`);
        return this.executeWithArgs(new ERC3643ManagementFacet__factory().attach(security.toString()), 'setIdentityRegistry', securityId, GAS.SET_IDENTITY_REGISTRY, [identityRegistry.toString()]);
    }
    async setCompliance(security, compliance, securityId) {
        LogService.logTrace(`Setting compliance to ${security.toString()}`);
        return this.executeWithArgs(new ERC3643ManagementFacet__factory().attach(security.toString()), 'setCompliance', securityId, GAS.SET_COMPLIANCE, [compliance.toString()]);
    }
    async freezePartialTokens(security, amount, targetId, securityId) {
        LogService.logTrace(`Freezing ${amount} tokens ${security.toString()} to account ${targetId.toString()}`);
        return this.executeWithArgs(new FreezeFacet__factory().attach(security.toString()), 'freezePartialTokens', securityId, GAS.FREEZE_PARTIAL_TOKENS, [targetId.toString(), amount.toBigNumber()]);
    }
    async unfreezePartialTokens(security, amount, targetId, securityId) {
        LogService.logTrace(`Unfreezing ${amount} tokens ${security.toString()} to account ${targetId.toString()}`);
        return this.executeWithArgs(new FreezeFacet__factory().attach(security.toString()), 'unfreezePartialTokens', securityId, GAS.UNFREEZE_PARTIAL_TOKENS, [targetId.toString(), amount.toBigNumber()]);
    }
    async recoveryAddress(security, lostWalletId, newWalletId, securityId) {
        LogService.logTrace(`Recovering address ${lostWalletId.toString()} to ${newWalletId.toString()}`);
        return this.executeWithArgs(new ERC3643ManagementFacet__factory().attach(security.toString()), 'recoveryAddress', securityId, GAS.RECOVERY_ADDRESS, [lostWalletId.toString(), newWalletId.toString(), EVM_ZERO_ADDRESS]);
    }
    async addAgent(security, agentId, securityId) {
        LogService.logTrace(`Granting agent role to ${agentId.toString()}`);
        return this.executeWithArgs(new ERC3643ManagementFacet__factory().attach(security.toString()), 'addAgent', securityId, GAS.ADD_AGENT, [agentId.toString()]);
    }
    async removeAgent(security, agentId, securityId) {
        LogService.logTrace(`Revoking agent role from ${agentId.toString()}`);
        return this.executeWithArgs(new ERC3643ManagementFacet__factory().attach(security.toString()), 'removeAgent', securityId, GAS.REMOVE_AGENT, [agentId.toString()]);
    }
    async batchTransfer(security, amountList, toList, securityId) {
        LogService.logTrace(`Batch transferring ${amountList.length} tokens from ${security.toString()} to ${toList.map((item) => item.toString())}`);
        return this.executeWithArgs(new ERC3643BatchFacet__factory().attach(security.toString()), 'batchTransfer', securityId, GAS.BATCH_TRANSFER, [
            toList.map((addr) => addr.toString()),
            amountList.map((amount) => amount.toBigNumber()),
        ]);
    }
    async batchForcedTransfer(security, amountList, fromList, toList, securityId) {
        LogService.logTrace(`Batch forced transferring ${amountList.length} tokens from ${fromList.map((item) => item.toString())} to ${toList.map((item) => item.toString())}`);
        return this.executeWithArgs(new ERC3643BatchFacet__factory().attach(security.toString()), 'batchForcedTransfer', securityId, GAS.BATCH_FORCED_TRANSFER, [
            fromList.map((addr) => addr.toString()),
            toList.map((addr) => addr.toString()),
            amountList.map((amount) => amount.toBigNumber()),
        ]);
    }
    async batchMint(security, amountList, toList, securityId) {
        LogService.logTrace(`Batch minting ${amountList.length} tokens to ${toList.map((item) => item.toString())}`);
        return this.executeWithArgs(new ERC3643BatchFacet__factory().attach(security.toString()), 'batchMint', securityId, GAS.BATCH_MINT, [
            toList.map((addr) => addr.toString()),
            amountList.map((amount) => amount.toBigNumber()),
        ]);
    }
    async batchBurn(security, amountList, targetList, securityId) {
        LogService.logTrace(`Batch burning ${amountList.length} tokens from ${targetList.map((item) => item.toString())}`);
        return this.executeWithArgs(new ERC3643BatchFacet__factory().attach(security.toString()), 'batchBurn', securityId, GAS.BATCH_BURN, [
            targetList.map((addr) => addr.toString()),
            amountList.map((amount) => amount.toBigNumber()),
        ]);
    }
    async batchSetAddressFrozen(security, freezeList, targetList, securityId) {
        LogService.logTrace(`Batch setting freeze status for ${targetList.length} addresses`);
        return this.executeWithArgs(new FreezeFacet__factory().attach(security.toString()), 'batchSetAddressFrozen', securityId, GAS.BATCH_SET_ADDRESS_FROZEN, [targetList.map((addr) => addr.toString()), freezeList]);
    }
    async batchFreezePartialTokens(security, amountList, targetList, securityId) {
        LogService.logTrace(`Batch freezing partial tokens for ${targetList.length} addresses`);
        return this.executeWithArgs(new FreezeFacet__factory().attach(security.toString()), 'batchFreezePartialTokens', securityId, GAS.BATCH_FREEZE_PARTIAL_TOKENS, [
            targetList.map((addr) => addr.toString()),
            amountList.map((amount) => amount.toBigNumber()),
        ]);
    }
    async batchUnfreezePartialTokens(security, amountList, targetList, securityId) {
        LogService.logTrace(`Batch unfreezing partial tokens for ${targetList.length} addresses`);
        return this.executeWithArgs(new FreezeFacet__factory().attach(security.toString()), 'batchUnfreezePartialTokens', securityId, GAS.BATCH_UNFREEZE_PARTIAL_TOKENS, [
            targetList.map((addr) => addr.toString()),
            amountList.map((amount) => amount.toBigNumber()),
        ]);
    }
    async setAddressFrozen(security, status, target, securityId) {
        LogService.logTrace(`Freezing address ${target.toString()}`);
        return this.executeWithArgs(new FreezeFacet__factory().attach(security.toString()), 'setAddressFrozen', securityId, GAS.SET_ADDRESS_FROZEN, [target.toString(), status]);
    }
    async redeemAtMaturityByPartition(security, partitionId, sourceId, amount, securityId) {
        LogService.logTrace(`Redeeming at maturity by partition to address ${security.toString()}`);
        const contract = new Contract(security.toString(), Bond__factory.abi);
        return this.executeWithArgs(contract, 'redeemAtMaturityByPartition', securityId, GAS.REDEEM_AT_MATURITY_BY_PARTITION_GAS, [sourceId.toString(), partitionId, amount.toBigNumber()]);
    }
    async fullRedeemAtMaturity(security, sourceId, securityId) {
        LogService.logTrace(`Redeeming at maturity by partition to address ${security.toString()}`);
        const contract = new Contract(security.toString(), Bond__factory.abi);
        return this.executeWithArgs(contract, 'fullRedeemAtMaturity', securityId, GAS.FULL_REDEEM_AT_MATURITY_GAS, [sourceId.toString()]);
    }
    async createTrexSuiteBond(salt, owner, irs, onchainId, irAgents, tokenAgents, compliancesModules, complianceSettings, claimTopics, issuers, issuerClaims, security, bondDetails, factory, resolver, configId, configVersion, compliance, identityRegistryAddress, diamondOwnerAccount, proceedRecipients = [], proceedRecipientsData = [], externalPauses, externalControlLists, externalKycLists, factoryId) {
        LogService.logTrace(`Deploying trex suite bond: ${security.toString()}`);
        if (!security.regulationType) {
            throw new MissingRegulationType();
        }
        if (!security.regulationsubType) {
            throw new MissingRegulationSubType();
        }
        const rbacAdmin = {
            role: SecurityRole._DEFAULT_ADMIN_ROLE,
            members: [diamondOwnerAccount.toString()],
        };
        const rbacs = [rbacAdmin];
        const erc20MetadataInfo = {
            name: security.name,
            symbol: security.symbol,
            isin: security.isin,
            decimals: security.decimals,
        };
        const resolverProxyConfiguration = {
            key: configId,
            version: configVersion,
        };
        const securityData = {
            arePartitionsProtected: security.arePartitionsProtected,
            isMultiPartition: security.isMultiPartition,
            resolver: resolver.toString(),
            resolverProxyConfiguration: resolverProxyConfiguration,
            rbacs: rbacs,
            isControllable: security.isControllable,
            isWhiteList: security.isWhiteList,
            maxSupply: security.maxSupply ? security.maxSupply.toString() : '0',
            erc20MetadataInfo: erc20MetadataInfo,
            clearingActive: security.clearingActive,
            internalKycActivated: security.internalKycActivated,
            externalPauses: externalPauses?.map((address) => address.toString()) ?? [],
            externalControlLists: externalControlLists?.map((address) => address.toString()) ?? [],
            externalKycLists: externalKycLists?.map((address) => address.toString()) ?? [],
            compliance: compliance.toString(),
            identityRegistry: identityRegistryAddress.toString(),
            erc20VotesActivated: security.erc20VotesActivated,
        };
        const bondDetailsData = new BondDetailsData(bondDetails.currency, bondDetails.nominalValue.toString(), bondDetails.nominalValueDecimals, bondDetails.startingDate.toString(), bondDetails.maturityDate.toString());
        const securityTokenToCreate = new FactoryBondToken(securityData, bondDetailsData, proceedRecipients.map((b) => b.toString()), proceedRecipientsData.map((data) => (data == '' ? '0x' : data)));
        const additionalSecurityData = {
            countriesControlListType: security.isCountryControlListWhiteList,
            listOfCountries: security.countries ?? '',
            info: security.info ?? '',
        };
        const factoryRegulationData = new FactoryRegulationData(CastRegulationType.toNumber(security.regulationType), CastRegulationSubType.toNumber(security.regulationsubType), additionalSecurityData);
        const contract = new Contract(factory.toString(), TREXFactoryAts__factory.abi);
        try {
            return this.executeWithArgs(contract, 'deployTREXSuiteAtsBond', factoryId, GAS.TREX_CREATE_SUITE, [
                salt,
                {
                    owner,
                    irs,
                    ONCHAINID: onchainId,
                    irAgents,
                    tokenAgents,
                    complianceModules: compliancesModules,
                    complianceSettings,
                },
                {
                    claimTopics,
                    issuers,
                    issuerClaims,
                },
                securityTokenToCreate,
                factoryRegulationData,
            ]);
        }
        catch (error) {
            LogService.logError(error);
            throw new SigningError(`Unexpected error in TREXFactoryAts__factory deploy operation : ${error}`);
        }
    }
    async createTrexSuiteEquity(salt, owner, irs, onchainId, irAgents, tokenAgents, compliancesModules, complianceSettings, claimTopics, issuers, issuerClaims, security, equityDetails, factory, resolver, configId, configVersion, compliance, identityRegistryAddress, diamondOwnerAccount, externalPauses, externalControlLists, externalKycLists, factoryId) {
        LogService.logTrace(`Deploying trex suite equity: ${security.toString()}`);
        try {
            if (!security.regulationType) {
                throw new MissingRegulationType();
            }
            if (!security.regulationsubType) {
                throw new MissingRegulationSubType();
            }
            const rbacAdmin = {
                role: SecurityRole._DEFAULT_ADMIN_ROLE,
                members: [diamondOwnerAccount.toString()],
            };
            const rbacs = [rbacAdmin];
            const erc20MetadataInfo = {
                name: security.name,
                symbol: security.symbol,
                isin: security.isin,
                decimals: security.decimals,
            };
            const resolverProxyConfiguration = {
                key: configId,
                version: configVersion,
            };
            const securityData = {
                arePartitionsProtected: security.arePartitionsProtected,
                isMultiPartition: security.isMultiPartition,
                resolver: resolver.toString(),
                resolverProxyConfiguration: resolverProxyConfiguration,
                rbacs: rbacs,
                isControllable: security.isControllable,
                isWhiteList: security.isWhiteList,
                maxSupply: security.maxSupply ? security.maxSupply.toString() : '0',
                erc20MetadataInfo: erc20MetadataInfo,
                clearingActive: security.clearingActive,
                internalKycActivated: security.internalKycActivated,
                externalPauses: externalPauses?.map((address) => address.toString()) ?? [],
                externalControlLists: externalControlLists?.map((address) => address.toString()) ?? [],
                externalKycLists: externalKycLists?.map((address) => address.toString()) ?? [],
                compliance: compliance.toString(),
                identityRegistry: identityRegistryAddress?.toString(),
                erc20VotesActivated: security.erc20VotesActivated,
            };
            const equityDetailsData = {
                votingRight: equityDetails.votingRight,
                informationRight: equityDetails.informationRight,
                liquidationRight: equityDetails.liquidationRight,
                subscriptionRight: equityDetails.subscriptionRight,
                conversionRight: equityDetails.conversionRight,
                redemptionRight: equityDetails.redemptionRight,
                putRight: equityDetails.putRight,
                dividendRight: CastDividendType.toNumber(equityDetails.dividendRight),
                currency: equityDetails.currency,
                nominalValue: equityDetails.nominalValue.toString(),
                nominalValueDecimals: equityDetails.nominalValueDecimals,
            };
            const securityTokenToCreate = new FactoryEquityToken(securityData, equityDetailsData);
            const additionalSecurityData = {
                countriesControlListType: security.isCountryControlListWhiteList,
                listOfCountries: security.countries ?? '',
                info: security.info ?? '',
            };
            const factoryRegulationData = new FactoryRegulationData(CastRegulationType.toNumber(security.regulationType), CastRegulationSubType.toNumber(security.regulationsubType), additionalSecurityData);
            LogService.logTrace(`Deploying equity: ${{
                security: securityTokenToCreate,
            }}`);
            const contract = new Contract(factory.toString(), TREXFactoryAts__factory.abi);
            return this.executeWithArgs(contract, 'deployTREXSuiteAtsEquity', factoryId, GAS.TREX_CREATE_SUITE, [
                salt,
                {
                    owner,
                    irs,
                    ONCHAINID: onchainId,
                    irAgents,
                    tokenAgents,
                    complianceModules: compliancesModules,
                    complianceSettings,
                },
                {
                    claimTopics,
                    issuers,
                    issuerClaims,
                },
                securityTokenToCreate,
                factoryRegulationData,
            ]);
        }
        catch (error) {
            LogService.logError(error);
            throw new SigningError(`Unexpected error in HederaTransactionAdapter create operation : ${error}`);
        }
    }
    addProceedRecipient(security, proceedRecipient, data, securityId) {
        LogService.logTrace(`Adding proceedRecipient: ${proceedRecipient} to security: ${security}`);
        return this.executeWithArgs(new ProceedRecipientsFacet__factory().attach(security.toString()), 'addProceedRecipient', securityId, GAS.ADD_PROCEED_RECIPIENT, [proceedRecipient.toString(), data]);
    }
    removeProceedRecipient(security, proceedRecipient, securityId) {
        LogService.logTrace(`Removing proceedRecipient: ${proceedRecipient} from security: ${security}`);
        return this.executeWithArgs(new ProceedRecipientsFacet__factory().attach(security.toString()), 'removeProceedRecipient', securityId, GAS.REMOVE_PROCEED_RECIPIENT, [proceedRecipient.toString()]);
    }
    updateProceedRecipientData(security, proceedRecipient, data, securityId) {
        LogService.logTrace(`Updating proceedRecipient: ${proceedRecipient} data in security: ${security}`);
        return this.executeWithArgs(new ProceedRecipientsFacet__factory().attach(security.toString()), 'updateProceedRecipientData', securityId, GAS.UPDATE_PROCEED_RECIPIENT, [proceedRecipient.toString(), data]);
    }
}
