# [Contract] Role

> このコントラクトは、「エージェント」という特別なロールを持つアドレスを管理するためのものです。

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

## 概要

このコントラクトは、「**エージェント**」という特別なロールを持つアドレスを管理するためのものです。
コントラクトの所有者（オーナー）のみがエージェントを追加・削除でき、`onlyAgent`修飾子を使うことで、他のコントラクトが特定機能の実行をエージェントのみに制限できるようになります。

この**AgentRole**コントラクトは、所有者（Owner）とは別に、特定の管理操作を実行できる「**エージェント（Agent）**」というロールを定義し、そのメンバーを管理する仕組みを提供します。
OpenZeppelinの`Roles`ライブラリを利用して実装されており、オーナーは`addAgent`や`removeAgent`関数を通じて、信頼できるアドレスをエージェントとして任命または解任できます。

このコントラクトを継承する他のコントラクト（例えば**Token**コントラクト）は、`onlyAgent`修飾子を使用することで、「**トークンの新規発行**」や「**アドレスの凍結**」といった操作の実行権限を、オーナーではなくエージェントに限定できます。
これにより、コントラクトの最高管理権限（所有権）を安全に保ちながら、日々の運用タスクを別の管理者へ安全に委任することが可能になります。

## 機能

* エージェントの追加・削除機能（オーナー限定）
* 特定のアドレスがエージェントであるかの確認機能
* 関数の実行者をエージェントのみに制限するための修飾子（`onlyAgent`）の提供

## フロー

### エージェントの任命と権限の行使

```mermaid
sequenceDiagram
    actor Owner as オーナー
    participant AgentRole as AgentRoleコントラクト
    actor Agent as エージェント
    participant TargetContract as 対象コントラクト<br>(onlyAgentを使用)

    Owner->>AgentRole: 1. addAgent(Agentのアドレス)
    activate AgentRole
    Note over AgentRole: エージェントを追加し、イベントを発行
    AgentRole-->>Owner: 成功
    deactivate AgentRole

    %% 時間が経過 %%

    Agent->>TargetContract: 2. agentOnlyFunction()
    activate TargetContract
    TargetContract->>AgentRole: 3. isAgent(Agentのアドレス)
    activate AgentRole
    AgentRole-->>TargetContract: true
    deactivate AgentRole
    Note over TargetContract: 権限を確認し、ロジックを実行
    TargetContract-->>Agent: 4. 成功
    deactivate TargetContract
```

## コード

```sol:AgentRole.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 "./Roles.sol";

contract AgentRole is Ownable {
    using Roles for Roles.Role;

    Roles.Role private _agents;

    event AgentAdded(address indexed _agent);
    event AgentRemoved(address indexed _agent);

    modifier onlyAgent() {
        require(isAgent(msg.sender), "AgentRole: caller does not have the Agent role");
        _;
    }

    function addAgent(address _agent) public onlyOwner {
        require(_agent != address(0), "invalid argument - zero address");
        _agents.add(_agent);
        emit AgentAdded(_agent);
    }

    function removeAgent(address _agent) public onlyOwner {
        require(_agent != address(0), "invalid argument - zero address");
        _agents.remove(_agent);
        emit AgentRemoved(_agent);
    }

    function isAgent(address _agent) public view returns (bool) {
        return _agents.has(_agent);
    }
}
```

## 変数

### `_agents`

```solidity
Roles.Role private _agents;
```

エージェントとして登録されたアドレスの集合を管理するための`Roles.Role`型のプライベート変数。
OpenZeppelinの`Roles`ライブラリによって提供されるデータ構造で、アドレスの追加、削除、存在確認といった操作を効率的に行います。

## イベント

### `AgentAdded`

```solidity
event AgentAdded(address indexed _agent);
```

`addAgent`関数によって新しいエージェントが追加された時に発行されるイベント。

### `AgentRemoved`

```solidity
event AgentRemoved(address indexed _agent);
```

`removeAgent`関数によってエージェントが削除された時に発行されるイベント。

## Modifier

### `onlyAgent`

```solidity
modifier onlyAgent() {
    require(isAgent(msg.sender), "AgentRole: caller does not have the Agent role");
    _;
}
```

この修飾子が付けられた関数の実行者を、エージェントとして登録されたアドレスのみに制限します。
内部で`isAgent(msg.sender)`を呼び出して呼び出し元がエージェントであるかを確認し、エージェントでない場合は`"AgentRole: caller does not have the Agent role"`というエラーメッセージと共にトランザクションを失敗させます。

## 関数

### `addAgent`

```solidity
function addAgent(address _agent) public onlyOwner {
    require(_agent != address(0), "invalid argument - zero address");
    _agents.add(_agent);
    emit AgentAdded(_agent);
}
```

新しいエージェントを追加する関数。
`onlyOwner`修飾子により、このコントラクトの所有者のみが呼び出し可能です。
指定されたアドレスをエージェントのリストに追加し、`AgentAdded`イベントを発行します。
ゼロアドレスは追加できません。

**引数**

- `_agent`
    - エージェントとして追加するアドレス。

### `removeAgent`

```solidity
function removeAgent(address _agent) public onlyOwner {
    require(_agent != address(0), "invalid argument - zero address");
    _agents.remove(_agent);
    emit AgentRemoved(_agent);
}
```

エージェントをリストから削除する関数。
`onlyOwner`修飾子により、このコントラクトの所有者のみが呼び出し可能です。
指定されたアドレスをエージェントのリストから削除し、`AgentRemoved`イベントを発行します。

**引数**

- `_agent`
    - エージェントから削除するアドレス。

### `isAgent`

```solidity
function isAgent(address _agent) public view returns (bool) {
    return _agents.has(_agent);
}
```

指定されたアドレスがエージェントかどうかを確認する関数。
`_agents`ロールに指定されたアドレスが含まれているかを`Roles`ライブラリの`has`関数を使って確認し、結果を返します。

**引数**

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

**戻り値**

- `bool`
    - エージェントであれば`true`、そうでなければ`false`。
