1use crate::{Cheatcode, CheatcodesCore, CheatsCtxt, Result, Vm::*, evm::touch_account};
4use alloy_consensus::{SidecarBuilder, SimpleCoder};
5use alloy_eips::eip7702::SignedAuthorization;
6use alloy_primitives::{Address, B256, KECCAK256_EMPTY, U256};
7use alloy_rpc_types::Authorization;
8use alloy_signer::SignerSync;
9use alloy_signer_local::PrivateKeySigner;
10use alloy_sol_types::SolValue;
11use evm2::{SpecId, bytecode::Bytecode};
12use foundry_evm_core::evm::FoundryEvmNetwork;
13use foundry_wallets::{WalletSigner, wallet_multi::MultiWallet};
14use parking_lot::Mutex;
15use std::sync::Arc;
16
17impl Cheatcode for broadcast_0Call {
18 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
19 let Self {} = self;
20 broadcast(ccx, None, true)
21 }
22}
23
24impl Cheatcode for broadcast_1Call {
25 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
26 let Self { signer } = self;
27 broadcast(ccx, Some(signer), true)
28 }
29}
30
31impl Cheatcode for broadcast_2Call {
32 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
33 let Self { privateKey } = self;
34 broadcast_key(ccx, privateKey, true)
35 }
36}
37
38impl Cheatcode for attachDelegation_0Call {
39 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
40 let Self { signedDelegation } = self;
41 attach_delegation(ccx, signedDelegation, false)
42 }
43}
44
45impl Cheatcode for attachDelegation_1Call {
46 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
47 let Self { signedDelegation, crossChain } = self;
48 attach_delegation(ccx, signedDelegation, *crossChain)
49 }
50}
51
52impl Cheatcode for signDelegation_0Call {
53 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
54 let Self { implementation, privateKey } = *self;
55 sign_delegation(ccx, privateKey, implementation, None, false, false)
56 }
57}
58
59impl Cheatcode for signDelegation_1Call {
60 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
61 let Self { implementation, privateKey, nonce } = *self;
62 sign_delegation(ccx, privateKey, implementation, Some(nonce), false, false)
63 }
64}
65
66impl Cheatcode for signDelegation_2Call {
67 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
68 let Self { implementation, privateKey, crossChain } = *self;
69 sign_delegation(ccx, privateKey, implementation, None, crossChain, false)
70 }
71}
72
73impl Cheatcode for signAndAttachDelegation_0Call {
74 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
75 let Self { implementation, privateKey } = *self;
76 sign_delegation(ccx, privateKey, implementation, None, false, true)
77 }
78}
79
80impl Cheatcode for signAndAttachDelegation_1Call {
81 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
82 let Self { implementation, privateKey, nonce } = *self;
83 sign_delegation(ccx, privateKey, implementation, Some(nonce), false, true)
84 }
85}
86
87impl Cheatcode for signAndAttachDelegation_2Call {
88 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
89 let Self { implementation, privateKey, crossChain } = *self;
90 sign_delegation(ccx, privateKey, implementation, None, crossChain, true)
91 }
92}
93
94fn attach_delegation<FEN: FoundryEvmNetwork>(
96 ccx: &mut CheatsCtxt<'_, '_, FEN>,
97 delegation: &SignedDelegation,
98 cross_chain: bool,
99) -> Result {
100 let SignedDelegation { v, r, s, nonce, implementation } = delegation;
101 let chain_id = if cross_chain { U256::ZERO } else { U256::from(ccx.chain_id()) };
104
105 let auth = Authorization { address: *implementation, nonce: *nonce, chain_id };
106 let signed_auth = SignedAuthorization::new_unchecked(auth, *v, (*r).into(), (*s).into());
107 write_delegation(ccx, signed_auth.clone())?;
108 ccx.state.add_delegation(signed_auth);
109 Ok(Default::default())
110}
111
112fn sign_delegation<FEN: FoundryEvmNetwork>(
115 ccx: &mut CheatsCtxt<'_, '_, FEN>,
116 private_key: U256,
117 implementation: Address,
118 nonce: Option<u64>,
119 cross_chain: bool,
120 attach: bool,
121) -> Result<Vec<u8>> {
122 let signer = PrivateKeySigner::from_bytes(&B256::from(private_key))?;
123 let nonce = if let Some(nonce) = nonce {
124 nonce
125 } else {
126 let account_nonce = {
127 let mut account = ccx.evm.state_mut().account(&signer.address())?;
128 account.warm();
129 account.nonce()
130 };
131 next_delegation_nonce(
133 &ccx.state.active_delegations,
134 signer.address(),
135 &ccx.state.broadcast,
136 account_nonce,
137 )
138 };
139 let chain_id = if cross_chain { U256::ZERO } else { U256::from(ccx.chain_id()) };
140
141 let auth = Authorization { address: implementation, nonce, chain_id };
142 let sig = signer.sign_hash_sync(&auth.signature_hash())?;
143 if attach {
145 let signed_auth = SignedAuthorization::new_unchecked(auth, sig.v() as u8, sig.r(), sig.s());
146 write_delegation(ccx, signed_auth.clone())?;
147 ccx.state.add_delegation(signed_auth);
148 }
149 Ok(SignedDelegation {
150 v: sig.v() as u8,
151 r: sig.r().into(),
152 s: sig.s().into(),
153 nonce,
154 implementation,
155 }
156 .abi_encode())
157}
158
159fn next_delegation_nonce(
161 active_delegations: &[SignedAuthorization],
162 authority: Address,
163 broadcast: &Option<Broadcast>,
164 account_nonce: u64,
165) -> u64 {
166 match active_delegations
167 .iter()
168 .rfind(|auth| auth.recover_authority().is_ok_and(|recovered| recovered == authority))
169 {
170 Some(auth) => {
171 auth.nonce() + 1
173 }
174 None => {
175 if let Some(broadcast) = broadcast {
177 if broadcast.new_origin == authority {
179 return account_nonce + 1;
180 }
181 }
182 account_nonce
184 }
185 }
186}
187
188fn write_delegation<FEN: FoundryEvmNetwork>(
189 ccx: &mut CheatsCtxt<'_, '_, FEN>,
190 auth: SignedAuthorization,
191) -> Result<()> {
192 ensure!(
193 ccx.spec().into() >= SpecId::PRAGUE,
194 "delegations are not supported before the Prague hard fork; \
195 see EIP-7702: https://eips.ethereum.org/EIPS/eip-7702"
196 );
197 let authority = auth.recover_authority().map_err(|e| format!("{e}"))?;
198 let account_nonce = {
199 let mut account = ccx.evm.state_mut().account(&authority)?;
200 account.warm();
201 account.nonce()
202 };
203
204 let expected_nonce = next_delegation_nonce(
205 &ccx.state.active_delegations,
206 authority,
207 &ccx.state.broadcast,
208 account_nonce,
209 );
210
211 if expected_nonce != auth.nonce() {
212 return Err(format!(
213 "invalid nonce for {authority:?}: expected {expected_nonce}, got {}",
214 auth.nonce()
215 )
216 .into());
217 }
218
219 let mut account = ccx.evm.state_mut().account(&authority)?;
220 if auth.address.is_zero() {
221 account.set_code(KECCAK256_EMPTY, Bytecode::default());
224 } else {
225 account.set_code_slow(Bytecode::new_eip7702(*auth.address()));
226 }
227 Ok(())
228}
229
230impl Cheatcode for attachBlobCall {
231 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
232 let Self { blob } = self;
233 ensure!(
234 ccx.spec().into() >= SpecId::CANCUN,
235 "`attachBlob` is not supported before the Cancun hard fork; \
236 see EIP-4844: https://eips.ethereum.org/EIPS/eip-4844"
237 );
238 let sidecar: SidecarBuilder<SimpleCoder> = SidecarBuilder::from_slice(blob);
239 let sidecar_variant = if ccx.spec().into() < SpecId::OSAKA {
240 sidecar.build_4844().map_err(|e| format!("{e}"))?.into()
241 } else {
242 sidecar.build_7594().map_err(|e| format!("{e}"))?.into()
243 };
244 ccx.state.active_blob_sidecar = Some(sidecar_variant);
245 Ok(Default::default())
246 }
247}
248
249impl Cheatcode for startBroadcast_0Call {
250 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
251 let Self {} = self;
252 broadcast(ccx, None, false)
253 }
254}
255
256impl Cheatcode for startBroadcast_1Call {
257 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
258 let Self { signer } = self;
259 broadcast(ccx, Some(signer), false)
260 }
261}
262
263impl Cheatcode for startBroadcast_2Call {
264 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
265 let Self { privateKey } = self;
266 broadcast_key(ccx, privateKey, false)
267 }
268}
269
270impl Cheatcode for stopBroadcastCall {
271 fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
272 let Self {} = self;
273 let Some(broadcast) = ccx.state.broadcast.take() else {
274 bail!("no broadcast in progress to stop");
275 };
276 debug!(target: "cheatcodes", ?broadcast, "stopped");
277 Ok(Default::default())
278 }
279}
280
281impl Cheatcode for getWalletsCall {
282 fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
283 let wallets = state.wallets().signers()?;
284 Ok(wallets.abi_encode())
285 }
286}
287
288#[derive(Clone, Debug, Default)]
289pub struct Broadcast {
290 pub new_origin: Address,
292 pub original_caller: Address,
294 pub original_origin: Address,
296 pub depth: usize,
298 pub single_call: bool,
300 pub deploy_from_code: bool,
302}
303
304#[derive(Debug)]
306pub struct WalletsInner {
307 pub multi_wallet: MultiWallet,
309 pub provided_sender: Option<Address>,
311 pub sender_owner: Option<Address>,
314}
315
316#[derive(Debug, Clone)]
318pub struct Wallets {
319 pub inner: Arc<Mutex<WalletsInner>>,
321}
322
323impl Wallets {
324 #[expect(missing_docs)]
325 pub fn new(multi_wallet: MultiWallet, provided_sender: Option<Address>) -> Self {
326 Self {
327 inner: Arc::new(Mutex::new(WalletsInner {
328 multi_wallet,
329 provided_sender,
330 sender_owner: None,
331 })),
332 }
333 }
334
335 pub fn into_multi_wallet(self) -> MultiWallet {
339 Arc::into_inner(self.inner)
340 .map(|m| m.into_inner().multi_wallet)
341 .unwrap_or_else(|| panic!("not all instances were dropped"))
342 }
343
344 pub fn add_local_signer(&self, wallet: PrivateKeySigner) {
346 self.inner.lock().multi_wallet.add_signer(WalletSigner::Local(wallet));
347 }
348
349 pub fn signers(&self) -> Result<Vec<Address>> {
351 Ok(self.inner.lock().multi_wallet.signers()?.keys().copied().collect())
352 }
353
354 pub fn addresses(&self) -> Vec<Address> {
356 self.inner.lock().multi_wallet.available_addresses()
357 }
358
359 pub fn len(&self) -> usize {
361 let mut inner = self.inner.lock();
362 inner.multi_wallet.signers().map_or(0, |signers| signers.len())
363 }
364
365 pub fn is_empty(&self) -> bool {
367 self.len() == 0
368 }
369}
370
371fn broadcast<FEN: FoundryEvmNetwork>(
373 ccx: &mut CheatsCtxt<'_, '_, FEN>,
374 new_origin: Option<&Address>,
375 single_call: bool,
376) -> Result {
377 let depth = ccx.depth();
378 ensure!(
379 ccx.state.get_prank(depth).is_none(),
380 "you have an active prank; broadcasting and pranks are not compatible"
381 );
382 ensure!(ccx.state.broadcast.is_none(), "a broadcast is active already");
383
384 let mut new_origin = new_origin.copied();
385
386 if new_origin.is_none() {
387 let mut wallets = ccx.state.core.wallets().inner.lock();
388 if let Some(provided_sender) = wallets.provided_sender {
389 new_origin = Some(provided_sender);
390 } else {
391 let signers = wallets.multi_wallet.signers()?;
392 if signers.len() == 1 {
393 let address = signers.keys().next().unwrap();
394 new_origin = Some(*address);
395 }
396 }
397 }
398 let new_origin = new_origin.unwrap_or(ccx.tx_caller());
399 touch_account(ccx.evm.state_mut(), new_origin)?;
401
402 let broadcast = Broadcast {
403 new_origin,
404 original_caller: ccx.caller,
405 original_origin: ccx.tx_caller(),
406 depth,
407 single_call,
408 deploy_from_code: false,
409 };
410 debug!(target: "cheatcodes", ?broadcast, "started");
411 ccx.state.broadcast = Some(broadcast);
412 Ok(Default::default())
413}
414
415fn broadcast_key<FEN: FoundryEvmNetwork>(
419 ccx: &mut CheatsCtxt<'_, '_, FEN>,
420 private_key: &U256,
421 single_call: bool,
422) -> Result {
423 let wallet = super::crypto::parse_wallet(private_key)?;
424 let new_origin = wallet.address();
425
426 let result = broadcast(ccx, Some(&new_origin), single_call);
427 if result.is_ok() {
428 let wallets = ccx.state.core.wallets();
429 wallets.add_local_signer(wallet);
430 }
431 result
432}