forked from foundry-rs/foundry
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.rs
347 lines (303 loc) · 11.6 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
mod build;
use build::BuildOutput;
mod runner;
use runner::Runner;
mod broadcast;
use ui::{TUIExitReason, Tui, Ui};
mod cmd;
mod executor;
mod receipts;
use crate::{cmd::forge::build::BuildArgs, opts::MultiWallet};
use clap::{Parser, ValueHint};
use ethers::{
abi::{Abi, Function},
prelude::{artifacts::ContractBytecodeSome, ArtifactId, Bytes, Project},
types::{transaction::eip2718::TypedTransaction, Address, Log, TransactionRequest, U256},
};
use forge::{
debug::DebugArena,
decode::decode_console_logs,
executor::opts::EvmOpts,
trace::{
identifier::{EtherscanIdentifier, LocalTraceIdentifier},
CallTraceArena, CallTraceDecoder, CallTraceDecoderBuilder, TraceKind,
},
};
use foundry_common::evm::EvmArgs;
use foundry_config::Config;
use foundry_utils::{encode_args, format_token, IntoFunction};
use std::{
collections::{BTreeMap, VecDeque},
path::PathBuf,
time::Duration,
};
use yansi::Paint;
// Loads project's figment and merges the build cli arguments into it
foundry_config::impl_figment_convert!(ScriptArgs, opts, evm_opts);
#[derive(Debug, Clone, Parser)]
pub struct ScriptArgs {
/// The contract you want to run. Either the file path or contract name.
///
/// If multiple contracts exist in the same file you must specify the target contract with
/// --target-contract.
#[clap(value_hint = ValueHint::FilePath, value_name = "PATH")]
pub path: String,
/// Arguments to pass to the script function.
#[clap(value_name = "ARGS")]
pub args: Vec<String>,
/// The name of the contract you want to run.
#[clap(long, visible_alias = "tc", value_name = "CONTRACT_NAME")]
pub target_contract: Option<String>,
/// The signature of the function you want to call in the contract, or raw calldata.
#[clap(long, short, default_value = "run()", value_name = "SIGNATURE")]
pub sig: String,
#[clap(
long,
help = "Use legacy transactions instead of EIP1559 ones. this is auto-enabled for common networks without EIP1559."
)]
pub legacy: bool,
#[clap(long, help = "Broadcasts the transactions.")]
pub broadcast: bool,
#[clap(flatten, next_help_heading = "BUILD OPTIONS")]
pub opts: BuildArgs,
#[clap(flatten)]
pub wallets: MultiWallet,
#[clap(flatten, next_help_heading = "EVM OPTIONS")]
pub evm_opts: EvmArgs,
/// Resumes submitting transactions that failed or timed-out previously.
///
/// It DOES NOT simulate the script again and it expects nonces to have remained the same.
///
/// Example: If transaction N has a nonce of 22, then the account should have a nonce of 22,
/// otherwise it fails.
#[clap(long)]
pub resume: bool,
#[clap(long, help = "Open the script in the debugger. Takes precedence over broadcast.")]
pub debug: bool,
#[clap(
long,
help = "Makes sure a transaction is sent, only after its previous one has been confirmed and succeeded."
)]
pub slow: bool,
}
pub struct ScriptResult {
pub success: bool,
pub logs: Vec<Log>,
pub traces: Vec<(TraceKind, CallTraceArena)>,
pub debug: Option<Vec<DebugArena>>,
pub gas: u64,
pub labeled_addresses: BTreeMap<Address, String>,
pub transactions: Option<VecDeque<TypedTransaction>>,
pub returned: bytes::Bytes,
}
impl ScriptArgs {
pub fn decode_traces(
&self,
script_config: &ScriptConfig,
result: &mut ScriptResult,
known_contracts: &BTreeMap<ArtifactId, (Abi, Vec<u8>)>,
) -> eyre::Result<CallTraceDecoder> {
let etherscan_identifier = EtherscanIdentifier::new(
script_config.evm_opts.get_remote_chain_id(),
script_config.config.etherscan_api_key.clone(),
Config::foundry_etherscan_chain_cache_dir(script_config.evm_opts.get_chain_id()),
Duration::from_secs(24 * 60 * 60),
);
let local_identifier = LocalTraceIdentifier::new(known_contracts);
let mut decoder =
CallTraceDecoderBuilder::new().with_labels(result.labeled_addresses.clone()).build();
for (_, trace) in &mut result.traces {
decoder.identify(trace, ðerscan_identifier);
decoder.identify(trace, &local_identifier);
}
Ok(decoder)
}
pub fn show_traces(
&self,
script_config: &ScriptConfig,
decoder: &CallTraceDecoder,
result: &mut ScriptResult,
) -> eyre::Result<()> {
let verbosity = script_config.evm_opts.verbosity;
let func = script_config.called_function.as_ref().expect("There should be a function.");
if verbosity >= 3 {
if result.traces.is_empty() {
eyre::bail!("Unexpected error: No traces despite verbosity level. Please report this as a bug: https://github.com/foundry-rs/foundry/issues/new?assignees=&labels=T-bug&template=BUG-FORM.yml");
}
if !result.success && verbosity == 3 || verbosity > 3 {
println!("Traces:");
for (kind, trace) in &mut result.traces {
let should_include = match kind {
TraceKind::Setup => (verbosity >= 5) || (verbosity == 4 && !result.success),
TraceKind::Execution => verbosity > 3 || !result.success,
_ => false,
};
if should_include {
decoder.decode(trace);
println!("{trace}");
}
}
println!();
}
}
if result.success {
println!("{}", Paint::green("Script ran successfully."));
} else {
println!("{}", Paint::red("Script failed."));
}
println!("Gas used: {}", result.gas);
if !result.returned.is_empty() {
println!("\n== Return ==");
match func.decode_output(&result.returned) {
Ok(decoded) => {
for (index, (token, output)) in decoded.iter().zip(&func.outputs).enumerate() {
let internal_type = output.internal_type.as_deref().unwrap_or("unknown");
let label = if !output.name.is_empty() {
output.name.to_string()
} else {
index.to_string()
};
println!("{}: {} {}", label.trim_end(), internal_type, format_token(token));
}
}
Err(_) => {
println!("{:x?}", (&result.returned));
}
}
}
let console_logs = decode_console_logs(&result.logs);
if !console_logs.is_empty() {
println!("\n== Logs ==");
for log in console_logs {
println!(" {}", log);
}
}
if !result.success {
eyre::bail!("{}", Paint::red("Script failed."));
}
Ok(())
}
/// It finds the deployer from the running script and uses it to predeploy libraries.
///
/// If there are multiple candidate addresses, it skips everything and lets `--sender` deploy
/// them instead.
fn maybe_new_sender(
&self,
evm_opts: &EvmOpts,
transactions: Option<&VecDeque<TypedTransaction>>,
predeploy_libraries: &[Bytes],
) -> eyre::Result<Option<Address>> {
let mut new_sender = None;
if let Some(txs) = transactions {
if !predeploy_libraries.is_empty() {
for tx in txs.iter() {
match tx {
TypedTransaction::Legacy(tx) => {
if tx.to.is_none() {
let sender = tx.from.expect("no sender");
if let Some(ns) = new_sender {
if sender != ns {
println!("You have more than one deployer who could predeploy libraries. Using `--sender` instead.");
return Ok(None)
}
} else if sender != evm_opts.sender {
new_sender = Some(sender);
}
}
}
_ => unreachable!(),
}
}
}
}
Ok(new_sender)
}
/// Helper for building the transactions for any libraries that need to be deployed ahead of
/// linking
fn create_deploy_transactions(
&self,
from: Address,
nonce: U256,
data: &[Bytes],
) -> VecDeque<TypedTransaction> {
data.iter()
.enumerate()
.map(|(i, bytes)| {
TypedTransaction::Legacy(TransactionRequest {
from: Some(from),
data: Some(bytes.clone()),
nonce: Some(nonce + i),
..Default::default()
})
})
.collect()
}
fn run_debugger(
&self,
decoder: &CallTraceDecoder,
sources: BTreeMap<u32, String>,
result: ScriptResult,
project: Project,
highlevel_known_contracts: BTreeMap<ArtifactId, ContractBytecodeSome>,
) -> eyre::Result<()> {
let source_code: BTreeMap<u32, String> = sources
.iter()
.map(|(id, path)| {
let resolved = project
.paths
.resolve_library_import(&PathBuf::from(path))
.unwrap_or_else(|| PathBuf::from(path));
(
*id,
std::fs::read_to_string(resolved).expect(&*format!(
"Something went wrong reading the source file: {:?}",
path
)),
)
})
.collect();
let calls: Vec<DebugArena> = result.debug.expect("we should have collected debug info");
let flattened = calls.last().expect("we should have collected debug info").flatten(0);
let tui = Tui::new(
flattened,
0,
decoder.contracts.clone(),
highlevel_known_contracts
.into_iter()
.map(|(id, artifact)| (id.name, artifact))
.collect(),
source_code,
)?;
match tui.start().expect("Failed to start tui") {
TUIExitReason::CharExit => Ok(()),
}
}
pub fn get_method_and_calldata(&self, abi: &Abi) -> eyre::Result<(Function, Bytes)> {
let (func, data) = match self.sig.strip_prefix("0x") {
Some(calldata) => (
abi.functions()
.find(|&func| {
func.short_signature().to_vec() == hex::decode(calldata).unwrap()[..4]
})
.expect("Function selector not found in the ABI"),
hex::decode(calldata).unwrap().into(),
),
_ => {
let func = IntoFunction::into(self.sig.clone());
(
abi.functions()
.find(|&abi_func| abi_func.short_signature() == func.short_signature())
.expect("Function signature not found in the ABI"),
encode_args(&func, &self.args)?.into(),
)
}
};
Ok((func.clone(), data))
}
}
pub struct ScriptConfig {
pub config: foundry_config::Config,
pub evm_opts: EvmOpts,
pub sender_nonce: U256,
pub called_function: Option<Function>,
}