Skip to main content

foundry_cheatcodes/
monad.rs

1//! Monad staking cheatcodes.
2
3use crate::{CheatsCtxt, Result};
4use alloy_primitives::{Address, Log, U256};
5use alloy_sol_types::SolInterface;
6use evm2::precompiles::PrecompileHalt;
7use foundry_evm_core::{constants::MONAD_CHEATCODE_ADDRESS, evm::FoundryEvmNetwork};
8use monad_evm2::{
9    staking::{
10        StorageReader,
11        constants::SYSTEM_ADDRESS,
12        storage::{STAKING_ADDRESS, global_slots, validator_key, validator_offsets},
13        write::{
14            StakingStorage, handle_syscall_on_epoch_change, handle_syscall_reward,
15            handle_syscall_snapshot,
16        },
17    },
18    system::{
19        syscall_on_epoch_change_calldata, syscall_reward_calldata, syscall_snapshot_calldata,
20    },
21};
22
23alloy_sol_types::sol! {
24    /// Monad-specific cheatcodes. Accessible via `MonadVm(MONAD_CHEATCODE_ADDRESS)`.
25    interface MonadVm {
26        /// Sets the current epoch and delay period for the staking precompile.
27        function setEpoch(uint64 epoch, bool inDelayPeriod) external;
28
29        /// Sets the current block proposer validator ID.
30        function setProposer(uint64 valId) external;
31
32        /// Directly sets a validator's accumulated reward per token.
33        function setAccumulator(uint64 valId, uint256 value) external;
34
35        /// Distribute block reward via the real syscallReward handler.
36        function blockReward(address author, uint256 reward) external;
37
38        /// Execute syscallSnapshot.
39        function epochSnapshot() external;
40
41        /// Execute syscallOnEpochChange.
42        function epochChange(uint64 newEpoch) external;
43
44        /// Convenience: epochSnapshot() then epochChange(newEpoch).
45        function epochBoundary(uint64 newEpoch) external;
46    }
47}
48
49pub(crate) fn is_monad_cheatcode_call(
50    extra_cheatcode_addresses: &[Address],
51    target: Address,
52) -> bool {
53    target == MONAD_CHEATCODE_ADDRESS && extra_cheatcode_addresses.contains(&target)
54}
55
56pub(crate) fn apply_monad_cheatcode<FEN: FoundryEvmNetwork>(
57    ccx: &mut CheatsCtxt<'_, '_, FEN>,
58    input: &[u8],
59) -> Result {
60    let decoded = MonadVm::MonadVmCalls::abi_decode(input).map_err(|e| {
61        if let alloy_sol_types::Error::UnknownSelector { selector, .. } = e {
62            let msg = format!(
63                "unknown monad cheatcode with selector {selector}; \
64                 check that your MonadVm interface matches this forge version"
65            );
66            return alloy_sol_types::Error::Other(std::borrow::Cow::Owned(msg));
67        }
68        e
69    })?;
70
71    match decoded {
72        MonadVm::MonadVmCalls::setEpoch(call) => apply_set_epoch(ccx, call),
73        MonadVm::MonadVmCalls::setProposer(call) => apply_set_proposer(ccx, call),
74        MonadVm::MonadVmCalls::setAccumulator(call) => apply_set_accumulator(ccx, call),
75        MonadVm::MonadVmCalls::blockReward(call) => apply_block_reward(ccx, call),
76        MonadVm::MonadVmCalls::epochSnapshot(call) => apply_epoch_snapshot(ccx, call),
77        MonadVm::MonadVmCalls::epochChange(call) => apply_epoch_change(ccx, call),
78        MonadVm::MonadVmCalls::epochBoundary(call) => apply_epoch_boundary(ccx, call),
79    }
80}
81
82fn u64_left_aligned(v: u64) -> U256 {
83    let mut bytes = [0u8; 32];
84    bytes[0..8].copy_from_slice(&v.to_be_bytes());
85    U256::from_be_bytes(bytes)
86}
87
88fn sstore_staking<FEN: FoundryEvmNetwork>(
89    ccx: &mut CheatsCtxt<'_, '_, FEN>,
90    key: U256,
91    value: U256,
92) -> Result<()> {
93    ccx.evm
94        .state_mut()
95        .storage_slot(&STAKING_ADDRESS, key)
96        .map_err(|e| fmt_err!("staking sstore failed: {e}"))?
97        .set(value);
98    Ok(())
99}
100
101struct CheatsCtxtStorage<'a, 'b, 'db, FEN: FoundryEvmNetwork> {
102    ccx: &'a mut CheatsCtxt<'b, 'db, FEN>,
103}
104
105impl<FEN: FoundryEvmNetwork> StorageReader for CheatsCtxtStorage<'_, '_, '_, FEN> {
106    fn sload(&mut self, key: U256) -> core::result::Result<U256, PrecompileHalt> {
107        self.ccx
108            .evm
109            .state_mut()
110            .storage_slot(&STAKING_ADDRESS, key)
111            .map(|slot| slot.current())
112            .map_err(|e| PrecompileHalt::Other(format!("sload failed: {e}").into()))
113    }
114}
115
116impl<FEN: FoundryEvmNetwork> StakingStorage for CheatsCtxtStorage<'_, '_, '_, FEN> {
117    fn sstore(&mut self, key: U256, value: U256) -> core::result::Result<(), PrecompileHalt> {
118        self.ccx
119            .evm
120            .state_mut()
121            .storage_slot(&STAKING_ADDRESS, key)
122            .map(|mut slot| slot.set(value))
123            .map_err(|e| PrecompileHalt::Other(format!("sstore failed: {e}").into()))
124    }
125
126    fn transfer(
127        &mut self,
128        from: Address,
129        to: Address,
130        amount: U256,
131    ) -> core::result::Result<(), PrecompileHalt> {
132        if amount.is_zero() {
133            return Ok(());
134        }
135
136        match self.ccx.evm.state_mut().transfer(&from, &to, &amount) {
137            Ok(true) => Ok(()),
138            Ok(false) => Err(PrecompileHalt::Other("transfer failed: insufficient balance".into())),
139            Err(e) => Err(PrecompileHalt::Other(format!("transfer error: {e}").into())),
140        }
141    }
142
143    fn emit_log(&mut self, log: Log) -> core::result::Result<(), PrecompileHalt> {
144        self.ccx.evm.log(log);
145        Ok(())
146    }
147}
148
149fn apply_set_epoch<FEN: FoundryEvmNetwork>(
150    ccx: &mut CheatsCtxt<'_, '_, FEN>,
151    call: MonadVm::setEpochCall,
152) -> Result {
153    let MonadVm::setEpochCall { epoch, inDelayPeriod } = call;
154    sstore_staking(ccx, global_slots::EPOCH, u64_left_aligned(epoch))?;
155
156    let boundary_val = if inDelayPeriod {
157        let mut bytes = [0u8; 32];
158        bytes[0] = 1;
159        U256::from_be_bytes(bytes)
160    } else {
161        U256::ZERO
162    };
163    sstore_staking(ccx, global_slots::IN_BOUNDARY, boundary_val)?;
164    Ok(Default::default())
165}
166
167fn apply_set_proposer<FEN: FoundryEvmNetwork>(
168    ccx: &mut CheatsCtxt<'_, '_, FEN>,
169    call: MonadVm::setProposerCall,
170) -> Result {
171    sstore_staking(ccx, global_slots::PROPOSER_VAL_ID, u64_left_aligned(call.valId))?;
172    Ok(Default::default())
173}
174
175fn apply_set_accumulator<FEN: FoundryEvmNetwork>(
176    ccx: &mut CheatsCtxt<'_, '_, FEN>,
177    call: MonadVm::setAccumulatorCall,
178) -> Result {
179    sstore_staking(
180        ccx,
181        validator_key(call.valId, validator_offsets::ACCUMULATED_REWARD_PER_TOKEN),
182        call.value,
183    )?;
184    Ok(Default::default())
185}
186
187fn apply_block_reward<FEN: FoundryEvmNetwork>(
188    ccx: &mut CheatsCtxt<'_, '_, FEN>,
189    call: MonadVm::blockRewardCall,
190) -> Result {
191    let MonadVm::blockRewardCall { author, reward } = call;
192    let calldata = syscall_reward_calldata(author, reward);
193
194    let mut storage = CheatsCtxtStorage { ccx };
195    handle_syscall_reward(&mut storage, &calldata, u64::MAX, &SYSTEM_ADDRESS, U256::ZERO)
196        .map_err(|e| fmt_err!("blockReward failed: {e}"))?;
197
198    storage
199        .ccx
200        .evm
201        .state_mut()
202        .account(&STAKING_ADDRESS)
203        .map_err(|e| fmt_err!("blockReward balance increment failed: {e}"))?
204        .add_balance(reward);
205
206    Ok(Default::default())
207}
208
209fn apply_epoch_snapshot<FEN: FoundryEvmNetwork>(
210    ccx: &mut CheatsCtxt<'_, '_, FEN>,
211    _call: MonadVm::epochSnapshotCall,
212) -> Result {
213    let calldata = syscall_snapshot_calldata();
214    let mut storage = CheatsCtxtStorage { ccx };
215    handle_syscall_snapshot(&mut storage, &calldata, u64::MAX, &SYSTEM_ADDRESS)
216        .map_err(|e| fmt_err!("epochSnapshot failed: {e}"))?;
217    Ok(Default::default())
218}
219
220fn apply_epoch_change<FEN: FoundryEvmNetwork>(
221    ccx: &mut CheatsCtxt<'_, '_, FEN>,
222    call: MonadVm::epochChangeCall,
223) -> Result {
224    let calldata = syscall_on_epoch_change_calldata(call.newEpoch);
225    let mut storage = CheatsCtxtStorage { ccx };
226    handle_syscall_on_epoch_change(&mut storage, &calldata, u64::MAX, &SYSTEM_ADDRESS)
227        .map_err(|e| fmt_err!("epochChange failed: {e}"))?;
228    Ok(Default::default())
229}
230
231fn apply_epoch_boundary<FEN: FoundryEvmNetwork>(
232    ccx: &mut CheatsCtxt<'_, '_, FEN>,
233    call: MonadVm::epochBoundaryCall,
234) -> Result {
235    apply_epoch_snapshot(ccx, MonadVm::epochSnapshotCall {})?;
236    apply_epoch_change(ccx, MonadVm::epochChangeCall { newEpoch: call.newEpoch })?;
237    Ok(Default::default())
238}