# [Contract] TREXGateway

> このコントラクトは、TREXFactoryコントラクトを管理し、トークンのデプロイプロセスを制御するためのゲートウェイとして機能します。

- URL: https://cardene.dev/books/erc3643/8c6b12
- 本: ERC3643 (https://cardene.dev/books/erc3643.md)
- 章: 12 / 20
- 前の章: https://cardene.dev/books/erc3643/79837a.md
- 次の章: https://cardene.dev/books/erc3643/45e52c.md
- 公開日: 2025-07-25
- 更新日: 2025-07-25
- トピック: Blockchain
- タグ: ブロックチェーン, solidity, ethereum, smartcontract

## 概要

このコントラクトは、**TREXFactory**コントラクトを管理し、トークンのデプロイプロセスを制御するためのゲートウェイとして機能します。
デプロイ権限を持つ「**デプロイヤー**」の管理、デプロイ手数料の設定と徴収、一般ユーザーによるデプロイの可否など、**TREXFactory**コントラクトへのアクセスに関する全てのルールを定義します。

**TREXGateway**は、**TREXFactory**の`owner`として設定されることで、そのデプロイ機能を管理します。
このゲートウェイを通じて、トークン発行者は直接ファクトリーを操作するのではなく、定義されたルールに従って安全にトークン一式をデプロイできます。

主な役割は、ロールベースのアクセス制御です。
オーナーとエージェントは「**デプロイヤー**」と呼ばれるアドレスを承認リストに追加・削除でき、パブリックデプロイが無効な場合は、このリストにあるアドレスのみがデプロイを実行できます。
さらに、デプロイ手数料を有効にし、指定されたトークンでの支払いを強制する機能や、特定のデプロイヤーに割引を適用する機能も備えています。

また、デプロイ時に使用される`salt`をトークン所有者のアドレスとトークン名から決定論的に生成することで、クロスチェーンでの不正な複製を防ぐセキュリティ機能も実装しています。
これにより、柔軟な権限管理とセキュリティを両立させた、統制のとれたトークン発行環境を提供します。

**TREXFactory**の管理については、デプロイしているコントラクトのロジックをUpgradeすることができます。


## 機能

* **TREXFactory**の管理とデプロイ機能の実行
* ロールベースのアクセス制御（オーナー、エージェント、デプロイヤー）
* デプロイ手数料の有効化、設定、徴収、割引適用
* 一般ユーザーによるデプロイ（パブリックデプロイ）の有効化・無効化
* クロスチェーンのセキュリティを考慮した`salt`の自動生成

## フロー

### ゲートウェイを通じたトークンスイートのデプロイ

```mermaid
sequenceDiagram
    actor Deployer as デプロイヤー
    participant Gateway as TREXGateway
    participant FeeToken as 手数料トークン (IERC20)
    participant Factory as TREXFactory

    Deployer->>Gateway: 1. deployTREXSuite(tokenDetails, claimDetails)
    activate Gateway

    alt 手数料が有効な場合
        Gateway->>Gateway: 2. calculateFee(Deployer)
        Note right of Gateway: 割引を適用した手数料を計算
        Gateway->>FeeToken: 3. transferFrom(Deployer, feeCollector, fee)
        Note left of FeeToken: 手数料を徴収
    end

    Gateway->>Gateway: 4. _salt を生成 (owner + name)
    
    Gateway->>Factory: 5. deployTREXSuite(_salt, tokenDetails, claimDetails)
    activate Factory
    Note over Factory: トークン一式をデプロイ
    Factory-->>Gateway: 成功
    deactivate Factory

    Gateway-->>Deployer: 6. 成功 (GatewaySuiteDeploymentProcessedイベント発行)
    deactivate Gateway
```

## コード

```sol:TREXGateway.sol
// SPDX-License-Identifier: GPL-3.0
//
//                                             :+#####%%%%%%%%%%%%%%+
//                                         .-*@@@%+.:+%@@@@@%%#***%@@%=
//                                     :=*%@@@#=.      :#@@%       *@@@%=
//                       .-+*%@%*-.:+%@@@@@@+.     -*+:  .=#.       :%@@@%-
//                   :=*@@@@%%@@@@@@@@@%@@@-   .=#@@@%@%=             =@@@@#.
//             -=+#%@@%#*=:.  :%@@@@%.   -*@@#*@@@@@@@#=:-              *@@@@+
//            =@@%=:.     :=:   *@@@@@%#-   =%*%@@@@#+-.        =+       :%@@@%-
//           -@@%.     .+@@@     =+=-.         @@#-           +@@@%-       =@@@@%:
//          :@@@.    .+@@#%:                   :    .=*=-::.-%@@@+*@@=       +@@@@#.
//          %@@:    +@%%*                         =%@@@@@@@@@@@#.  .*@%-       +@@@@*.
//         #@@=                                .+@@@@%:=*@@@@@-      :%@%:      .*@@@@+
//        *@@*                                +@@@#-@@%-:%@@*          +@@#.      :%@@@@-
//       -@@%           .:-=++*##%%%@@@@@@@@@@@@*. :@+.@@@%:            .#@@+       =@@@@#:
//      .@@@*-+*#%%%@@@@@@@@@@@@@@@@%%#**@@%@@@.   *@=*@@#                :#@%=      .#@@@@#-
//      -%@@@@@@@@@@@@@@@*+==-:-@@@=    *@# .#@*-=*@@@@%=                 -%@@@*       =@@@@@%-
//         -+%@@@#.   %@%%=   -@@:+@: -@@*    *@@*-::                   -%@@%=.         .*@@@@@#
//            *@@@*  +@* *@@##@@-  #@*@@+    -@@=          .         :+@@@#:           .-+@@@%+-
//             +@@@%*@@:..=@@@@*   .@@@*   .#@#.       .=+-       .=%@@@*.         :+#@@@@*=:
//              =@@@@%@@@@@@@@@@@@@@@@@@@@@@%-      :+#*.       :*@@@%=.       .=#@@@@%+:
//               .%@@=                 .....    .=#@@+.       .#@@@*:       -*%@@@@%+.
//                 +@@#+===---:::...         .=%@@*-         +@@@+.      -*@@@@@%+.
//                  -@@@@@@@@@@@@@@@@@@@@@@%@@@@=          -@@@+      -#@@@@@#=.
//                    ..:::---===+++***###%%%@@@#-       .#@@+     -*@@@@@#=.
//                                           @@@@@@+.   +@@*.   .+@@@@@%=.
//                                          -@@@@@=   =@@%:   -#@@@@%+.
//                                          +@@@@@. =@@@=  .+@@@@@*:
//                                          #@@@@#:%@@#. :*@@@@#-
//                                          @@@@@%@@@= :#@@@@+.
//                                         :@@@@@@@#.:#@@@%-
//                                         +@@@@@@-.*@@@*:
//                                         #@@@@#.=@@@+.
//                                         @@@@+-%@%=
//                                        :@@@#%@%=
//                                        +@@@@%-
//                                        :#%%=
//
/**
 *     NOTICE
 *
 *     The T-REX software is licensed under a proprietary license or the GPL v.3.
 *     If you choose to receive it under the GPL v.3 license, the following applies:
 *     T-REX is a suite of smart contracts implementing the ERC-3643 standard and
 *     developed by Tokeny to manage and transfer financial assets on EVM blockchains
 *
 *     Copyright (C) 2023, Tokeny sàrl.
 *
 *     This program is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     This program is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
pragma solidity 0.8.17;

import "./ITREXGateway.sol";
import "../roles/AgentRole.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/// A required parameter was set to the Zero address.
error ZeroAddress();

/// The Public Deployment Status is already set properly
error PublicDeploymentAlreadyEnabled();

/// The Public Deployment Status is already set properly
error PublicDeploymentAlreadyDisabled();

/// The Deployment fees are already enabled
error DeploymentFeesAlreadyEnabled();

/// The Deployment fees are already disabled
error DeploymentFeesAlreadyDisabled();

/// The address is already a deployer
error DeployerAlreadyExists(address deployer);

/// The address is not a deployer
error DeployerDoesNotExist(address deployer);

/// Cannot deploy if not deployer when public deployment disabled
error PublicDeploymentsNotAllowed();

/// Public deployers can only deploy for themselves
error PublicCannotDeployOnBehalf();

/// Discount cannot be bigger than 10000 (100%)
error DiscountOutOfRange();

/// Only Owner or Agent can call
error OnlyAdminCall();

/// Batch Size is too big, could run out of gas
error BatchMaxLengthExceeded(uint16 lengthLimit);


contract TREXGateway is ITREXGateway, AgentRole {

    /// address of the TREX Factory that is managed by the Gateway
    address private _factory;

    /// public deployment status variable
    bool private _publicDeploymentStatus;

    /// deployment fee details
    Fee private _deploymentFee;

    /// deployment fees enabling variable
    bool private _deploymentFeeEnabled;

    /// mapping containing all deployer addresses
    mapping(address => bool) private _deployers;

    /// mapping for deployment discounts on fees
    mapping(address => uint16) private _feeDiscount;

    /// constructor of the contract, setting up the factory address and
    /// the public deployment status
    constructor(address factory, bool publicDeploymentStatus) {
        _factory = factory;
        _publicDeploymentStatus = publicDeploymentStatus;
        emit FactorySet(factory);
        emit PublicDeploymentStatusSet(publicDeploymentStatus);
    }

    /**
     *  @dev See {ITREXGateway-setFactory}.
     */
    function setFactory(address factory) external override onlyOwner {
        if(factory == address(0)) {
            revert ZeroAddress();
        }
        _factory = factory;
        emit FactorySet(factory);
    }

    /**
     *  @dev See {ITREXGateway-setPublicDeploymentStatus}.
     */
    function setPublicDeploymentStatus(bool _isEnabled) external override onlyOwner {
        if(_isEnabled == _publicDeploymentStatus && _isEnabled == true) {
            revert PublicDeploymentAlreadyEnabled();
        }
        if(_isEnabled == _publicDeploymentStatus && _isEnabled == false) {
            revert PublicDeploymentAlreadyDisabled();
        }
        _publicDeploymentStatus = _isEnabled;
        emit PublicDeploymentStatusSet(_isEnabled);
    }

    /**
     *  @dev See {ITREXGateway-transferFactoryOwnership}.
     */
    function transferFactoryOwnership(address _newOwner) external override onlyOwner {
        Ownable(_factory).transferOwnership(_newOwner);
    }

    /**
     *  @dev See {ITREXGateway-enableDeploymentFee}.
     */
    function enableDeploymentFee(bool _isEnabled) external override onlyOwner {
        if(_isEnabled == _deploymentFeeEnabled && _isEnabled == true) {
            revert DeploymentFeesAlreadyEnabled();
        }
        if(_isEnabled == _deploymentFeeEnabled && _isEnabled == false) {
            revert DeploymentFeesAlreadyDisabled();
        }
        _deploymentFeeEnabled = _isEnabled;
        emit DeploymentFeeEnabled(_isEnabled);
    }

    /**
     *  @dev See {ITREXGateway-setDeploymentFee}.
     */
    function setDeploymentFee(uint256 _fee, address _feeToken, address _feeCollector) external override onlyOwner {
        if(_feeToken == address(0) || _feeCollector == address(0)) {
            revert ZeroAddress();
        }
        _deploymentFee.fee = _fee;
        _deploymentFee.feeToken = _feeToken;
        _deploymentFee.feeCollector = _feeCollector;
        emit DeploymentFeeSet(_fee, _feeToken, _feeCollector);
    }

    /**
     *  @dev See {ITREXGateway-batchAddDeployer}.
     */
    function batchAddDeployer(address[] calldata deployers) external override {
        if(!isAgent(msg.sender) && msg.sender != owner()) {
            revert OnlyAdminCall();
        }
        if(deployers.length > 500) {
            revert BatchMaxLengthExceeded(500);
        }
        for (uint256 i = 0; i < deployers.length; i++) {
            if(isDeployer(deployers[i])) {
                revert DeployerAlreadyExists(deployers[i]);
            }
            _deployers[deployers[i]] = true;
            emit DeployerAdded(deployers[i]);
        }
    }

    /**
     *  @dev See {ITREXGateway-addDeployer}.
     */
    function addDeployer(address deployer) external override {
        if(!isAgent(msg.sender) && msg.sender != owner()) {
            revert OnlyAdminCall();
        }
        if(isDeployer(deployer)) {
            revert DeployerAlreadyExists(deployer);
        }
        _deployers[deployer] = true;
        emit DeployerAdded(deployer);
    }

    /**
     *  @dev See {ITREXGateway-batchRemoveDeployer}.
     */
    function batchRemoveDeployer(address[] calldata deployers) external override {
        if(!isAgent(msg.sender) && msg.sender != owner()) {
            revert OnlyAdminCall();
        }
        if(deployers.length > 500) {
            revert BatchMaxLengthExceeded(500);
        }
        for (uint256 i = 0; i < deployers.length; i++) {
            if(!isDeployer(deployers[i])) {
                revert DeployerDoesNotExist(deployers[i]);
            }
            delete _deployers[deployers[i]];
            emit DeployerRemoved(deployers[i]);
        }
    }

    /**
     *  @dev See {ITREXGateway-removeDeployer}.
     */
    function removeDeployer(address deployer) external override {
        if(!isAgent(msg.sender) && msg.sender != owner()) {
            revert OnlyAdminCall();
        }
        if(!isDeployer(deployer)) {
            revert DeployerDoesNotExist(deployer);
        }
        delete _deployers[deployer];
        emit DeployerRemoved(deployer);
    }

    /**
     *  @dev See {ITREXGateway-batchApplyFeeDiscount}.
     */
    function batchApplyFeeDiscount(address[] calldata deployers, uint16[] calldata discounts) external override {
        if(!isAgent(msg.sender) && msg.sender != owner()) {
            revert OnlyAdminCall();
        }
        if(deployers.length > 500) {
            revert BatchMaxLengthExceeded(500);
        }
        for (uint256 i = 0; i < deployers.length; i++) {
            if(discounts[i] > 10000) {
                revert DiscountOutOfRange();
            }
            _feeDiscount[deployers[i]] = discounts[i];
            emit FeeDiscountApplied(deployers[i], discounts[i]);
        }
    }

    /**
     *  @dev See {ITREXGateway-applyFeeDiscount}.
     */
    function applyFeeDiscount(address deployer, uint16 discount) external override {
        if(!isAgent(msg.sender) && msg.sender != owner()) {
            revert OnlyAdminCall();
        }
        if(discount > 10000) {
            revert DiscountOutOfRange();
        }
        _feeDiscount[deployer] = discount;
        emit FeeDiscountApplied(deployer, discount);
    }

    /**
     *  @dev See {ITREXGateway-batchDeployTREXSuite}.
     */
    function batchDeployTREXSuite(
        ITREXFactory.TokenDetails[] memory _tokenDetails,
        ITREXFactory.ClaimDetails[] memory _claimDetails) external override
    {
        if(_tokenDetails.length > 5) {
            revert BatchMaxLengthExceeded(5);
        }
        for (uint256 i = 0; i < _tokenDetails.length; i++) {
            deployTREXSuite(_tokenDetails[i], _claimDetails[i]);
        }
    }

    /**
     *  @dev See {ITREXGateway-getPublicDeploymentStatus}.
     */
    function getPublicDeploymentStatus() external override view returns(bool) {
        return _publicDeploymentStatus;
    }

    /**
     *  @dev See {ITREXGateway-getFactory}.
     */
    function getFactory() external override view returns(address) {
        return _factory;
    }

    /**
     *  @dev See {ITREXGateway-getDeploymentFee}.
     */
    function getDeploymentFee() external override view returns(Fee memory) {
        return _deploymentFee;
    }

    /**
     *  @dev See {ITREXGateway-isDeploymentFeeEnabled}.
     */
    function isDeploymentFeeEnabled() external override view returns(bool) {
        return _deploymentFeeEnabled;
    }

    /**
     *  @dev See {ITREXGateway-deployTREXSuite}.
     */
    function deployTREXSuite(ITREXFactory.TokenDetails memory _tokenDetails, ITREXFactory.ClaimDetails memory _claimDetails)
    public override {
        if(_publicDeploymentStatus == false && !isDeployer(msg.sender)) {
            revert PublicDeploymentsNotAllowed();
        }
        if(_publicDeploymentStatus == true && msg.sender != _tokenDetails.owner && !isDeployer(msg.sender)) {
            revert PublicCannotDeployOnBehalf();
        }
        uint256 feeApplied = 0;
        if(_deploymentFeeEnabled == true) {
            if(_deploymentFee.fee > 0 && _feeDiscount[msg.sender] < 10000) {
                feeApplied = calculateFee(msg.sender);
                IERC20(_deploymentFee.feeToken).transferFrom(
                    msg.sender,
                    _deploymentFee.feeCollector,
                    feeApplied
                );
            }
        }
        string memory _salt  = string(abi.encodePacked(Strings.toHexString(_tokenDetails.owner), _tokenDetails.name));
        ITREXFactory(_factory).deployTREXSuite(_salt, _tokenDetails, _claimDetails);
        emit GatewaySuiteDeploymentProcessed(msg.sender, _tokenDetails.owner, feeApplied);
    }

    /**
     *  @dev See {ITREXGateway-isDeployer}.
     */
    function isDeployer(address deployer) public override view returns(bool) {
        return _deployers[deployer];
    }

    /**
     *  @dev See {ITREXGateway-calculateFee}.
     */
    function calculateFee(address deployer) public override view returns(uint256) {
        return _deploymentFee.fee - ((_feeDiscount[deployer] * _deploymentFee.fee) / 10000);
    }
}
```

## 変数

### `_factory`

```solidity
address private _factory;
```

このゲートウェイが管理・操作する**TREXFactory**コントラクトのアドレスを保持。

### `_publicDeploymentStatus`

```solidity
bool private _publicDeploymentStatus;
```

一般ユーザーによるトークンのデプロイ（パブリックデプロイ）が許可されているかどうかの状態を`true`または`false`で保持。

### `_deploymentFee`

```solidity
Fee private _deploymentFee;
```

デプロイ手数料に関する詳細（金額、支払いトークンアドレス、徴収先アドレス）を`Fee`構造体で管理。

### `_deploymentFeeEnabled`

```solidity
bool private _deploymentFeeEnabled;
```

デプロイ手数料が有効化されているかどうかの状態を`true`または`false`で保持。

### `_deployers`

```solidity
mapping(address => bool) private _deployers;
```

デプロイ権限を承認された「**デプロイヤー**」のアドレスをキーとして、その権限の有無を`true`または`false`で記録する`mapping`。

### `_feeDiscount`

```solidity
mapping(address => uint16) private _feeDiscount;
```

デプロイヤーのアドレスをキーとして、そのデプロイヤーに適用される手数料の割引率を10,000分率（`uint16`）で記録する`mapping`。

## イベント

### `FactorySet`

```solidity
event FactorySet(address indexed factory);
```

管理対象の**TREXFactory**コントラクトのアドレスが設定または変更された時に発行されるイベント。

### `PublicDeploymentStatusSet`

```solidity
event PublicDeploymentStatusSet(bool indexed publicDeploymentStatus);
```

パブリックデプロイのステータスが有効または無効に設定された時に発行されるイベント。

### `DeploymentFeeSet`

```solidity
event DeploymentFeeSet(uint256 indexed fee, address indexed feeToken, address indexed feeCollector);
```

デプロイ手数料の詳細（金額、トークン、徴収先）が設定または変更された時に発行されるイベント。

### `DeploymentFeeEnabled`

```solidity
event DeploymentFeeEnabled(bool indexed isEnabled);
```

デプロイ手数料が有効化または無効化された時に発行されるイベント。

### `DeployerAdded`

```solidity
event DeployerAdded(address indexed deployer);
```

新しいアドレスがデプロイヤーとして承認リストに追加された時に発行されるイベント。

### `DeployerRemoved`

```solidity
event DeployerRemoved(address indexed deployer);
```

デプロイヤーのアドレスが承認リストから削除された時に発行されるイベント。

### `FeeDiscountApplied`

```solidity
event FeeDiscountApplied(address indexed deployer, uint16 discount);
```

特定のデプロイヤーに手数料の割引が適用された時に発行されるイベント。

### `GatewaySuiteDeploymentProcessed`

```solidity
event GatewaySuiteDeploymentProcessed(address indexed requester, address intendedOwner, uint256 feeApplied);
```

このゲートウェイを通じて**TREXFactory**コントラクトがトークン一式のデプロイを正常に処理した時に発行されるイベント。

## 関数

### `setFactory`

```solidity
function setFactory(address factory) external override onlyOwner {
    if(factory == address(0)) {
        revert ZeroAddress();
    }
    _factory = factory;
    emit FactorySet(factory);
}
```

このゲートウェイが管理する**TREXFactory**コントラクトのアドレスを設定する関数。
`onlyOwner`修飾子により、このコントラクトの所有者のみが呼び出し可能です。
引数にゼロアドレスを渡すと、`ZeroAddress`エラーで処理が失敗します。

**引数**

- `factory`
    - 新しく設定する**TREXFactory**のコントラクトアドレス。

### `setPublicDeploymentStatus`

```solidity
function setPublicDeploymentStatus(bool _isEnabled) external override onlyOwner {
    if(_isEnabled == _publicDeploymentStatus && _isEnabled == true) {
        revert PublicDeploymentAlreadyEnabled();
    }
    if(_isEnabled == _publicDeploymentStatus && _isEnabled == false) {
        revert PublicDeploymentAlreadyDisabled();
    }
    _publicDeploymentStatus = _isEnabled;
    emit PublicDeploymentStatusSet(_isEnabled);
}
```

一般ユーザーによるトークンのデプロイ（パブリックデプロイ）を有効または無効にする関数。
`onlyOwner`修飾子により、所有者のみが呼び出し可能です。
現在の設定と同じ状態に変更しようとすると、カスタムエラーで処理が失敗します。

**引数**

- `_isEnabled`
    - パブリックデプロイを有効にする場合は`true`、無効にする場合は`false`。

### `transferFactoryOwnership`

```solidity
function transferFactoryOwnership(address _newOwner) external override onlyOwner {
    Ownable(_factory).transferOwnership(_newOwner);
}
```

このゲートウェイが管理している**TREXFactory**コントラクトの所有権を、別のアドレスに移管する関数。
`onlyOwner`修飾子により、所有者のみが呼び出し可能です。
内部で、`_factory`アドレスのコントラクトが持つ`transferOwnership`関数を呼び出します。

**引数**

- `_newOwner`
    - **TREXFactory**の新しい所有者となるアドレス。

### `enableDeploymentFee`

```solidity
function enableDeploymentFee(bool _isEnabled) external override onlyOwner {
    if(_isEnabled == _deploymentFeeEnabled && _isEnabled == true) {
        revert DeploymentFeesAlreadyEnabled();
    }
    if(_isEnabled == _deploymentFeeEnabled && _isEnabled == false) {
        revert DeploymentFeesAlreadyDisabled();
    }
    _deploymentFeeEnabled = _isEnabled;
    emit DeploymentFeeEnabled(_isEnabled);
}
```

トークンのデプロイ時に手数料を徴収するかどうかを有効または無効にする関数。
`onlyOwner`修飾子により、所有者のみが呼び出し可能です。
現在の設定と同じ状態に変更しようとすると、カスタムエラーで処理が失敗します。

**引数**

- `_isEnabled`
    - 手数料を有効にする場合は`true`、無効にする場合は`false`。

### `setDeploymentFee`

```solidity
function setDeploymentFee(uint256 _fee, address _feeToken, address _feeCollector) external override onlyOwner {
    if(_feeToken == address(0) || _feeCollector == address(0)) {
        revert ZeroAddress();
    }
    _deploymentFee.fee = _fee;
    _deploymentFee.feeToken = _feeToken;
    _deploymentFee.feeCollector = _feeCollector;
    emit DeploymentFeeSet(_fee, _feeToken, _feeCollector);
}
```

デプロイ手数料の具体的な内容（金額、支払いトークン、徴収先）を設定する関数。
`onlyOwner`修飾子により、所有者のみが呼び出し可能です。
支払いトークンまたは徴収先アドレスにゼロアドレスを指定すると、`ZeroAddress`エラーで処理が失敗します。

**引数**

- `_fee`
    - 手数料の金額。
- `_feeToken`
    - 手数料の支払いに使用するトークンのアドレス。
- `_feeCollector`
    - 徴収した手数料が送金されるアドレス。

### `batchAddDeployer`

```solidity
function batchAddDeployer(address[] calldata deployers) external override {
    if(!isAgent(msg.sender) && msg.sender != owner()) {
        revert OnlyAdminCall();
    }
    if(deployers.length > 500) {
        revert BatchMaxLengthExceeded(500);
    }
    for (uint256 i = 0; i < deployers.length; i++) {
        if(isDeployer(deployers[i])) {
            revert DeployerAlreadyExists(deployers[i]);
        }
        _deployers[deployers[i]] = true;
        emit DeployerAdded(deployers[i]);
    }
}
```

複数のアドレスを承認済みデプロイヤーのリストに一括で追加する関数。
オーナーまたはエージェントのみが呼び出し可能です。
一度に追加できるアドレスは500件までです。
既に追加済みのアドレスが含まれている場合は、`DeployerAlreadyExists`エラーで処理が失敗します。

**引数**

- `deployers`
    - デプロイヤーとして追加するアドレスの配列。

### `addDeployer`

```solidity
function addDeployer(address deployer) external override {
    if(!isAgent(msg.sender) && msg.sender != owner()) {
        revert OnlyAdminCall();
    }
    if(isDeployer(deployer)) {
        revert DeployerAlreadyExists(deployer);
    }
    _deployers[deployer] = true;
    emit DeployerAdded(deployer);
}
```

承認済みデプロイヤーのリストにアドレスを1件追加する関数。
オーナーまたはエージェントのみが呼び出し可能です。
指定したアドレスが既に追加済みの場合、`DeployerAlreadyExists`エラーで処理が失敗します。

**引数**

- `deployer`
    - デプロイヤーとして追加するアドレス。

### `batchRemoveDeployer`

```solidity
function batchRemoveDeployer(address[] calldata deployers) external override {
    if(!isAgent(msg.sender) && msg.sender != owner()) {
        revert OnlyAdminCall();
    }
    if(deployers.length > 500) {
        revert BatchMaxLengthExceeded(500);
    }
    for (uint256 i = 0; i < deployers.length; i++) {
        if(!isDeployer(deployers[i])) {
            revert DeployerDoesNotExist(deployers[i]);
        }
        delete _deployers[deployers[i]];
        emit DeployerRemoved(deployers[i]);
    }
}
```

複数のアドレスを承認済みデプロイヤーのリストから一括で削除する関数。
オーナーまたはエージェントのみが呼び出し可能です。
一度に削除できるアドレスは500件までです。
リストに存在しないアドレスが含まれている場合は、`DeployerDoesNotExist`エラーで処理が失敗します。

**引数**

- `deployers`
    - デプロイヤーから削除するアドレスの配列。

### `removeDeployer`

```solidity
function removeDeployer(address deployer) external override {
    if(!isAgent(msg.sender) && msg.sender != owner()) {
        revert OnlyAdminCall();
    }
    if(!isDeployer(deployer)) {
        revert DeployerDoesNotExist(deployer);
    }
    delete _deployers[deployer];
    emit DeployerRemoved(deployer);
}
```

承認済みデプロイヤーのリストからアドレスを1件削除する関数。
オーナーまたはエージェントのみが呼び出し可能です。
指定したアドレスがリストに存在しない場合、`DeployerDoesNotExist`エラーで処理が失敗します。

**引数**

- `deployer`
    - デプロイヤーから削除するアドレス。

### `batchApplyFeeDiscount`

```solidity
function batchApplyFeeDiscount(address[] calldata deployers, uint16[] calldata discounts) external override {
    if(!isAgent(msg.sender) && msg.sender != owner()) {
        revert OnlyAdminCall();
    }
    if(deployers.length > 500) {
        revert BatchMaxLengthExceeded(500);
    }
    for (uint256 i = 0; i < deployers.length; i++) {
        if(discounts[i] > 10000) {
            revert DiscountOutOfRange();
        }
        _feeDiscount[deployers[i]] = discounts[i];
        emit FeeDiscountApplied(deployers[i], discounts[i]);
    }
}
```

複数のデプロイヤーに手数料の割引を一括で適用する関数。
オーナーまたはエージェントのみが呼び出し可能です。
一度に設定できるアドレスは500件までです。割引率が10000（100%）を超える値が含まれている場合は、`DiscountOutOfRange`エラーで処理が失敗します。

**引数**

- `deployers`
    - 割引を適用するデプロイヤーのアドレスの配列。
- `discounts`
    - 適用する割引率（10,000分率）の配列。

### `applyFeeDiscount`

```solidity
function applyFeeDiscount(address deployer, uint16 discount) external override {
    if(!isAgent(msg.sender) && msg.sender != owner()) {
        revert OnlyAdminCall();
    }
    if(discount > 10000) {
        revert DiscountOutOfRange();
    }
    _feeDiscount[deployer] = discount;
    emit FeeDiscountApplied(deployer, discount);
}
```

特定のデプロイヤーのアドレスに手数料の割引を適用する関数。
オーナーまたはエージェントのみが呼び出し可能です。
割引率が10000（100%）を超える場合、`DiscountOutOfRange`エラーで処理が失敗します。

**引数**

- `deployer`
    - 割引を適用するデプロイヤーのアドレス。
- `discount`
    - 適用する割引率（10,000分率）。

### `batchDeployTREXSuite`

```solidity
function batchDeployTREXSuite(
    ITREXFactory.TokenDetails[] memory _tokenDetails,
    ITREXFactory.ClaimDetails[] memory _claimDetails) external override
{
    if(_tokenDetails.length > 5) {
        revert BatchMaxLengthExceeded(5);
    }
    for (uint256 i = 0; i < _tokenDetails.length; i++) {
        deployTREXSuite(_tokenDetails[i], _claimDetails[i]);
    }
}
```

複数のT-REXスイートを一度のトランザクションでデプロイする関数。
内部で`deployTREXSuite`関数をループ処理で呼び出します。
一度にデプロイできるスイートは5つまでです。各スイートに対して、個別の権限チェックと手数料処理が行われます。

**引数**

- `_tokenDetails`
    - デプロイするトークン設定の配列。
- `_claimDetails`
    - デプロイするコンプライアンス要件の配列。

### `getPublicDeploymentStatus`

```solidity
function getPublicDeploymentStatus() external override view returns(bool) {
    return _publicDeploymentStatus;
}
```

現在のパブリックデプロイのステータスを取得する関数。
`_publicDeploymentStatus`の値を返します。

**戻り値**

- `bool`
    - パブリックデプロイが有効な場合は`true`、無効な場合は`false`。

### `getFactory`

```solidity
function getFactory() external override view returns(address) {
    return _factory;
}
```

このゲートウェイが連携している**TREXFactory**のアドレスを取得する関数。
`_factory`の値を返します。

**戻り値**

- `address`
    - **TREXFactory**のコントラクトアドレス。

### `getDeploymentFee`

```solidity
function getDeploymentFee() external override view returns(Fee memory) {
    return _deploymentFee;
}
```

現在のデプロイ手数料の詳細を取得する関数。
`_deploymentFee`の値を`Fee`構造体として返します。

**戻り値**

- `Fee memory`
    - デプロイ手数料の詳細情報。

### `isDeploymentFeeEnabled`

```solidity
function isDeploymentFeeEnabled() external override view returns(bool) {
    return _deploymentFeeEnabled;
}
```

デプロイ手数料が現在有効かどうかを確認する関数。
`_deploymentFeeEnabled`の値を返します。

**戻り値**

- `bool`
    - 手数料が有効な場合は`true`、無効な場合は`false`。

### `deployTREXSuite`

```solidity
function deployTREXSuite(ITREXFactory.TokenDetails memory _tokenDetails, ITREXFactory.ClaimDetails memory _claimDetails)
public override {
    if(_publicDeploymentStatus == false && !isDeployer(msg.sender)) {
        revert PublicDeploymentsNotAllowed();
    }
    if(_publicDeploymentStatus == true && msg.sender != _tokenDetails.owner && !isDeployer(msg.sender)) {
        revert PublicCannotDeployOnBehalf();
    }
    uint256 feeApplied = 0;
    if(_deploymentFeeEnabled == true) {
        if(_deploymentFee.fee > 0 && _feeDiscount[msg.sender] < 10000) {
            feeApplied = calculateFee(msg.sender);
            IERC20(_deploymentFee.feeToken).transferFrom(
                msg.sender,
                _deploymentFee.feeCollector,
                feeApplied
            );
        }
    }
    string memory _salt  = string(abi.encodePacked(Strings.toHexString(_tokenDetails.owner), _tokenDetails.name));
    ITREXFactory(_factory).deployTREXSuite(_salt, _tokenDetails, _claimDetails);
    emit GatewaySuiteDeploymentProcessed(msg.sender, _tokenDetails.owner, feeApplied);
}
```

T-REXコントラクト一式をデプロイするメイン関数。
まず、呼び出し元がデプロイ権限を持っているかを検証します。
パブリックデプロイが無効な場合は、承認済みデプロイヤーでなければなりません。
次に、手数料が有効な場合は、割引を適用した手数料を計算し、`transferFrom`で徴収します。
最後に、トークン所有者のアドレスとトークン名から`salt`を生成し、**TREXFactory**コントラクトの`deployTREXSuite`関数を呼び出して実際のデプロイを実行します。

**引数**

- `_tokenDetails`
    - デプロイするトークン一式の詳細設定。
- `_claimDetails`
    - デプロイするトークンのコンプライアンス要件。

### `isDeployer`

```solidity
function isDeployer(address deployer) public override view returns(bool) {
    return _deployers[deployer];
}
```

指定されたアドレスが承認済みデプロイヤーかどうかを確認する関数。
`_deployers`マッピングから指定されたアドレスの権限の有無を調べて返します。

**引数**

- `deployer`
    - 確認したいアドレス。

**戻り値**

- `bool`
    - 承認済みデプロイヤーであれば`true`、そうでなければ`false`。

### `calculateFee`

```solidity
function calculateFee(address deployer) public override view returns(uint256) {
    return _deploymentFee.fee - ((_feeDiscount[deployer] * _deploymentFee.fee) / 10000);
}
```

特定のデプロイヤーが支払うべきデプロイ手数料を、割引を適用して計算する関数。
基本手数料から、`_feeDiscount`マッピングに記録された割引率（10,000分率）に基づいて計算した割引額を差し引いた最終的な手数料額を返します。

**引数**

- `deployer`
    - 手数料を計算する対象のデプロイヤーアドレス。

**戻り値**

- `uint256`
    - 計算された手数料の額。
