# [Precompile] FeeManager

> FeeManagerは、Avalanche Subnet-EVMに組み込まれたプリコンパイルコントラクトです。

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

## 概要

`FeeManager`は、Avalanche Subnet-EVMに組み込まれたプリコンパイルコントラクトです。
このプリコンパイルは、ブロックチェーンネットワーク全体のガス料金に関連するパラメータ（**EIP1559**のベースフィー変動ロジックなど）を、権限を持つアドレスによって動的に変更する機能を提供します。

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

https://qiita.com/cardene/items/ce77124940010280717b

このプリコンパイルは、Solidityのスマートコントラクトから呼び出すことができる、Go言語で実装されたEVMのコア機能です。
ネットワークのガス料金設定という重要な操作を保護するため、AllowListの仕組みを利用しており、`Admin`や`Enabled`などのロールを持つアドレスのみが設定変更を実行できます。

ブロックチェーンの初期設定ファイルを通じて、`InitialFeeConfig`として初期のガス料金パラメータを設定できます。
また、`setFeeConfig`関数を呼び出すことで、稼働中のネットワークのパラメータを更新することも可能です。
`getFeeConfig`関数を使えば、誰でも現在のガス料金設定を照会できます。

## 機能

このプリコンパイルの主要な機能は以下の通りです。

- **ガス料金設定の変更**
    権限を持つアドレスが、ガスリミットやベースフィーの変動ロジックなどのパラメータを変更します。
- **ガス料金設定の参照**
    現在のネットワークのガス料金設定を誰でも照会できます。
- **最終変更ブロックの参照**
    ガス料金設定が最後に変更されたブロック番号を照会できます。
- **アクセス制御**
    AllowListの仕組みを利用し、設定変更操作を許可されたアドレスのみに制限します。
- **初期設定**
    ブロックチェーンの初期設定ファイルを通じて、最初のガス料金パラメータを定義します。

## フロー

- ガス料金設定の変更フロー

### ガス料金設定の変更フロー

```mermaid
sequenceDiagram
    participant Caller as 呼び出し元 (許可されたユーザー)
    participant FeeManager Precompile as FeeManagerプリコンパイル
    participant State as EVMステート

    Caller->>FeeManager Precompile: setFeeConfig(新しいFeeConfig) を呼び出す
    activate FeeManager Precompile
    Note right of FeeManager Precompile: ガスコストを消費
    FeeManager Precompile->>State: 呼び出し元アドレスの権限を確認
    activate State
    State-->>FeeManager Precompile: 権限情報を返す
    deactivate State
    alt 権限あり (Enabled以上)
        Note right of FeeManager Precompile: 新しいFeeConfigの妥当性を検証
        FeeManager Precompile->>State: 現在のFeeConfigとブロック番号をステートに書き込む
        activate State
        State-->>FeeManager Precompile: 
        deactivate State
        FeeManager Precompile->>State: FeeConfigChangedイベントのログを追加
        activate State
        State-->>FeeManager Precompile: 
        deactivate State
        FeeManager Precompile-->>Caller: 成功
    else 権限なし
        FeeManager Precompile-->>Caller: エラー (ErrCannotChangeFee)
    end
    deactivate FeeManager Precompile
```

## 設定

`config.go`は、このプリコンパイルの初期設定を定義します。
ブロックチェーン起動時に初期設定ファイルから読み込まれ、プリコンパイルの初期状態が決定されます。

### `Config`

```go
type Config struct {
	allowlist.AllowListConfig // Config for the fee config manager allow list
	precompileconfig.Upgrade
	InitialFeeConfig *commontype.FeeConfig `json:"initialFeeConfig,omitempty"` // initial fee config to be immediately activated
}
```

初期設定ファイルに記述される`FeeManager`の設定内容を格納するデータ構造です。

- **`allowlist.AllowListConfig`**
    Goの埋め込み機能により、`AllowList`の設定（`AdminAddresses`, `EnabledAddresses`など）をこの構造体内で直接定義できます。
- **`precompileconfig.Upgrade`**
    このプリコンパイルがいつ有効になるかを示す`BlockTimestamp`など、アップグレードに関する設定を埋め込みます。
- **`InitialFeeConfig`**
    ブロックチェーン起動時に適用される、初期のガス料金パラメータセットです。

### `NewConfig`

```go
func NewConfig(blockTimestamp *uint64, admins []common.Address, enableds []common.Address, managers []common.Address, initialConfig *commontype.FeeConfig) *Config {
	return &Config{
		AllowListConfig: allowlist.AllowListConfig{
			AdminAddresses:   admins,
			EnabledAddresses: enableds,
			ManagerAddresses: managers,
		},
		Upgrade:          precompileconfig.Upgrade{BlockTimestamp: blockTimestamp},
		InitialFeeConfig: initialConfig,
	}
}
```

`Config`構造体のインスタンスを生成し、初期化するコンストラクタです。
引数で受け取った有効化タイムスタンプ、各権限のアドレスリスト、初期ガス料金設定を、`Config`構造体の各フィールドに割り当て、完全な設定オブジェクトを構築します。

### `Verify`

```go
func (c *Config) Verify(chainConfig precompileconfig.ChainConfig) error {
	if err := c.AllowListConfig.Verify(chainConfig, c.Upgrade); err != nil {
		return err
	}
	if c.InitialFeeConfig == nil {
		return nil
	}

	return c.InitialFeeConfig.Verify()
}
```

設定内容が不正でないかを検証します。

1. まず、埋め込まれている`AllowListConfig`の`Verify`を呼び出し、AllowListに関連する設定（アドレスの重複など）が妥当であるかを確認します。
    エラーがあれば、そのエラーを返します。
2. `InitialFeeConfig`が設定されていない（`nil`である）場合は、それ以上の検証は不要なため、処理を正常に終了します。
3. `InitialFeeConfig`が設定されている場合、その`InitialFeeConfig`自身の`Verify`メソッドを呼び出します。
    これにより、ガス料金パラメータ間の整合性（例：`GasLimit`が0より大きいか、`MinBlockGasCost`が`MaxBlockGasCost`を超えていないかなど）がチェックされます。
    検証に失敗するとエラーが返されます。
4. すべての検証を通過した場合、エラーなし（`nil`）を返します。

## コントラクト

`contract.go`は、`FeeManager`プリコンパイルの本体ロジックを実装します。
関数の定義、入力の解析、権限チェック、ステートの変更などがここで行われます。

### `setFeeConfig`

```go
func setFeeConfig(accessibleState contract.AccessibleState, caller common.Address, addr common.Address, input []byte, suppliedGas uint64, readOnly bool) (ret []byte, remainingGas uint64, err error) {
	if remainingGas, err = contract.DeductGas(suppliedGas, SetFeeConfigGasCost); err != nil {
		// ...
	}
	// ... (readOnly check)
	useStrictMode := !contract.IsDurangoActivated(accessibleState)
	feeConfig, err := UnpackSetFeeConfigInput(input, useStrictMode)
	if err != nil {
		// ...
	}

	stateDB := accessibleState.GetStateDB()
	callerStatus := GetFeeManagerStatus(stateDB, caller)
	if !callerStatus.IsEnabled() {
		return nil, remainingGas, fmt.Errorf("%w: %s", ErrCannotChangeFee, caller)
	}

	if contract.IsDurangoActivated(accessibleState) {
		// ... (emit FeeConfigChanged event)
	}

	if err := StoreFeeConfig(stateDB, feeConfig, accessibleState.GetBlockContext()); err != nil {
		return nil, remainingGas, err
	}

	return []byte{}, remainingGas, nil
}
```

ガス料金設定を変更するメインの実行関数。

1. **ガス消費と権限確認**
    `SetFeeConfigGasCost`で定義されたガスを消費し、読み取り専用でないことを確認した後、呼び出し元`caller`がAllowListで`Enabled`以上の権限を持つかチェックします。
    権限がなければ`ErrCannotChangeFee`エラーを返します。
2. **入力のデコード**
    `UnpackSetFeeConfigInput`を使い、入力データを`FeeConfig`構造体にデコードします。
    テストコードにあるように、Durangoアップグレード後は入力データに余分なパディングがあっても許容されます。
3. **イベント発行**
    Durangoアップグレードが有効な場合、`FeeConfigChanged`イベントを発行するための処理を行います。
4. **ステートの更新**
    `StoreFeeConfig`を呼び出し、デコードした新しい`feeConfig`と現在のブロック番号をステートに保存します。
    この時、`StoreFeeConfig`内部で設定値の妥当性検証も行われ、無効な場合はエラーが返されます。

### `getFeeConfig`

```go
func getFeeConfig(accessibleState contract.AccessibleState, caller common.Address, addr common.Address, input []byte, suppliedGas uint64, readOnly bool) (ret []byte, remainingGas uint64, err error) {
	if remainingGas, err = contract.DeductGas(suppliedGas, GetFeeConfigGasCost); err != nil {
		return nil, 0, err
	}

	feeConfig := GetStoredFeeConfig(accessibleState.GetStateDB())

	output, err := PackGetFeeConfigOutput(feeConfig)
	if err != nil {
		return nil, remainingGas, err
	}

	return output, remainingGas, err
}
```

現在のガス料金設定を取得する関数。

1. **ガス消費**
    `GetFeeConfigGasCost`で定義されたガスを消費します。
2. **ステートの読み出し**
    `GetStoredFeeConfig`を使い、ステートから現在の`FeeConfig`を読み出します。
3. **出力のエンコード**
    `PackGetFeeConfigOutput`を使い、読み出した`FeeConfig`をABIエンコードされたバイトデータに変換して返します。

### `getFeeConfigLastChangedAt`

```go
func getFeeConfigLastChangedAt(accessibleState contract.AccessibleState, caller common.Address, addr common.Address, input []byte, suppliedGas uint64, readOnly bool) (ret []byte, remainingGas uint64, err error) {
	if remainingGas, err = contract.DeductGas(suppliedGas, GetLastChangedAtGasCost); err != nil {
		// ...
	}

	lastChangedAt := GetFeeConfigLastChangedAt(accessibleState.GetStateDB())
	packedOutput, err := PackGetFeeConfigLastChangedAtOutput(lastChangedAt)
	// ...

	return packedOutput, remainingGas, err
}
```

ガス料金設定が最後に変更されたブロック番号を返す関数。
処理は`getFeeConfig`とほぼ同様で、ステートから特定のキー（`feeConfigLastChangedAtKey`）の値を読み出し、ABIエンコードして返します。

### `StoreFeeConfig` と `GetStoredFeeConfig`

これらのヘルパー関数は、`FeeConfig`構造体をEVMのステートに保存したり、ステートから読み出したりする役割を担います。
`FeeConfig`の各パラメータ（`GasLimit`, `MinBaseFee`など）は、それぞれ異なるキーを持つステートのスロットに個別に保存されます。

## イベント

`event.go`は、このプリコンパイルが発行するイベントの定義と、そのデータを扱うためのヘルパー関数を実装します。

### `FeeConfigChanged`

`contract.abi`で以下のように定義されています。
```json
  {
    "anonymous": false,
    "inputs": [
      { "indexed": true, "name": "sender", "type": "address" },
      { "indexed": false, "name": "oldFeeConfig", "type": "tuple" },
      { "indexed": false, "name": "newFeeConfig", "type": "tuple" }
    ],
    "name": "FeeConfigChanged",
    "type": "event"
  }
```

- `setFeeConfig`によってガス料金設定が正常に変更された時に発行されるイベント。
    - `sender`
        設定変更を実行したアドレス。
    - `oldFeeConfig`
        変更前の`FeeConfig`。
    - `newFeeConfig`
        変更後の`FeeConfig`。

### `PackFeeConfigChangedEvent`

```go
func PackFeeConfigChangedEvent(sender common.Address, oldConfig commontype.FeeConfig, newConfig commontype.FeeConfig) ([]common.Hash, []byte, error) {
	oldConfigC := convertFromCommonConfig(oldConfig)
	newConfigC := convertFromCommonConfig(newConfig)
	return FeeManagerABI.PackEvent("FeeConfigChanged", sender, oldConfigC, newConfigC)
}
```

`FeeConfigChanged`イベントを発行するために、送信者アドレス、変更前後の`FeeConfig`をABI仕様に従ってエンコード（パック）します。
内部で`TargetBlockRate`の型（`uint64`から`*big.Int`へ）をABIと合わせるための変換処理を行っています。

## モジュール

`module.go`は、このプリコンパイルをSubnet-EVMのモジュールとして登録し、初期設定を適用します。

### `Module`

```go
var Module = modules.Module{
	ConfigKey:    ConfigKey,
	Address:      ContractAddress,
	Contract:     FeeManagerPrecompile,
	Configurator: &configurator{},
}
```

このプリコンパイルをEVMにモジュールとして登録する変数です。

- **`ConfigKey`**
    初期設定ファイル内でこのプリコンパイルの設定を識別するキー (`feeManagerConfig`)。
- **`Address`**
    このプリコンパイルが配置される固定のアドレス (`0x0200...0003`)。
- **`Contract`**
    プリコンパイルのロジック本体。
- **`Configurator`**
    初期設定を適用するインターフェース。

### `Configure`

```go
func (*configurator) Configure(chainConfig precompileconfig.ChainConfig, cfg precompileconfig.Config, state contract.StateDB, blockContext contract.ConfigurationBlockContext) error {
	config, ok := cfg.(*Config)
	if !ok {
		// ...
	}
	// Store the initial fee config into the state when the fee manager activates.
	if config.InitialFeeConfig != nil {
		if err := StoreFeeConfig(state, *config.InitialFeeConfig, blockContext); err != nil {
			// ...
		}
	} else {
		if err := StoreFeeConfig(state, chainConfig.GetFeeConfig(), blockContext); err != nil {
			// ...
		}
	}
	return config.AllowListConfig.Configure(chainConfig, ContractAddress, state, blockContext)
}
```

EVMが初期設定を読み込む時に呼び出され、プリコンパイルの初期ステートを構築します。

1. 引数で渡された設定`cfg`を、このプリコンパイル専用の`*Config`型にキャストします。
2. `config.InitialFeeConfig`が初期設定ファイルで指定されているかを確認します。
3. 指定されていれば、その`InitialFeeConfig`を`StoreFeeConfig`を使ってステートに書き込みます。
4. 指定されていない場合は、チェーン全体のデフォルト設定である`chainConfig.GetFeeConfig()`をステートに書き込みます。
5. 最後に、`config.AllowListConfig.Configure`を呼び出し、AllowListの初期メンバー（Admin, Enabledなど）をステートに書き込みます。
