概要

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

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

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

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

機能

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

フロー

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

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

コード

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。