# [Precompile] nativeminter

> NativeMinterは、Avalanche Subnet-EVMに事前に組み込まれたプリコンパイルコントラクトの1つです。

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

## 概要

`NativeMinter`は、Avalanche Subnet-EVMに事前に組み込まれたプリコンパイルコントラクトの1つです。
その主な役割は、AllowList（許可リスト）によってアクセスを許可された特定のアドレスが、そのSubnetのネイティブトークン（ガス代の支払いに使われる基軸トークン）を新たにMint（発行）できるようにすることです。

このプリコンパイルは、Solidityのスマートコントラクトから直接呼び出すことができる、Go言語で実装されたEVMのコア機能です。
通常のスマートコントラクトとは異なり、ブロックチェーンの初期設定ファイルを通じて、どのアドレスがMint（発行）権限を持つか（AllowList）、そしてチェーン起動時にどのアドレスに初期量のネイティブトークンを配布するか（InitialMint）を事前に定義できます。

`ERC20NativeMinter.sol`のようなラッパーコントラクトは、この`NativeMinter`プリコンパイルの`mintNativeCoin`関数を内部的に呼び出すことで、**ERC20**トークンとネイティブトークンの交換機能を実行しています。
アクセス制御には`AllowList`の仕組みが利用されており、`Admin`, `Manager`, `Enabled`のロールを持つアドレスのみがMint（発行）操作を実行できます。

## 機能

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

- **ネイティブトークンのMint（発行）**
    権限を持つアドレスが、指定したアドレスに対してネイティブトークンをMint（発行）します。
- **アクセス制御**
    `AllowList`プリコンパイルの仕組みを利用し、`mintNativeCoin`関数を呼び出せるアドレスを制限します。
- **初期配布設定**
    ブロックチェーンの起動時に、初期設定ファイルを通じて特定のアドレスに初期量のネイティブトークンを配布します。

## フロー

- ネイティブトークンのMint（発行）フロー

### ネイティブトークンMint（発行）フロー

```mermaid
sequenceDiagram
    participant Caller as 呼び出し元 (コントラクト/EOA)
    participant NativeMinter Precompile as NativeMinterプリコンパイル
    participant StateDB as EVMステートデータベース

    Caller->>NativeMinter Precompile: mintNativeCoin(宛先アドレス, 量) を呼び出す
    activate NativeMinter Precompile
    Note right of NativeMinter Precompile: ガスコストを消費
    NativeMinter Precompile->>StateDB: 呼び出し元アドレスの権限を確認
    activate StateDB
    StateDB-->>NativeMinter Precompile: 権限情報を返す
    deactivate StateDB
    alt 権限あり (Enabled以上)
        NativeMinter Precompile->>StateDB: 宛先アドレスの残高を増やす
        activate StateDB
        StateDB-->>NativeMinter Precompile: 
        deactivate StateDB
        NativeMinter Precompile->>StateDB: NativeCoinMintedイベントのログを追加
        activate StateDB
        StateDB-->>NativeMinter Precompile: 
        deactivate StateDB
        NativeMinter Precompile-->>Caller: 成功
    else 権限なし
        NativeMinter Precompile-->>Caller: エラー (ErrCannotMint)
    end
    deactivate NativeMinter Precompile
```

## コード

https://github.com/ava-labs/subnet-evm/tree/master/precompile/contracts/nativeminter

## 設定

`config.go`は、`NativeMinter`プリコンパイルの初期設定を定義するためのGoのコードです。
ブロックチェーンを起動する時や特定のネットワークアップグレード時に、初期設定ファイル（ブロックチェーンの設計図となるファイル）からこの設定が読み込まれ、プリコンパイルの初期状態（どのアドレスが権限を持つか、誰に初期トークンを配布するかなど）が決定されます。

### `Config`

```go
type Config struct {
	allowlist.AllowListConfig
	precompileconfig.Upgrade
	InitialMint map[common.Address]*math.HexOrDecimal256 `json:"initialMint,omitempty"` // addresses to receive the initial mint mapped to the amount to mint
}
```

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

- **`allowlist.AllowListConfig`**
    Goの埋め込み機能により、`AllowList`の設定構造体が直接この`Config`構造体の一部として扱われます。
    これにより、`AdminAddresses`, `EnabledAddresses`, `ManagerAddresses`といったAllowListの権限を持つアドレスリストをこの設定内で直接定義できます。
- **`precompileconfig.Upgrade`**
    同様に、ネットワークアップグレードに関する設定が埋め込まれています。
    このプリコンパイルがいつ有効になるかを示す`BlockTimestamp`や、機能を無効化するための`Disable`フラグなどが含まれます。
- **`InitialMint`**
    ネイティブトークンの初期配布リストを定義します。
    これはマップ（キーと値のペア）であり、キーにネイティブトークンを受け取るウォレットアドレス、値に配布する量を指定します。

### `NewConfig`

```go
func NewConfig(blockTimestamp *uint64, admins []common.Address, enableds []common.Address, managers []common.Address, initialMint map[common.Address]*math.HexOrDecimal256) *Config {
	return &Config{
		AllowListConfig: allowlist.AllowListConfig{
			AdminAddresses:   admins,
			EnabledAddresses: enableds,
			ManagerAddresses: managers,
		},
		Upgrade:     precompileconfig.Upgrade{BlockTimestamp: blockTimestamp},
		InitialMint: initialMint,
	}
}
```

この関数は、`Config`構造体のインスタンスを生成し、初期化するためのコンストラクタです。
引数で受け取った設定値を、`Config`構造体の各フィールドに正確に割り当てて、完全な設定オブジェクトを構築します。

1. 関数は、`blockTimestamp`（有効化時刻）、`admins`, `enableds`, `managers`（各権限のアドレスリスト）、`initialMint`（初期配布リスト）を引数として受け取ります。
2. `Config`構造体の新しいインスタンスを生成します。
3. 引数で受け取った`admins`, `enableds`, `managers`の各リストを、`AllowListConfig`フィールド内の対応する`AdminAddresses`, `EnabledAddresses`, `ManagerAddresses`にそれぞれ設定します。
4. 引数`blockTimestamp`を、`Upgrade`フィールド内の`BlockTimestamp`に設定します。
5. 引数`initialMint`を、`InitialMint`フィールドに設定します。
6. 全てのフィールドが設定された`Config`オブジェクトへのポインタ（参照）を返します。

### `Verify`

```go
func (c *Config) Verify(chainConfig precompileconfig.ChainConfig) error {
	// ensure that all of the initial mint values in the map are non-nil positive values
	for addr, amount := range c.InitialMint {
		if amount == nil {
			return fmt.Errorf("initial mint cannot contain nil amount for address %s", addr)
		}
		bigIntAmount := (*big.Int)(amount)
		if bigIntAmount.Sign() < 1 {
			return fmt.Errorf("initial mint cannot contain invalid amount %v for address %s", bigIntAmount, addr)
		}
	}
	return c.AllowListConfig.Verify(chainConfig, c.Upgrade)
}
```

この関数は、`Config`に設定された値が、ブロックチェーンに適用する上で不正な値でないかを検証する役割を持ちます。

1. まず、`InitialMint`マップ内の全エントリ（アドレスと量のペア）を1つずつチェックするためのループを開始します。
2. **Null値のチェック**
    ループの中で、各エントリの`amount`（量）が`nil`（空）でないかを確認します。
    もし`nil`であれば、それは不正な設定なので、どのアドレスの設定が無効であるかを示すエラーメッセージを即座に返して処理を中断します。
3. **正の数のチェック**
    `amount`が`nil`でなければ、その値をGoの標準的な多倍長整数型`*big.Int`に変換します。
    その後、`.Sign()`メソッドを使って数値の符号を判定します。
    このメソッドは、数値が負なら`-1`、ゼロなら`0`、正なら`1`を返します。
    コードでは、この返り値が`1`未満（つまりゼロまたは負）であるかをチェックします。
    初期配布量がゼロやマイナスであることは無効なため、該当した場合はどのアドレスの量が不正であるかを示すエラーメッセージを返して処理を中断します。
4. **AllowList設定の検証**
    `InitialMint`に関するループが全て問題なく完了した場合、次に`AllowListConfig`に埋め込まれている`Verify`関数を呼び出します。
    これにより、`AllowListConfig`側で定義されている検証ロジック（例えば、同じアドレスが複数の権限リストに重複して登録されていないかなど）が実行されます。
5. `AllowListConfig.Verify`が返した結果（エラーがない場合は`nil`）を、この`Verify`関数の最終的な結果として返します。

## コントラクト

`contract.go`は、`NativeMinter`プリコンパイルの本体ロジックを実装しています。

### `mintNativeCoin`

```go
func mintNativeCoin(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, MintGasCost); err != nil {
		return nil, 0, err
	}

	if readOnly {
		return nil, remainingGas, vm.ErrWriteProtection
	}

	useStrictMode := !contract.IsDurangoActivated(accessibleState)
	to, amount, err := UnpackMintNativeCoinInput(input, useStrictMode)
	if err != nil {
		return nil, remainingGas, err
	}

	stateDB := accessibleState.GetStateDB()
	// Verify that the caller is in the allow list and therefore has the right to call this function.
	callerStatus := allowlist.GetAllowListStatus(stateDB, ContractAddress, caller)
	if !callerStatus.IsEnabled() {
		return nil, remainingGas, fmt.Errorf("%w: %s", ErrCannotMint, caller)
	}

	if contract.IsDurangoActivated(accessibleState) {
		if remainingGas, err = contract.DeductGas(remainingGas, NativeCoinMintedEventGasCost); err != nil {
			return nil, 0, err
		}
		topics, data, err := PackNativeCoinMintedEvent(caller, to, amount)
		if err != nil {
			return nil, remainingGas, err
		}
		stateDB.AddLog(&types.Log{
			// ... (log details)
		})
	}
	// ... (CreateAccount if not exist) ...
	amountU256, _ := uint256.FromBig(amount)
	stateDB.AddBalance(to, amountU256)
	// Return an empty output and the remaining gas
	return []byte{}, remainingGas, nil
}
```

プリコンパイルのメインの実行関数です。

1. **ガス消費**
    まず、`MintGasCost`で定義された固定のガス代を消費します。
2. **読み取り専用チェック**
    `readOnly`フラグが立っている場合（静的な呼び出しの場合）、ステートを変更できないため`vm.ErrWriteProtection`エラーを返します。
3. **入力のアンパック**
    `UnpackMintNativeCoinInput`を使い、入力データから宛先アドレス`to`と量`amount`をデコードします。
    Durangoアップグレード前は厳格な入力長チェックが行われます。
4. **権限チェック**
    `allowlist.GetAllowListStatus`を呼び出し、`caller`（この関数を呼び出したアドレス）がAllowListに登録され、`Enabled`以上の権限を持っているかを確認します。
    権限がなければ`ErrCannotMint`エラーを返します。
5. **イベント発行**
    Durangoアップグレードが有効な場合、`NativeCoinMinted`イベントを発行するためのガスを追加で消費し、イベントログを`stateDB`に追加します。
6. **残高追加**
    `stateDB.AddBalance`を呼び出し、宛先アドレス`to`のネイティブトークン残高を`amount`だけ増やします。
7. **リターン**
    処理が成功した場合、空のバイト配列と残りのガス量を返します。

### `UnpackMintNativeCoinInput`

```go
func UnpackMintNativeCoinInput(input []byte, useStrictMode bool) (common.Address, *big.Int, error) {
	// ...
	if useStrictMode && len(input) != mintInputLen {
		return common.Address{}, nil, fmt.Errorf("%w: %d", ErrInvalidLen, len(input))
	}
	inputStruct := MintNativeCoinInput{}
	err := NativeMinterABI.UnpackInputIntoInterface(&inputStruct, "mintNativeCoin", input, useStrictMode)

	return inputStruct.Addr, inputStruct.Amount, err
}
```

ABI定義に基づき、`mintNativeCoin`関数の入力バイトデータをアドレスと量の構造体（`MintNativeCoinInput`）にアンパック（デコード）します。
`useStrictMode`が`true`の場合、入力データの長さが厳密にチェックされます。
Durangoアップグレードによって余分なパディングバイトがあっても許容されるようになりました。

## イベント

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

### `NativeCoinMinted`

このイベントは`contract.abi`で以下のように定義されています。

```json
  {
    "anonymous": false,
    "inputs": [
      { "indexed": true, "name": "sender", "type": "address" },
      { "indexed": true, "name": "recipient", "type": "address" },
      { "indexed": false, "name": "amount", "type": "uint256" }
    ],
    "name": "NativeCoinMinted",
    "type": "event"
  }
```

- ネイティブトークンが`mintNativeCoin`関数によってMint（発行）された時に発行されるイベント。
    - `sender`
        Mint（発行）操作を実行したアドレス。
    - `recipient`
        ネイティブトークンを受け取ったアドレス。
    - `amount`
        Mint（発行）された量。

### `PackNativeCoinMintedEvent`

```go
func PackNativeCoinMintedEvent(sender common.Address, recipient common.Address, amount *big.Int) ([]common.Hash, []byte, error) {
	return NativeMinterABI.PackEvent("NativeCoinMinted", sender, recipient, amount)
}
```

`NativeCoinMinted`イベントを発行するために必要なデータ（トピックと非インデックスデータ）をABI仕様に従ってエンコード（パック）する関数です。

## モジュール

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

### `Module` 変数

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

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

- `ConfigKey`
    初期設定ファイル内でこのプリコンパイルの設定を識別するためのキー (`contractNativeMinterConfig`)。
- `Address`
    このプリコンパイルが配置される固定のアドレス (`0x0200...0001`)。
- `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 {
		return fmt.Errorf("expected config type %T, got %T: %v", &Config{}, cfg, cfg)
	}
	for to, amount := range config.InitialMint {
		if amount != nil {
			amountBig := (*big.Int)(amount)
			amountU256, _ := uint256.FromBig(amountBig)
			state.AddBalance(to, amountU256)
		}
	}

	return config.AllowListConfig.Configure(chainConfig, ContractAddress, state, blockContext)
}
```

EVMが初期設定設定を読み込む際に呼び出される関数。

1. 引数で渡された設定`cfg`を`*Config`型にキャストします。
2. `config.InitialMint`マップをループ処理し、指定された各アドレス`to`に対して`state.AddBalance`を呼び出し、初期のネイティブトークン残高を設定します。
3. `config.AllowListConfig.Configure`を呼び出して、AllowListの初期メンバー（Admin, Enabled, Manager）をステートデータベースに書き込みます。
