# [Contract] TREXImplementationAuthority

> このコントラクトは、T-REXプロトコルで使用されるプロキシコントラクト群のバージョン管理を一元的に行うためのコントラクトです。

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

## 概要

このコントラクトは、T-REXプロトコルで使用されるプロキシコントラクト群のバージョン管理を一元的に行うためのコントラクトです。
全てのプロキシが参照する実装（ロジック）コントラクトのアドレスをバージョンごとに記録し、システム全体のアップグレードを管理します。

**TREXImplementationAuthority**コントラクトは、T-REXエコシステムのUpgradeable機能の根幹です。
**TREXFactory**コントラクトによってデプロイされる全てのプロキシコントラクト（Token, IR, CTRなど）は、自身のロジック（実装）アドレスを直接保持するのではなく、この**ImplementationAuthority**コントラクトのアドレスを保持します。
プロキシが関数呼び出しを受け取ると、まずこのコントラクトに「**現在使用すべき実装コントラクトのアドレスはどれか？**」と問い合わせ、そのアドレスに対して処理を委任（`delegatecall`）します。

このコントラクトのオーナーは、`addTREXVersion`で新しいバージョンの実装コントラクト群を登録し、`useTREXVersion`で全プロキシが参照するバージョンを一斉に切り替えることができます。
これにより、トークンの状態やアドレスを変更することなく、システム全体の機能更新やバグ修正が可能になります。

また、このコントラクトには「**リファレンス（メイン）**」と「**補助（Auxiliary）**」の2種類が存在します。
リファレンスIAはファクトリーが使用する公式のもので、補助IA（**ImplementationAuthority**）はトークン発行者が自身でアップグレードのタイミングを管理したい場合に、リファレンスIAからバージョン情報を引き継いで個別に運用するために使用されます。

### 「リファレンス（メイン）」と「補助（Auxiliary）」の違い

この2つのIAは、誰が、どのようにコントラクトのバージョンアップを管理するかという点で役割が異なります。

#### リファレンスIA (Reference / Main IA)

エコシステム全体の「公式」なバージョン管理台帳。
* **管理者**
    **TREXFactory**の管理者（通常はプロトコルの開発チームやアソシエーション）。

**TREXFactory**コントラクトからトークンをデプロイすると、デフォルトで全てのプロキシはこのリファレンスIAを参照します。
新しいバージョンの実装コントラクトを追加できるのは、このリファレンスIAだけです。（`addTREXVersion`関数はリファレンスIAでしか実行できません）
リファレンスIAの管理者が`useTREXVersion`でバージョンを切り替えると、このIAを参照している全てのトークンが一斉にアップグレードされます。
プロトコル全体のセキュリティアップデートや機能追加を、効率的かつ統一的に行うために使用されます。

#### 補助IA (Auxiliary IA)

特定のトークン発行者専用の「**個人用**」バージョン管理台帳。
* **管理者**
    トークン発行者自身。

トークン発行者は、自分のトークンが参照するIAを、公式のリファレンスIAから、自分専用の補助IAに切り替えることができます。（`changeImplementationAuthority`関数を使用）
補助IAは、新しいバージョンを追加することはできません。
その代わりに、リファレンスIAに登録されているバージョンの中から、必要なものを「**取得（`fetchVersion`）**」してきます。
トークン発行者は、自分の好きなタイミングで、取得してきたバージョンの中から使用するバージョンを自由に切り替えることができます。

トークン発行者が、プロトコル全体の一斉アップグレードに追従するのではなく、自身でテストや準備を行った上で任意のタイミングで自分のトークンだけをアップグレードするという、独立したバージョン管理を行えるようにするために使用されます。

### 呼び出し元コントラクト

**TREXImplementationAuthority**（以下、IA）は、主に以下の2種類のコントラクトによって直接使用されます。

#### 全てのプロキシコントラクト (Proxy Contracts)

これがIAの最も主要な利用者です。
**TREXFactory**コントラクトによってデプロイされる、以下の全てのプロキシコントラクトがIAを使用します。

* **TokenProxy**
* **IdentityRegistryProxy**
* **IdentityRegistryStorageProxy**
* **TrustedIssuersRegistryProxy**
* **ClaimTopicsRegistryProxy**
* **ModularComplianceProxy**

これらのプロキシコントラクトは、自身の内部にIAのアドレスを保持しています。
ユーザーや他のコントラクトから何らかの関数呼び出し（例：`transfer`）を受け取ると、以下の処理を行います。

1. **問い合わせ**
    自身の`fallback`関数内で、まずIAに「**今使うべき実装コントラクトのアドレスはどれか？**」と問い合わせます。
    例えば**TokenProxy**コントラクトは、IAの`getTokenImplementation()`を呼び出します。
    **IdentityRegistryProxy**コントラクトは、IAの`getIRImplementation()`を呼び出します。

2. **処理の委任**
    IAから返された実装コントラクトのアドレスに対して、受け取った関数呼び出しをそのまま`delegatecall`で委任します。

この仕組みにより、プロキシは常にIAが指定する最新バージョンのロジックを実行することができます。

#### TREXFactoryコントラクト

**TREXFactory**は、新しいトークンスイートをデプロイする際に、IAを**設定・参照元**として使用します。

#### どのように使用されるか？

1. **デプロイ時の参照**
    `deployTREXSuite`関数が実行されると、**TREXFactory**コントラクトはまず自身の内部変数`_implementationAuthority`に格納されているIAのアドレスを読み取ります。
2. **プロキシへの設定**
    次に、**TREXFactory**コントrかうとがデプロイする全てのプロキシコントラクト（**TokenProxy**コントラクトなど）の`constructor`に、このIAのアドレスを引数として渡します。
    これにより、新しくデプロイされたプロキシは、どのIAを参照すればよいかを知ることができます。

## 機能

* T-REXコントラクトスイートのバージョンごとの実装アドレス管理
* システム全体のコントラクトバージョンの一斉切り替え（アップグレード）
* トークン発行者による独自のアップグレード管理を可能にする補助IAの仕組み
* リファレンスIAと補助IA間のバージョン情報の同期

## フロー

### コントラクトバージョンの一斉アップグレード

```mermaid
sequenceDiagram
    actor Owner as IAオーナー
    participant IA as TREXImplementationAuthority
    participant TokenProxy as トークンプロキシ
    participant TokenImplV1 as トークン実装V1
    participant TokenImplV2 as トークン実装V2

    Owner->>IA: 1. addTREXVersion(Version2, {token: TokenImplV2, ...})
    Note over IA: 新しいバージョン(V2)を登録

    Owner->>IA: 2. useTREXVersion(Version2)
    Note over IA: 現在のバージョンをV2に切り替え

    %% 時間が経過 %%
    actor User as ユーザー
    User->>TokenProxy: 3. transfer(...)
    activate TokenProxy
    TokenProxy->>IA: 4. getTokenImplementation()
    activate IA
    IA-->>TokenProxy: 5. TokenImplV2のアドレス
    deactivate IA

    TokenProxy->>TokenImplV2: 6. delegatecall(transfer(...))
    activate TokenImplV2
    Note over TokenImplV2: V2のロジックで処理を実行
    TokenImplV2-->>TokenProxy: 結果
    deactivate TokenImplV2
    
    TokenProxy-->>User: 7. 成功
    deactivate TokenProxy
```

## コード

```sol:TREXImplementationAuthority.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 "@openzeppelin/contracts/access/Ownable.sol";
import "./ITREXImplementationAuthority.sol";
import "../../token/IToken.sol";
import "../interface/IProxy.sol";
import "../../factory/ITREXFactory.sol";
import "./IIAFactory.sol";

contract TREXImplementationAuthority is ITREXImplementationAuthority, Ownable {

    /// variables

    /// current version
    Version private _currentVersion;

    /// mapping to get contracts of each version
    mapping(bytes32 => TREXContracts) private _contracts;

    /// reference ImplementationAuthority used by the TREXFactory
    bool private _reference;

    /// address of TREXFactory contract
    address private _trexFactory;

    /// address of factory for TREXImplementationAuthority contracts
    address private _iaFactory;

    /// functions

    /**
     *  @dev Constructor of the ImplementationAuthority contract
     *  @param referenceStatus boolean value determining if the contract
     *  is the main IA or an auxiliary contract
     *  @param trexFactory the address of TREXFactory referencing the main IA
     *  if `referenceStatus` is true then `trexFactory` at deployment is set
     *  on zero address. In that scenario, call `setTREXFactory` post-deployment
     *  @param iaFactory the address for the factory of IA contracts
     *  emits `ImplementationAuthoritySet` event
     *  emits a `IAFactorySet` event
     */
    constructor (bool referenceStatus, address trexFactory, address iaFactory) {
        _reference = referenceStatus;
        _trexFactory = trexFactory;
        _iaFactory = iaFactory;
        emit ImplementationAuthoritySet(referenceStatus, trexFactory);
        emit IAFactorySet(iaFactory);
    }

    /**
     *  @dev See {ITREXImplementationAuthority-setTREXFactory}.
     */
    function setTREXFactory(address trexFactory) external override onlyOwner {
        require(
            isReferenceContract() &&
            ITREXFactory(trexFactory).getImplementationAuthority() == address(this)
        , "only reference contract can call");
        _trexFactory = trexFactory;
        emit TREXFactorySet(trexFactory);
    }

    /**
     *  @dev See {ITREXImplementationAuthority-setIAFactory}.
     */
    function setIAFactory(address iaFactory) external override onlyOwner {
        require(
            isReferenceContract() &&
            ITREXFactory(_trexFactory).getImplementationAuthority() == address(this)
        , "only reference contract can call");
        _iaFactory = iaFactory;
        emit IAFactorySet(iaFactory);
    }

    /**
     *  @dev See {ITREXImplementationAuthority-useTREXVersion}.
     */
    function addAndUseTREXVersion(Version calldata _version, TREXContracts calldata _trex) external override {
        addTREXVersion(_version, _trex);
        useTREXVersion(_version);
    }

    /**
     *  @dev See {ITREXImplementationAuthority-fetchVersionList}.
     */
    function fetchVersion(Version calldata _version) external override {
        require(!isReferenceContract(), "cannot call on reference contract");
        if (_contracts[_versionToBytes(_version)].tokenImplementation != address(0)) {
            revert("version fetched already");
        }
        _contracts[_versionToBytes(_version)] =
        ITREXImplementationAuthority(getReferenceContract()).getContracts(_version);
        emit TREXVersionFetched(_version, _contracts[_versionToBytes(_version)]);
    }

    /**
     *  @dev See {ITREXImplementationAuthority-changeImplementationAuthority}.
     */
    // solhint-disable-next-line code-complexity, function-max-lines
    function changeImplementationAuthority(address _token, address _newImplementationAuthority) external override {
        require(_token != address(0), "invalid argument - zero address");
        if(_newImplementationAuthority == address(0) && !isReferenceContract()){
            revert("only reference contract can deploy new IAs");}

        address _ir = address(IToken(_token).identityRegistry());
        address _mc = address(IToken(_token).compliance());
        address _irs = address(IIdentityRegistry(_ir).identityStorage());
        address _ctr = address(IIdentityRegistry(_ir).topicsRegistry());
        address _tir = address(IIdentityRegistry(_ir).issuersRegistry());

        // calling this function requires ownership of ALL contracts of the T-REX suite
        if(
            Ownable(_token).owner() != msg.sender
            || Ownable(_ir).owner() != msg.sender
            || Ownable(_mc).owner() != msg.sender
            || Ownable(_irs).owner() != msg.sender
            || Ownable(_ctr).owner() != msg.sender
            || Ownable(_tir).owner() != msg.sender) {
            revert("caller NOT owner of all contracts impacted");
        }

        if(_newImplementationAuthority == address(0)) {
            _newImplementationAuthority = IIAFactory(_iaFactory).deployIA(_token);
        }
        else {
            if(
                _versionToBytes(ITREXImplementationAuthority(_newImplementationAuthority).getCurrentVersion()) !=
                _versionToBytes(_currentVersion)) {
                revert("version of new IA has to be the same as current IA");
            }
            if(
                ITREXImplementationAuthority(_newImplementationAuthority).isReferenceContract() &&
                _newImplementationAuthority != getReferenceContract()) {
                revert("new IA is NOT reference contract");
            }
            if(
                !IIAFactory(_iaFactory).deployedByFactory(_newImplementationAuthority) &&
            _newImplementationAuthority != getReferenceContract()) {
                revert("invalid IA");
            }
        }

        IProxy(_token).setImplementationAuthority(_newImplementationAuthority);
        IProxy(_ir).setImplementationAuthority(_newImplementationAuthority);
        IProxy(_mc).setImplementationAuthority(_newImplementationAuthority);
        IProxy(_ctr).setImplementationAuthority(_newImplementationAuthority);
        IProxy(_tir).setImplementationAuthority(_newImplementationAuthority);
        // IRS can be shared by multiple tokens, and therefore could have been updated already
        if (IProxy(_irs).getImplementationAuthority() == address(this)) {
            IProxy(_irs).setImplementationAuthority(_newImplementationAuthority);
        }
        emit ImplementationAuthorityChanged(_token, _newImplementationAuthority);
    }

    /**
     *  @dev See {ITREXImplementationAuthority-getCurrentVersion}.
     */
    function getCurrentVersion() external view override returns (Version memory) {
        return _currentVersion;
    }

    /**
     *  @dev See {ITREXImplementationAuthority-getContracts}.
     */
    function getContracts(Version calldata _version) external view override returns (TREXContracts memory) {
        return _contracts[_versionToBytes(_version)];
    }

    /**
     *  @dev See {ITREXImplementationAuthority-getTREXFactory}.
     */
    function getTREXFactory() external view override returns (address) {
        return _trexFactory;
    }

    /**
     *  @dev See {ITREXImplementationAuthority-getTokenImplementation}.
     */
    function getTokenImplementation() external view override returns (address) {
        return _contracts[_versionToBytes(_currentVersion)].tokenImplementation;
    }

    /**
     *  @dev See {ITREXImplementationAuthority-getCTRImplementation}.
     */
    function getCTRImplementation() external view override returns (address) {
        return _contracts[_versionToBytes(_currentVersion)].ctrImplementation;
    }

    /**
     *  @dev See {ITREXImplementationAuthority-getIRImplementation}.
     */
    function getIRImplementation() external view override returns (address) {
        return _contracts[_versionToBytes(_currentVersion)].irImplementation;
    }

    /**
     *  @dev See {ITREXImplementationAuthority-getIRSImplementation}.
     */
    function getIRSImplementation() external view override returns (address) {
        return _contracts[_versionToBytes(_currentVersion)].irsImplementation;
    }

    /**
     *  @dev See {ITREXImplementationAuthority-getTIRImplementation}.
     */
    function getTIRImplementation() external view override returns (address) {
        return _contracts[_versionToBytes(_currentVersion)].tirImplementation;
    }

    /**
     *  @dev See {ITREXImplementationAuthority-getMCImplementation}.
     */
    function getMCImplementation() external view override returns (address) {
        return _contracts[_versionToBytes(_currentVersion)].mcImplementation;
    }

    /**
     *  @dev See {ITREXImplementationAuthority-addTREXVersion}.
     */
    function addTREXVersion(Version calldata _version, TREXContracts calldata _trex) public override onlyOwner {
        require(isReferenceContract(), "ONLY reference contract can add versions");
        if (_contracts[_versionToBytes(_version)].tokenImplementation != address(0)) {
            revert("version already exists");
        }
        require(
            _trex.ctrImplementation != address(0)
            && _trex.irImplementation != address(0)
            && _trex.irsImplementation != address(0)
            && _trex.mcImplementation != address(0)
            && _trex.tirImplementation != address(0)
            && _trex.tokenImplementation != address(0)
        , "invalid argument - zero address");
        _contracts[_versionToBytes(_version)] = _trex;
        emit TREXVersionAdded(_version, _trex);
    }

    /**
     *  @dev See {ITREXImplementationAuthority-useTREXVersion}.
     */
    function useTREXVersion(Version calldata _version) public override onlyOwner {
        if (_versionToBytes(_version) == _versionToBytes(_currentVersion)) {
            revert("version already in use");
        }
        if (_contracts[_versionToBytes(_version)].tokenImplementation == address(0)) {
            revert("invalid argument - non existing version");
        }
        _currentVersion = _version;
        emit VersionUpdated(_version);
    }

    /**
     *  @dev See {ITREXImplementationAuthority-isReferenceContract}.
     */
    function isReferenceContract() public view override returns (bool) {
        return _reference;
    }

    /**
     *  @dev See {ITREXImplementationAuthority-getReferenceContract}.
     */
    function getReferenceContract() public view override returns (address) {
        return ITREXFactory(_trexFactory).getImplementationAuthority();
    }

    /**
     *  @dev casting function Version => bytes to allow compare values easier
     */
    function _versionToBytes(Version memory _version) private pure returns(bytes32) {
        return bytes32(keccak256(abi.encodePacked(_version.major, _version.minor, _version.patch)));
    }
}
```

## 構造体

### `TREXContracts`

```solidity
struct TREXContracts {
    address tokenImplementation;
    address ctrImplementation;
    address irImplementation;
    address irsImplementation;
    address tirImplementation;
    address mcImplementation;
}
```

T-REXコントラクトスイートを構成する各実装コントラクトのアドレスを保持する構造体。
特定のバージョンに対応する、6つの主要な実装コントラクトのアドレスをまとめて管理します。

**フィールド**

- `tokenImplementation`
    - **Token**の実装コントラクトアドレス。
- `ctrImplementation`
    - **ClaimTopicsRegistry**の実装コントラクトアドレス。
- `irImplementation`
    - **IdentityRegistry**の実装コントラクトアドレス。
- `irsImplementation`
    - **IdentityRegistryStorage**の実装コントラクトアドレス。
- `tirImplementation`
    - **TrustedIssuersRegistry**の実装コントラクトアドレス。
- `mcImplementation`
    - **ModularCompliance**の実装コントラクトアドレス。

### `Version`

```solidity
struct Version {
    uint8 major;
    uint8 minor;
    uint8 patch;
}
```

セマンティックバージョニングに基づいたバージョン番号を保持する構造体。
コントラクトのバージョンを`major.minor.patch`形式で管理します。

**フィールド**

- `major`
    - メジャーバージョン番号。
- `minor`
    - マイナーバージョン番号。
- `patch`
    - パッチバージョン番号。

## 変数

### `_currentVersion`

```solidity
Version private _currentVersion;
```

現在、プロキシが参照すべき有効なバージョンとして設定されている`Version`構造体を保持。

### `_contracts`

```solidity
mapping(bytes32 => TREXContracts) private _contracts;
```

`Version`構造体をハッシュ化した`bytes32`をキーとして、そのバージョンに対応する`TREXContracts`構造体（各実装コントラクトのアドレス群）を記録する`mapping`。

### `_reference`

```solidity
bool private _reference;
```

この**ImplementationAuthority**コントラクトが、**TREXFactory**コントラクトによって使用される「**リファレンス（メイン）**」のIAであるか（`true`）、トークン発行者が個別に管理する「**補助**」のIAであるか（`false`）を示します。

### `_trexFactory`

```solidity
address private _trexFactory;
```

関連する**TREXFactory**コントラクトのアドレスを保持。

### `_iaFactory`

```solidity
address private _iaFactory;
```

補助IAをデプロイするための**IAFactory**コントラクトのアドレスを保持。

## イベント

### `TREXVersionAdded`

```solidity
event TREXVersionAdded(Version indexed version, TREXContracts indexed trex);
```

`addTREXVersion`関数によって、新しいバージョンのコントラクト群がリファレンスIAに追加された時に発行されるイベント。

### `TREXVersionFetched`

```solidity
event TREXVersionFetched(Version indexed version, TREXContracts indexed trex);
```

補助IAが`fetchVersion`関数によって、リファレンスIAから新しいバージョン情報を取得（同期）した時に発行されるイベント。

### `VersionUpdated`

```solidity
event VersionUpdated(Version indexed version);
```

`useTREXVersion`関数によって、プロキシが参照すべき現在のバージョンが更新された時に発行されるイベント。

### `ImplementationAuthoritySet`

```solidity
event ImplementationAuthoritySet(bool referenceStatus, address trexFactory);
```

このコントラクトがデプロイされた際に、その種類（リファレンスか補助か）と関連するファクトリーアドレスを記録する時に発行されるイベント。

### `TREXFactorySet`

```solidity
event TREXFactorySet(address indexed trexFactory);
```

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

### `IAFactorySet`

```solidity
event IAFactorySet(address indexed iaFactory);
```

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

### `ImplementationAuthorityChanged`

```solidity
event ImplementationAuthorityChanged(address indexed _token, address indexed _newImplementationAuthority);
```

`changeImplementationAuthority`関数によって、特定のトークンが参照するIAが新しいものに変更された時に発行されるイベント。

## 関数

### `setTREXFactory`

```solidity
function setTREXFactory(address trexFactory) external override onlyOwner {
    require(
        isReferenceContract() &&
        ITREXFactory(trexFactory).getImplementationAuthority() == address(this)
    , "only reference contract can call");
    _trexFactory = trexFactory;
    emit TREXFactorySet(trexFactory);
}
```

このIAに関連する**TREXFactory**コントラクトのアドレスを設定する関数。
`onlyOwner`修飾子により、所有者のみが呼び出し可能です。
このIAがリファレンスIAであること、かつ、設定しようとしているファクトリーがこのIAを正しく参照していることを検証した上で、`_trexFactory`を更新します。

**引数**

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

### `setIAFactory`

```solidity
function setIAFactory(address iaFactory) external override onlyOwner {
    require(
        isReferenceContract() &&
        ITREXFactory(_trexFactory).getImplementationAuthority() == address(this)
    , "only reference contract can call");
    _iaFactory = iaFactory;
    emit IAFactorySet(iaFactory);
}
```

補助IAをデプロイするための**IAFactory**コントラクトのアドレスを設定する関数。
`onlyOwner`修飾子により、所有者のみが呼び出し可能です。
このIAがリファレンスIAである場合にのみ設定できます。

**引数**

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

### `addAndUseTREXVersion`

```solidity
function addAndUseTREXVersion(Version calldata _version, TREXContracts calldata _trex) external override {
    addTREXVersion(_version, _trex);
    useTREXVersion(_version);
}
```

新しいバージョンを追加し、即座にそのバージョンを使用中のバージョンとして設定する関数。
内部で`addTREXVersion`と`useTREXVersion`を連続して呼び出します。
アクセス制御はそれぞれの内部関数で行われるため、結果的にリファレンスIAの所有者のみが実行可能です。

**引数**

- `_version`
    - 追加して使用する新しいバージョン情報。
- `_trex`
    - 新しいバージョンに対応する実装コントラクト群のアドレス。

### `fetchVersion`

```solidity
function fetchVersion(Version calldata _version) external override {
    require(!isReferenceContract(), "cannot call on reference contract");
    if (_contracts[_versionToBytes(_version)].tokenImplementation != address(0)) {
        revert("version fetched already");
    }
    _contracts[_versionToBytes(_version)] =
    ITREXImplementationAuthority(getReferenceContract()).getContracts(_version);
    emit TREXVersionFetched(_version, _contracts[_versionToBytes(_version)]);
}
```

補助IAが、リファレンスIAから特定のバージョン情報を取得（同期）するための関数。
補助IA（`!isReferenceContract()`が`true`）でのみ呼び出し可能です。
まだ取得していないバージョンであれば、リファレンスIAの`getContracts`関数を呼び出してバージョン情報を取得し、自身のストレージに保存します。

**引数**

- `_version`
    - リファレンスIAから取得したいバージョン情報。

### `changeImplementationAuthority`

```solidity
function changeImplementationAuthority(address _token, address _newImplementationAuthority) external override {
    require(_token != address(0), "invalid argument - zero address");
    if(_newImplementationAuthority == address(0) && !isReferenceContract()){
        revert("only reference contract can deploy new IAs");}

    address _ir = address(IToken(_token).identityRegistry());
    address _mc = address(IToken(_token).compliance());
    address _irs = address(IIdentityRegistry(_ir).identityStorage());
    address _ctr = address(IIdentityRegistry(_ir).topicsRegistry());
    address _tir = address(IIdentityRegistry(_ir).issuersRegistry());

    // calling this function requires ownership of ALL contracts of the T-REX suite
    if(
        Ownable(_token).owner() != msg.sender
        || Ownable(_ir).owner() != msg.sender
        || Ownable(_mc).owner() != msg.sender
        || Ownable(_irs).owner() != msg.sender
        || Ownable(_ctr).owner() != msg.sender
        || Ownable(_tir).owner() != msg.sender) {
        revert("caller NOT owner of all contracts impacted");
    }

    if(_newImplementationAuthority == address(0)) {
        _newImplementationAuthority = IIAFactory(_iaFactory).deployIA(_token);
    }
    else {
        if(
            _versionToBytes(ITREXImplementationAuthority(_newImplementationAuthority).getCurrentVersion()) !=
            _versionToBytes(_currentVersion)) {
            revert("version of new IA has to be the same as current IA");
        }
        if(
            ITREXImplementationAuthority(_newImplementationAuthority).isReferenceContract() &&
            _newImplementationAuthority != getReferenceContract()) {
            revert("new IA is NOT reference contract");
        }
        if(
            !IIAFactory(_iaFactory).deployedByFactory(_newImplementationAuthority) &&
        _newImplementationAuthority != getReferenceContract()) {
            revert("invalid IA");
        }
    }

    IProxy(_token).setImplementationAuthority(_newImplementationAuthority);
    IProxy(_ir).setImplementationAuthority(_newImplementationAuthority);
    IProxy(_mc).setImplementationAuthority(_newImplementationAuthority);
    IProxy(_ctr).setImplementationAuthority(_newImplementationAuthority);
    IProxy(_tir).setImplementationAuthority(_newImplementationAuthority);
    // IRS can be shared by multiple tokens, and therefore could have been updated already
    if (IProxy(_irs).getImplementationAuthority() == address(this)) {
        IProxy(_irs).setImplementationAuthority(_newImplementationAuthority);
    }
    emit ImplementationAuthorityChanged(_token, _newImplementationAuthority);
}
```

特定のトークンスイートが参照するIAを、新しいIAに変更する関数。
この関数を呼び出せるのは、対象となるトークンスイート（Token, IR, MCなど全て）の所有者のみです。
`_newImplementationAuthority`にゼロアドレスを指定すると、リファレンスIAに紐づく**IAFactory**コントラクトを通じて新しい補助IAをデプロイしてそれに切り替えます。
アドレスが指定された場合は、いくつかの検証を行った上でそのIAに切り替えます。
最後に、関連する全てのプロキシコントラクトの`setImplementationAuthority`を呼び出して参照先を更新します。

**引数**

- `_token`
    - IAを変更したいトークンスイートの**Token**プロキシアドレス。
- `_newImplementationAuthority`
    - 新しく設定するIAのアドレス。
    - ゼロアドレスを指定すると新規デプロイ。

### `getCurrentVersion`

```solidity
function getCurrentVersion() external view override returns (Version memory) {
    return _currentVersion;
}
```

現在このIAで使用されているバージョン情報を返す関数。
`_currentVersion`の値を`Version`構造体として返します。

**戻り値**

- `Version memory`
    - 現在のバージョン情報。

### `getContracts`

```solidity
function getContracts(Version calldata _version) external view override returns (TREXContracts memory) {
    return _contracts[_versionToBytes(_version)];
}
```

指定されたバージョンに対応する実装コントラクト群のアドレスを返す関数。
`_contracts`マッピングから、指定されたバージョンに紐づく`TREXContracts`構造体を検索して返します。

**引数**

- `_version`
    - 取得したいバージョン情報。

**戻り値**

- `TREXContracts memory`
    - 指定されたバージョンに対応する実装コントラクト群のアドレス。

### `getTREXFactory`

```solidity
function getTREXFactory() external view override returns (address) {
    return _trexFactory;
}
```

このIAに関連する**TREXFactory**コントラクトのアドレスを返す関数。
`_trexFactory`の値を返します。

**戻り値**

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

### `getTokenImplementation`

```solidity
function getTokenImplementation() external view override returns (address) {
    return _contracts[_versionToBytes(_currentVersion)].tokenImplementation;
}
```

現在使用中のバージョンの**Token**実装コントラクトのアドレスを返す関数。
`_contracts`マッピングから現在のバージョンに対応する情報を取得し、その中の`tokenImplementation`フィールドの値を返します。プロキシが処理を委任する際にこの関数を呼び出します。

**戻り値**

- `address`
    - 現在の**Token**実装コントラクトのアドレス。

### `getCTRImplementation`

```solidity
function getCTRImplementation() external view override returns (address) {
    return _contracts[_versionToBytes(_currentVersion)].ctrImplementation;
}
```

現在使用中のバージョンの**ClaimTopicsRegistry**実装コントラクトのアドレスを返す関数。
`_contracts`マッピングから現在のバージョンに対応する情報を取得し、その中の`ctrImplementation`フィールドの値を返します。

**戻り値**

- `address`
    - 現在の**ClaimTopicsRegistry**実装コントラクトのアドレス。

### `getIRImplementation`

```solidity
function getIRImplementation() external view override returns (address) {
    return _contracts[_versionToBytes(_currentVersion)].irImplementation;
}
```

現在使用中のバージョンの**IdentityRegistry**実装コントラクトのアドレスを返す関数。
`_contracts`マッピングから現在のバージョンに対応する情報を取得し、その中の`irImplementation`フィールドの値を返します。

**戻り値**

- `address`
    - 現在の**IdentityRegistry**実装コントラクトのアドレス。

### `getIRSImplementation`

```solidity
function getIRSImplementation() external view override returns (address) {
    return _contracts[_versionToBytes(_currentVersion)].irsImplementation;
}
```

現在使用中のバージョンの**IdentityRegistryStorage**実装コントラクトのアドレスを返す関数。
`_contracts`マッピングから現在のバージョンに対応する情報を取得し、その中の`irsImplementation`フィールドの値を返します。

**戻り値**

- `address`
    - 現在の**IdentityRegistryStorage**実装コントラクトのアドレス。

### `getTIRImplementation`

```solidity
function getTIRImplementation() external view override returns (address) {
    return _contracts[_versionToBytes(_currentVersion)].tirImplementation;
}
```

現在使用中のバージョンの**TrustedIssuersRegistry**実装コントラクトのアドレスを返す関数。
`_contracts`マッピングから現在のバージョンに対応する情報を取得し、その中の`tirImplementation`フィールドの値を返します。

**戻り値**

- `address`
    - 現在の**TrustedIssuersRegistry**実装コントラクトのアドレス。

### `getMCImplementation`

```solidity
function getMCImplementation() external view override returns (address) {
    return _contracts[_versionToBytes(_currentVersion)].mcImplementation;
}
```

現在使用中のバージョンの**ModularCompliance**実装コントラクトのアドレスを返す関数。
`_contracts`マッピングから現在のバージョンに対応する情報を取得し、その中の`mcImplementation`フィールドの値を返します。

**戻り値**

- `address`
    - 現在の**ModularCompliance**実装コントラクトのアドレス。

### `addTREXVersion`

```solidity
function addTREXVersion(Version calldata _version, TREXContracts calldata _trex) public override onlyOwner {
    require(isReferenceContract(), "ONLY reference contract can add versions");
    if (_contracts[_versionToBytes(_version)].tokenImplementation != address(0)) {
        revert("version already exists");
    }
    require(
        _trex.ctrImplementation != address(0)
        && _trex.irImplementation != address(0)
        && _trex.irsImplementation != address(0)
        && _trex.mcImplementation != address(0)
        && _trex.tirImplementation != address(0)
        && _trex.tokenImplementation != address(0)
    , "invalid argument - zero address");
    _contracts[_versionToBytes(_version)] = _trex;
    emit TREXVersionAdded(_version, _trex);
}
```

新しいバージョンの実装コントラクト群をIAに登録する関数。
`onlyOwner`修飾子により所有者のみが呼び出し可能です。
また、リファレンスIAでのみ実行できます。
指定されたバージョンがまだ存在しないこと、および実装アドレスにゼロアドレスが含まれていないことを確認した上で、新しいバージョン情報を`_contracts`マッピングに保存します。

**引数**

- `_version`
    - 追加する新しいバージョン情報。
- `_trex`
    - 新しいバージョンに対応する実装コントラクト群のアドレス。

### `useTREXVersion`

```solidity
function useTREXVersion(Version calldata _version) public override onlyOwner {
    if (_versionToBytes(_version) == _versionToBytes(_currentVersion)) {
        revert("version already in use");
    }
    if (_contracts[_versionToBytes(_version)].tokenImplementation == address(0)) {
        revert("invalid argument - non existing version");
    }
    _currentVersion = _version;
    emit VersionUpdated(_version);
}
```

プロキシが参照すべき現在のバージョンを切り替える関数。
`onlyOwner`修飾子により所有者のみが呼び出し可能です。
指定されたバージョンが現在使用中のバージョンと異なること、およびそのバージョンが既に登録済みであることを確認した上で`_currentVersion`を更新します。
これにより、プロキシの一斉アップグレードが実行されます。

**引数**

- `_version`
    - 新しく使用するバージョン情報。

### `isReferenceContract`

```solidity
function isReferenceContract() public view override returns (bool) {
    return _reference;
}
```

このIAがリファレンスIAかどうかを返す関数。
`_reference`の値を返します。

**戻り値**

- `bool`
    - リファレンスIAの場合は`true`、補助IAの場合は`false`。

### `getReferenceContract`

```solidity
function getReferenceContract() public view override returns (address) {
    return ITREXFactory(_trexFactory).getImplementationAuthority();
}
```

このIAが関連するリファレンスIAのアドレスを返す関数。
`_trexFactory`に設定された**TREXFactory**に問い合わせ、そのファクトリーが参照しているIAのアドレスを返します。
このIA自身がリファレンスIAの場合、自身のアドレスを返すことになります。

**戻り値**

- `address`
    - リファレンスIAのコントラクトアドレス。
