本文へ移動
← Building with the Stack — 実アプリを作る
アプリケーションパターン

L1 を作り、運用する · 本番 — 順不同

このコースの 7 / 1145 分

レッスン6 — Foundry スタイルのカスタム cheatcode を Rust で作る

問い

vm.deal(alice, 100 ether) は EVM opcode でも Solidity contract でもない。テストがマジックアドレス 0x7109709ECfa91a80626fF3989D68f67F5b1DD12D を call すると、Foundry の Revm inspector がその call を横取りして Rust で処理する(横取りは Foundry の crates/cheatcodes/src/inspector.rs、CHEATCODE_ADDRESS 定数は crates/evm/core/src/constants.rs)。Solidity からは Vm.sol インターフェースで見える。precompile ではないが precompile(EVM エンジンに組み込まれた「コードがチェーン上にない」コントラクト)のように振る舞うので、自前版は precompile で作れる。自前 cheatcode(例: cheats.measureGas(target, data))をどう出荷するか?

原理(最小モデル)

  • precompile は executor に組み込まれ、プロトコル本体には入らない。 mainnet Revm はあなたの precompile を持たない、テストランナー Revm だけが持つ。コンセンサスを壊さず Rust のフルパワーを使える(普通の Solidity contract は EVM op しか呼べない、新 opcode はコンセンサス fork)。
  • セレクタ dispatch + ABI decode で Solidity と同じ呼び出し感。 Solidity は「アドレスへの呼び出しを ABI エンコードする方法」を既に知っているので、precompile が input[..4] をセレクタとして分岐し sol! 生成コードで型安全に decode すれば、テスト作者から見て普通の contract と区別がつかない。
  • 入れ子 EVM 実行でガスを測る。 親 journal から target アカウントをコピーした独立 DB に fresh Context を立ち上げ、ワンショット tx を走らせ、intrinsic コストを除いた実行ガスを返す。Success/Revert/Halt 全部が gas: ResultGas を持つ。
  • state に触るには precompile 関数では足りない。 素の precompile 関数(fn(&[u8], u64) -> EthPrecompileResult)は入力 bytes しか見えない。custom PrecompileProvider は &mut CTX(journal 込み)を受け取る。Foundry は inspector から journal に触る。
  • 戻り値は PrecompileOutput::new(...) か PrecompileOutput::halt(PrecompileHalt::*, ...)。 前者は結果 bytes、後者は呼び出し停止。

データ経路を 1 枚で(cheatcode の呼び出しから測定まで):

flowchart TB
    Test["Solidity test"] -->|call| Cheats["0x7110... precompile"]
    Cheats -->|nested EVM call| Inner["Revm sub-EVM<br/>target.data を実行"]
    Inner -->|gas_used| Cheats
    Cheats -->|abi-encoded uint256| Test

具体例

precompile provider とセレクタ dispatch。Revm 38 の素の precompile 関数(fn(&[u8], u64) -> EthPrecompileResult)は入力 bytes と gas limit しか見えない。一段上の PrecompileProvider は run(&mut self, context: &mut CTX, inputs: &CallInputs) で親 EVM の journal を含む context 全体を受け取る。measureGas は target のコードを読む必要があるので、CHEATS_ADDRESS だけ自分で処理し、他のアドレスは標準の EthPrecompiles に委ねる provider を書く(以下 3 つの Rust ブロックを順に src/lib.rs に置けば、そのままコンパイルが通る):

use alloy_primitives::{address, Address, Bytes, U256};
use alloy_sol_types::{sol, SolCall, SolValue};
use revm::{
    context::{Cfg, ContextTr, JournalTr},
    handler::{precompile_output_to_interpreter_result, EthPrecompiles, PrecompileProvider},
    interpreter::{CallInputs, InterpreterResult},
    primitives::hardfork::SpecId,
};
use revm_precompile::{PrecompileHalt, PrecompileOutput};

pub const CHEATS_ADDRESS: Address = address!("7110000000000000000000000000000000000000");

sol! {
    function measureGas(address target, bytes calldata data) external returns (uint256 gasUsed);
}

/// Flat gas charged to the caller for the cheatcode call itself.
const CHEATCODE_BASE_COST: u64 = 100;

/// Mainnet precompiles plus our cheatcode at `CHEATS_ADDRESS`.
#[derive(Debug, Clone)]
pub struct CheatsPrecompiles {
    inner: EthPrecompiles,
}

impl CheatsPrecompiles {
    pub fn new(spec: SpecId) -> Self {
        Self { inner: EthPrecompiles::new(spec) }
    }
}

impl<CTX: ContextTr> PrecompileProvider<CTX> for CheatsPrecompiles {
    type Output = InterpreterResult;

    fn set_spec(&mut self, spec: <CTX::Cfg as Cfg>::Spec) -> bool {
        <EthPrecompiles as PrecompileProvider<CTX>>::set_spec(&mut self.inner, spec)
    }

    fn run(
        &mut self,
        context: &mut CTX,
        inputs: &CallInputs,
    ) -> Result<Option<InterpreterResult>, String> {
        if inputs.bytecode_address != CHEATS_ADDRESS {
            // ECRECOVER, SHA256, ..., KZG: unchanged mainnet behaviour.
            return self.inner.run(context, inputs);
        }
        let input = inputs.input.as_bytes(context).to_vec();
        let output = match cheats_run(context, &input, inputs.gas_limit) {
            Ok((gas_used, bytes)) => PrecompileOutput::new(gas_used, bytes, inputs.reservoir),
            Err(halt) => PrecompileOutput::halt(halt, inputs.reservoir),
        };
        Ok(Some(precompile_output_to_interpreter_result(output, inputs.gas_limit)))
    }

    fn warm_addresses(&self) -> Box<impl Iterator<Item = Address>> {
        Box::new(self.inner.warm_addresses().chain(std::iter::once(CHEATS_ADDRESS)))
    }

    fn contains(&self, address: &Address) -> bool {
        *address == CHEATS_ADDRESS || self.inner.contains(address)
    }
}

/// Selector dispatch: same 4-byte ABI model as a Solidity contract.
fn cheats_run<CTX: ContextTr>(
    context: &mut CTX,
    input: &[u8],
    gas_limit: u64,
) -> Result<(u64, Bytes), PrecompileHalt> {
    if gas_limit < CHEATCODE_BASE_COST {
        return Err(PrecompileHalt::OutOfGas);
    }
    if input.len() < 4 {
        return Err(PrecompileHalt::other_static("cheats: missing selector"));
    }
    let (selector, calldata) = input.split_at(4);

    if selector == measureGasCall::SELECTOR {
        let call = measureGasCall::abi_decode_raw(calldata)
            .map_err(|_| PrecompileHalt::other_static("cheats: bad measureGas args"))?;

        // Read the target account (balance, nonce, code) from the *parent* EVM's journal,
        // so contracts deployed earlier in the same transaction are visible.
        let target_info = context
            .journal_mut()
            .load_account_with_code(call.target)
            .map_err(|_| PrecompileHalt::other_static("cheats: database error"))?
            .data
            .info
            .clone();

        let gas_used = run_measure_gas(call.target, target_info, call.data, gas_limit)?;
        return Ok((CHEATCODE_BASE_COST, U256::from(gas_used).abi_encode().into()));
    }

    Err(PrecompileHalt::other_static("cheats: unknown selector"))
}
  • sol! が measureGasCall を生成し、SolCall トレイト(だから import が要る)が SELECTOR([u8; 4])と abi_decode_raw(calldata) を提供する(alloy-sol-types 1.x では validate 引数は無い)。
  • 結果は PrecompileOutput::new(gas, bytes, reservoir)(flat の CHEATCODE_BASE_COST を課金)か PrecompileOutput::halt(PrecompileHalt::*, reservoir)。precompile_output_to_interpreter_result(EthPrecompiles 自身が使う helper)で InterpreterResult に変換する。

cheatcode ロジック(入れ子 EVM で測る。nested DB は target アカウントのコピーだけを持つ簡略版、本物は親 state を直接扱う):

use revm::{
    context::TxEnv,
    context_interface::{cfg::gas::calculate_initial_tx_gas, result::ExecutionResult},
    database::{CacheDB, EmptyDB},
    primitives::TxKind,
    state::AccountInfo,
    Context, ExecuteEvm, MainBuilder, MainContext,
};

fn run_measure_gas(
    target: Address,
    target_info: AccountInfo,
    data: Bytes,
    gas_limit: u64,
) -> Result<u64, PrecompileHalt> {
    // Simplification: the nested EVM gets the target's code and balance, but
    // empty storage and no other accounts. Sharing the full parent state is Drill 3.
    let mut db = CacheDB::new(EmptyDB::default());
    db.insert_account_info(target, target_info);

    let mut evm = Context::mainnet().with_db(&mut db).build_mainnet();

    // Intrinsic cost of the nested tx (21,000 + calldata), subtracted below so we
    // report only the gas spent executing `target`.
    let intrinsic = calculate_initial_tx_gas(SpecId::default(), &data, false, 0, 0, 0)
        .initial_total_gas;

    let tx = TxEnv::builder()
        .caller(Address::ZERO)
        .kind(TxKind::Call(target))
        .data(data)
        .gas_limit(gas_limit)
        .build()
        .map_err(|_| PrecompileHalt::other_static("cheats: bad nested tx"))?;

    let result = evm
        .transact_one(tx)
        .map_err(|_| PrecompileHalt::other_static("cheats: nested tx invalid"))?;

    // Success, Revert and Halt all carry a `gas: ResultGas`. Even reverted txs consumed gas.
    let spent = match &result {
        ExecutionResult::Success { gas, .. }
        | ExecutionResult::Revert { gas, .. }
        | ExecutionResult::Halt { gas, .. } => gas.total_gas_spent(),
    };
    Ok(spent.saturating_sub(intrinsic))
}
  • Revm 38 の transact_one は ExecutionResult を直接返す(.result は無い)。Success / Revert / Halt はどれも gas_used フィールドではなく gas: ResultGas を持つ。
  • total_gas_spent() は返金前の消費ガスで、入れ子 tx の intrinsic コスト(21,000 + calldata)を含む。calculate_initial_tx_gas(...).initial_total_gas を引いて、target の実行ガスだけを返す。新品の Counter.increment() で 22,396 gas。
  • nested DB の storage は空で、target 以外のアカウントも無い。

ハーネスに登録(build_mainnet() 後に provider を差し替え):

use revm::ExecuteCommitEvm;

pub fn run_test_contract(
    test_contract_bytecode: Bytes,
    test_calldata: Bytes,
) -> eyre::Result<ExecutionResult> {
    let mut db = CacheDB::new(EmptyDB::default());

    // Standard mainnet EVM, then swap in our precompile provider.
    let mut evm = Context::mainnet()
        .with_db(&mut db)
        .build_mainnet()
        .with_precompiles(CheatsPrecompiles::new(SpecId::default()));

    let deployer = Address::repeat_byte(0xAB);

    // 1. Deploy the test contract (committed, so the next tx sees it).
    let deploy_tx = TxEnv::builder()
        .caller(deployer)
        .kind(TxKind::Create)
        .data(test_contract_bytecode)
        .gas_limit(10_000_000)
        .nonce(0)
        .build()?;
    let test_addr = match evm.transact_commit(deploy_tx)? {
        ExecutionResult::Success { output, .. } => output
            .address()
            .copied()
            .ok_or_else(|| eyre::eyre!("no created address"))?,
        other => eyre::bail!("test contract deploy failed: {other:?}"),
    };

    // 2. Call the test method.
    let test_tx = TxEnv::builder()
        .caller(deployer)
        .kind(TxKind::Call(test_addr))
        .data(test_calldata)
        .gas_limit(10_000_000)
        .nonce(1)
        .build()?;
    Ok(evm.transact_commit(test_tx)?)
}
  • build_mainnet() は標準 EthPrecompiles 入りの Evm を返し、Evm::with_precompiles で任意の PrecompileProvider に差し替える。Context に with_precompiles は無く、EthPrecompiles は &'static Precompiles を持つので、集合を extend する代わりにラップしている。Reth では examples/custom-evm のように custom EvmFactory(PrecompilesMap)で同じことをする。
  • デプロイを次の tx から見えるよう transact_commit で確定し、2 本目の tx は .nonce(1)。

Solidity 側からは vm.deal と同じ呼び方:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

interface Cheats {
    function measureGas(address target, bytes calldata data) external returns (uint256);
}

contract Counter {
    uint256 public count;
    function increment() public { count++; }
}

contract CounterTest {
    Cheats constant cheats = Cheats(0x7110000000000000000000000000000000000000);

    function test_increment_gas_under_25k() public returns (uint256 gas) {
        Counter c = new Counter();
        bytes memory data = abi.encodeWithSignature("increment()");
        gas = cheats.measureGas(address(c), data);
        require(gas < 25_000, "increment too expensive");
    }
}

sol/src/CounterTest.sol に置いて sol/ で forge build(pragma に合う solc が選ばれる。今回は 0.8.35)、sol/out/CounterTest.sol/CounterTest.json の bytecode と test_increment_gas_under_25k() の calldata を run_test_contract に渡すと成功し 22,396 を返す(測定値を返すのはハーネスで表示するためだけ)。

失敗例(誤解)

「vm.deal 系の機能は普通の Solidity contract で実装できる」は誤り — Solidity contract は EVM op しか呼べず、Revm 内部(同じ world state での入れ子実行など)にアクセスできない。「新 EVM opcode を足せばいい」も誤り — opcode は 即コンセンサスを fork する(mainnet が拒否)。precompile は あなたの Revm ビルドにだけ存在し、mainnet には影響しない(~100 行で全 Rust パワー)。


ここまでで「precompile = executor 拡張、セレクタ dispatch で Solidity contract に見える」は着地した。ここから 4 ステップで組み立てる。コードは抜粋(実行時は補助コードが必要)。

🛑 予測。 なぜ precompile で実装するのか、precompile でしかできない点は?(答え: Revm 内部(fresh Context、入れ子 EVM 実行、Inspector 経由の親 state 共有)にフル Rust でアクセスできる。普通の Solidity contract は EVM op しか持たず、新 opcode はコンセンサスを fork する。mainnet 影響なしで Rust 関数を VM から呼ぶ道は、テストランナー側の precompile か inspector(Foundry 本体の方式)。このレッスンは単純な precompile を使う。)

ステップで組み立てる

Step 0: プロジェクトと依存

# Cargo.toml
[package]
name = "rust-cheatcode"
version = "0.1.0"
edition = "2021"

[dependencies]
revm                = { version = "38" }
revm-precompile     = { version = "34" }
alloy-primitives    = "1.5"
alloy-sol-types     = "1.5"
eyre                = "0.6"

[dev-dependencies]
serde_json          = "1"   # reads forge's build artifacts in the Test gate

Step 1-4

上の 4 ブロック: ① PrecompileProvider + セレクタ dispatch + ABI decode → ② cheatcode ロジック(入れ子 EVM、Success/Revert/Halt 全部の ResultGas から実行ガス、nested DB は target のコピーのみ、本物は親 state を直接扱う)→ ③ ハーネス登録(.build_mainnet().with_precompiles(CheatsPrecompiles::new(...)))→ ④ Solidity テスト(普通の interface call、forge build でコンパイルし bytecode + calldata を run_test_contract に渡す)。

production gap: Solidity コンパイル(forge が solc を呼ぶ、ユーザに事前コンパイルさせる方が普通)/ 親 state 共有(親 journal への書き戻し、Foundry は inspector から)/ 並列性(テストごと独立 DB の tokio タスク)/ 失敗レポート(stack trace、decoded revert、fuzz shrink)/ 呼び出し間 state 永続化(vm.expectRevert は次の call にだけ状態を設定、Inspector に保存)。

Step 5: 実行と differential テスト

参照実装との differential テスト(dual-use: Rust で速度、Solidity で正しさ担保)。forge test では動かない: forge の EVM にはこの provider が無く、0x7110... は空アカウントになる。テスト contract は 自前の ハーネスで走らせる。sol/src/Differential.sol に置いて sol/ で forge build:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

interface Cheats {
    function measureGas(address target, bytes calldata data) external returns (uint256);
}

contract Target {
    uint256 public acc;
    function work(uint256 n) external {
        for (uint256 i; i < n; i++) acc += i;
    }
}

contract MeasureGasDifferential {
    Cheats constant cheats = Cheats(0x7110000000000000000000000000000000000000);

    function check(uint256 input) external returns (uint256 viaCheat, uint256 referenceGas) {
        Target target = new Target();
        bytes memory data = abi.encodeCall(Target.work, (input));

        // (a) Rust cheatcode
        viaCheat = cheats.measureGas(address(target), data);

        // (b) Solidity-only reference
        uint256 before = gasleft();
        (bool ok,) = address(target).call(data);
        referenceGas = before - gasleft();
        require(ok);
    }
}

check は毎回新しい Target をデプロイするので、入れ子 EVM の空 storage と親の storage が一致する。Rust 側(tests/cheats.rs)が run_test_contract 経由で両 contract を動かす:

// tests/cheats.rs — run `forge build` in sol/ first
use alloy_primitives::{Bytes, U256};
use alloy_sol_types::{sol, SolCall};
use revm::context_interface::result::ExecutionResult;
use rust_cheatcode::run_test_contract;

sol! {
    function test_increment_gas_under_25k() returns (uint256 gas);
    function check(uint256 input) returns (uint256 viaCheat, uint256 referenceGas);
}

fn bytecode(artifact: &str) -> Bytes {
    let json: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(artifact).unwrap()).unwrap();
    json["bytecode"]["object"].as_str().unwrap().parse().unwrap()
}

fn call<C: SolCall>(artifact: &str, call: C) -> C::Return {
    match run_test_contract(bytecode(artifact), call.abi_encode().into()).unwrap() {
        ExecutionResult::Success { output, .. } => C::abi_decode_returns(output.data()).unwrap(),
        other => panic!("test call failed: {other:?}"),
    }
}

const COUNTER: &str = "sol/out/CounterTest.sol/CounterTest.json";
const DIFF: &str = "sol/out/Differential.sol/MeasureGasDifferential.json";

/// (c, r) = (cheatcode result, Solidity reference)
fn check(input: u64) -> (u64, u64) {
    let r = call(DIFF, checkCall { input: U256::from(input) });
    (r.viaCheat.to::<u64>(), r.referenceGas.to::<u64>())
}

#[test]
fn counter_increment_under_budget() {
    let gas = call(COUNTER, test_increment_gas_under_25kCall {});
    println!("measureGas(increment) = {gas}");
}

#[test]
fn matches_reference_for_known_input() {
    let (c, r) = check(42);
    println!("input=42 cheat={c} reference={r} gap={}", r - c);
    assert!(c > 0 && r > c && r - c < 1_000, "cheat={c} reference={r}");
}

#[test]
fn always_agrees_with_reference() {
    let (c0, r0) = check(0);
    let gap = r0 - c0; // the reference's own CALL overhead
    for i in 0..256u64 {
        let input = (i * 7_919) % 1_001; // 256 deterministic inputs in 0..=1000
        let (c, r) = check(input);
        assert_eq!(r - c, gap, "input={input} cheat={c} reference={r}");
    }
    println!("256 inputs, constant gap = {gap} gas");
}

2 つの値は一致しない: リファレンスは自分の CALL を発行するコスト(warm アカウントアクセス、calldata のメモリコピー、前後の GAS)も払う。このオーバーヘッドは入力に依存しないので、合格条件は 全入力でギャップが同一 であること。cargo test --test cheats -- --nocapture の出力(revm 38.0.0、solc 0.8.35):

running 3 tests
measureGas(increment) = 22396
test counter_increment_under_budget ... ok
input=42 cheat=41882 reference=42381 gap=499
test matches_reference_for_known_input ... ok
256 inputs, constant gap = 499 gas
test always_agrees_with_reference ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 2.53s

256 入力すべてで同じギャップになるまで未完了。1 件でもずれたら、その入力で cheatcode は誤計測する(ギャップの値自体は solc のバージョンや設定で変わる。重要なのは一定であること)。この gate が保証するのは入れ子 DB が再現できる範囲だけだ: 毎回新しい Target をデプロイするので空 storage が一致する。既存の storage を持つ target や他の contract を呼ぶ target は誤った state で計測される。それを直すのが Drill 3。

合格基準

  • 上記テスト(固定入力 + 256 入力)が green(参照とのギャップが全入力で同一)。
  • なぜ precompile が contract/opcode より優れているか(コンセンサス壊さず Rust フルアクセス)を 1 文で言える。
  • セレクタ dispatch + ABI decode が「Solidity 既知の呼び出し規約」とどう噛むかを即答できる。

Drill

  1. balanceOf(address) セレクタを追加(親 journal から: context.journal_mut().load_account(addr) → .data.info.balance)(15 分)。
  2. measureGas に value 引数を足し payable 化(30 分)。
  3. cheats.deal(address, uint256) で親 state を mutate(親 journal に書く: load_account_mut / balance_incr、または Foundry のように Inspector で)(3 時間)。
  4. ディレクトリの .sol を solc でコンパイル → test_ 関数を発見・実行・pass/fail 出力する最小ランナー(4 時間)。
  5. Counter increment × 1000 で自前 vs forge test のレイテンシ差を測る(1 時間)。

まとめ(3行)

  • このレッスンの cheatcode = テストランナーの executor に登録した precompile = mainnet コンセンサスに影響なし + フル Rust パワー(contract は EVM op のみ、新 opcode は fork を招く)。Foundry 本体は同じ効果を 0x7109709E... への call を inspector で横取りして得ている。
  • PrecompileProvider(.build_mainnet().with_precompiles(...) で差し替え)+ セレクタ dispatch + sol!/SolCall の ABI decode + 入れ子 EVM で実行ガス計測。Solidity からは普通の interface call にしか見えない(ABI 互換性が「騙し」を可能にする)。
  • Test gate: 256 入力で Rust cheatcode と Solidity-only gasleft() リファレンスのギャップ(リファレンス自身の CALL オーバーヘッド)が一定。次は DB 層 consistent snapshot の swap aggregator。

次のレッスン(レッスン7)

Swap Aggregator を作る(DEX state を fork して Rust で)。Revm fork で全 quote が同じ atomic state を読み、Uniswap V2 + Sushi + V3 から reserve を引いて出力を計算しベストを選ぶ。QuoterV2 differential で 5 bps まで担保。