# [Contract] ModularCompliance

> このコントラクトは、ERC3643トークンの取引ルールを管理・実行するための「ルーター」として機能します。

- URL: https://cardene.dev/books/erc3643/6372e4
- 本: ERC3643 (https://cardene.dev/books/erc3643.md)
- 章: 19 / 20
- 前の章: https://cardene.dev/books/erc3643/ba0689.md
- 次の章: https://cardene.dev/books/erc3643/692c4d.md
- 公開日: 2025-07-25
- 更新日: 2025-07-25
- トピック: Blockchain
- タグ: ブロックチェーン, solidity, ethereum, smartcontract

## 概要

このコントラクトは、**ERC3643**トークンの取引ルールを管理・実行するための「**ルーター**」として機能します。
保有上限や国籍制限といった具体的なコンプライアンスルールを実装した、独立した「**モジュール**」コントラクトを複数登録し、トークン移転の際にこれらのモジュールに一括で問い合わせを行います。

**ModularCompliance**コントラクトは、トークンのコンプライアンスロジックを柔軟かつ拡張可能にするためのコンポーネントです。
トークンコントラクトは、この**ModularCompliance**コントラクトを連携先として知っていればよく、具体的なルール（保有上限など）の詳細は知りません。

トークン発行者（オーナー）は、`addModule`関数を使って、必要なコンプライアンスルールを実装したモジュール（例: **MaxBalanceModule**）をこのコントラクトに「**プラグイン**」のように追加できます。
トークン送付時にトークンコントラクトは`canTransfer`関数を呼び出します。
その後、このコントラクトは登録されている全てのモジュールの`moduleCheck`関数を順番に呼び出し、全てのモジュールが許可した場合にのみ送付を許可する仕組みです。

また、`transferred`, `created`, `destroyed`といった関数を通じて、トークンの状態変化を各モジュールに通知し、モジュールが内部状態（例: 取引量カウンター）を更新するのを助けます。
このモジュール式のアーキテクチャにより、複雑な規制要件にも柔軟に対応できます。

## 機能

* コンプライアンスモジュールの追加・削除（オーナー限定）
* トークン送付がコンプライアンスに適合しているかの検証（`canTransfer`）
* トークンの状態変化（送付、発行、Burn）を全モジュールに通知
* 特定のモジュールに関数を直接呼び出す機能（オーナー限定）

## フロー

### トークン送付時のコンプライアンス検証

```mermaid
sequenceDiagram
    participant Token as Tokenコントラクト
    participant Compliance as ModularCompliance
    participant ModuleA as コンプライアンスモジュールA
    participant ModuleB as コンプライアンスモジュールB

    Token->>Compliance: 1. canTransfer(from, to, amount)
    activate Compliance

    Compliance->>ModuleA: 2. moduleCheck(from, to, amount)
    activate ModuleA
    ModuleA-->>Compliance: 3. true (許可)
    deactivate ModuleA

    Compliance->>ModuleB: 4. moduleCheck(from, to, amount)
    activate ModuleB
    ModuleB-->>Compliance: 5. true (許可)
    deactivate ModuleB
    
    Note over Compliance: 全てのモジュールが許可
    Compliance-->>Token: 6. true (送付許可)
    deactivate Compliance
```

## コード

```sol:ModularCompliance.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-upgradeable/access/OwnableUpgradeable.sol";
import "../../token/IToken.sol";
import "./IModularCompliance.sol";
import "./MCStorage.sol";
import "./modules/IModule.sol";


contract ModularCompliance is IModularCompliance, OwnableUpgradeable, MCStorage {

    /// modifiers

    /**
     * @dev Throws if called by any address that is not a token bound to the compliance.
     */
    modifier onlyToken() {
        require(msg.sender == _tokenBound, "error : this address is not a token bound to the compliance contract");
        _;
    }

    function init() external initializer {
        __Ownable_init();
    }

    /**
     *  @dev See {IModularCompliance-bindToken}.
     */
    function bindToken(address _token) external override {
        require(owner() == msg.sender || (_tokenBound == address(0) && msg.sender == _token),
        "only owner or token can call");
        require(_token != address(0), "invalid argument - zero address");
        _tokenBound = _token;
        emit TokenBound(_token);
    }

    /**
    *  @dev See {IModularCompliance-unbindToken}.
    */
    function unbindToken(address _token) external override {
        require(owner() == msg.sender || msg.sender == _token , "only owner or token can call");
        require(_token == _tokenBound, "This token is not bound");
        require(_token != address(0), "invalid argument - zero address");
        delete _tokenBound;
        emit TokenUnbound(_token);
    }

    /**
     *  @dev See {IModularCompliance-addModule}.
     */
    function addModule(address _module) external override onlyOwner {
        require(_module != address(0), "invalid argument - zero address");
        require(!_moduleBound[_module], "module already bound");
        require(_modules.length <= 24, "cannot add more than 25 modules");
        IModule module = IModule(_module);
        if (!module.isPlugAndPlay()) {
            require(module.canComplianceBind(address(this)), "compliance is not suitable for binding to the module");
        }

        module.bindCompliance(address(this));
        _modules.push(_module);
        _moduleBound[_module] = true;
        emit ModuleAdded(_module);
    }

    /**
     *  @dev See {IModularCompliance-removeModule}.
     */
    function removeModule(address _module) external override onlyOwner {
        require(_module != address(0), "invalid argument - zero address");
        require(_moduleBound[_module], "module not bound");
        uint256 length = _modules.length;
        for (uint256 i = 0; i < length; i++) {
            if (_modules[i] == _module) {
                IModule(_module).unbindCompliance(address(this));
                _modules[i] = _modules[length - 1];
                _modules.pop();
                _moduleBound[_module] = false;
                emit ModuleRemoved(_module);
                break;
            }
        }
    }

    /**
    *  @dev See {IModularCompliance-transferred}.
    */
    function transferred(address _from, address _to, uint256 _value) external onlyToken override {
        require(
            _from != address(0)
            && _to != address(0)
        , "invalid argument - zero address");
        require(_value > 0, "invalid argument - no value transfer");
        uint256 length = _modules.length;
        for (uint256 i = 0; i < length; i++) {
            IModule(_modules[i]).moduleTransferAction(_from, _to, _value);
        }
    }

    /**
     *  @dev See {IModularCompliance-created}.
     */
    function created(address _to, uint256 _value) external onlyToken override {
        require(_to != address(0), "invalid argument - zero address");
        require(_value > 0, "invalid argument - no value mint");
        uint256 length = _modules.length;
        for (uint256 i = 0; i < length; i++) {
            IModule(_modules[i]).moduleMintAction(_to, _value);
        }
    }

    /**
     *  @dev See {IModularCompliance-destroyed}.
     */
    function destroyed(address _from, uint256 _value) external onlyToken override {
        require(_from != address(0), "invalid argument - zero address");
        require(_value > 0, "invalid argument - no value burn");
        uint256 length = _modules.length;
        for (uint256 i = 0; i < length; i++) {
            IModule(_modules[i]).moduleBurnAction(_from, _value);
        }
    }

    /**
     *  @dev see {IModularCompliance-callModuleFunction}.
     */
    function callModuleFunction(bytes calldata callData, address _module) external override onlyOwner {
        require(_moduleBound[_module], "call only on bound module");
        // NOTE: Use assembly to call the interaction instead of a low level
        // call for two reasons:
        // - We don't want to copy the return data, since we discard it for
        // interactions.
        // - Solidity will under certain conditions generate code to copy input
        // calldata twice to memory (the second being a "memcopy loop").
        // solhint-disable-next-line no-inline-assembly
        assembly {
            let freeMemoryPointer := mload(0x40)
            calldatacopy(freeMemoryPointer, callData.offset, callData.length)
            if iszero(
            call(
            gas(),
            _module,
            0,
            freeMemoryPointer,
            callData.length,
            0,
            0
            ))
            {
                returndatacopy(0, 0, returndatasize())
                revert(0, returndatasize())
            }
        }

        emit ModuleInteraction(_module, _selector(callData));

    }

    /**
     *  @dev See {IModularCompliance-isModuleBound}.
     */
    function isModuleBound(address _module) external view override returns (bool) {
        return _moduleBound[_module];
    }

    /**
     *  @dev See {IModularCompliance-getModules}.
     */
    function getModules() external view override returns (address[] memory) {
        return _modules;
    }

    /**
     *  @dev See {IModularCompliance-getTokenBound}.
     */
    function getTokenBound() external view override returns (address) {
        return _tokenBound;
    }

    /**
     *  @dev See {IModularCompliance-canTransfer}.
     */
    function canTransfer(address _from, address _to, uint256 _value) external view override returns (bool) {
        uint256 length = _modules.length;
        for (uint256 i = 0; i < length; i++) {
            if (!IModule(_modules[i]).moduleCheck(_from, _to, _value, address(this))) {
                return false;
            }
        }
        return true;
    }

    /// @dev Extracts the Solidity ABI selector for the specified interaction.
    /// @param callData Interaction data.
    /// @return result The 4 byte function selector of the call encoded in
    /// this interaction.
    function _selector(bytes calldata callData) internal pure returns (bytes4 result) {
        if (callData.length >= 4) {
            // NOTE: Read the first word of the interaction's calldata. The
            // value does not need to be shifted since `bytesN` values are left
            // aligned, and the value does not need to be masked since masking
            // occurs when the value is accessed and not stored:
            // <https://docs.soliditylang.org/en/v0.7.6/abi-spec.html#encoding-of-indexed-event-parameters>
            // <https://docs.soliditylang.org/en/v0.7.6/assembly.html#access-to-external-variables-functions-and-libraries>
            // solhint-disable-next-line no-inline-assembly
            assembly {
                result := calldataload(callData.offset)
            }
        }
    }
}
```

## 変数

### `_tokenBound`

```solidity
address internal _tokenBound;
```

このコンプライアンスコントラクトが紐付けられている**Token**コントラクトのアドレスを保持。

### `_modules`

```solidity
address[] internal _modules;
```

このコンプライアンスコントラクトに登録（バインド）されている、全てのコンプライアンスモジュールのコントラクトアドレスを格納する動的配列。

### `_moduleBound`

```solidity
mapping(address => bool) internal _moduleBound;
```

モジュールのアドレスをキーとして、そのモジュールが現在このコントラクトに登録されているかどうかを`true`または`false`で記録する`mapping`。

## イベント

### `ModuleInteraction`

```solidity
event ModuleInteraction(address indexed target, bytes4 selector);
```

`callModuleFunction`関数によって、オーナーがモジュールとやり取りした時に発行されるイベント。

### `TokenBound`

```solidity
event TokenBound(address _token);
```

`bindToken`関数によって、**Token**コントラクトがこのコンプライアンスコントラクトに紐付けられた時に発行されるイベント。

### `TokenUnbound`

```solidity
event TokenUnbound(address _token);
```

`unbindToken`関数によって、**Token**コントラクトの紐付けが解除された時に発行されるイベント。

### `ModuleAdded`

```solidity
event ModuleAdded(address indexed _module);
```

`addModule`関数によって、新しいコンプライアンスモジュールが追加された時に発行されるイベント。

### `ModuleRemoved`

```solidity
event ModuleRemoved(address indexed _module);
```

`removeModule`関数によって、コンプライアンスモジュールが削除された時に発行されるイベント。

## Modifier

### `onlyToken`

```solidity
modifier onlyToken() {
    require(msg.sender == _tokenBound, "error : this address is not a token bound to the compliance contract");
    _;
}
```

関数の呼び出し元が、このコンプライアンスコントラクトに紐付けられた**Token**コントラクトであることを要求する修飾子。
`_tokenBound`に保存されているアドレスと、関数の呼び出し元（`msg.sender`）が一致するかを検証します。
これにより、`transferred`のような状態更新関数が、連携するトークンからのみ呼び出されることを保証します。

## 関数

### `init`

```solidity
function init() external initializer {
    __Ownable_init();
}
```

プロキシコントラクトの初期設定を行う初期化関数。
`initializer`修飾子により、一度だけ呼び出し可能です。
内部で`__Ownable_init`を呼び出し、デプロイ者をコントラクトの所有者として設定します。

### `bindToken`

```solidity
function bindToken(address _token) external override {
    require(owner() == msg.sender || (_tokenBound == address(0) && msg.sender == _token),
    "only owner or token can call");
    require(_token != address(0), "invalid argument - zero address");
    _tokenBound = _token;
    emit TokenBound(_token);
}
```

**Token**コントラクトをこのコンプライアンスコントラクトに紐付ける関数。
オーナー、またはまだ何も紐付いていない状態であればトークンコントラクト自身から呼び出すことができます。
`_tokenBound`変数にトークンのアドレスを保存します。

**引数**

- `_token`
    - 紐付ける**Token**のコントラクトアドレス。

### `unbindToken`

```solidity
function unbindToken(address _token) external override {
    require(owner() == msg.sender || msg.sender == _token , "only owner or token can call");
    require(_token == _tokenBound, "This token is not bound");
    require(_token != address(0), "invalid argument - zero address");
    delete _tokenBound;
    emit TokenUnbound(_token);
}
```

**Token**コントラクトの紐付けを解除する関数。
オーナーまたは紐付けられているトークン自身から呼び出すことができます。
`_tokenBound`変数をリセットします。

**引数**

- `_token`
    - 紐付けを解除する**Token**のコントラクトアドレス。

### `addModule`

```solidity
function addModule(address _module) external override onlyOwner {
    require(_module != address(0), "invalid argument - zero address");
    require(!_moduleBound[_module], "module already bound");
    require(_modules.length <= 24, "cannot add more than 25 modules");
    IModule module = IModule(_module);
    if (!module.isPlugAndPlay()) {
        require(module.canComplianceBind(address(this)), "compliance is not suitable for binding to the module");
    }

    module.bindCompliance(address(this));
    _modules.push(_module);
    _moduleBound[_module] = true;
    emit ModuleAdded(_module);
}
```

新しいコンプライアンスモジュールを追加する関数。
`onlyOwner`修飾子により、所有者のみが呼び出し可能です。モジュールが未登録であること、および総モジュール数が上限（25個）を超えないことを確認します。
その後、モジュール側の`bindCompliance`を呼び出して相互に紐付け、自身のリストにモジュールを追加します。

**引数**

- `_module`
    - 追加するモジュールのコントラクトアドレス。

### `removeModule`

```solidity
function removeModule(address _module) external override onlyOwner {
    require(_module != address(0), "invalid argument - zero address");
    require(_moduleBound[_module], "module not bound");
    uint256 length = _modules.length;
    for (uint256 i = 0; i < length; i++) {
        if (_modules[i] == _module) {
            IModule(_module).unbindCompliance(address(this));
            _modules[i] = _modules[length - 1];
            _modules.pop();
            _moduleBound[_module] = false;
            emit ModuleRemoved(_module);
            break;
        }
    }
}
```

登録されているコンプライアンスモジュールを削除する関数。
`onlyOwner`修飾子により、所有者のみが呼び出し可能です。
モジュールが登録済みであることを確認後、モジュール側の`unbindCompliance`を呼び出し、自身のリストからモジュールを削除します。

**引数**

- `_module`
    - 削除するモジュールのコントラクトアドレス。

### `transferred`

```solidity
function transferred(address _from, address _to, uint256 _value) external onlyToken override {
    require(
        _from != address(0)
        && _to != address(0)
    , "invalid argument - zero address");
    require(_value > 0, "invalid argument - no value transfer");
    uint256 length = _modules.length;
    for (uint256 i = 0; i < length; i++) {
        IModule(_modules[i]).moduleTransferAction(_from, _to, _value);
    }
}
```

トークンが送付された後に、**Token**コントラクトから呼び出される関数。
`onlyToken`修飾子により、紐付けられたトークンからのみ呼び出し可能です。
登録されている全てのモジュールの`moduleTransferAction`関数を呼び出し、送付があったことを通知します。
これにより、各モジュールは自身の内部状態を更新できます。

**引数**

- `_from`
    - 送付元のアドレス。
- `_to`
    - 送付先のアドレス。
- `_value`
    - 送付されたトークンの数量。

### `created`

```solidity
function created(address _to, uint256 _value) external onlyToken override {
    require(_to != address(0), "invalid argument - zero address");
    require(_value > 0, "invalid argument - no value mint");
    uint256 length = _modules.length;
    for (uint256 i = 0; i < length; i++) {
        IModule(_modules[i]).moduleMintAction(_to, _value);
    }
}
```

トークンが新規発行（ミント）された後に、**Token**コントラクトから呼び出される関数。
`onlyToken`修飾子により、紐付けられたトークンからのみ呼び出し可能です。
登録されている全てのモジュールの`moduleMintAction`関数を呼び出し、新規発行があったことを通知します。

**引数**

- `_to`
    - トークンを受け取ったアドレス。
- `_value`
    - 発行されたトークンの数量。

### `destroyed`

```solidity
function destroyed(address _from, uint256 _value) external onlyToken override {
    require(_from != address(0), "invalid argument - zero address");
    require(_value > 0, "invalid argument - no value burn");
    uint256 length = _modules.length;
    for (uint256 i = 0; i < length; i++) {
        IModule(_modules[i]).moduleBurnAction(_from, _value);
    }
}
```

トークンがBurnされた後に、**Token**コントラクトから呼び出される関数。
`onlyToken`修飾子により、紐付けられたトークンからのみ呼び出し可能です。
登録されている全てのモジュールの`moduleBurnAction`関数を呼び出し、焼却があったことを通知します。

**引数**

- `_from`
    - トークンがBurnされた元のアドレス。
- `_value`
    - Burnされたトークンの数量。

### `callModuleFunction`

```solidity
function callModuleFunction(bytes calldata callData, address _module) external override onlyOwner {
    require(_moduleBound[_module], "call only on bound module");
    // ... (assembly low-level call)
}
```

オーナーが登録済みのモジュールに対して、任意の関数を直接呼び出すための関数。
`onlyOwner`修飾子により、所有者のみが呼び出し可能です。
モジュールのパラメータ設定など、管理目的で使用されます。低レベルの`call`を使用して、任意の`calldata`をターゲットのモジュールに渡します。

**引数**

- `callData`
    - モジュールで実行したい関数のABIエンコードされたコールデータ。
- `_module`
    - 呼び出し先のモジュールのコントラクトアドレス。

### `isModuleBound`

```solidity
function isModuleBound(address _module) external view override returns (bool) {
    return _moduleBound[_module];
}
```

指定されたモジュールがこのコンプライアンスコントラクトに登録されているかを返す関数。
`_moduleBound`マッピングの値を返します。

**引数**

- `_module`
    - 確認したいモジュールのコントラクトアドレス。

**戻り値**

- `bool`
    - 登録されていれば`true`、そうでなければ`false`。

### `getModules`

```solidity
function getModules() external view override returns (address[] memory) {
    return _modules;
}
```

登録されている全てのコンプライアンスモジュールのリストを返す関数。
`_modules`配列の現在の内容を返します。

**戻り値**

- `address[] memory`
    - 登録されているモジュールのアドレスの配列。

### `getTokenBound`

```solidity
function getTokenBound() external view override returns (address) {
    return _tokenBound;
}
```

このコンプライアンスコントラクトに紐付けられている**Token**コントラクトのアドレスを返す関数。
`_tokenBound`の値を返します。

**戻り値**

- `address`
    - 紐付けられた**Token**のコントラクトアドレス。

### `canTransfer`

```solidity
function canTransfer(address _from, address _to, uint256 _value) external view override returns (bool) {
    uint256 length = _modules.length;
    for (uint256 i = 0; i < length; i++) {
        if (!IModule(_modules[i]).moduleCheck(_from, _to, _value, address(this))) {
            return false;
        }
    }
    return true;
}
```

提案された送付が、登録されている全てのコンプライアンスルールに適合しているかを確認する関数。
**Token**コントラクトから呼び出される、コンプライアンス検証のメイン関数です。
登録されている全てのモジュールの`moduleCheck`関数を順番に呼び出します。
もし一つでも`false`を返すモジュールがあれば、即座に`false`を返して処理を中断します。
全てのモジュールが`true`を返した場合にのみ、最終的に`true`を返します。

**引数**

- `_from`
    - 送付元のアドレス。
- `_to`
    - 送付先のアドレス。
- `_value`
    - 送付予定のトークンの数量。

**戻り値**

- `bool`
    - 送付が全てのルールに適合していれば`true`、そうでなければ`false`。
