# アーキテクチャ

> 大きく分けて、設定と実行の2つに分けられ、この2つが連携してプリコンパイルシステム全体を構成しています。

- URL: https://cardene.dev/books/avalanche-subnet-precompile/c93d2f
- 本: [Avalanche] Subnet Precompile (https://cardene.dev/books/avalanche-subnet-precompile.md)
- 章: 3 / 21
- 前の章: https://cardene.dev/books/avalanche-subnet-precompile/889825.md
- 次の章: https://cardene.dev/books/avalanche-subnet-precompile/ef0136.md
- 公開日: 2025-08-20
- 更新日: 2025-08-20
- トピック: Blockchain
- タグ: ブロックチェーン, solidity, ethereum, smartcontract

## コントラクト

```mermaid
classDiagram
    direction LR

    class Ownable {
        <<Interface>>
        +owner() address
        +transferOwnership(address)
    }

    class ERC20 {
        <<Interface>>
        +totalSupply() uint256
        +balanceOf(address) uint256
        +transfer(address, uint256)
    }

    class AllowList {
        <<Wrapper>>
        +setAdmin(address)
        +setEnabled(address)
        +setManager(address)
        +revoke(address)
        +readAllowList(address) uint256
    }

    class ExampleWarp {
        +sendWarpMessage(bytes)
        +validateWarpMessage(...)
        +validateWarpBlockHash(...)
        +validateGetBlockchainID(bytes32)
    }

    class ExampleFeeManager {
        +enableWAGMIFees()
        +enableCChainFees()
        +enableCustomFees(FeeConfig)
        +getCurrentFeeConfig() FeeConfig
        +getFeeConfigLastChangedAt() uint256
    }

    class ExampleDeployerList {
        +deployContract()
    }

    class ExampleTxAllowList {
        +deployContract()
    }

    class ERC20NativeMinter {
        +mint(address, uint256)
        +burn(address, uint256)
        +mintdraw(uint256)
        +deposit()
        +decimals() uint8
    }

    class ExampleRewardManager {
        +currentRewardAddress() address
        +setRewardAddress(address)
        +allowFeeRecipients()
        +disableRewards()
        +areFeeRecipientsAllowed() bool
    }

    Ownable <|-- AllowList
    Ownable <|-- ExampleRewardManager

    AllowList <|-- ERC20NativeMinter
    AllowList <|-- ExampleFeeManager
    AllowList <|-- ExampleDeployerList
    AllowList <|-- ExampleTxAllowList
    
    ERC20 <|-- ERC20NativeMinter
```

- **`Ownable`**
    OpenZeppelinの標準的なコントラクト。
    コントラクトの所有権（オーナー）を管理する基本的な機能を提供します。
- **`ERC20`**
    OpenZeppelinの標準的なトークンコントラクト。
    **ERC20**トークンの基本機能を実装します。
- **`AllowList`**
    プリコンパイルを操作するためのラッパーコントラクトの基盤。
    `Ownable`を継承し、オーナーのみが権限設定を変更できるようにします。
    `setAdmin`や`setEnabled`などの権限管理関数を持ちます。
- **`ExampleWarp`**
    `WarpMessenger`プリコンパイルを操作するサンプル。
    クロスチェーンメッセージを送信する`sendWarpMessage`や、受信したメッセージを検証する`validateWarpMessage`などの関数を持ちます。
- **`ExampleFeeManager`**
    `FeeManager`プリコンパイルを操作するサンプル。
    `AllowList`を継承し、権限を持つユーザーのみが`enableWAGMIFees`などのガス料金設定変更関数を呼び出せます。
- **`ExampleDeployerList`**
    `ContractDeployerAllowList`プリコンパイルを操作するサンプル。
    `AllowList`を継承しており、テスト用に`deployContract`関数を持ちます。
- **`ExampleTxAllowList`**
    `TxAllowList`プリコンパイルを操作するサンプル。
    `ExampleDeployerList`と同様に`AllowList`を継承し、`deployContract`関数を持ちます。
- **`ERC20NativeMinter`**
    ネイティブトークンと**ERC20**トークンを交換するコントラクト。
    **ERC20**のトークン機能と、`AllowList`のオーナーによる`mint`/`burn`権限管理機能を継承しています。
- **`ExampleRewardManager`**
    `RewardManager`プリコンパイルを操作するサンプル。
    `Ownable`を継承し、オーナーのみが`setRewardAddress`などの報酬設定関数を呼び出せます。


## プリコンパイル

### 設定と実行

大きく分けて、設定と実行の2つに分けられ、この2つが連携してプリコンパイルシステム全体を構成しています。

#### EVM起動時（設定フェーズ）

Subnet-EVMが起動すると、まず`modules.Registerer`が、Goの`init()`機能を通じてシステムに存在する全てのプリコンパイル`Module`をグローバルなリストに登録します。
次に、EVMはブロックチェーンの初期設定ファイル（ジェネシス）を読み込みます。
設定ファイル内の各キー（例: `"feeManagerConfig"`）に対応する`Module`の`Configurator`を使って、JSON設定をGoの具体的な`Config`構造体（例: `feemanager.FeeManagerConfig`）にデコードします。
デコードされた`Config`オブジェクトの`Verify()`メソッドを呼び出し、設定値が不正でないか検証します。
検証を通過すると、`Configurator`の`Configure()`メソッドが呼び出され、`Config`に定義された初期設定（例: `AllowList`の初期メンバー）がEVMのステートに書き込まれます。
この段階で、設定アーキテクチャの役割は完了し、プリコンパイルの初期状態が確定します。

#### トランザクション実行時（実行フェーズ）

ユーザーがプリコンパイルのアドレス（例: `0x0200...0003` for FeeManager）にトランザクションを送信します。
EVMは、そのアドレスがプリコンパイルに属することを認識し、起動時に登録された`Module`リストから対応する`Module`を検索します。
EVMは、見つかった`Module`から`Contract`フィールド（実行アーキテクチャで定義された実行ロジック本体）を取得します。
取得した`Contract`の`Run()`メソッドを呼び出します。
このとき、現在のステート情報などを含む`AccessibleState`を引数として渡します。
`Run()`メソッド（通常は`statefulPrecompileWithFunctionSelectors`）は、トランザクションの`calldata`から関数セレクタを読み取り、対応するGoの内部関数（例: `setFeeConfig`）を実行します。
実行関数は、`AccessibleState`を通じてEVMのステートを読み書きし、処理結果を返します。

このように、設定アーキテクチャは「**起動時に一度だけ、プリコンパイルの初期状態を準備する**」ためのものであり、実行アーキテクチャは「**トランザクションが来るたびに具体的な処理を実行する**」**ためのものです。

### 設定アーキテクチャ

この図は、各プリコンパイルがブロックチェーンの初期設定ファイルやネットワークアップグレードによって、どのように設定され、検証されるかを示しています。

```mermaid
classDiagram
    direction TB

    %% ===== precompileconfig =====
    class precompileconfig_Config {
        <<Interface>>
        +Key() : string
        +Timestamp() : *uint64
        +Verify(cfg : precompileconfig_ChainConfig)
        +Equal(cfg : precompileconfig_Config) : bool
    }
    class precompileconfig_Upgrade {
        +BlockTimestamp : *uint64
        +Disable : bool
    }
    class precompileconfig_ChainConfig {
        <<Interface>>
        +IsDurango(height : uint64) : bool
    }

    %% ===== allowlist =====
    class allowlist_AllowListConfig {
        +AdminAddresses : []common.Address
        +ManagerAddresses : []common.Address
        +EnabledAddresses : []common.Address
    }

    %% ===== concrete_configs =====
    class concrete_configs_TxAllowListConfig
    class concrete_configs_FeeManagerConfig {
        +InitialFeeConfig : *commontype.FeeConfig
    }
    class concrete_configs_NativeMinterConfig {
        +InitialMint : map[common.Address]*math.HexOrDecimal256
    }
    class concrete_configs_RewardManagerConfig {
        +InitialRewardConfig : *InitialRewardConfig
    }
    class concrete_configs_WarpConfig {
        +QuorumNumerator : uint64
    }

    %% ===== Relationships =====
    precompileconfig_Config <|-- concrete_configs_TxAllowListConfig
    concrete_configs_TxAllowListConfig *-- precompileconfig_Upgrade
    concrete_configs_TxAllowListConfig *-- allowlist_AllowListConfig

    precompileconfig_Config <|-- concrete_configs_FeeManagerConfig
    concrete_configs_FeeManagerConfig *-- precompileconfig_Upgrade
    concrete_configs_FeeManagerConfig *-- allowlist_AllowListConfig

    precompileconfig_Config <|-- concrete_configs_NativeMinterConfig
    concrete_configs_NativeMinterConfig *-- precompileconfig_Upgrade
    concrete_configs_NativeMinterConfig *-- allowlist_AllowListConfig

    precompileconfig_Config <|-- concrete_configs_RewardManagerConfig
    concrete_configs_RewardManagerConfig *-- precompileconfig_Upgrade
    concrete_configs_RewardManagerConfig *-- allowlist_AllowListConfig

    precompileconfig_Config <|-- concrete_configs_WarpConfig
    concrete_configs_WarpConfig *-- precompileconfig_Upgrade

```

#### `precompileconfig.Config`

全てのプリコンパイル設定構造体が実装しなければならないインターフェースです。
EVMが様々な種類のプリコンパイル設定を統一的に扱うためのルールを定義します。
- `Key()`
    `genesis.json`内のJSONオブジェクトを、どのプリコンパイルの設定か識別するための文字列キーを返します。
- `Timestamp()`
    プリコンパイルが有効化されるブロックのタイムスタンプを返します。
- `Verify()`
    設定値が論理的に正しいか（例: アドレスの重複がないか、数値が範囲内か）を検証します。
    EVM起動時に呼び出され、失敗するとノードは起動しません。

#### `precompileconfig.Upgrade`

プリコンパイルの有効化・無効化のタイミングを定義する再利用可能な構造体です。
`BlockTimestamp`フィールドと`Disable`フラグを持ちます。
ほとんどの`Config`実装は、この構造体を自身のフィールドとして埋め込み（Composition `*--`）、アップグレード機能を取り込みます。

#### `allowlist.AllowListConfig`

`AllowList`機能を持つプリコンパイルが、初期メンバー（`AdminAddresses`, `ManagerAddresses`など）を定義するために利用する、再利用可能な設定構造体です。

#### `concrete_configs`内の各Config

各プリコンパイル（`TxAllowList`, `FeeManager`など）に特化した設定構造体です。
これらは全て`precompileconfig.Config`インターフェースを実装（Inheritance `<|--`）します。
図が示すように、多くは`precompileconfig.Upgrade`と`allowlist.AllowListConfig`を埋め込むことで、これらの共通設定機能を使用しています。
それに加え、`FeeManagerConfig`が`InitialFeeConfig`を持つように、各プリコンパイルは自身に固有の初期設定項目をフィールドとして追加で持ちます。

### 実行アーキテクチャ

この図は、EVMからの呼び出しに応じて、各プリコンパイルがどのように実行されるかを示しています。

```mermaid
classDiagram
    direction TB

    %% ===== contract =====
    class contract_StatefulPrecompiledContract {
        <<Interface>>
        +Run(state, caller, addr, input, gas, readOnly) : any
    }

    %% ===== modules =====
    class modules_Module {
        +ConfigKey : string
        +Address : common.Address
        +Contract : contract_StatefulPrecompiledContract
        +Configurator : Configurator
    }
    class modules_Registerer {
        +RegisterModule(m : modules_Module) : void
    }

    %% ===== concrete_precompiles =====
    class concrete_precompiles_AllowListPrecompile {
        +Run(...) : any
        #createAllowListRoleSetter(...) : any
        #createReadAllowList(...) : any
    }
    class concrete_precompiles_TxAllowListPrecompile
    class concrete_precompiles_FeeManagerPrecompile {
        +Run(...) : any
        #setFeeConfig(...) : void
        #getFeeConfig(...) : any
    }
    class concrete_precompiles_NativeMinterPrecompile {
        +Run(...) : any
        #mintNativeCoin(...) : any
    }
    class concrete_precompiles_RewardManagerPrecompile {
        +Run(...) : any
        #setRewardAddress(...) : void
        #allowFeeRecipients() : any
    }
    class concrete_precompiles_WarpPrecompile {
        +Run(...) : any
        #sendWarpMessage(...) : any
        #getVerifiedWarpMessage(...) : any
    }

    %% ===== Relationships =====
    contract_StatefulPrecompiledContract <|-- concrete_precompiles_AllowListPrecompile
    contract_StatefulPrecompiledContract <|-- concrete_precompiles_TxAllowListPrecompile
    contract_StatefulPrecompiledContract <|-- concrete_precompiles_FeeManagerPrecompile
    contract_StatefulPrecompiledContract <|-- concrete_precompiles_NativeMinterPrecompile
    contract_StatefulPrecompiledContract <|-- concrete_precompiles_RewardManagerPrecompile
    contract_StatefulPrecompiledContract <|-- concrete_precompiles_WarpPrecompile

    concrete_precompiles_TxAllowListPrecompile ..> concrete_precompiles_AllowListPrecompile : "<< uses factory >>"

    modules_Module *-- contract_StatefulPrecompiledContract : contains
    modules_Registerer o-- modules_Module : manages

```

#### `contract.StatefulPrecompiledContract`

全てのプリコンパイルが実装するインターフェース。
EVMがプリコンパイルを呼び出すための単一のエントリーポイント`Run`メソッドを定義します。

#### `modules.Module` / `modules.Registerer`

`Module`は、個々のプリコンパイルの実行ロジック本体 (`Contract`フィールド) を含むコンテナです。
`Registerer`は、EVM起動時に全ての`Module`を一元的に登録し、アドレスと`Contract`の対応関係を管理します。

#### `concrete_precompiles`内の各Precompile

これらは全て`StatefulPrecompiledContract`インターフェースを実装するプリコンパイルの実行ロジックです。
`Run`メソッドは通常、`contract.statefulPrecompileWithFunctionSelectors`によって実装され、`calldata`の関数セレクタに応じて、`setFeeConfig`, `mintNativeCoin`などの内部実行関数（図では保護されたメソッド`#`で表現）に処理をディスパッチします。

- **`AllowListPrecompile`**
    汎用的なロールベースのアクセス制御（ホワイトリスト）機能を提供する再利用可能なプリコンパイル実装の基盤です。
    他のプリコンパイルは、このロジックを直接再利用することで、独自のアクセス制御を簡単に実装できます。

- **`TxAllowListPrecompile`**
    Subnet上でトランザクションを発行できるアドレスを管理するプリコンパイルです。
    この実装は`allowlist`が提供するファクトリ関数を呼び出すことで、`AllowListPrecompile`のロジックをそのまま再利用しています。

- **`FeeManagerPrecompile`**
    ネットワーク全体のガス料金パラメータ（**EIP1559**のベースフィーなど）を動的に変更するプリコンパイルです。
    `allowlist`パッケージが提供するヘルパー関数（例: `GetAllowListStatus`）を内部で呼び出して「**誰が料金設定を変更できるか**」というアクセス制御を行いつつ、ガス料金設定という固有のコア機能を実装しています。

- **`NativeMinterPrecompile`**
    Subnetのネイティブトークンを新たにMint（発行）する機能を持つプリコンパイルです。
    `allowlist`のヘルパー関数を利用して「**誰がMintできるか**」を制御しつつ、ネイティブトークンの供給量を増やすという独自のロジックを持っています。

- **`RewardManagerPrecompile`**
    トランザクション手数料の分配方法（リワード）を管理するプリコンパイルです。
    `allowlist`のヘルパー関数で「**誰が報酬設定を変更できるか**」を制御しながら、手数料の分配先を特定アドレスに指定したり、バリデーターに分配したりする固有の機能を実装しています。

- **`WarpPrecompile`**
    異なるSubnet間で非同期のクロスチェーンメッセージを安全に送受信するための、Avalanche Warp Messaging (AWM) を実装したプリコンパイルです。
    その性質上、特定の管理者によるアクセス制御は不要なため`allowlist`には依存せず、BLSマルチシグネチャの検証など、独自の高度なロジックを実装しています。
