# カスタムプリコンパイル

> Ethereum Virtual Machine (EVM) では、特定の暗号学的計算（楕円曲線暗号など）をSolidityで実装すると非効率であるため、より高速なネイティブコードで実装された関数を呼び出すための「プリコンパイル」という仕組

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

## 概要

https://build.avax.network/docs/virtual-machines/custom-precompiles

:::message
最新の情報は上記のドキュメントを参考にしてください。
:::

### Precompiled Contracts (従来のプリコンパイル)

Ethereum Virtual Machine (EVM) では、特定の暗号学的計算（楕円曲線暗号など）をSolidityで実装すると非効率であるため、より高速なネイティブコードで実装された関数を呼び出すための「**プリコンパイル**」という仕組みが用意されています。

現在Ethereumに実装されている主なプリコンパイルには、`ecrecover`, `sha256`, `blake2f`, `ripemd-160`, `Bn256Add`, `Bn256Mul`, `Bn256Pairing` などがあります。
これらのプリコンパイルは、以下のように`0x1`から始まる連番の固定アドレスにハードコードで割り当てられています。

```go
// PrecompiledContractsBerlin contains the default set of pre-compiled Ethereum
// contracts used in the Berlin release.
var PrecompiledContractsBerlin = map[common.Address]PrecompiledContract{
	common.BytesToAddress([]byte{1}): &ecrecover{},
	common.BytesToAddress([]byte{2}): &sha256hash{},
	common.BytesToAddress([]byte{3}): &ripemd160hash{},
	common.BytesToAddress([]byte{4}): &dataCopy{},
	common.BytesToAddress([]byte{5}): &bigModExp{eip2565: true},
	common.BytesToAddress([]byte{6}): &bn256AddIstanbul{},
	common.BytesToAddress([]byte{7}): &bn256ScalarMulIstanbul{},
	common.BytesToAddress([]byte{8}): &bn256PairingIstanbul{},
	common.BytesToAddress([]byte{9}): &blake2F{},
}
```

これらのプリコンパイルは、Go言語で以下の`PrecompiledContract`インターフェースを実装します。

```go
// PrecompiledContract is the basic interface for native Go contracts. The implementation
// requires a deterministic gas count based on the input size of the Run method of the
// contract.
type PrecompiledContract interface {
	RequiredGas(input []byte) uint64  // RequiredPrice calculates the contract gas use
	Run(input []byte) ([]byte, error) // Run runs the precompiled contract
}
```

- **`RequiredGas`**
    実行に必要なガス量を、入力データのサイズに基づいて決定論的に計算します。
- **`Run`**
    実際の処理を実行し、結果をバイト配列として返します。

`sha256`ハッシュ計算プリコンパイルの実装例は以下の通りです。
入力データ(`input`)を受け取り、ハッシュ計算を行って結果を返すだけのシンプルな構造です。

```go
type sha256hash struct{}

func (c *sha256hash) RequiredGas(input []byte) uint64 {
	return uint64(len(input)+31)/32*params.Sha256PerWordGas + params.Sha256BaseGas
}

func (c *sha256hash) Run(input []byte) ([]byte, error) {
	h := sha256.Sum256(input)
	return h[:], nil
}
```

これらの従来のプリコンパイルはステートレスであり、EVMのステート（ストレージや残高など）には一切アクセスできません。
入力データに基づいて計算を行い、結果を返すことのみが可能です。

### Stateful Precompiled Contracts (ステートフルプリコンパイル)

Subnet-EVMやCorethといったAvalancheのEVM実装では、従来のプリコンパイルを拡張したステートフルプリコンパイルという独自の機能が導入されています。
これは、プリコンパイルがEVMのステートへのアクセスを可能にするものです。

ステートフルプリコンパイルは、以下の拡張されたインターフェースを実装します。

```go
// StatefulPrecompiledContract is the interface for executing a precompiled contract
type StatefulPrecompiledContract interface {
	// Run executes the precompiled contract.
	Run(accessibleState PrecompileAccessibleState,
	caller common.Address,
	addr  common.Address,
	input []byte,
	suppliedGas uint64,
	readOnly bool)
	(ret []byte, remainingGas uint64, err error)
}
```

`Run`メソッドの引数に`accessibleState`が追加されている点が重要です。
この`PrecompileAccessibleState`インターフェースを通じて、プリコンパイルはEVMのステートDBにアクセスし、ストレージの読み書き、アカウント残高の変更、イベントログの発行といった、通常のスマートコントラクトと同等以上の操作が可能になります。
これにより、EVMのカスタマイズ性が飛躍的に向上し、より高度なネイティブ機能を実装できます。

### AllowList

`AllowList`は、ステートフルプリコンパイルにアクセス制御（パーミッション）機能を簡単に追加するための、再利用可能なヘルパーコンポーネントです。
`AllowList`自体はプリコンパイルではありませんが、他のプリコンパイルがこの仕組みを利用することで、特定の操作を実行できるアドレスをホワイトリスト形式で管理できます。

`AllowList`は、スマートコントラクトから利用するための`IAllowList`というSolidityインターフェースを提供します。

```solidity
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IAllowList {
  event RoleSet(
    uint256 indexed role,
    address indexed account,
    address indexed sender,
    uint256 oldRole
  );

  // Set [addr] to have the admin role over the precompile contract.
  function setAdmin(address addr) external;

  // Set [addr] to be enabled on the precompile contract.
  function setEnabled(address addr) external;

  // Set [addr] to have the manager role over the precompile contract.
  function setManager(address addr) external;

  // Set [addr] to have no role for the precompile contract.
  function setNone(address addr) external;

  // Read the status of [addr].
  function readAllowList(address addr) external view returns (uint256 role);
}
```

このインターフェースを通じて、スマートコントラクトから特定のアドレスに`Admin`（管理者）、`Manager`（中間管理者）、`Enabled`（実行者）といったロール（権限）を付与したり、剥奪したり、現在のロールを照会できます。
プリコンパイルは、自身の実行ロジックの中で呼び出し元アドレスのロールを確認し、操作を許可するかどうかを判断します。

## ステートフルプリコンパイルの生成

ステートフルプリコンパイルをゼロから構築するプロセスは、まずGo言語のテンプレートコードを自動生成することから始まります。

### Step 1: Solidityインターフェースの作成

プリコンパイル開発の最初のステップは、その機能がスマートコントラクトからどのように見えるかをSolidityの`interface`として定義することです。
ここでは例として、`HelloWorld`というシンプルなプリコンパイルを作成します。

このインターフェースは、ステートに保存された文字列を取得する`sayHello()`（`view`関数）と、その文字列を設定する`setGreeting()`（ステート変更関数）を持ちます。
さらに、アクセス制御機能を追加するために`IAllowList`インターフェースを継承します。

**Subnet-EVMでの実装**

Subnet-EVMのリポジトリ内で作業する場合、`./contracts/contracts/interfaces/`に`IHelloWorld.sol`というファイルを作成し、以下のコードを記述します。

```solidity title="contracts/contracts/interfaces/IHelloWorld.sol"
// (c) 2022-2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.

// SPDX-License-Identifier: MIT

pragma solidity >=0.8.0;
import "./IAllowList.sol";

interface IHelloWorld is IAllowList {
  event GreetingChanged(
    address indexed sender,
    string oldGreeting,
    string newGreeting
  );

  // sayHello returns the stored greeting string
  function sayHello() external view returns (string calldata result);

  // setGreeting  stores the greeting string
  function setGreeting(string calldata response) external;
}
```

**Precompile-EVMでの実装**

Precompile-EVMリポジトリで作業する場合、`IAllowList`のようなSubnet-EVMの標準インターフェースはNPMパッケージ (`@avalabs/subnet-evm-contracts`) を通じてインポートします。

```solidity
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import "@avalabs/subnet-evm-contracts/contracts/interfaces/IAllowList.sol";

interface IHelloWorld is IAllowList {
  event GreetingChanged(
    address indexed sender,
    string oldGreeting,
    string newGreeting
  );

  // sayHello returns the stored greeting string
  function sayHello() external view returns (string calldata result);

  // setGreeting stores the greeting string
  function setGreeting(string calldata response) external;
}
```

### Step 2: ABI (Application Binary Interface) の生成

次に、作成したSolidityインターフェースを、マシンが解釈可能なJSON形式に変換した「**仕様書**」であるABIを生成します。

**Subnet-EVMでのコマンド**

```bash
solc --abi ./contracts/interfaces/IHelloWorld.sol -o ./abis
```

**Precompile-EVMでのコマンド**

Precompile-EVMでは、NPMパッケージからインポートしたファイルを見つけるために追加のフラグが必要です。

```bash
solc --abi ./contracts/interfaces/IHelloWorld.sol -o ./abis --base-path . --include-path ./node_modules
```

これにより生成されるABIファイル (`contracts_interfaces_IHelloWorld_sol_IHelloWorld.abi`) には、`IHelloWorld`で定義した関数とイベントに加え、継承した`IAllowList`の関数（`setAdmin`など）とイベント（`RoleSet`）も含まれていることがわかります。

```json
[
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "address",
        "name": "sender",
        "type": "address"
      },
      // ... (GreetingChanged event fields)
    ],
    "name": "GreetingChanged",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "uint256",
        "name": "role",
        "type": "uint256"
      },
      // ... (RoleSet event fields)
    ],
    "name": "RoleSet",
    "type": "event"
  },
  {
    "inputs": [
      { "internalType": "address", "name": "addr", "type": "address" }
    ],
    "name": "readAllowList",
    // ...
  },
  {
    "inputs": [],
    "name": "sayHello",
    "outputs": [
      { "internalType": "string", "name": "result", "type": "string" }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      { "internalType": "address", "name": "addr", "type": "address" }
    ],
    "name": "setAdmin",
    // ...
  },
  {
    "inputs": [
      { "internalType": "string", "name": "response", "type": "string" }
    ],
    "name": "setGreeting",
    // ...
  }
  // ... (other IAllowList functions)
]
```

テンプレート生成ツールが正しく動作するためには、ABI内の全ての関数の戻り値に名前が付いている必要があります（例: `string calldata result`）。

### Step 3: Goテンプレートコードの自動生成

生成したABIを基に、Subnet-EVMが提供するコードジェネレーター`precompilegen`を使って、プリコンパイルの骨格となるGoのファイル群を自動生成します。

**ジェネレーターのヘルプ表示**

`./scripts/generate_precompile.sh --help` を実行すると、利用可能なオプションが表示されます。

- `--abi`
    入力となるABIファイルへのパス。
- `--out`
    生成されたファイルを出力するフォルダ。
- `--pkg`
    生成されるGoパッケージの名前。
- `--type`
    生成されるGoの構造体の名前。

**Subnet-EVMでの生成コマンド**

Subnet-EVMでは、プリコンパイルは`./precompile/contracts`配下に配置するのが慣例です。

```bash
./scripts/generate_precompile.sh --abi ./contracts/abis/contracts_interfaces_IHelloWorld_sol_IHelloWorld.abi --type HelloWorld --pkg helloworld
```

**Precompile-EVMでの生成コマンド**

Precompile-EVMでは、よりシンプルなディレクトリ構造が推奨されます。

```bash
./scripts/generate_precompile.sh --abi ./contracts/abis/contracts_interfaces_IHelloWorld_sol_IHelloWorld.abi --type HelloWorld --pkg helloworld --out ./helloworld
```

このコマンドを実行すると、`contract.go`, `contract.abi`, `config.go`, `module.go`, `event.go`といったGoのテンプレートファイルが指定されたディレクトリに生成されます。
これらのファイルには、開発者が具体的なロジックを追記すべき箇所が`CUSTOM CODE`というコメントで示されています。

## ステートフルプリコンパイルのロジック定義

自動生成されたテンプレートコードを基に、プリコンパイルの具体的なロジックを実装していきます。

### `module.go`での基本設定

まず、プリコンパイルのアイデンティティを定義する`module.go`ファイルから始めます。

#### `ConfigKey`の設定

`ConfigKey`は、ジェネシス（ブロックチェーンの初期設定）やアップグレード設定のJSONファイル内で、このプリコンパイルの設定ブロックを識別するための一意な文字列キーです。

```json
{
  "helloWorldConfig": {
    "blockTimestamp": 0,
		"adminAddresses": [...]
  }
}
```

この例では、`"helloWorldConfig"`が`ConfigKey`にあたります。

#### `ContractAddress`の設定

`ContractAddress`は、プリコンパイルが配置される一意で固定のEthereumアドレスです。
このアドレスへの`CALL`系オペコードは、EVMによって通常のコントラクト実行ではなく、このプリコンパイルのネイティブコード実行にルーティングされます。

アドレスの選択には衝突を避けるための規約があります。

- `0x01...`
    Coreth由来のプリコンパイル用に予約されています。
- `0x02...`
    Subnet-EVMで公式に実装されるオプションのプリコンパイル用に予約されています。
- `0x03...`
    ユーザーが独自に開発するカスタムプリコンパイルが使用するために予約されています。

したがって、新しいカスタムプリコンパイルには`0x03...`から始まるアドレスを割り当てます。

```go title="helloworld/module.go"
// ... (address range comments)
// ContractDeployerAllowListAddress = common.HexToAddress("0x0200000000000000000000000000000000000000")
// ...
// HelloWorldAddress                = common.HexToAddress("0x0300000000000000000000000000000000000000")
// ADD YOUR PRECOMPILE HERE
// {YourPrecompile}Address          = common.HexToAddress("0x03000000000000000000000000000000000000??")
```

この規約に従い、`module.go`内の`ContractAddress`変数を更新します。

```go title="helloworld/module.go"
var ContractAddress = common.HexToAddress("0x0300000000000000000000000000000000000000")
```

### `config.go`での設定構造体の定義

`config.go`ファイルは、ジェネシスやアップグレード設定ファイルから読み込む設定の構造を定義します。

```go title="precompile/helloworld/config.go"
// Config implements the precompileconfig.Config interface and
// adds specific configuration for HelloWorld.
type Config struct {
	allowlist.AllowListConfig
	precompileconfig.Upgrade
}
```

- **`Config`構造体**
    `precompileconfig.Config`インターフェースを実装します。
    - `allowlist.AllowListConfig`
        `AllowList`機能の初期メンバー（Adminなど）を設定するための構造体を埋め込んでいます。
    - `precompileconfig.Upgrade`
        プリコンパイルの有効化タイムスタンプなどを設定するための構造体を埋め込んでいます。
    - （必要であれば、ここに`InitialGreeting string`のようなカスタムフィールドを追加できます。）

- **`Verify()`**
    ジェネシス設定が正しいか（例: `AllowList`のアドレスに重複がないか）を検証する関数です。
    `HelloWorld`の例ではカスタム設定がないため、`AllowListConfig`の検証を呼び出すだけです。

    ```go title="precompile/helloworld/config.go"
    func (c *Config) Verify() error {
    	if err := c.AllowListConfig.Verify(); err != nil {
    		return err
    	}
    	// Add your own custom verify code for Config here
    	return nil
    }
    ```

- **`Equal()`**
    2つの設定を比較し、アップグレードが必要かどうかを判断するために使用されます。

    ```go title="precompile/helloworld/config.go"
    func (c *Config) Equal(s precompileconfig.Config) bool {
    	other, ok := (s).(*Config)
    	if !ok {
    		return false
    	}
    	equals := c.Upgrade.Equal(&other.Upgrade) && c.AllowListConfig.Equal(&other.AllowListConfig)
    	return equals
    }
    ```

### `module.go`での初期ステート設定

`Configure`関数は、プリコンパイルが有効化される際に一度だけ実行され、その初期状態をEVMのステートに書き込みます。

`HelloWorld`の例では、`"Hello World!"`という`defaultGreeting`をステートに保存します。

```go title="precompile/helloworld/module.go"
const defaultGreeting = "Hello World!"

func (*configurator) Configure(chainConfig contract.ChainConfig, cfg precompileconfig.Config, state contract.StateDB, _ contract.BlockContext) error {
	config, ok := cfg.(*Config)
	if !ok {
		return fmt.Errorf("incorrect config %T: %v", config, config)
	}

	// 1. Set the initial value under a specific storage key.
	StoreGreeting(state, defaultGreeting)

	// 2. Configure the initial members of the AllowList.
	return config.AllowListConfig.Configure(state, ContractAddress)
}
```

### `event.go`でのイベント定義

`event.go`ファイルでは、プリコンパイルが発行するイベントのガス代計算や、イベントデータをABIエンコードするための`Packer`関数を定義します。

`setGreeting`関数で発行する`GreetingChanged`イベントのガス代は、含まれる文字列の長さに応じて変動させる必要があります。

### `contract.go`での実行ロジック実装

`contract.go`ファイルに、プリコンパイルのコアとなる実行ロジックを実装します。

- **ヘルパー関数**
    ステートの読み書きを抽象化するヘルパー関数を定義すると便利です。

    ```go title="precompile/helloworld/contract.go"
    var (
    	storageKeyHash = common.BytesToHash([]byte("storageKey"))
    )

    func GetGreeting(stateDB contract.StateDB) string {
    	value := stateDB.GetState(ContractAddress, storageKeyHash)
    	return string(common.TrimLeftZeroes(value.Bytes()))
    }

    func StoreGreeting(stateDB contract.StateDB, input string) {
    	inputPadded := common.LeftPadBytes([]byte(input), common.HashLength)
    	inputHash := common.BytesToHash(inputPadded)
    	stateDB.SetState(ContractAddress, storageKeyHash, inputHash)
    }
    ```

- **`sayHello()`の実装**
    ステートから値を取得し、ABIエンコードして返す`view`関数です。

    ```go title="precompile/helloworld/contract.go"
    func sayHello(accessibleState contract.AccessibleState, ... ) (ret []byte, remainingGas uint64, err error) {
    	if remainingGas, err = contract.DeductGas(suppliedGas, SayHelloGasCost); err != nil {
    		return nil, 0, err
    	}
    	currentState := accessibleState.GetStateDB()
    	value := GetGreeting(currentState)
    	packedOutput, err := PackSayHelloOutput(value)
    	if err != nil {
    		return nil, remainingGas, err
    	}
    	return packedOutput, remainingGas, nil
    }
    ```

- **`setGreeting()`の実装**
    ステートを変更する関数です。

    ```go title="precompile/helloworld/contract.go"
    func setGreeting(accessibleState contract.AccessibleState, caller common.Address, ... ) (ret []byte, remainingGas uint64, err error) {
    	// 1. Gasの消費とreadOnlyモードのチェック
    	if remainingGas, err = contract.DeductGas(suppliedGas, SetGreetingGasCost); err != nil { /* ... */ }
    	if readOnly { /* ... */ }

    	// 2. 入力データをABIデコード
    	inputStruct, err := UnpackSetGreetingInput(input, useStrictMode)
    	if err != nil { /* ... */ }

    	// 3. AllowListによる権限チェック
    	stateDB := accessibleState.GetStateDB()
    	callerStatus := allowlist.GetAllowListStatus(stateDB, ContractAddress, caller)
    	if !callerStatus.IsEnabled() {
    		return nil, remainingGas, fmt.Errorf("%w: %s", ErrCannotSetGreeting, caller)
    	}

    	// 4. イベント発行の準備（古い値の読み出しとガス消費）
    	if remainingGas, err = contract.DeductGas(remainingGas, contract.ReadGasCostPerSlot); err != nil { /* ... */ }
    	oldGreeting := GetGreeting(stateDB)

    	// 5. イベントデータとトピックをABIエンコードし、ガスを消費
    	topics, data, err := PackGreetingChangedEvent(caller, eventData)
    	if err != nil { /* ... */ }
    	eventGasCost := GetGreetingChangedEventGasCost(eventData)
    	if remainingGas, err = contract.DeductGas(remainingGas, eventGasCost); err != nil { /* ... */ }

    	// 6. イベントをログに追加
    	stateDB.AddLog(&types.Log{ /* ... */ })

    	// 7. ステートに新しい値を書き込み
    	StoreGreeting(stateDB, inputStruct)

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

- **ガス代の設定**
    `contract.go`の先頭で、各関数のガス代を定義します。

    ```go title="precompile/helloworld/contract.go"
    // Before
    SayHelloGasCost    uint64 = 0                                  // SET A GAS COST HERE
    SetGreetingGasCost uint64 = 0 + allowlist.ReadAllowListGasCost // SET A GAS COST HERE

    // After
    SayHelloGasCost    uint64 = contract.ReadGasCostPerSlot
    SetGreetingGasCost uint64 = contract.WriteGasCostPerSlot + allowlist.ReadAllowListGasCost
    ```

### プリコンパイルの登録

最後に、作成したプリコンパイルのパッケージをEVMに認識させるため、`import`文を追加します。

- **Subnet-EVMの場合**
    `precompile/registry/registry.go`に追記します。
    ```go title="precompile/registry/registry.go"
    import (
    	// ...
    	_ "github.com/ava-labs/subnet-evm/precompile/contracts/helloworld"
    	// ADD YOUR PRECOMPILE HERE
    )
    ```

- **Precompile-EVMの場合**
    `plugin/main.go`に追記します。
    ```go title="plugin/main.go"
    import (
    	// ...
    	_ "github.com/ava-labs/precompile-evm/helloworld"
    	// ADD YOUR PRECOMPILE HERE
    )
    ```
    Goの`init()`機能により、パッケージがインポートされるだけで、`module.go`内の登録処理が自動的に実行されます。

## ステートフルプリコンパイルのテストケース作成

作成したステートフルプリコンパイルが意図通りに動作することを保証するためには、多層的なテストが不可欠です。
ここでは、Go言語でのユニットテストから、Solidityコントラクト、Hardhatを利用したE2Eテストまで、段階的なテスト手法を解説します。

### Go言語でのユニットテスト

プリコンパイルのコアロジックはGoで実装されているため、Goの標準的なテストフレームワークを用いたユニットテストが最も基本的な検証手段となります。

#### `config_test.go`での設定テスト

`config.go`で定義した`Config`構造体の検証ロジック（`Verify`）や比較ロジック（`Equal`）が正しく機能するかをテストします。

これにより、ジェネシス設定に不正な値（例: `AllowList`でのアドレス重複）が含まれている場合に、`Verify`が正しくエラーを検出することを確認します。
また、`Equal`が、同一および異なる設定を正しく識別できるかを確認します。
これは、不要なネットワークアップグレードを防ぐために重要です。

- Subnet-EVM
    `./precompile/contracts/helloworld/config_test.go`
- Precompile-EVM
    `./helloworld/config_test.go`

#### `contract_test.go`での実行ロジックテスト

`contract.go`で実装したプリコンパイルの実行ロジックをテストします。
これには、関数の正常系・異常系、ガス消費計算、`AllowList`による権限チェックなどが含まれます。
テストは、以下の`PrecompileTest`構造体を使って体系的に定義されます。

```go
// PrecompileTest is a test case for a precompile
type PrecompileTest struct {
	Caller      common.Address
	Input       []byte
	InputFn     func(t *testing.T) []byte
	SuppliedGas uint64
	ReadOnly    bool
	Config      precompileconfig.Config
	BeforeHook  func(t *testing.T, state contract.StateDB)
	AfterHook   func(t *testing.T, state contract.StateDB)
	ExpectedRes []byte
	ExpectedErr string
	BlockNumber int64
}
```

これは、以下のことを確認します。

- `sayHello()`が正しい値を返すこと、`setGreeting()`がステートを正しく更新する。
- `AllowList`が機能し、権限のないアドレスからの`setGreeting()`呼び出しが失敗する。
- ガスが不足している場合に、`ErrOutOfGas`が正しく返される。
- `readOnly`モードでステート変更関数を呼び出した場合に、`ErrWriteProtection`が返される。

`allowlist.RunPrecompileWithAllowListTests`というヘルパー関数を使うことで、`AllowList`に関する標準的なテストケース群と、独自に定義したカスタムテストケース群をまとめて実行できます。

### Solidityコントラクトによるテスト

Goでのユニットテストに加え、実際にEVM上でプリコンパイルがどのように振る舞うかを確認するために、Solidityのテストコントラクトを作成します。

#### ラッパーコントラクトの作成

まず、プリコンパイルを簡単に呼び出すためのラッパーコントラクトを作成します。
プリコンパイルの固定アドレスを、Solidityインターフェース（`IHelloWorld`）にキャストすることで、通常のスマートコントラクトのように関数を呼び出せるようになります。

```solidity:ExampleHelloWorld.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IHelloWorld.sol";

// ExampleHelloWorld shows how the HelloWorld precompile can be used in a smart contract.
contract ExampleHelloWorld {
  address constant HELLO_WORLD_ADDRESS =
    0x0300000000000000000000000000000000000000;
  IHelloWorld helloWorld = IHelloWorld(HELLO_WORLD_ADDRESS);

  function sayHello() public view returns (string memory) {
    return helloWorld.sayHello();
  }

  function setGreeting(string calldata greeting) public {
    helloWorld.setGreeting(greeting);
  }
}
```

このラッパーコントラクト（`ExampleHelloWorld`）からプリコンパイルを呼び出す場合、プリコンパイルから見ると`msg.sender`はラッパーコントラクトのアドレスになります。
`AllowList`で権限を付与する際は、このラッパーコントラクトのアドレスを`setEnabled`する必要があります。

#### テストコントラクトの作成

次に、DS-Testスタイルのテストコントラクトを作成し、具体的なテストシナリオを実装します。

```solidity:ExampleHelloWorldTest.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ExampleHelloWorld.sol";
import "../interfaces/IHelloWorld.sol";
import "./AllowListTest.sol";

contract ExampleHelloWorldTest is AllowListTest {
  IHelloWorld helloWorld = IHelloWorld(HELLO_WORLD_ADDRESS);

  function step_getDefaultHelloWorld() public {
    ExampleHelloWorld example = new ExampleHelloWorld();
    // ...
    assertEq(example.sayHello(), "Hello World!");
  }

  function step_doesNotSetGreetingBeforeEnabled() public {
    ExampleHelloWorld example = new ExampleHelloWorld();
    // ...
    try example.setGreeting("testing") {
      assertTrue(false, "setGreeting should fail");
    } catch {}
  }

  function step_setAndGetGreeting() public {
    ExampleHelloWorld example = new ExampleHelloWorld();
    address exampleAddress = address(example);
    // ...
    helloWorld.setEnabled(exampleAddress);
    // ...
    example.setGreeting("testgreeting");
    assertEq(example.sayHello(), "testgreeting");
  }
}
```

- **`step_getDefaultHelloWorld`**
    デプロイ直後に`sayHello`を呼び出し、ジェネシスで設定されたデフォルト値が返されることを確認します。
- **`step_doesNotSetGreetingBeforeEnabled`**
    `AllowList`で有効化する前に`setGreeting`を呼び出し、トランザクションが正しく失敗することを確認します。
- **`step_setAndGetGreeting`**
    ラッパーコントラクトのアドレスを`setEnabled`した後、`setGreeting`で値を更新し、`sayHello`で更新後の値が取得できることを確認します。

### HardhatによるE2Eテスト (DS-Test)

最後に、作成したSolidityテストコントラクトを、HardhatとTypeScript/JavaScriptを使ってエンドツーエンドで実行します。
これにより、ローカルのSubnet-EVMネットワーク上で、実際のトランザクションとしてテストを実行できます。

```typescript
// ...
import { expect } from "chai";
import { ethers } from "hardhat";
import { test } from "./utils"; // Subnet-EVMのテストユーティリティ

const ADMIN_ADDRESS = "0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC";
const HELLO_WORLD_ADDRESS = "0x0300000000000000000000000000000000000000";

describe("ExampleHelloWorldTest", function () {
  // ...
  beforeEach("Setup DS-Test contract", async function () {
    const signer = await ethers.getSigner(ADMIN_ADDRESS);
    // ... (テストコントラクトのデプロイ)
    // テストコントラクト自体をAdminに設定し、テスト内の権限操作を許可
    await helloWorld.setAdmin(this.testContract.address);
  });

  // Solidityテストコントラクト内の関数を呼び出す
  test("should gets default hello world", ["step_getDefaultHelloWorld"]);
  test("should not set greeting before enabled", "step_doesNotSetGreetingBeforeEnabled");
  test("should set and get greeting with enabled account", "step_setAndGetGreeting");
});

describe("IHelloWorld events", function () {
  // ...
  it("should emit GreetingChanged event", async function () {
    let newGreeting = "helloprecompile";
    // イベントが正しい引数で発行されることを検証
    await expect(contract.setGreeting(newGreeting))
      .to.emit(contract, "GreetingChanged")
      .withArgs(
        owner.address,
        defaultGreeting,
        newGreeting
      );
  });
});
```

このスクリプトは、テストを実行する前に、`beforeEach`フックでテストコントラクト（`ExampleHelloWorldTest`）をデプロイし、そのアドレスをプリコンパイルの`Admin`として設定します。
これにより、テストコントラクトは自身のテストシナリオの中で`setEnabled`などの権限設定操作を行えるようになります。

また、`events`のテストでは、`setGreeting`を直接呼び出し、期待される`GreetingChanged`イベントが、期待される引数と共に正しく発行されたかを検証します。




はい、承知いたしました。ご提供いただいたドキュメントの「Executing Test Cases」セクションについて、コードを含めながら、各ステップを詳しく解説します。

---

### ステートフルプリコンパイルのテスト実行

前のセクションで作成した各テストケースを実行するための具体的な手順を解説します。E2E（エンドツーエンド）テストを実行するには、作成したプリコンパイルを有効化した状態で、実際にローカルなAvalancheネットワークを起動する必要があります。

#### Step 1: ジェネシスファイルの作成

E2Eテスト用のカスタムブロックチェーンを起動するため、その初期状態を定義する**ジェネシスファイル**を作成します。このファイルは、プリコンパイルを有効化し、その初期設定を行う役割を持ちます。

`/tests/precompile/genesis/`ディレクトリに、Hardhatのテストファイル名と同じ名前で（この例では`hello_world.json`）、以下の内容のファイルを作成します。

```json title="/tests/precompile/genesis/hello_world.json"
{
  "config": {
    "chainId": 99999,
    "homesteadBlock": 0,
    // ... (standard EVM config fields)
    "feeConfig": {
      // ... (gas fee parameters)
    },
    "helloWorldConfig": {
      "blockTimestamp": 0,
      "adminAddresses": ["0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC"]
    }
  },
  "alloc": {
    "8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC": {
      "balance": "0x52B7D2DCC80CD2E4000000"
    },
    // ...
  },
  // ... (other genesis fields)
}
```

このジェネシスファイルで最も重要な部分は`"helloWorldConfig"`ブロックです。

```json
"helloWorldConfig": {
  "blockTimestamp": 0,
  "adminAddresses": ["0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC"]
}
```

-   `"helloWorldConfig"`: このキーは、`module.go`で設定した`ConfigKey`と一致している必要があります。
-   `"blockTimestamp": 0`: プリコンパイルがジェネシスブロック（0番目のブロック）から有効になることを示します。
-   `"adminAddresses": [...]`: `AllowList`の初期`Admin`ロールを持つアドレスを設定します。このアドレスは、後のHardhatテストで権限操作を行うために使用されます。

#### Step 2: E2Eテストスイートへの登録

次に、作成したテストをE2Eテストランナーに認識させるため、`/tests/precompile/solidity/suites.go`ファイルにテストケースを登録します。

ファイル内のコメント`// ADD YOUR PRECOMPILE HERE`に従い、Ginkgoのテストノード（`It`ブロック）を追加します。

```go title="suites.go"
ginkgo.It("hello world", ginkgo.Label("Precompile"), ginkgo.Label("HelloWorld"), func() {
  ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
  defer cancel()

  blockchainID := subnetsSuite.GetBlockchainID("hello_world")
  runDefaultHardhatTests(ctx, blockchainID, "hello_world")
})
```

-   **`ginkgo.It("hello world", ...)`**: テストケースを定義します。
-   **`ginkgo.Label("HelloWorld")`**: このテストケースを特定のラベルで分類します。後のステップで、このラベルを指定して特定のテストのみを実行できます。
-   **`runDefaultHardhatTests(ctx, blockchainID, "hello_world")`**:
    -   このヘルパー関数が、テストの実行を orchestrate します。
    -   最後の引数`"hello_world"`が、`/tests/precompile/genesis/`ディレクトリ内の`hello_world.json`と、`/contracts/test/`ディレクトリ内の`hello_world.ts`（Hardhatテストスクリプト）の両方を探すための共通のキーとして使用されます。

#### Step 3: バイナリのビルド

テストを実行する前に、AvalancheGo本体と、カスタムプリコンパイルを含むSubnet-EVMのバイナリをビルドする必要があります。

##### AvalancheGoのビルド

```bash
cd $GOPATH/src/github.com/ava-labs/avalanchego
./scripts/build.sh
```

ビルドが成功したか、バージョンを確認します。

```bash
./build/avalanchego --version
# example output
# avalanchego/1.11.0 [..., rpcchainvm=33, ...]
```

##### Subnet-EVM (またはPrecompile-EVM) のビルド

```bash
# For Subnet-EVM
cd $GOPATH/src/github.com/ava-labs/subnet-evm
./scripts/build.sh

# For Precompile-EVM
cd $GOPATH/src/github.com/ava-labs/precompile-evm
./scripts/build.sh
```

このスクリプトは、Subnet-EVMのバイナリをビルドし、AvalancheGoの`plugins`ディレクトリに配置します。AvalancheGoとSubnet-EVMの**RPCChainVMバージョンが一致していること**が、正常に動作するための必須条件です。

```bash
$GOPATH/src/github.com/ava-labs/avalanchego/build/plugins/{VM-ID} --version
# example output
# Subnet-EVM/v0.6.1 [..., rpcchainvm=33]
```

#### Step 4: E2Eテストの実行

全ての準備が整ったら、`run_ginkgo.sh`スクリプトを使ってE2Eテストを実行します。`GINKGO_LABEL_FILTER`環境変数に、Step 2で設定したラベルを指定することで、`HelloWorld`のテストのみを実行できます。

```bash
GINKGO_LABEL_FILTER=HelloWorld ./scripts/run_ginkgo.sh
```

このコマンドを実行すると、以下のプロセスが自動的に行われます。

1.  **`BeforeSuite`**: Ginkgoのテストスイートが開始され、`avalanche-network-runner`を使ってローカルにAvalancheネットワークを起動します。
    この時、`hello_world.json`ジェネシスファイルが使用され、`HelloWorld`プリコンパイルが有効化されたカスタムSubnetが作成されます。
2. **テストの実行**
    `GINKGO_LABEL_FILTER`に基づき、他のプリコンパイルのテストはスキップされ、`hello_world`のテストのみが実行されます。
3. **Hardhatの実行**
    `runDefaultHardhatTests`関数が内部で`npx hardhat test`コマンドを呼び出し、`hello_world.ts`スクリプトを実行します。
    これにより、Solidityで書かれたテストコントラクトがデプロイされ、テストシナリオが実行されます。
4. **結果の表示**
    テストの実行結果（成功、失敗、スキップ）がコンソールに出力されます。

```bash
# example output
  ExampleHelloWorldTest
    ✓ should gets default hello world (4057ms)
    ✓ should not set greeting before enabled (4067ms)
    ✓ should set and get greeting with enabled account (4074ms)

  3 passing (33s)
```

テストが成功すれば、カスタムプリコンパイルのE2E検証は完了です。

## プリコンパイルのローカルネットワークへのデプロイ

テストが完了したカスタムプリコンパイルを、実際に動作するローカルネットワークにデプロイする手順は以下の通りです。
ここでは、`HelloWorld`プリコンパイルを有効化したローカルのAvalancheネットワークを起動します。

### Step 1: Avalanche Network Runner (ANR) サーバーの起動

`avalanche-network-runner` (ANR) は、ローカルでのAvalancheネットワークの起動、管理、破棄を簡単に行うためのツールです。
まず、APIリクエストを待ち受けるためのANRサーバーを起動します。

プロジェクトのルートディレクトリ（Subnet-EVMまたはPrecompile-EVM）から、以下のコマンドを実行します。

```bash
avalanche-network-runner server \
--log-level debug \
--port=":8080" \
--grpc-gateway-port=":8081"
```

これにより、ポート`8080`でAPIコールを待ち受けるサーバーが起動します。

### Step 2: 実行バイナリのパス設定

次に、ANRが使用するAvalancheGoとSubnet-EVMの実行バイナリの場所を環境変数に設定します。
これらは前のステップでビルド済みである必要があります。

```bash
export AVALANCHEGO_EXEC_PATH="${GOPATH}/src/github.com/ava-labs/avalanchego/build/avalanchego"
export AVALANCHEGO_PLUGIN_PATH="${HOME}/.avalanchego/plugins"
```
- `AVALANCHEGO_EXEC_PATH`
    AvalancheGoの実行バイナリへのパス。
- `AVALANCHEGO_PLUGIN_PATH`
    Subnet-EVMのようなVMプラグインが格納されているディレクトリへのパス。

### Step 3: カスタムネットワークの起動

別のターミナルから、ANRサーバーにリクエストを送り、カスタムプリコンパイルを有効化した5ノード構成のローカルネットワークを起動します。

```bash
  avalanche-network-runner control start \
  --log-level debug \
  --endpoint="0.0.0.0:8080" \
  --number-of-nodes=5 \
  --avalanchego-path ${AVALANCHEGO_EXEC_PATH} \
  --plugin-dir ${AVALANCHEGO_PLUGIN_PATH} \
  --blockchain-specs '[{"vm_name": "subnetevm", "genesis": "./tests/precompile/genesis/hello_world.json"}]'
```

このコマンドの`--blockchain-specs`フラグが最も重要です。
- `"vm_name": "subnetevm"`
    Subnet-EVMを仮想マシンとして使用することを指定します。
- `"genesis"
    "./tests/precompile/genesis/hello_world.json"`: 前のステップで作成したジェネシスファイルを指定します。
    これにより、`HelloWorld`プリコンパイルがジェネシスブロックから有効化された状態でブロックチェーンが起動します。

### Step 4: ネットワークの確認と対話

ネットワークが正常に起動すると、ANRサーバーを起動したターミナルに各ノードのRPCエンドポイントが表示されます。

```bash
[blockchain RPC for "srEXiWaHuhNyGwPUi444Tu47ZEDwxTWrbQiuD7FmgSAQ6X7Dy"] "http://12.0.0.1:9650/ext/bc/2jDWMrF9yKK8gZfJaaaSfACKeMasiNgHmuZip5mWxUfhKaYoEU"
[blockchain RPC for "srEXiWaHuhNyGwPUi444Tu47ZEDwxTWrbQiuD7FmgSAQ6X7Dy"] "http://127.0.0.1:9652/ext/bc/2jDWMrF9yKK8gZfJaaaSfACKeMasiNgHmuZip5mWxUfhKaYoEU"
# ... (残り3ノード分)
```

これらのURLは、作成されたカスタムSubnetのエンドポイントです。
MetaMaskや各種ツールからこのSubnetと対話するには、URLの末尾に`/rpc`を追加した、以下のようなRPC URLを使用します。

`http://127.0.0.1:9650/ext/bc/2jDWMrF9yKK8gZfJaaaSfACKeMasiNgHmuZip5mWxUfhKaYoEU/rpc`

## メンテナンス

開発したプリコンパイルを長期的に維持するためには、ベースとなるSubnet-EVMのバージョンアップに追従することが重要です。

- **Subnet-EVMをフォークした場合**
    公式の`subnet-evm`リポジトリから最新の変更を定期的に`git pull`または`git merge`する必要があります。
    ベースコードの変更によっては、コンフリクトを手動で解決する必要が生じる場合があります。

- **Precompile-EVMを使用した場合**
    より簡単な方法で更新が可能です。
    `go.mod`ファイルと`scripts/versions.sh`ファイルに記載されているSubnet-EVMのバージョン番号を更新し、依存関係を再ダウンロードするだけで、最新のベース機能を取り込むことができます。

    ```go title="go.mod"
    ...
    require (
    	github.com/ava-labs/subnet-evm v0.6.1 // <-- このバージョン番号を更新
    	...
    )
    ...
    ```
