# ERC20AllowlistUpgradeable.sol

> ERC20AllowlistUpgradeableは、ERC20トークンに対してアカウント単位の送受信および承認可否制御（Allowlist）を実装するためのコントラクト拡張です。

- URL: https://cardene.dev/books/jpmd/cd00f6
- 本: JPMD (https://cardene.dev/books/jpmd.md)
- 章: 4 / 8
- 前の章: https://cardene.dev/books/jpmd/410c8d.md
- 次の章: https://cardene.dev/books/jpmd/515cc5.md
- 公開日: 2025-07-08
- 更新日: 2025-07-08
- トピック: Blockchain
- タグ: ブロックチェーン, solidity, ethereum, smartcontract

## 概要

**ERC20AllowlistUpgradeable**は、**ERC20**トークンに対してアカウント単位の送受信および承認可否制御（Allowlist）を実装するためのコントラクト拡張です。
OpenZeppelin の**ERC20Upgradeable**を継承しており、管理者による許可制トークン転送・承認管理を実現します。

このコントラクトは、各アカウントがトークンの送信（`transfer`, `transferFrom`）や承認（`approve`）を行う前に、明示的に `allow` 状態に設定されていることを確認します。
許可されていないアカウントがこれらの操作を試みた場合、トランザクションは**ERC20Disallowed**エラーを返して `revert` されます。

ストレージは `AllowlistStorage` 構造体により `keccak256` で決定された固定スロットに保存されるため、アップグレード対応のストレージ管理を採用しています。

## コード

```sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";

/**
 * @title ERC20 Allowlist Extension
 * @author Kinexys by J.P.Morgan
 * @dev Extension of {ERC20} that allows to implement an allowlist mechanism that can be managed by
 *      an authorized account with the {_disallowAccount} and {_allowAccount} functions.
 *
 *      The allowlist provides the guarantee to the contract owner that any account won't be
 *      able to execute transfers or approvals to other entities to operate
 *      on its behalf if {_allowAccount} was not called with such account as an
 *      argument. Similarly, the account will be disallowed again if {_disallowAccount} is called.
 */
abstract contract ERC20AllowlistUpgradeable is ERC20Upgradeable {
    function __ERC20Allowlist_init() internal onlyInitializing {
        __ERC20Allowlist_init_unchained();
    }

    function __ERC20Allowlist_init_unchained() internal onlyInitializing {
    }

    /**
     * @dev Allowed status of addresses. True if allowed, False otherwise.
     */
    struct AllowlistStorage {
        mapping(address account => bool) _allowed;
    }

    // keccak256(abi.encode(uint256(keccak256("Token.storage.Allowlist")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant AllowlistStorageLocation = 0x00103c35cbcc56e29efc1a6b87de3ed6a47ff54b603aa92d36c9f0b5a6a05900;

    /**
     * @dev Private function that returns the AllowlistStorage struct from a fixed storage slot.
     * @return $ AllowlistStorage struct that contains the mapping of accounts that are allow-listed.
     */
    function _getAllowlistStorage() private pure returns (AllowlistStorage storage $) {
        assembly {
            $.slot := AllowlistStorageLocation
        }
    }

    /**
     * @dev Emitted when an `account` is allowed to transfer and approve.
     * @param account Address that has been allow-listed.
     */
    event AccountAllowed(address indexed account);

    /**
     * @dev Emitted when a account is disallowed.
     * @param account Address that has been removed from allow-list.
     */
    event AccountDisallowed(address indexed account);

    /**
     * @dev The operation failed because the account is not allowed.
     * @param account Address that is not allow-listed.
     */
    error ERC20Disallowed(address account);

    /**
     * @dev Returns the allowed status of an account.
     * @return Whether the account is allows-listed.
     */
    function allowed(address account) public view virtual returns (bool) {
        AllowlistStorage storage $ = _getAllowlistStorage();
        return $._allowed[account];
    }

    /**
     * @dev Allows a account to receive and transfer tokens, including minting and burning.
     * @param account The account to be allow-listed.
     */
    function _allowAccount(address account) internal virtual {
        AllowlistStorage storage $ = _getAllowlistStorage();
        if (!$._allowed[account]) {
            $._allowed[account] = true;
            emit AccountAllowed(account);
        }
    }

    /**
     * @dev Disallows a account from receiving and transferring tokens, including minting and burning.
     * @param account The account to be removed from allow-list.
     */
    function _disallowAccount(address account) internal virtual {
        AllowlistStorage storage $ = _getAllowlistStorage();
        if ($._allowed[account]) {
            $._allowed[account] = false;
            emit AccountDisallowed(account);
        }
    }

    /**
     * @dev See {ERC20Upgradeable-_update}.
     */
    function _update(address from, address to, uint256 value) internal virtual override {
        if (from != address(0) && !allowed(from)) revert ERC20Disallowed(from);
        if (to != address(0) && !allowed(to)) revert ERC20Disallowed(to);
        super._update(from, to, value);
    }

    /**
     * @dev See {ERC20Upgradeable-_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual override {
        if (!allowed(owner)) revert ERC20Disallowed(owner);
        super._approve(owner, spender, value, emitEvent);
    }
}
```

## 変数

```sol
AllowlistStorageLocation
```

固定ストレージスロットの位置を示す `bytes32` 定数。
* 値

    * `0x00103c35cbcc56e29efc1a6b87de3ed6a47ff54b603aa92d36c9f0b5a6a05900`

```sol
struct AllowlistStorage {
    mapping(address account => bool) _allowed;
}
```

各アカウントが許可されているかどうかを示すフラグ。

## 関数

### `allowed`

```solidity
function allowed(address account) public view virtual returns (bool) {
    AllowlistStorage storage $ = _getAllowlistStorage();
    return $._allowed[account];
}
```

アカウントがAllowlistに含まれているかを判定する関数。
指定したアドレスが許可された状態にあるかを `bool` で返します。
この関数は外部からの参照に使われ、`_update` や `_approve` 内部処理で検証に使われます。

**引数**

* `account`
    * 確認対象のアカウントアドレス。

**戻り値**

* `bool`
    * `true`
        * 許可済み。
  * `false`
      * 未許可。

### `_allowAccount`

```solidity
function _allowAccount(address account) internal virtual {
    AllowlistStorage storage $ = _getAllowlistStorage();
    if (!$._allowed[account]) {
        $._allowed[account] = true;
        emit AccountAllowed(account);
    }
}
```

指定アカウントをAllowlistに追加する内部関数。
対象アカウントが未登録の場合に `true` に設定し、`AccountAllowed` イベントを発行します。

**引数**

* `account`
    * Allowlistに追加するアドレス。

### `_disallowAccount`

```solidity
function _disallowAccount(address account) internal virtual {
    AllowlistStorage storage $ = _getAllowlistStorage();
    if ($._allowed[account]) {
        $._allowed[account] = false;
        emit AccountDisallowed(account);
    }
}
```

指定アカウントをAllowlistから除外する内部関数。
対象アカウントが `true`（許可状態）の場合に `false` に変更し、`AccountDisallowed` イベントを発行します。

**引数**

* `account`
    * Allowlistから除外するアドレス。

### `_getAllowlistStorage`

```solidity
function _getAllowlistStorage() private pure returns (AllowlistStorage storage $) {
    assembly {
        $.slot := AllowlistStorageLocation
    }
}
```

`AllowlistStorage` にアクセスするためのストレージスロット取得関数。
低レベルの `assembly` を使用して、固定スロットから `AllowlistStorage` を返します。
**ERC2535**（Diamond Storage）と同様のストレージ管理戦略。

:::message
**ERC2535**については以下の記事を参考にしてください。
:::

https://qiita.com/cardene/items/51fc6fc998421c4d931a

**戻り値**

* `$`
    * `AllowlistStorage` への参照。

### `_update`

```solidity
function _update(address from, address to, uint256 value) internal virtual override {
    if (from != address(0) && !allowed(from)) revert ERC20Disallowed(from);
    if (to != address(0) && !allowed(to)) revert ERC20Disallowed(to);
    super._update(from, to, value);
}
```

**ERC20**トークンの送信・受信時にAllowlistを確認する関数。
通常の `_update` を拡張し、`from`・`to` の両アカウントが許可済みであるかを検証します。
未許可の場合、`ERC20Disallowed` エラーを返します。

**引数**

* `from`
    * 送信元アドレス（`address(0)`はmint扱い）。
* `to`
    * 受信先アドレス（`address(0)`はburn扱い）。
* `value`
    * トークン数量。

### `_approve`

```solidity
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual override {
    if (!allowed(owner)) revert ERC20Disallowed(owner);
    super._approve(owner, spender, value, emitEvent);
}
```

`approve`の際にAllowlistチェックを追加する関数。
`owner`が未許可である場合に `ERC20Disallowed` エラーを返して承認をブロックします。`spender`側の検証は含まれません（本体で追加されている可能性あり）。

**引数**

* `owner`
    * トークンの保有者。
* `spender`
    * 承認対象アドレス。
* `value`
    * 承認するトークン数量。
* `emitEvent`
    * `Approval` イベントを出力するかどうかのフラグ。

## Event・Error

```sol
event AccountAllowed(address indexed account)
```

アカウントがAllowlistに追加されたことを通知。

```sol
event AccountDisallowed(address indexed account)
```

アカウントがAllowlistから削除されたことを通知。

```sol
error ERC20Disallowed(address account)
```

許可されていないアカウントによる操作をブロック。
