# [Contract] TREXFactory

> このコントラクトは、ERC3643に準拠したトークン一式（スイート）を、一度のトランザクションでまとめてデプロイするためのファクトリーコントラクトです。

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

## 概要

このコントラクトは、**ERC3643**に準拠したトークン一式（スイート）を、一度のトランザクションでまとめてデプロイするためのファクトリーコントラクトです。
トークンの基本情報、コンプライアンス要件、管理者設定などを引数として受け取り、関連する全てのスマートコントラクトを自動的に生成・設定します。

**TREXFactory**コントラクトは、セキュリティトークンの発行プロセスを簡素化し、標準化するために設計されています。
`deployTREXSuite`という関数を通じて、トークン本体、ID管理、コンプライアンスルールなどを担う6つの主要なコントラクト群を、アップグレード可能なプロキシとして一度にデプロイします。

このコントラクトは`CREATE2`オペコードを利用してコントラクトを生成するため、事前に決定されたアドレスにデプロイすることが可能です。
これにより、異なるEVM互換チェーン上でも同じアドレスでトークンを発行できるというクロスチェーンの一貫性を実現します。

デプロイ機能は`onlyOwner`修飾子によって保護されており、通常はこのファクトリーを管理する**TREXGateway**コントラクトから呼び出されます。
また、デプロイされるプロキシが参照する実装コントラクトのバージョンは、**Implementation Authority**コントラクトによって一元管理されています。

## 機能

* **ERC3643**トークン一式のワンストップデプロイ機能
* `CREATE2`を利用した決定論的なアドレスへのコントラクト生成
* デプロイと同時に詳細な初期設定（トークン情報、コンプライアンスルール、エージェント権限など）を実行
* 既存の**IdentityRegistryStorage**の再利用、新規作成の選択
* デプロイ済みコントラクトの所有権移管機能

## フロー

### トークンスイートのデプロイ

```mermaid
sequenceDiagram
    actor Owner as オーナー (Gateway)
    participant Factory as TREXFactory
    participant TIR as TrustedIssuersRegistryProxy
    participant CTR as ClaimTopicsRegistryProxy
    participant MC as ModularComplianceProxy
    participant IRS as IdentityRegistryStorageProxy
    participant IR as IdentityRegistryProxy
    participant Token as TokenProxy
    participant User as 最終的な所有者

    Owner->>Factory: 1. deployTREXSuite(salt, tokenDetails, claimDetails)
    activate Factory
    
    Factory->>Factory: 2. _deployTIR(salt, ...)
    Factory-->>TIR: 3. (デプロイ)
    
    Factory->>Factory: 4. _deployCTR(salt, ...)
    Factory-->>CTR: 5. (デプロイ)

    Factory->>Factory: 6. ... (MC, IRS, IR, Tokenも同様にデプロイ)

    Note over Factory: デプロイしたコントラクトのアドレスを<br>一時的に保持し、設定に使用

    Factory->>CTR: 7. addClaimTopic(...)
    Factory->>TIR: 8. addTrustedIssuer(...)
    Factory->>IRS: 9. bindIdentityRegistry(IRのアドレス)
    Factory->>IR: 10. addAgent(Tokenのアドレス, ...irAgents)
    Factory->>Token: 11. addAgent(...tokenAgents)
    Factory->>MC: 12. addModule(...) & callModuleFunction(...)

    Note over Factory: 全ての設定が完了

    Factory->>Token: 13. transferOwnership(Userのアドレス)
    Factory->>IR: 14. transferOwnership(Userのアドレス)
    Factory->>...: (他のコントラクトも同様に所有権移管)

    Factory-->>Owner: 15. 成功 (TREXSuiteDeployedイベント発行)
    deactivate Factory
```

## コード

```sol:TREXFactory.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 "../roles/AgentRole.sol";
import "../token/IToken.sol";
import "../registry/interface/IClaimTopicsRegistry.sol";
import "../registry/interface/IIdentityRegistry.sol";
import "../compliance/modular/IModularCompliance.sol";
import "../registry/interface/ITrustedIssuersRegistry.sol";
import "../registry/interface/IIdentityRegistryStorage.sol";
import "../proxy/authority/ITREXImplementationAuthority.sol";
import "../proxy/TokenProxy.sol";
import "../proxy/ClaimTopicsRegistryProxy.sol";
import "../proxy/IdentityRegistryProxy.sol";
import "../proxy/IdentityRegistryStorageProxy.sol";
import "../proxy/TrustedIssuersRegistryProxy.sol";
import "../proxy/ModularComplianceProxy.sol";
import "./ITREXFactory.sol";
import "@onchain-id/solidity/contracts/factory/IIdFactory.sol";


contract TREXFactory is ITREXFactory, Ownable {

    /// the address of the implementation authority contract used in the tokens deployed by the factory
    address private _implementationAuthority;

    /// the address of the Identity Factory used to deploy token OIDs
    address private _idFactory;

    /// mapping containing info about the token contracts corresponding to salt already used for CREATE2 deployments
    mapping(string => address) public tokenDeployed;

    /// constructor is setting the implementation authority and the Identity Factory of the TREX factory
    constructor(address implementationAuthority_, address idFactory_) {
        setImplementationAuthority(implementationAuthority_);
        setIdFactory(idFactory_);
    }

    /**
     *  @dev See {ITREXFactory-deployTREXSuite}.
     */
    // solhint-disable-next-line code-complexity, function-max-lines
    function deployTREXSuite(string memory _salt, TokenDetails calldata _tokenDetails, ClaimDetails calldata
        _claimDetails)
    external override onlyOwner {
        require(tokenDeployed[_salt] == address(0)
        , "token already deployed");
        require((_claimDetails.issuers).length == (_claimDetails.issuerClaims).length
        , "claim pattern not valid");
        require((_claimDetails.issuers).length <= 5
        , "max 5 claim issuers at deployment");
        require((_claimDetails.claimTopics).length <= 5
        , "max 5 claim topics at deployment");
        require((_tokenDetails.irAgents).length <= 5 && (_tokenDetails.tokenAgents).length <= 5
        , "max 5 agents at deployment");
        require((_tokenDetails.complianceModules).length <= 30
        , "max 30 module actions at deployment");
        require((_tokenDetails.complianceModules).length >= (_tokenDetails.complianceSettings).length
        , "invalid compliance pattern");

        ITrustedIssuersRegistry tir = ITrustedIssuersRegistry(_deployTIR(_salt, _implementationAuthority));
        IClaimTopicsRegistry ctr = IClaimTopicsRegistry(_deployCTR(_salt, _implementationAuthority));
        IModularCompliance mc = IModularCompliance(_deployMC(_salt, _implementationAuthority));
        IIdentityRegistryStorage irs;
        if (_tokenDetails.irs == address(0)) {
            irs = IIdentityRegistryStorage(_deployIRS(_salt, _implementationAuthority));
        }
        else {
            irs = IIdentityRegistryStorage(_tokenDetails.irs);
        }
        IIdentityRegistry ir = IIdentityRegistry(_deployIR(_salt, _implementationAuthority, address(tir),
            address(ctr), address(irs)));
        IToken token = IToken(_deployToken
            (
                _salt,
                _implementationAuthority,
                address(ir),
                address(mc),
                _tokenDetails.name,
                _tokenDetails.symbol,
                _tokenDetails.decimals,
                _tokenDetails.ONCHAINID
            ));
        if(_tokenDetails.ONCHAINID == address(0)) {
            address _tokenID = IIdFactory(_idFactory).createTokenIdentity(address(token), _tokenDetails.owner, _salt);
            token.setOnchainID(_tokenID);
        }
        for (uint256 i = 0; i < (_claimDetails.claimTopics).length; i++) {
            ctr.addClaimTopic(_claimDetails.claimTopics[i]);
        }
        for (uint256 i = 0; i < (_claimDetails.issuers).length; i++) {
            tir.addTrustedIssuer(IClaimIssuer((_claimDetails).issuers[i]), _claimDetails.issuerClaims[i]);
        }
        irs.bindIdentityRegistry(address(ir));
        AgentRole(address(ir)).addAgent(address(token));
        for (uint256 i = 0; i < (_tokenDetails.irAgents).length; i++) {
            AgentRole(address(ir)).addAgent(_tokenDetails.irAgents[i]);
        }
        for (uint256 i = 0; i < (_tokenDetails.tokenAgents).length; i++) {
            AgentRole(address(token)).addAgent(_tokenDetails.tokenAgents[i]);
        }
        for (uint256 i = 0; i < (_tokenDetails.complianceModules).length; i++) {
            if (!mc.isModuleBound(_tokenDetails.complianceModules[i])) {
                mc.addModule(_tokenDetails.complianceModules[i]);
            }
            if (i < (_tokenDetails.complianceSettings).length) {
                mc.callModuleFunction(_tokenDetails.complianceSettings[i], _tokenDetails.complianceModules[i]);
            }
        }
        tokenDeployed[_salt] = address(token);
        (Ownable(address(token))).transferOwnership(_tokenDetails.owner);
        (Ownable(address(ir))).transferOwnership(_tokenDetails.owner);
        (Ownable(address(tir))).transferOwnership(_tokenDetails.owner);
        (Ownable(address(ctr))).transferOwnership(_tokenDetails.owner);
        (Ownable(address(mc))).transferOwnership(_tokenDetails.owner);
        emit TREXSuiteDeployed(address(token), address(ir), address(irs), address(tir), address(ctr), address(mc), _salt);
    }

    /**
     *  @dev See {ITREXFactory-recoverContractOwnership}.
     */
    function recoverContractOwnership(address _contract, address _newOwner) external override onlyOwner {
        (Ownable(_contract)).transferOwnership(_newOwner);
    }

    /**
     *  @dev See {ITREXFactory-getImplementationAuthority}.
     */
    function getImplementationAuthority() external override view returns(address) {
        return _implementationAuthority;
    }

    /**
     *  @dev See {ITREXFactory-getIdFactory}.
     */
    function getIdFactory() external override view returns(address) {
        return _idFactory;
    }

    /**
     *  @dev See {ITREXFactory-getToken}.
     */
    function getToken(string calldata _salt) external override view returns(address) {
        return tokenDeployed[_salt];
    }

    /**
     *  @dev See {ITREXFactory-setImplementationAuthority}.
     */
    function setImplementationAuthority(address implementationAuthority_) public override onlyOwner {
        require(implementationAuthority_ != address(0), "invalid argument - zero address");
        // should not be possible to set an implementation authority that is not complete
        require(
            (ITREXImplementationAuthority(implementationAuthority_)).getTokenImplementation() != address(0)
            && (ITREXImplementationAuthority(implementationAuthority_)).getCTRImplementation() != address(0)
            && (ITREXImplementationAuthority(implementationAuthority_)).getIRImplementation() != address(0)
            && (ITREXImplementationAuthority(implementationAuthority_)).getIRSImplementation() != address(0)
            && (ITREXImplementationAuthority(implementationAuthority_)).getMCImplementation() != address(0)
            && (ITREXImplementationAuthority(implementationAuthority_)).getTIRImplementation() != address(0),
            "invalid Implementation Authority");
        _implementationAuthority = implementationAuthority_;
        emit ImplementationAuthoritySet(implementationAuthority_);
    }

    /**
     *  @dev See {ITREXFactory-setIdFactory}.
     */
    function setIdFactory(address idFactory_) public override onlyOwner {
        require(idFactory_ != address(0), "invalid argument - zero address");
        _idFactory = idFactory_;
        emit IdFactorySet(idFactory_);
    }

    /// deploy function with create2 opcode call
    /// returns the address of the contract created
    function _deploy(string memory salt, bytes memory bytecode) private returns (address) {
        bytes32 saltBytes = bytes32(keccak256(abi.encodePacked(salt)));
        address addr;
        // solhint-disable-next-line no-inline-assembly
        assembly {
            let encoded_data := add(0x20, bytecode) // load initialization code.
            let encoded_size := mload(bytecode)     // load init code's length.
            addr := create2(0, encoded_data, encoded_size, saltBytes)
            if iszero(extcodesize(addr)) {
                revert(0, 0)
            }
        }
        emit Deployed(addr);
        return addr;
    }

    /// function used to deploy a trusted issuers registry using CREATE2
    function _deployTIR
    (
        string memory _salt,
        address implementationAuthority_
    ) private returns (address){
        bytes memory _code = type(TrustedIssuersRegistryProxy).creationCode;
        bytes memory _constructData = abi.encode(implementationAuthority_);
        bytes memory bytecode = abi.encodePacked(_code, _constructData);
        return _deploy(_salt, bytecode);
    }

    /// function used to deploy a claim topics registry using CREATE2
    function  _deployCTR
    (
        string memory _salt,
        address implementationAuthority_
    ) private returns (address) {
        bytes memory _code = type(ClaimTopicsRegistryProxy).creationCode;
        bytes memory _constructData = abi.encode(implementationAuthority_);
        bytes memory bytecode = abi.encodePacked(_code, _constructData);
        return _deploy(_salt, bytecode);
    }

    /// function used to deploy modular compliance contract using CREATE2
    function  _deployMC
    (
        string memory _salt,
        address implementationAuthority_
    ) private returns (address) {
        bytes memory _code = type(ModularComplianceProxy).creationCode;
        bytes memory _constructData = abi.encode(implementationAuthority_);
        bytes memory bytecode = abi.encodePacked(_code, _constructData);
        return _deploy(_salt, bytecode);
    }

    /// function used to deploy an identity registry storage using CREATE2
    function _deployIRS
    (
        string memory _salt,
        address implementationAuthority_
    ) private returns (address) {
        bytes memory _code = type(IdentityRegistryStorageProxy).creationCode;
        bytes memory _constructData = abi.encode(implementationAuthority_);
        bytes memory bytecode = abi.encodePacked(_code, _constructData);
        return _deploy(_salt, bytecode);
    }

    /// function used to deploy an identity registry using CREATE2
    function _deployIR
    (
        string memory _salt,
        address implementationAuthority_,
        address _trustedIssuersRegistry,
        address _claimTopicsRegistry,
        address _identityStorage
    ) private returns (address) {
        bytes memory _code = type(IdentityRegistryProxy).creationCode;
        bytes memory _constructData = abi.encode
        (
            implementationAuthority_,
            _trustedIssuersRegistry,
            _claimTopicsRegistry,
            _identityStorage
        );
        bytes memory bytecode = abi.encodePacked(_code, _constructData);
        return _deploy(_salt, bytecode);
    }

    /// function used to deploy a token using CREATE2
    function _deployToken
    (
        string memory _salt,
        address implementationAuthority_,
        address _identityRegistry,
        address _compliance,
        string memory _name,
        string memory _symbol,
        uint8 _decimals,
        address _onchainId
    ) private returns (address) {
        bytes memory _code = type(TokenProxy).creationCode;
        bytes memory _constructData = abi.encode
        (
            implementationAuthority_,
            _identityRegistry,
            _compliance,
            _name,
            _symbol,
            _decimals,
            _onchainId
        );
        bytes memory bytecode = abi.encodePacked(_code, _constructData);
        return _deploy(_salt, bytecode);
    }
}
```

## 構造体

### `TokenDetails`

```solidity
struct TokenDetails {
    address owner;
    string name;
    string symbol;
    uint8 decimals;
    address irs;
    address ONCHAINID;
    address[] irAgents;
    address[] tokenAgents;
    address[] complianceModules;
    bytes[] complianceSettings;
}
```

新しいT-REXトークンと関連コントラクト群をデプロイするために必要な、全ての詳細情報を保持する構造体。
デプロイするトークン一式の構成を定義するために使用されます。
トークンの基本情報から、各コンポーネントの所有者や管理者（エージェント）、適用するコンプライアンスルールまで、広範な初期設定をこの一つの構造体で指定します。

**フィールド**

- `owner`
    - デプロイされる全コントラクトの最終的な所有者となるアドレス。
- `name`
    - トークンの名前。
- `symbol`
    - トークンのシンボル。
- `decimals`
    - トークンの小数点の桁数（0から18）。
- `irs`
    - 既存の**IdentityRegistryStorage**コントラクトを再利用する場合、そのコントラクトアドレス。`address(0)`を指定すると新規に作成されます。
- `ONCHAINID`
    - トークン自体に紐付けるオンチェーンIDのアドレス。
- `irAgents`
    - **IdentityRegistry**コントラクトのエージェントとして設定するアドレスの配列。
- `tokenAgents`
    - **Token**コントラクトのエージェントとして設定するアドレスの配列。
- `complianceModules`
    - **ModularCompliance**コントラクトに紐付けるモジュールのアドレスの配列。
- `complianceSettings`
    - 各コンプライアンスモジュールに対する初期設定を行うためのコールデータの配列。

### `ClaimDetails`

```solidity
struct ClaimDetails {
    uint256[] claimTopics;
    address[] issuers;
    uint256[][] issuerClaims;
}
```

クレームとクレーム発行者に関するコンプライアンス要件を定義するための構造体。
デプロイするトークンがどのような検証ルールに従うかを定義するために使用されます。
どの種類の資格証明が必要で、誰がそれを発行できるかを指定します。

**フィールド**

- `claimTopics`
    - 必須となるクレームトピックの番号の配列。
- `issuers`
    - 信頼できるクレーム発行者として登録するアドレスの配列。
- `issuerClaims`
    - `issuers`配列の各発行者が発行を許可されるクレームトピックを定義する二次元配列。

## 変数

### `_implementationAuthority`

```solidity
address private _implementationAuthority;
```

このファクトリーがデプロイするプロキシコントラクトが参照する、**ImplementationAuthority**コントラクトのアドレスを保持。

### `_idFactory`

```solidity
address private _idFactory;
```

トークン自体のオンチェーンIDをデプロイするために使用する**IdFactory**コントラクトのアドレスを保持。

### `tokenDeployed`

```solidity
mapping(string => address) public tokenDeployed;
```

デプロイ時に使用した`salt`文字列をキーとして、デプロイされた**Token**コントラクトのアドレスを記録する`mapping`。
同じ`salt`での二重デプロイを防ぐために使用されます。

## イベント

### `Deployed`

```solidity
event Deployed(address indexed _addr);
```

`_deploy`関数によって単一のプロキシコントラクトがデプロイされた時に発行されるイベント。

### `IdFactorySet`

```solidity
event IdFactorySet(address _idFactory);
```

`setIdFactory`関数によって、連携する**IdFactory**コントラクトのアドレスが設定された時に発行されるイベント。

### `ImplementationAuthoritySet`

```solidity
event ImplementationAuthoritySet(address _implementationAuthority);
```

`setImplementationAuthority`関数によって、連携する**ImplementationAuthority**コントラクトのアドレスが設定された時に発行されるイベント。

### `TREXSuiteDeployed`

```solidity
event TREXSuiteDeployed(address indexed _token, address _ir, address _irs, address _tir, address _ctr, address _mc, string indexed _salt);
```

`deployTREXSuite`関数によってトークン一式が正常にデプロイされた時に発行されるイベント。
デプロイされた各コントラクトのアドレスと使用された`salt`を記録します。

## 関数

### `deployTREXSuite`

```solidity
function deployTREXSuite(string memory _salt, TokenDetails calldata _tokenDetails, ClaimDetails calldata
    _claimDetails)
external override onlyOwner {
    require(tokenDeployed[_salt] == address(0)
    , "token already deployed");
    require((_claimDetails.issuers).length == (_claimDetails.issuerClaims).length
    , "claim pattern not valid");
    require((_claimDetails.issuers).length <= 5
    , "max 5 claim issuers at deployment");
    require((_claimDetails.claimTopics).length <= 5
    , "max 5 claim topics at deployment");
    require((_tokenDetails.irAgents).length <= 5 && (_tokenDetails.tokenAgents).length <= 5
    , "max 5 agents at deployment");
    require((_tokenDetails.complianceModules).length <= 30
    , "max 30 module actions at deployment");
    require((_tokenDetails.complianceModules).length >= (_tokenDetails.complianceSettings).length
    , "invalid compliance pattern");

    ITrustedIssuersRegistry tir = ITrustedIssuersRegistry(_deployTIR(_salt, _implementationAuthority));
    IClaimTopicsRegistry ctr = IClaimTopicsRegistry(_deployCTR(_salt, _implementationAuthority));
    IModularCompliance mc = IModularCompliance(_deployMC(_salt, _implementationAuthority));
    IIdentityRegistryStorage irs;
    if (_tokenDetails.irs == address(0)) {
        irs = IIdentityRegistryStorage(_deployIRS(_salt, _implementationAuthority));
    }
    else {
        irs = IIdentityRegistryStorage(_tokenDetails.irs);
    }
    IIdentityRegistry ir = IIdentityRegistry(_deployIR(_salt, _implementationAuthority, address(tir),
        address(ctr), address(irs)));
    IToken token = IToken(_deployToken
        (
            _salt,
            _implementationAuthority,
            address(ir),
            address(mc),
            _tokenDetails.name,
            _tokenDetails.symbol,
            _tokenDetails.decimals,
            _tokenDetails.ONCHAINID
        ));
    if(_tokenDetails.ONCHAINID == address(0)) {
        address _tokenID = IIdFactory(_idFactory).createTokenIdentity(address(token), _tokenDetails.owner, _salt);
        token.setOnchainID(_tokenID);
    }
    for (uint256 i = 0; i < (_claimDetails.claimTopics).length; i++) {
        ctr.addClaimTopic(_claimDetails.claimTopics[i]);
    }
    for (uint256 i = 0; i < (_claimDetails.issuers).length; i++) {
        tir.addTrustedIssuer(IClaimIssuer((_claimDetails).issuers[i]), _claimDetails.issuerClaims[i]);
    }
    irs.bindIdentityRegistry(address(ir));
    AgentRole(address(ir)).addAgent(address(token));
    for (uint256 i = 0; i < (_tokenDetails.irAgents).length; i++) {
        AgentRole(address(ir)).addAgent(_tokenDetails.irAgents[i]);
    }
    for (uint256 i = 0; i < (_tokenDetails.tokenAgents).length; i++) {
        AgentRole(address(token)).addAgent(_tokenDetails.tokenAgents[i]);
    }
    for (uint256 i = 0; i < (_tokenDetails.complianceModules).length; i++) {
        if (!mc.isModuleBound(_tokenDetails.complianceModules[i])) {
            mc.addModule(_tokenDetails.complianceModules[i]);
        }
        if (i < (_tokenDetails.complianceSettings).length) {
            mc.callModuleFunction(_tokenDetails.complianceSettings[i], _tokenDetails.complianceModules[i]);
        }
    }
    tokenDeployed[_salt] = address(token);
    (Ownable(address(token))).transferOwnership(_tokenDetails.owner);
    (Ownable(address(ir))).transferOwnership(_tokenDetails.owner);
    (Ownable(address(tir))).transferOwnership(_tokenDetails.owner);
    (Ownable(address(ctr))).transferOwnership(_tokenDetails.owner);
    (Ownable(address(mc))).transferOwnership(_tokenDetails.owner);
    emit TREXSuiteDeployed(address(token), address(ir), address(irs), address(tir), address(ctr), address(mc), _salt);
}
```

T-REXコントラクト一式（スイート）を一度のトランザクションでデプロイし、初期設定を行う関数。
`onlyOwner`修飾子により、このファクトリーの所有者のみが呼び出し可能です。
まず、引数で渡された設定値の妥当性を検証します。
次に、`_deployTIR`, `_deployCTR`などの内部関数を呼び出して、T-REXスイートを構成する各コントラクトをプロキシとして順番にデプロイします。
デプロイ後、各コントラクトに対して`addClaimTopic`, `addTrustedIssuer`, `addAgent`などの設定関数を呼び出し、最後に全てのコントラクトの所有権をユーザーが指定した`owner`アドレスに移管します。

**ステップ1: 入力値の検証 (Validation)**
まず、引数で渡された設定値が妥当であるかを一連の`require`文で検証します。
- **`_salt`の一意性**
    この`_salt`が過去に使用されていないことを確認し、トークンの二重デプロイを防ぎます。
- **引数の整合性**
    `_claimDetails`や`_tokenDetails`内の配列の長さが正しいか、要素数がガス代上限を超えない妥当な範囲内かなどをチェックします。

**ステップ2: コントラクト群のデプロイ (Deployment)**
次に、`_deploy`プレフィックスを持つ内部関数を呼び出し、`CREATE2`オペコードを用いてT-REXスイートを構成する各コントラクトをプロキシとして順番にデプロイします。
- `_deployTIR`
    **TrustedIssuersRegistry**コントラクトをデプロイ。
- `_deployCTR`
    **ClaimTopicsRegistry**コントラクトをデプロイ。
- `_deployMC`
    **ModularCompliance**コントラクトをデプロイ。
- `_deployIRS` (条件付き)
    もし`_tokenDetails.irs`がゼロアドレスであれば、新しい**IdentityRegistryStorage**コントラクトをデプロイ。
    指定があれば、そのアドレスを再利用します。
- `_deployIR`
    上記でデプロイしたTIR, CTR, IRSのアドレスを引数として、**IdentityRegistry**コントラクトをデプロイ。
- `_deployToken`
    - 上記でデプロイしたIRとMCのアドレス、およびトークンの基本情報を引数として、**Token**コントラクトをデプロイ。

**ステップ3: トークンIDの生成 (Token ID Generation)**

もし`_tokenDetails.ONCHAINID`がゼロアドレスで指定された場合、連携する**IdFactory**コントラクトを呼び出して、このトークン自体に紐づく新しいオンチェーンID（AssetID）を生成し、トークンに設定します。

**ステップ4: コンプライアンスルールの初期設定 (Compliance Setup)**
デプロイした各コントラクトに対し、`_claimDetails`と`_tokenDetails`で指定された初期設定を行います。
- **`ctr.addClaimTopic`**
    `_claimDetails`で指定された必須クレームトピックを**ClaimTopicsRegistry**コントラクトに登録します。
- **`tir.addTrustedIssuer`**
    `_claimDetails`で指定された信頼できる発行者を**TrustedIssuersRegistry**コントラクトに登録します。
- **`irs.bindIdentityRegistry`**
    **IdentityRegistryStorage**コントラクトを、今回デプロイした**IdentityRegistry**コントラクトと紐付けます。

**ステップ5: エージェント権限の設定 (Agent Setup)**
- **`AgentRole(address(ir)).addAgent(...)`**
    **Token**コントラクト自身と、`_tokenDetails`で指定されたエージェントを、**IdentityRegistry**コントラクトのエージェントとして登録します。
- **`AgentRole(address(token)).addAgent(...)`**
    `_tokenDetails`で指定されたエージェントを、**Token**コントラクトのエージェントとして登録します。

**ステップ6: コンプライアンスモジュールの設定 (Module Setup)**
- **`mc.addModule`**
    `_tokenDetails`で指定されたコンプライアンスモジュールを**ModularCompliance**コントラクトに登録します。
- **`mc.callModuleFunction`**
    各モジュールに対して、`_tokenDetails`で指定された初期設定用の関数呼び出しを実行します。

**ステップ7: 最終処理 (Finalization)**
- **`tokenDeployed[_salt] = ...`**
    デプロイが完了したことを`salt`と紐づけて記録します。
- **`transferOwnership(...)`**
    最後に、このファクトリーが一時的に所有していたデプロイ済みの全コントラクトの所有権を、`_tokenDetails.owner`で指定された最終的な所有者に全て移管します。
- **`emit TREXSuiteDeployed(...)`**
    全ての処理が完了したことを示すイベントを発行します。

**引数**

- `_salt`
    - `CREATE2`によるデプロイで使用する一意の文字列。
- `_tokenDetails`
    - デプロイするトークンと関連コントラクトの設定詳細を格納した`TokenDetails`構造体。
- `_claimDetails`
    - デプロイするトークンのコンプライアンス要件を格納した`ClaimDetails`構造体。

### `recoverContractOwnership`

```solidity
function recoverContractOwnership(address _contract, address _newOwner) external override onlyOwner {
    (Ownable(_contract)).transferOwnership(_newOwner);
}
```

このファクトリーが所有するコントラクトの所有権を、指定した新しい所有者に移動する関数。
`onlyOwner`修飾子により、所有者のみが呼び出し可能です。
主に、共有の**IdentityRegistryStorage**（IRS）コントラクトなど、デプロイ後も一時的にファクトリーが所有権を持つコントラクトの管理権限を、本来の管理者に渡すために使用されます。

**引数**

- `_contract`
    - 所有権を移管する対象のコントラクトアドレス。
- `_newOwner`
    - 新しい所有者のアドレス。

### `getImplementationAuthority`

```solidity
function getImplementationAuthority() external override view returns(address) {
    return _implementationAuthority;
}
```

設定されている**ImplementationAuthority**コントラクトのアドレスを返す関数。
`_implementationAuthority`の値を返します。

**戻り値**

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

### `getIdFactory`

```solidity
function getIdFactory() external override view returns(address) {
    return _idFactory;
}
```

設定されている**IdFactory**コントラクトのアドレスを返す関数。
`_idFactory`の値を返します。

**戻り値**

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

### `getToken`

```solidity
function getToken(string calldata _salt) external override view returns(address) {
    return tokenDeployed[_salt];
}
```

指定された`salt`に対応するトークンのアドレスを返す関数。
`tokenDeployed`マッピングから、`_salt`をキーとしてデプロイ済みの**Token**コントラクトのアドレスを検索して返します。

**引数**

- `_salt`
    - トークンをデプロイする際に使用した`salt`文字列。

**戻り値**

- `address`
    - 対応する**Token**コントラクトのアドレス。

### `setImplementationAuthority`

```solidity
function setImplementationAuthority(address implementationAuthority_) public override onlyOwner {
    require(implementationAuthority_ != address(0), "invalid argument - zero address");
    // should not be possible to set an implementation authority that is not complete
    require(
        (ITREXImplementationAuthority(implementationAuthority_)).getTokenImplementation() != address(0)
        && (ITREXImplementationAuthority(implementationAuthority_)).getCTRImplementation() != address(0)
        && (ITREXImplementationAuthority(implementationAuthority_)).getIRImplementation() != address(0)
        && (ITREXImplementationAuthority(implementationAuthority_)).getIRSImplementation() != address(0)
        && (ITREXImplementationAuthority(implementationAuthority_)).getMCImplementation() != address(0)
        && (ITREXImplementationAuthority(implementationAuthority_)).getTIRImplementation() != address(0),
        "invalid Implementation Authority");
    _implementationAuthority = implementationAuthority_;
    emit ImplementationAuthoritySet(implementationAuthority_);
}
```

このファクトリーが使用する**ImplementationAuthority**コントラクトのアドレスを更新する関数。
`onlyOwner`修飾子により、所有者のみが呼び出し可能です。
新しい**ImplementationAuthority**が、T-REXスイートに必要な全ての実装コントラクトのアドレスを正しく含んでいるかを検証した上で、参照先を更新します。

**引数**

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

### `setIdFactory`

```solidity
function setIdFactory(address idFactory_) public override onlyOwner {
    require(idFactory_ != address(0), "invalid argument - zero address");
    _idFactory = idFactory_;
    emit IdFactorySet(idFactory_);
}
```

このファクトリーが使用する**IdFactory**コントラクトのアドレスを更新する関数。
`onlyOwner`修飾子により、所有者のみが呼び出し可能です。

**引数**

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