"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 __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RPCTransactionAdapter = void 0;
const TransactionAdapter_1 = __importDefault(require("../TransactionAdapter"));
const tsyringe_1 = require("tsyringe");
const LazyInjectDecorator_1 = require("../../../core/decorator/LazyInjectDecorator");
const MirrorNodeAdapter_1 = require("../mirror/MirrorNodeAdapter");
const EventService_1 = __importDefault(require("../../../app/service/event/EventService"));
const LogService_1 = __importDefault(require("../../../app/service/log/LogService"));
const CommandBus_1 = require("../../../core/command/CommandBus");
const RPCTransactionResponseAdapter_1 = require("./RPCTransactionResponseAdapter");
const Constants_1 = require("../../../core/Constants");
const FactorySecurityToken_1 = require("../../../domain/context/factory/FactorySecurityToken");
const SigningError_1 = require("../error/SigningError");
const asset_tokenization_contracts_1 = require("@hashgraph/asset-tokenization-contracts");
const Clearing_1 = require("../../../domain/context/security/Clearing");
const SecurityDataBuilder_1 = require("../../../domain/context/util/SecurityDataBuilder");
const NetworkService_1 = __importDefault(require("../../../app/service/network/NetworkService"));
const MetamaskService_1 = __importDefault(require("../../../app/service/wallet/metamask/MetamaskService"));
let RPCTransactionAdapter = class RPCTransactionAdapter extends TransactionAdapter_1.default {
    constructor(mirrorNodeAdapter, networkService, eventService, commandBus) {
        super();
        this.mirrorNodeAdapter = mirrorNodeAdapter;
        this.networkService = networkService;
        this.eventService = eventService;
        this.commandBus = commandBus;
        this.metamaskService = new MetamaskService_1.default(this.eventService, this.commandBus, this.networkService, this.mirrorNodeAdapter);
        this.metamaskService.registerMetamaskEvents();
    }
    async init(debug = false) {
        return this.metamaskService.init(debug);
    }
    async register(account, debug = false) {
        return this.metamaskService.register(this, account, debug);
    }
    async stop() {
        return this.metamaskService.stop();
    }
    getMirrorNodeAdapter() {
        return this.mirrorNodeAdapter;
    }
    getAccount() {
        return this.metamaskService.getAccount();
    }
    setConfig(config) {
        this.metamaskService.setConfig({
            mirrorNodes: config.mirrorNodes,
            jsonRpcRelays: config.jsonRpcRelays,
            factories: config.factories,
            resolvers: config.resolvers,
        });
    }
    getSignerOrProvider() {
        return this.metamaskService.getSignerOrProvider();
    }
    setSignerOrProvider(signerOrProvider) {
        return this.metamaskService.setSignerOrProvider(signerOrProvider);
    }
    async createEquity(securityInfo, equityInfo, factory, resolver, configId, configVersion, compliance, identityRegistryAddress, externalPauses, externalControlLists, externalKycLists, diamondOwnerAccount) {
        return this.createSecurity(securityInfo, SecurityDataBuilder_1.SecurityDataBuilder.buildEquityDetails(equityInfo), factory, resolver, configId, configVersion, externalPauses, externalControlLists, externalKycLists, diamondOwnerAccount, (security, details) => new FactorySecurityToken_1.FactoryEquityToken(security, details), 'deployEquity', Constants_1.GAS.CREATE_EQUITY_ST, 'EquityDeployed', compliance, identityRegistryAddress);
    }
    async createBond(securityInfo, bondInfo, factory, resolver, configId, configVersion, compliance, identityRegistryAddress, externalPauses, externalControlLists, externalKycLists, diamondOwnerAccount, proceedRecipients = [], proceedRecipientsData = []) {
        return this.createSecurity(securityInfo, {
            bondDetails: SecurityDataBuilder_1.SecurityDataBuilder.buildBondDetails(bondInfo),
        }, factory, resolver, configId, configVersion, externalPauses, externalControlLists, externalKycLists, diamondOwnerAccount, (security, details) => new FactorySecurityToken_1.FactoryBondToken(security, details.bondDetails, proceedRecipients.map((addr) => addr.toString()), proceedRecipientsData.map((data) => (data == '' ? '0x' : data))), 'deployBond', Constants_1.GAS.CREATE_BOND_ST, 'BondDeployed', compliance, identityRegistryAddress);
    }
    async transfer(security, targetId, amount) {
        LogService_1.default.logTrace(`Transfering ${amount} securities to account ${targetId.toString()}`);
        const basicTransferInfo = {
            to: targetId.toString(),
            value: amount.toHexString(),
        };
        return this.executeTransaction(asset_tokenization_contracts_1.ERC1410TokenHolderFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'transferByPartition', [Constants_1._PARTITION_ID_1, basicTransferInfo, '0x'], Constants_1.GAS.TRANSFER);
    }
    async transferAndLock(security, targetId, amount, expirationDate) {
        LogService_1.default.logTrace(`Transfering ${amount} securities to account ${targetId.toString()} and locking them until ${expirationDate.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.TransferAndLockFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'transferAndLockByPartition', [
            Constants_1._PARTITION_ID_1,
            targetId.toString(),
            amount.toBigNumber(),
            '0x',
            expirationDate.toBigNumber(),
        ], Constants_1.GAS.TRANSFER_AND_LOCK);
    }
    async redeem(security, amount) {
        LogService_1.default.logTrace(`Redeeming ${amount} securities`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC1410TokenHolderFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'redeemByPartition', [Constants_1._PARTITION_ID_1, amount.toBigNumber(), '0x'], Constants_1.GAS.REDEEM);
    }
    async burn(security, source, amount) {
        LogService_1.default.logTrace(`Burning ${amount} securities from source: ${source.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC3643OperationsFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'burn', [source.toString(), amount.toBigNumber()], Constants_1.GAS.BURN);
    }
    async pause(security) {
        LogService_1.default.logTrace(`Pausing security: ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.PauseFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'pause', [], Constants_1.GAS.PAUSE);
    }
    async unpause(security) {
        LogService_1.default.logTrace(`Unpausing security: ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.PauseFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'unpause', [], Constants_1.GAS.UNPAUSE);
    }
    async grantRole(security, targetId, role) {
        LogService_1.default.logTrace(`Granting role ${role.toString()} to account: ${targetId.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.AccessControlFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'grantRole', [role, targetId.toString()], Constants_1.GAS.GRANT_ROLES);
    }
    async applyRoles(security, targetId, roles, actives) {
        let gas = roles.length * Constants_1.GAS.GRANT_ROLES;
        gas = gas > Constants_1.GAS.MAX_ROLES ? Constants_1.GAS.MAX_ROLES : gas;
        return this.executeTransaction(asset_tokenization_contracts_1.AccessControlFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'applyRoles', [roles, actives, targetId.toString()], gas);
    }
    async revokeRole(security, targetId, role) {
        LogService_1.default.logTrace(`Revoking role ${role.toString()} to account: ${targetId.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.AccessControlFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'revokeRole', [role, targetId.toString()], Constants_1.GAS.GRANT_ROLES);
    }
    async renounceRole(security, role) {
        LogService_1.default.logTrace(`Renounce role ${role.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.AccessControlFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'renounceRole', [role], Constants_1.GAS.RENOUNCE_ROLES);
    }
    async issue(security, targetId, amount) {
        LogService_1.default.logTrace(`Issue ${amount} ${security} to account: ${targetId.toString()}`);
        const issueData = {
            partition: Constants_1._PARTITION_ID_1,
            tokenHolder: targetId.toString(),
            value: amount.toHexString(),
            data: '0x',
        };
        return this.executeTransaction(asset_tokenization_contracts_1.ERC1410IssuerFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'issueByPartition', [issueData], Constants_1.GAS.ISSUE);
    }
    async mint(security, target, amount) {
        LogService_1.default.logTrace(`Minting ${amount} ${security} to account: ${target.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC3643OperationsFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'mint', [target.toString(), amount.toBigNumber()], Constants_1.GAS.MINT);
    }
    async addToControlList(security, targetId) {
        LogService_1.default.logTrace(`Adding account ${targetId.toString()} to a control list`);
        return this.executeTransaction(asset_tokenization_contracts_1.ControlListFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'addToControlList', [targetId.toString()], Constants_1.GAS.ADD_TO_CONTROL_LIST);
    }
    async removeFromControlList(security, targetId) {
        LogService_1.default.logTrace(`Adding account ${targetId.toString()} to a control list`);
        return this.executeTransaction(asset_tokenization_contracts_1.ControlListFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'removeFromControlList', [targetId.toString()], Constants_1.GAS.REMOVE_FROM_CONTROL_LIST);
    }
    async controllerTransfer(security, sourceId, targetId, amount) {
        LogService_1.default.logTrace(`Controller transfer ${amount} tokens from account ${sourceId.toString()} to account ${targetId.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC1410ManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'controllerTransferByPartition', [
            Constants_1._PARTITION_ID_1,
            sourceId.toString(),
            targetId.toString(),
            amount.toBigNumber(),
            '0x',
            '0x',
        ], Constants_1.GAS.CONTROLLER_TRANSFER);
    }
    async forcedTransfer(security, source, target, amount) {
        LogService_1.default.logTrace(`Forced transfer ${amount} tokens from account ${source.toString()} to account ${target.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC3643OperationsFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'forcedTransfer', [source.toString(), target.toString(), amount.toBigNumber()], Constants_1.GAS.FORCED_TRANSFER);
    }
    async controllerRedeem(security, sourceId, amount) {
        LogService_1.default.logTrace(`Force redeem ${amount} tokens from account ${sourceId.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC1410ManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'controllerRedeemByPartition', [Constants_1._PARTITION_ID_1, sourceId.toString(), amount.toBigNumber(), '0x', '0x'], Constants_1.GAS.CONTROLLER_REDEEM);
    }
    async setDividends(security, recordDate, executionDate, amount) {
        LogService_1.default.logTrace(`equity: ${security} ,
      recordDate :${recordDate} , 
      executionDate: ${executionDate},
      amount : ${amount}  `);
        const dividendStruct = {
            recordDate: recordDate.toBigNumber(),
            executionDate: executionDate.toBigNumber(),
            amount: amount.toBigNumber(),
            amountDecimals: amount.decimals,
        };
        return this.executeTransaction(asset_tokenization_contracts_1.Equity__factory.connect(security.toString(), this.getSignerOrProvider()), 'setDividends', [dividendStruct], Constants_1.GAS.SET_DIVIDENDS, Constants_1.SET_DIVIDEND_EVENT);
    }
    async setVotingRights(security, recordDate, data) {
        LogService_1.default.logTrace(`equity: ${security} ,
      recordDate :${recordDate} , `);
        const votingStruct = {
            recordDate: recordDate.toBigNumber(),
            data: data,
        };
        return this.executeTransaction(asset_tokenization_contracts_1.Equity__factory.connect(security.toString(), this.getSignerOrProvider()), 'setVoting', [votingStruct], Constants_1.GAS.SET_VOTING_RIGHTS, Constants_1.SET_VOTING_RIGHTS_EVENT);
    }
    async setCoupon(security, recordDate, executionDate, rate, period, securityId) {
        LogService_1.default.logTrace(`bond: ${security} ,
      recordDate :${recordDate} , 
      executionDate: ${executionDate},
      rate : ${rate},
      period: ${period}`);
        const couponStruct = {
            recordDate: recordDate.toBigNumber(),
            executionDate: executionDate.toBigNumber(),
            rate: rate.toBigNumber(),
            rateDecimals: rate.decimals,
            period: period.toBigNumber(),
        };
        return this.executeTransaction(asset_tokenization_contracts_1.Bond__factory.connect(security.toString(), this.getSignerOrProvider()), 'setCoupon', [couponStruct], Constants_1.GAS.SET_COUPON, Constants_1.SET_COUPON_EVENT);
    }
    async takeSnapshot(security) {
        LogService_1.default.logTrace(`Take snapshot of: ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.SnapshotsFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'takeSnapshot', [], Constants_1.GAS.TAKE_SNAPSHOT);
    }
    async setDocument(security, name, uri, hash) {
        LogService_1.default.logTrace(`Setting document: ${name}, with ${uri}, and hash ${hash} for security ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC1643Facet__factory.connect(security.toString(), this.getSignerOrProvider()), 'setDocument', [name, uri, hash], Constants_1.GAS.SET_DOCUMENT);
    }
    async removeDocument(security, name) {
        LogService_1.default.logTrace(`Removing document: ${name} for security ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC1643Facet__factory.connect(security.toString(), this.getSignerOrProvider()), 'removeDocument', [name], Constants_1.GAS.REMOVE_DOCUMENT);
    }
    async authorizeOperator(security, targetId) {
        LogService_1.default.logTrace(`authorizing operator: ${targetId.toString()} for security ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC1410TokenHolderFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'authorizeOperator', [targetId.toString()], Constants_1.GAS.AUTHORIZE_OPERATOR);
    }
    async revokeOperator(security, targetId) {
        LogService_1.default.logTrace(`revoking operator: ${targetId.toString()} for security ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC1410TokenHolderFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'revokeOperator', [targetId.toString()], Constants_1.GAS.REVOKE_OPERATOR);
    }
    async authorizeOperatorByPartition(security, targetId, partitionId) {
        LogService_1.default.logTrace(`authorizing operator: ${targetId.toString()} for security ${security.toString()} and partition ${partitionId}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC1410TokenHolderFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'authorizeOperatorByPartition', [partitionId, targetId.toString()], Constants_1.GAS.AUTHORIZE_OPERATOR);
    }
    async revokeOperatorByPartition(security, targetId, partitionId) {
        LogService_1.default.logTrace(`revoking operator: ${targetId.toString()} for security ${security.toString()} and partition ${partitionId}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC1410TokenHolderFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'revokeOperatorByPartition', [partitionId, targetId.toString()], Constants_1.GAS.REVOKE_OPERATOR);
    }
    async operatorTransferByPartition(security, sourceId, targetId, amount, partitionId) {
        LogService_1.default.logTrace(`Transfering ${amount} securities to account ${targetId.toString()} for partition ${partitionId}`);
        const operatorTransferData = {
            partition: partitionId,
            from: sourceId.toString(),
            to: targetId.toString(),
            value: amount.toHexString(),
            data: '0x',
            operatorData: '0x',
        };
        return this.executeTransaction(asset_tokenization_contracts_1.ERC1410ManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'operatorTransferByPartition', [operatorTransferData], Constants_1.GAS.TRANSFER_OPERATOR);
    }
    async setMaxSupply(security, maxSupply) {
        LogService_1.default.logTrace(`Setting max supply ${maxSupply} for security ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.CapFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'setMaxSupply', [maxSupply.toBigNumber()], Constants_1.GAS.SET_MAX_SUPPLY);
    }
    async triggerPendingScheduledSnapshots(security) {
        LogService_1.default.logTrace(`Triggerring pending scheduled snapshots for ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ScheduledCrossOrderedTasksFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'triggerPendingScheduledCrossOrderedTasks', [], Constants_1.GAS.TRIGGER_PENDING_SCHEDULED_SNAPSHOTS);
    }
    async triggerScheduledSnapshots(security, max) {
        LogService_1.default.logTrace(`Triggerring up to ${max.toString()} pending scheduled snapshots for ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ScheduledCrossOrderedTasksFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'triggerScheduledCrossOrderedTasks', [max.toBigNumber()], Constants_1.GAS.TRIGGER_PENDING_SCHEDULED_SNAPSHOTS);
    }
    async lock(security, sourceId, amount, expirationDate) {
        LogService_1.default.logTrace(`Locking ${amount} tokens from account ${sourceId.toString()} until ${expirationDate}`);
        return this.executeTransaction(asset_tokenization_contracts_1.LockFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'lockByPartition', [
            Constants_1._PARTITION_ID_1,
            amount.toBigNumber(),
            sourceId.toString(),
            expirationDate.toBigNumber(),
        ], Constants_1.GAS.LOCK);
    }
    async release(security, sourceId, lockId) {
        LogService_1.default.logTrace(`Releasing lock ${lockId} from account ${sourceId.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.LockFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'releaseByPartition', [Constants_1._PARTITION_ID_1, lockId.toBigNumber(), sourceId.toString()], Constants_1.GAS.RELEASE);
    }
    async updateConfigVersion(security, configVersion) {
        LogService_1.default.logTrace(`Updating config version ${configVersion} for security ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.DiamondFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'updateConfigVersion', [configVersion], Constants_1.GAS.UPDATE_CONFIG_VERSION);
    }
    async updateConfig(security, configId, configVersion) {
        LogService_1.default.logTrace(`Updating config ${configId} & version ${configVersion} for security ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.DiamondFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'updateConfig', [configId, configVersion], Constants_1.GAS.UPDATE_CONFIG);
    }
    async updateResolver(security, resolver, configVersion, configId) {
        LogService_1.default.logTrace(`Updating resolver ${resolver.toString()} for security ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.DiamondFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'updateResolver', [resolver.toString(), configId, configVersion], Constants_1.GAS.UPDATE_RESOLVER);
    }
    async updateMaturityDate(security, maturityDate) {
        LogService_1.default.logTrace(`Updating bond maturity date ${maturityDate} for security ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.Bond__factory.connect(security.toString(), this.getSignerOrProvider()), 'updateMaturityDate', [maturityDate], Constants_1.GAS.UPDATE_MATURITY_DATE);
    }
    async setScheduledBalanceAdjustment(security, executionDate, factor, decimals) {
        LogService_1.default.logTrace(`equity: ${security} ,
            executionDate :${executionDate} ,
            factor: ${factor},
            decimals : ${decimals}  `);
        const scheduledBalanceAdjustmentStruct = {
            executionDate: executionDate.toBigNumber(),
            factor: factor.toBigNumber(),
            decimals: decimals.toBigNumber(),
        };
        return this.executeTransaction(asset_tokenization_contracts_1.Equity__factory.connect(security.toString(), this.getSignerOrProvider()), 'setScheduledBalanceAdjustment', [scheduledBalanceAdjustmentStruct], Constants_1.GAS.SET_SCHEDULED_BALANCE_ADJUSTMENT, Constants_1.SET_SCHEDULED_BALANCE_ADJUSTMENT_EVENT);
    }
    async protectPartitions(address) {
        LogService_1.default.logTrace(`Protecting Partitions for security: ${address.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ProtectedPartitionsFacet__factory.connect(address.toString(), this.getSignerOrProvider()), 'protectPartitions', [], Constants_1.GAS.PROTECT_PARTITION);
    }
    async unprotectPartitions(address) {
        LogService_1.default.logTrace(`Unprotecting Partitions for security: ${address.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ProtectedPartitionsFacet__factory.connect(address.toString(), this.getSignerOrProvider()), 'unprotectPartitions', [], Constants_1.GAS.UNPROTECT_PARTITION);
    }
    async protectedRedeemFromByPartition(security, partitionId, sourceId, amount, deadline, nounce, signature) {
        LogService_1.default.logTrace(`Protected Redeeming ${amount} securities from account ${sourceId.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC1410ManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'protectedRedeemFromByPartition', [
            partitionId,
            sourceId.toString(),
            amount.toBigNumber(),
            deadline.toBigNumber(),
            nounce.toBigNumber(),
            signature,
        ], Constants_1.GAS.PROTECTED_REDEEM);
    }
    async protectedTransferFromByPartition(security, partitionId, sourceId, targetId, amount, deadline, nounce, signature) {
        LogService_1.default.logTrace(`Protected Transfering ${amount} securities from account ${sourceId.toString()} to account ${targetId.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC1410ManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'protectedTransferFromByPartition', [
            partitionId,
            sourceId.toString(),
            targetId.toString(),
            amount.toBigNumber(),
            deadline.toBigNumber(),
            nounce.toBigNumber(),
            signature,
        ], Constants_1.GAS.PROTECTED_TRANSFER);
    }
    async protectedTransferAndLockByPartition(security, partitionId, amount, sourceId, targetId, expirationDate, deadline, nounce, signature) {
        LogService_1.default.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.executeTransaction(asset_tokenization_contracts_1.TransferAndLockFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'protectedTransferAndLockByPartition', [
            partitionId,
            transferAndLockData,
            deadline.toBigNumber(),
            nounce.toBigNumber(),
            signature,
        ], Constants_1.GAS.PROTECTED_TRANSFER_AND_LOCK);
    }
    async createHoldByPartition(security, partitionId, escrowId, amount, targetId, expirationDate) {
        LogService_1.default.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.executeTransaction(asset_tokenization_contracts_1.HoldTokenHolderFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'createHoldByPartition', [partitionId, hold], Constants_1.GAS.CREATE_HOLD);
    }
    async createHoldFromByPartition(security, partitionId, escrowId, amount, sourceId, targetId, expirationDate) {
        LogService_1.default.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.executeTransaction(asset_tokenization_contracts_1.HoldTokenHolderFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'createHoldFromByPartition', [partitionId, sourceId.toString(), hold, '0x'], Constants_1.GAS.CREATE_HOLD_FROM);
    }
    async controllerCreateHoldByPartition(security, partitionId, escrowId, amount, sourceId, targetId, expirationDate) {
        LogService_1.default.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.executeTransaction(asset_tokenization_contracts_1.HoldManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'controllerCreateHoldByPartition', [partitionId, sourceId.toString(), hold, '0x'], Constants_1.GAS.CONTROLLER_CREATE_HOLD);
    }
    async protectedCreateHoldByPartition(security, partitionId, amount, escrowId, sourceId, targetId, expirationDate, deadline, nonce, signature) {
        LogService_1.default.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,
            deadline: deadline.toBigNumber(),
            nonce: nonce.toBigNumber(),
        };
        return this.executeTransaction(asset_tokenization_contracts_1.HoldManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'protectedCreateHoldByPartition', [partitionId, sourceId.toString(), protectedHold, signature], Constants_1.GAS.PROTECTED_CREATE_HOLD);
    }
    async releaseHoldByPartition(security, partitionId, holdId, targetId, amount) {
        LogService_1.default.logTrace(`Releasing hold amount ${amount} from account ${targetId.toString()}}`);
        const holdIdentifier = {
            partition: partitionId,
            tokenHolder: targetId.toString(),
            holdId,
        };
        return this.executeTransaction(asset_tokenization_contracts_1.HoldTokenHolderFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'releaseHoldByPartition', [holdIdentifier, amount.toBigNumber()], Constants_1.GAS.RELEASE_HOLD);
    }
    async reclaimHoldByPartition(security, partitionId, holdId, targetId) {
        LogService_1.default.logTrace(`Reclaiming hold amount from account ${targetId.toString()}}`);
        const holdIdentifier = {
            partition: partitionId,
            tokenHolder: targetId.toString(),
            holdId,
        };
        return this.executeTransaction(asset_tokenization_contracts_1.HoldTokenHolderFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'reclaimHoldByPartition', [holdIdentifier], Constants_1.GAS.RECLAIM_HOLD);
    }
    async executeHoldByPartition(security, sourceId, targetId, amount, partitionId, holdId) {
        LogService_1.default.logTrace(`Executing hold with Id ${holdId} from account ${sourceId.toString()} to account ${targetId.toString()}`);
        const holdIdentifier = {
            partition: partitionId,
            tokenHolder: sourceId.toString(),
            holdId,
        };
        return this.executeTransaction(asset_tokenization_contracts_1.HoldTokenHolderFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'executeHoldByPartition', [holdIdentifier, targetId.toString(), amount.toBigNumber()], Constants_1.GAS.EXECUTE_HOLD_BY_PARTITION);
    }
    async setRevocationRegistryAddress(security, revocationRegistry) {
        LogService_1.default.logTrace(`Setting revocation registry address ${revocationRegistry}`);
        return this.executeTransaction(asset_tokenization_contracts_1.SsiManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'setRevocationRegistryAddress', [revocationRegistry.toString()], Constants_1.GAS.SET_REVOCATION_REGISTRY);
    }
    async addIssuer(security, issuer) {
        LogService_1.default.logTrace(`Adding issuer ${issuer}`);
        return this.executeTransaction(asset_tokenization_contracts_1.SsiManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'addIssuer', [issuer.toString()], Constants_1.GAS.ADD_ISSUER);
    }
    async removeIssuer(security, issuer) {
        LogService_1.default.logTrace(`Removing issuer ${issuer}`);
        return this.executeTransaction(asset_tokenization_contracts_1.SsiManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'removeIssuer', [issuer.toString()], Constants_1.GAS.REMOVE_ISSUER);
    }
    async grantKyc(security, targetId, vcId, validFrom, validTo, issuer) {
        LogService_1.default.logTrace(`Granting KYC from issuer ${issuer.toString()} to address ${targetId.toString()} with VC id ${vcId}`);
        return this.executeTransaction(asset_tokenization_contracts_1.KycFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'grantKyc', [
            targetId.toString(),
            vcId,
            validFrom.toBigNumber(),
            validTo.toBigNumber(),
            issuer.toString(),
        ], Constants_1.GAS.GRANT_KYC);
    }
    async revokeKyc(security, targetId) {
        LogService_1.default.logTrace(`Revoking KYC to address ${targetId.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.KycFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'revokeKyc', [targetId.toString()], Constants_1.GAS.REVOKE_KYC);
    }
    async activateClearing(security) {
        LogService_1.default.logTrace(`Activating Clearing to address ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ClearingActionsFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'activateClearing', [], Constants_1.GAS.ACTIVATE_CLEARING);
    }
    async deactivateClearing(security) {
        LogService_1.default.logTrace(`Deactivate Clearing to address ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ClearingActionsFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'deactivateClearing', [], Constants_1.GAS.DEACTIVATE_CLEARING);
    }
    async clearingTransferByPartition(security, partitionId, amount, targetId, expirationDate) {
        LogService_1.default.logTrace(`Clearing Transfer By Partition to address ${security.toString()}`);
        const clearingOperation = {
            partition: partitionId,
            expirationTimestamp: expirationDate.toBigNumber(),
            data: '0x',
        };
        return this.executeTransaction(asset_tokenization_contracts_1.ClearingTransferFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'clearingTransferByPartition', [clearingOperation, amount.toBigNumber(), targetId.toString()], Constants_1.GAS.CLEARING_TRANSFER_BY_PARTITION);
    }
    async clearingTransferFromByPartition(security, partitionId, amount, sourceId, targetId, expirationDate) {
        LogService_1.default.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.executeTransaction(asset_tokenization_contracts_1.ClearingTransferFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'clearingTransferFromByPartition', [clearingOperationFrom, amount.toBigNumber(), targetId.toString()], Constants_1.GAS.CLEARING_TRANSFER_FROM_BY_PARTITION);
    }
    async protectedClearingTransferByPartition(security, partitionId, amount, sourceId, targetId, expirationDate, deadline, nonce, signature) {
        LogService_1.default.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.executeTransaction(asset_tokenization_contracts_1.ClearingTransferFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'protectedClearingTransferByPartition', [
            protectedClearingOperation,
            amount.toBigNumber(),
            targetId.toString(),
            signature,
        ], Constants_1.GAS.PROTECTED_CLEARING_TRANSFER_BY_PARTITION);
    }
    async approveClearingOperationByPartition(security, partitionId, targetId, clearingId, clearingOperationType) {
        LogService_1.default.logTrace(`Approve Clearing Operation By Partition to address ${security.toString()}`);
        const clearingOperationIdentifier = {
            partition: partitionId,
            tokenHolder: targetId.toString(),
            clearingOperationType: Clearing_1.CastClearingOperationType.toNumber(clearingOperationType),
            clearingId: clearingId,
        };
        return this.executeTransaction(asset_tokenization_contracts_1.ClearingActionsFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'approveClearingOperationByPartition', [clearingOperationIdentifier], Constants_1.GAS.APPROVE_CLEARING_TRANSFER_BY_PARTITION);
    }
    async cancelClearingOperationByPartition(security, partitionId, targetId, clearingId, clearingOperationType) {
        LogService_1.default.logTrace(`Cancel Clearing Operation By Partition to address ${security.toString()}`);
        const clearingOperationIdentifier = {
            partition: partitionId,
            tokenHolder: targetId.toString(),
            clearingOperationType: Clearing_1.CastClearingOperationType.toNumber(clearingOperationType),
            clearingId: clearingId,
        };
        return this.executeTransaction(asset_tokenization_contracts_1.ClearingActionsFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'cancelClearingOperationByPartition', [clearingOperationIdentifier], Constants_1.GAS.CANCEL_CLEARING_TRANSFER_BY_PARTITION);
    }
    async reclaimClearingOperationByPartition(security, partitionId, targetId, clearingId, clearingOperationType) {
        LogService_1.default.logTrace(`Reclaim Clearing Operation By Partition to address ${security.toString()}`);
        const clearingOperationIdentifier = {
            partition: partitionId,
            tokenHolder: targetId.toString(),
            clearingOperationType: Clearing_1.CastClearingOperationType.toNumber(clearingOperationType),
            clearingId: clearingId,
        };
        return this.executeTransaction(asset_tokenization_contracts_1.ClearingActionsFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'reclaimClearingOperationByPartition', [clearingOperationIdentifier], Constants_1.GAS.RECLAIM_CLEARING_TRANSFER_BY_PARTITION);
    }
    async clearingRedeemByPartition(security, partitionId, amount, expirationDate) {
        LogService_1.default.logTrace(`Clearing Redeem By Partition to address ${security.toString()}`);
        const clearingOperation = {
            partition: partitionId,
            expirationTimestamp: expirationDate.toBigNumber(),
            data: '0x',
        };
        return this.executeTransaction(asset_tokenization_contracts_1.ClearingRedeemFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'clearingRedeemByPartition', [clearingOperation, amount.toBigNumber()], Constants_1.GAS.CLEARING_REDEEM_BY_PARTITION);
    }
    async clearingRedeemFromByPartition(security, partitionId, amount, sourceId, expirationDate) {
        LogService_1.default.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.executeTransaction(asset_tokenization_contracts_1.ClearingRedeemFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'clearingRedeemFromByPartition', [clearingOperationFrom, amount.toBigNumber()], Constants_1.GAS.CLEARING_REDEEM_FROM_BY_PARTITION);
    }
    async protectedClearingRedeemByPartition(security, partitionId, amount, sourceId, expirationDate, deadline, nonce, signature) {
        LogService_1.default.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.executeTransaction(asset_tokenization_contracts_1.ClearingRedeemFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'protectedClearingRedeemByPartition', [protectedClearingOperation, amount.toBigNumber(), signature], Constants_1.GAS.PROTECTED_CLEARING_REDEEM_BY_PARTITION);
    }
    async clearingCreateHoldByPartition(security, partitionId, escrowId, amount, targetId, clearingExpirationDate, holdExpirationDate) {
        LogService_1.default.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.executeTransaction(asset_tokenization_contracts_1.ClearingHoldCreationFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'clearingCreateHoldByPartition', [clearingOperation, hold], Constants_1.GAS.CLEARING_CREATE_HOLD_BY_PARTITION);
    }
    async clearingCreateHoldFromByPartition(security, partitionId, escrowId, amount, sourceId, targetId, clearingExpirationDate, holdExpirationDate) {
        LogService_1.default.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.executeTransaction(asset_tokenization_contracts_1.ClearingHoldCreationFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'clearingCreateHoldFromByPartition', [clearingOperationFrom, hold], Constants_1.GAS.CLEARING_CREATE_HOLD_FROM_BY_PARTITION);
    }
    async protectedClearingCreateHoldByPartition(security, partitionId, amount, escrowId, sourceId, targetId, clearingExpirationDate, holdExpirationDate, deadline, nonce, signature) {
        LogService_1.default.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.executeTransaction(asset_tokenization_contracts_1.ClearingHoldCreationFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'protectedClearingCreateHoldByPartition', [protectedClearingOperation, hold, signature], Constants_1.GAS.PROTECTED_CLEARING_CREATE_HOLD_BY_PARTITION);
    }
    async operatorClearingCreateHoldByPartition(security, partitionId, escrowId, amount, sourceId, targetId, clearingExpirationDate, holdExpirationDate) {
        LogService_1.default.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.executeTransaction(asset_tokenization_contracts_1.ClearingHoldCreationFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'operatorClearingCreateHoldByPartition', [clearingOperationFrom, hold], Constants_1.GAS.OPERATOR_CLEARING_CREATE_HOLD_BY_PARTITION);
    }
    async operatorClearingRedeemByPartition(security, partitionId, amount, sourceId, expirationDate) {
        LogService_1.default.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.executeTransaction(asset_tokenization_contracts_1.ClearingRedeemFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'operatorClearingRedeemByPartition', [clearingOperationFrom, amount.toBigNumber()], Constants_1.GAS.OPERATOR_CLEARING_REDEEM_BY_PARTITION);
    }
    async operatorClearingTransferByPartition(security, partitionId, amount, sourceId, targetId, expirationDate) {
        LogService_1.default.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.executeTransaction(asset_tokenization_contracts_1.ClearingTransferFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'clearingTransferFromByPartition', [clearingOperationFrom, amount.toBigNumber(), targetId.toString()], Constants_1.GAS.OPERATOR_CLEARING_TRANSFER_BY_PARTITION);
    }
    async updateExternalPauses(security, externalPausesAddresses, actives) {
        LogService_1.default.logTrace(`Updating External Pauses for security ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ExternalPauseManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'updateExternalPauses', [externalPausesAddresses.map((addr) => addr.toString()), actives], Constants_1.GAS.UPDATE_EXTERNAL_PAUSES);
    }
    async addExternalPause(security, externalPauseAddress) {
        LogService_1.default.logTrace(`Adding External Pause for security ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ExternalPauseManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'addExternalPause', [externalPauseAddress.toString()], Constants_1.GAS.ADD_EXTERNAL_PAUSE);
    }
    async removeExternalPause(security, externalPauseAddress) {
        LogService_1.default.logTrace(`Removing External Pause for security ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ExternalPauseManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'removeExternalPause', [externalPauseAddress.toString()], Constants_1.GAS.REMOVE_EXTERNAL_PAUSE);
    }
    async setPausedMock(contract, paused) {
        LogService_1.default.logTrace(`Setting paused to external pause mock contract ${contract.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.MockedExternalPause__factory.connect(contract.toString(), this.getSignerOrProvider()), 'setPaused', [paused], Constants_1.GAS.SET_PAUSED_MOCK);
    }
    async createExternalPauseMock() {
        LogService_1.default.logTrace(`Deploying External Pause Mock contract`);
        const factory = new asset_tokenization_contracts_1.MockedExternalPause__factory(this.getSignerOrProvider());
        const contract = await factory.deploy({
            gasLimit: Constants_1.GAS.CREATE_EXTERNAL_PAUSE_MOCK,
        });
        await contract.deployed();
        return contract.address;
    }
    async updateExternalControlLists(security, externalControlListsAddresses, actives) {
        LogService_1.default.logTrace(`Updating External Control Lists for security ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ExternalControlListManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'updateExternalControlLists', [externalControlListsAddresses.map((addr) => addr.toString()), actives], Constants_1.GAS.UPDATE_EXTERNAL_CONTROL_LISTS);
    }
    async addExternalControlList(security, externalControlListAddress) {
        LogService_1.default.logTrace(`Adding External Control List for security ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ExternalControlListManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'addExternalControlList', [externalControlListAddress.toString()], Constants_1.GAS.ADD_EXTERNAL_CONTROL_LIST);
    }
    async removeExternalControlList(security, externalControlListAddress) {
        LogService_1.default.logTrace(`Removing External Control List for security ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ExternalControlListManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'removeExternalControlList', [externalControlListAddress.toString()], Constants_1.GAS.REMOVE_EXTERNAL_CONTROL_LIST);
    }
    async addToBlackListMock(contract, targetId) {
        LogService_1.default.logTrace(`Adding address ${targetId.toString()} to external Control black List mock ${contract.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.MockedBlacklist__factory.connect(contract.toString(), this.getSignerOrProvider()), 'addToBlacklist', [targetId.toString()], Constants_1.GAS.ADD_TO_BLACK_LIST_MOCK);
    }
    async addToWhiteListMock(contract, targetId) {
        LogService_1.default.logTrace(`Adding address ${targetId.toString()} to external Control white List mock ${contract.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.MockedWhitelist__factory.connect(contract.toString(), this.getSignerOrProvider()), 'addToWhitelist', [targetId.toString()], Constants_1.GAS.ADD_TO_WHITE_LIST_MOCK);
    }
    async removeFromBlackListMock(contract, targetId) {
        LogService_1.default.logTrace(`Removing address ${targetId.toString()} from external Control black List mock ${contract.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.MockedBlacklist__factory.connect(contract.toString(), this.getSignerOrProvider()), 'removeFromBlacklist', [targetId.toString()], Constants_1.GAS.REMOVE_FROM_BLACK_LIST_MOCK);
    }
    async removeFromWhiteListMock(contract, targetId) {
        LogService_1.default.logTrace(`Removing address ${targetId.toString()} from external Control white List mock ${contract.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.MockedWhitelist__factory.connect(contract.toString(), this.getSignerOrProvider()), 'removeFromWhitelist', [targetId.toString()], Constants_1.GAS.REMOVE_FROM_WHITE_LIST_MOCK);
    }
    async createExternalBlackListMock() {
        LogService_1.default.logTrace(`Deploying External Control Black List Mock contract`);
        const factory = new asset_tokenization_contracts_1.MockedBlacklist__factory(this.getSignerOrProvider());
        const contract = await factory.deploy({
            gasLimit: Constants_1.GAS.CREATE_EXTERNAL_BLACK_LIST_MOCK,
        });
        await contract.deployed();
        return contract.address;
    }
    async createExternalWhiteListMock() {
        LogService_1.default.logTrace(`Deploying External Control White List Mock contract`);
        const factory = new asset_tokenization_contracts_1.MockedWhitelist__factory(this.getSignerOrProvider());
        const contract = await factory.deploy({
            gasLimit: Constants_1.GAS.CREATE_EXTERNAL_WHITE_LIST_MOCK,
        });
        await contract.deployed();
        return contract.address;
    }
    async updateExternalKycLists(security, externalKycListsAddresses, actives) {
        LogService_1.default.logTrace(`Updating External Kyc Lists for security ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ExternalKycListManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'updateExternalKycLists', [externalKycListsAddresses.map((address) => address.toString()), actives], Constants_1.GAS.UPDATE_EXTERNAL_KYC_LISTS);
    }
    async addExternalKycList(security, externalKycListAddress) {
        LogService_1.default.logTrace(`Adding External kyc List for security ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ExternalKycListManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'addExternalKycList', [externalKycListAddress.toString()], Constants_1.GAS.ADD_EXTERNAL_KYC_LIST);
    }
    async removeExternalKycList(security, externalKycListAddress) {
        LogService_1.default.logTrace(`Removing External kyc List for security ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ExternalKycListManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'removeExternalKycList', [externalKycListAddress.toString()], Constants_1.GAS.REMOVE_EXTERNAL_KYC_LIST);
    }
    async grantKycMock(contract, targetId) {
        LogService_1.default.logTrace(`Grant kyc address ${targetId.toString()} to external kyc mock ${contract.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.MockedExternalKycList__factory.connect(contract.toString(), this.getSignerOrProvider()), 'grantKyc', [targetId.toString()], Constants_1.GAS.GRANT_KYC_MOCK);
    }
    async revokeKycMock(contract, targetId) {
        LogService_1.default.logTrace(`Revoke kyc address ${targetId.toString()} to external kyc mock ${contract.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.MockedExternalKycList__factory.connect(contract.toString(), this.getSignerOrProvider()), 'revokeKyc', [targetId.toString()], Constants_1.GAS.REVOKE_KYC_MOCK);
    }
    async createExternalKycListMock() {
        LogService_1.default.logTrace(`Deploying External Kyc List Mock contract`);
        const factory = new asset_tokenization_contracts_1.MockedExternalKycList__factory(this.getSignerOrProvider());
        const contract = await factory.deploy({
            gasLimit: Constants_1.GAS.CREATE_EXTERNAL_KYC_LIST_MOCK,
        });
        await contract.deployed();
        return contract.address;
    }
    async activateInternalKyc(security) {
        LogService_1.default.logTrace(`Activating Internal Kyc to address ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.KycFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'activateInternalKyc', [], Constants_1.GAS.ACTIVATE_INTERNAL_KYC);
    }
    async deactivateInternalKyc(security) {
        LogService_1.default.logTrace(`Deactivate Internal Kyc to address ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.KycFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'deactivateInternalKyc', [], Constants_1.GAS.DEACTIVATE_INTERNAL_KYC);
    }
    async setName(security, name) {
        LogService_1.default.logTrace(`Setting name to ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC3643ManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'setName', [name], Constants_1.GAS.SET_NAME);
    }
    async setSymbol(security, symbol) {
        LogService_1.default.logTrace(`Setting symbol to ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC3643ManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'setSymbol', [symbol], Constants_1.GAS.SET_SYMBOL);
    }
    async setOnchainID(security, onchainID) {
        LogService_1.default.logTrace(`Setting onchainID to ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC3643ManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'setOnchainID', [onchainID.toString()], Constants_1.GAS.SET_ONCHAIN_ID);
    }
    async setIdentityRegistry(security, identityRegistry) {
        LogService_1.default.logTrace(`Setting Identity Registry to ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC3643ManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'setIdentityRegistry', [identityRegistry.toString()], Constants_1.GAS.SET_IDENTITY_REGISTRY);
    }
    async setCompliance(security, compliance) {
        LogService_1.default.logTrace(`Setting Compliance to ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC3643ManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'setCompliance', [compliance.toString()], Constants_1.GAS.SET_COMPLIANCE);
    }
    async freezePartialTokens(security, amount, targetId) {
        LogService_1.default.logTrace(`Freezing ${amount} tokens ${security.toString()} to account ${targetId.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.FreezeFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'freezePartialTokens', [targetId.toString(), amount.toBigNumber()], Constants_1.GAS.FREEZE_PARTIAL_TOKENS);
    }
    async unfreezePartialTokens(security, amount, targetId) {
        LogService_1.default.logTrace(`Unfreezing ${amount} tokens ${security.toString()} to account ${targetId.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.FreezeFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'unfreezePartialTokens', [targetId.toString(), amount.toBigNumber()], Constants_1.GAS.UNFREEZE_PARTIAL_TOKENS);
    }
    async recoveryAddress(security, lostWallet, newWallet) {
        LogService_1.default.logTrace(`Recovering address ${lostWallet.toString()} to ${newWallet.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC3643ManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'recoveryAddress', [lostWallet.toString(), newWallet.toString(), Constants_1.EVM_ZERO_ADDRESS], Constants_1.GAS.RECOVERY_ADDRESS);
    }
    async addAgent(security, agentId) {
        LogService_1.default.logTrace(`Granting agent role to ${agentId.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC3643ManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'addAgent', [agentId.toString()], Constants_1.GAS.ADD_AGENT);
    }
    async removeAgent(security, agentId) {
        LogService_1.default.logTrace(`Revoking agent role from ${agentId.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC3643ManagementFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'removeAgent', [agentId.toString()], Constants_1.GAS.REMOVE_AGENT);
    }
    async batchTransfer(security, amountList, toList) {
        LogService_1.default.logTrace(`Batch transferring ${amountList.length} token amounts from ${security.toString()} to ${toList.map((item) => item.toString()).join(', ')}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC3643BatchFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'batchTransfer', [
            toList.map((account) => account.toString()),
            amountList.map((item) => item.toBigNumber()),
        ], Constants_1.GAS.BATCH_TRANSFER);
    }
    async batchForcedTransfer(security, amountList, fromList, toList) {
        LogService_1.default.logTrace(`Batch forced transferring ${amountList.length} token amounts from ${fromList.map((item) => item.toString())} to ${toList.map((item) => item.toString())}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC3643BatchFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'batchForcedTransfer', [
            fromList.map((item) => item.toString()),
            toList.map((item) => item.toString()),
            amountList.map((item) => item.toBigNumber()),
        ], Constants_1.GAS.BATCH_FORCED_TRANSFER);
    }
    async batchMint(security, amountList, toList) {
        LogService_1.default.logTrace(`Batch minting ${amountList.length} token amounts on ${security.toString()} to ${toList.map((item) => item.toString())}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC3643BatchFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'batchMint', [
            toList.map((item) => item.toString()),
            amountList.map((item) => item.toBigNumber()),
        ], Constants_1.GAS.BATCH_MINT);
    }
    async batchBurn(security, amountList, targetList) {
        LogService_1.default.logTrace(`Batch burning ${amountList.length} token amounts from ${targetList.map((item) => item.toString())}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ERC3643BatchFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'batchBurn', [
            targetList.map((item) => item.toString()),
            amountList.map((item) => item.toBigNumber()),
        ], Constants_1.GAS.BATCH_BURN);
    }
    async batchSetAddressFrozen(security, freezeList, targetList) {
        LogService_1.default.logTrace(`Batch setting address frozen status on ${targetList.length} addresses from ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.FreezeFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'batchSetAddressFrozen', [targetList.map((item) => item.toString()), freezeList], Constants_1.GAS.BATCH_SET_ADDRESS_FROZEN);
    }
    async batchFreezePartialTokens(security, amountList, targetList) {
        LogService_1.default.logTrace(`Batch freezing partial tokens (${amountList.length}) on ${security.toString()} for targets ${targetList.map((item) => item.toString())}`);
        return this.executeTransaction(asset_tokenization_contracts_1.FreezeFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'batchFreezePartialTokens', [
            targetList.map((item) => item.toString()),
            amountList.map((item) => item.toBigNumber()),
        ], Constants_1.GAS.BATCH_FREEZE_PARTIAL_TOKENS);
    }
    async batchUnfreezePartialTokens(security, amountList, targetList) {
        LogService_1.default.logTrace(`Batch unfreezing partial tokens (${amountList.length}) on ${security.toString()} for targets ${targetList.map((item) => item.toString())}`);
        return this.executeTransaction(asset_tokenization_contracts_1.FreezeFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'batchUnfreezePartialTokens', [
            targetList.map((item) => item.toString()),
            amountList.map((item) => item.toBigNumber()),
        ], Constants_1.GAS.BATCH_UNFREEZE_PARTIAL_TOKENS);
    }
    async setAddressFrozen(security, status, target) {
        LogService_1.default.logTrace(`Freezing address ${target.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.FreezeFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'setAddressFrozen', [target.toString(), status], Constants_1.GAS.SET_ADDRESS_FROZEN);
    }
    async redeemAtMaturityByPartition(security, partitionId, sourceId, amount) {
        LogService_1.default.logTrace(`Redeeming at maturity by partition to address ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.Bond__factory.connect(security.toString(), this.getSignerOrProvider()), 'redeemAtMaturityByPartition', [sourceId.toString(), partitionId, amount.toBigNumber()], Constants_1.GAS.REDEEM_AT_MATURITY_BY_PARTITION_GAS);
    }
    async fullRedeemAtMaturity(security, sourceId) {
        LogService_1.default.logTrace(`Full redeeming at maturity to address ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.Bond__factory.connect(security.toString(), this.getSignerOrProvider()), 'fullRedeemAtMaturity', [sourceId.toString()], Constants_1.GAS.FULL_REDEEM_AT_MATURITY_GAS);
    }
    async executeTransaction(factory, method, args, gasLimit, eventName) {
        LogService_1.default.logTrace(`Executing ${method} with args:`, args);
        const fn = factory[method];
        const tx = await fn(...args, { gasLimit });
        return RPCTransactionResponseAdapter_1.RPCTransactionResponseAdapter.manageResponse(tx, this.networkService.environment, eventName);
    }
    async createSecurity(securityInfo, details, factory, resolver, configId, configVersion, externalPauses = [], externalControlLists = [], externalKycLists = [], diamondOwnerAccount, createToken, deployMethod, gasLimit, eventName, compliance, identityRegistry) {
        try {
            const securityData = SecurityDataBuilder_1.SecurityDataBuilder.buildSecurityData(securityInfo, resolver, configId, configVersion, externalPauses, externalControlLists, externalKycLists, diamondOwnerAccount, compliance, identityRegistry);
            const regulationData = SecurityDataBuilder_1.SecurityDataBuilder.buildRegulationData(securityInfo);
            const securityToken = createToken(securityData, details);
            const factoryInstance = asset_tokenization_contracts_1.Factory__factory.connect(factory.toString(), this.getSignerOrProvider());
            LogService_1.default.logTrace(`Deploying ${deployMethod}: `, {
                security: securityToken,
            });
            const res = await factoryInstance[deployMethod](securityToken, regulationData, { gasLimit });
            return await RPCTransactionResponseAdapter_1.RPCTransactionResponseAdapter.manageResponse(res, this.networkService.environment, eventName);
        }
        catch (error) {
            LogService_1.default.logError(error);
            throw new SigningError_1.SigningError(`Unexpected error in ${deployMethod} operation: ${error}`);
        }
    }
    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) {
        return this.createTrexSuite('bond', 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);
    }
    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) {
        return this.createTrexSuite('equity', salt, owner, irs, onchainId, irAgents, tokenAgents, compliancesModules, complianceSettings, claimTopics, issuers, issuerClaims, security, equityDetails, factory, resolver, configId, configVersion, compliance, identityRegistryAddress, diamondOwnerAccount, [], [], externalPauses, externalControlLists, externalKycLists);
    }
    async createTrexSuite(tokenType, salt, owner, irs, onchainId, irAgents, tokenAgents, compliancesModules, complianceSettings, claimTopics, issuers, issuerClaims, security, tokenDetails, factory, resolver, configId, configVersion, compliance, identityRegistryAddress, diamondOwnerAccount, proceedRecipientsId, proceedRecipientsData, externalPauses, externalControlLists, externalKycLists) {
        const securityData = SecurityDataBuilder_1.SecurityDataBuilder.buildSecurityData(security, resolver, configId, configVersion, externalPauses, externalControlLists, externalKycLists, diamondOwnerAccount, compliance, identityRegistryAddress);
        const regulationData = SecurityDataBuilder_1.SecurityDataBuilder.buildRegulationData(security);
        let tokenData;
        if (tokenType === 'bond') {
            const details = tokenDetails;
            tokenData = {
                security: securityData,
                bondDetails: SecurityDataBuilder_1.SecurityDataBuilder.buildBondDetails(details.bondDetails),
                proceedRecipients: proceedRecipientsId.map((addr) => addr.toString()),
                proceedRecipientsData: proceedRecipientsData.map((data) => data == '' ? '0x' : data),
            };
        }
        else {
            tokenData = {
                security: securityData,
                equityDetails: SecurityDataBuilder_1.SecurityDataBuilder.buildEquityDetails(tokenDetails),
            };
        }
        const factoryContract = asset_tokenization_contracts_1.TREXFactoryAts__factory.connect(factory.toString(), this.getSignerOrProvider());
        LogService_1.default.logTrace(`Deploying TrexSuiteAts${tokenType.charAt(0).toUpperCase() + tokenType.slice(1)}:`, {
            security: tokenData,
        });
        const methodMap = {
            bond: 'deployTREXSuiteAtsBond',
            equity: 'deployTREXSuiteAtsEquity',
        };
        try {
            return this.executeTransaction(factoryContract, methodMap[tokenType], [
                salt,
                {
                    owner,
                    irs,
                    ONCHAINID: onchainId,
                    irAgents,
                    tokenAgents,
                    complianceModules: compliancesModules,
                    complianceSettings,
                },
                {
                    claimTopics,
                    issuers,
                    issuerClaims,
                },
                tokenData,
                regulationData,
            ], Constants_1.GAS.TREX_CREATE_SUITE, 'TREXSuiteDeployed');
        }
        catch (error) {
            LogService_1.default.logError(error);
            throw new SigningError_1.SigningError(`Unexpected error in ${methodMap[tokenType]} operation: ${error}`);
        }
    }
    addProceedRecipient(security, proceedRecipient, data, securityId) {
        LogService_1.default.logTrace(`Adding proceed recipient ${proceedRecipient.toString()} to security ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ProceedRecipientsFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'addProceedRecipient', [proceedRecipient.toString(), data], Constants_1.GAS.ADD_PROCEED_RECIPIENT);
    }
    removeProceedRecipient(security, proceedRecipient, securityId) {
        LogService_1.default.logTrace(`Removing proceed recipient ${proceedRecipient.toString()} from security ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ProceedRecipientsFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'removeProceedRecipient', [proceedRecipient.toString()], Constants_1.GAS.REMOVE_PROCEED_RECIPIENT);
    }
    updateProceedRecipientData(security, proceedRecipient, data) {
        LogService_1.default.logTrace(`Updating proceed recipient ${proceedRecipient.toString()} for security ${security.toString()}`);
        return this.executeTransaction(asset_tokenization_contracts_1.ProceedRecipientsFacet__factory.connect(security.toString(), this.getSignerOrProvider()), 'updateProceedRecipientData', [proceedRecipient.toString(), data], Constants_1.GAS.UPDATE_PROCEED_RECIPIENT);
    }
};
exports.RPCTransactionAdapter = RPCTransactionAdapter;
exports.RPCTransactionAdapter = RPCTransactionAdapter = __decorate([
    (0, tsyringe_1.singleton)(),
    __param(0, (0, LazyInjectDecorator_1.lazyInject)(MirrorNodeAdapter_1.MirrorNodeAdapter)),
    __param(1, (0, LazyInjectDecorator_1.lazyInject)(NetworkService_1.default)),
    __param(2, (0, LazyInjectDecorator_1.lazyInject)(EventService_1.default)),
    __param(3, (0, LazyInjectDecorator_1.lazyInject)(CommandBus_1.CommandBus)),
    __metadata("design:paramtypes", [MirrorNodeAdapter_1.MirrorNodeAdapter,
        NetworkService_1.default,
        EventService_1.default,
        CommandBus_1.CommandBus])
], RPCTransactionAdapter);
