-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
create.rs
692 lines (628 loc) · 23.6 KB
/
create.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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
use alloy_chains::Chain;
use alloy_dyn_abi::{DynSolValue, JsonAbiExt, Specifier};
use alloy_json_abi::{Constructor, JsonAbi};
use alloy_network::{AnyNetwork, EthereumWallet, TransactionBuilder};
use alloy_primitives::{hex, Address, Bytes};
use alloy_provider::{PendingTransactionError, Provider, ProviderBuilder};
use alloy_rpc_types::{AnyTransactionReceipt, TransactionRequest};
use alloy_serde::WithOtherFields;
use alloy_signer::Signer;
use alloy_transport::{Transport, TransportError};
use clap::{Parser, ValueHint};
use eyre::{Context, Result};
use forge_verify::RetryArgs;
use foundry_cli::{
opts::{CoreBuildArgs, EthereumOpts, EtherscanOpts, TransactionOpts},
utils::{self, read_constructor_args_file, remove_contract, LoadConfig},
};
use foundry_common::{
compile::{self},
fmt::parse_tokens,
};
use foundry_compilers::{artifacts::BytecodeObject, info::ContractInfo, utils::canonicalize};
use foundry_config::{
figment::{
self,
value::{Dict, Map},
Metadata, Profile,
},
merge_impl_figment_convert, Config,
};
use serde_json::json;
use std::{borrow::Borrow, marker::PhantomData, path::PathBuf, sync::Arc};
merge_impl_figment_convert!(CreateArgs, opts, eth);
/// CLI arguments for `forge create`.
#[derive(Clone, Debug, Parser)]
pub struct CreateArgs {
/// The contract identifier in the form `<path>:<contractname>`.
contract: ContractInfo,
/// The constructor arguments.
#[arg(
long,
num_args(1..),
conflicts_with = "constructor_args_path",
value_name = "ARGS",
)]
constructor_args: Vec<String>,
/// The path to a file containing the constructor arguments.
#[arg(
long,
value_hint = ValueHint::FilePath,
value_name = "PATH",
)]
constructor_args_path: Option<PathBuf>,
/// Print the deployment information as JSON.
#[arg(long, help_heading = "Display options")]
json: bool,
/// Verify contract after creation.
#[arg(long)]
verify: bool,
/// Send via `eth_sendTransaction` using the `--from` argument or `$ETH_FROM` as sender
#[arg(long, requires = "from")]
unlocked: bool,
/// Prints the standard json compiler input if `--verify` is provided.
///
/// The standard json compiler input can be used to manually submit contract verification in
/// the browser.
#[arg(long, requires = "verify")]
show_standard_json_input: bool,
/// Timeout to use for broadcasting transactions.
#[arg(long, env = "ETH_TIMEOUT")]
pub timeout: Option<u64>,
#[command(flatten)]
opts: CoreBuildArgs,
#[command(flatten)]
tx: TransactionOpts,
#[command(flatten)]
eth: EthereumOpts,
#[command(flatten)]
pub verifier: forge_verify::VerifierArgs,
#[command(flatten)]
retry: RetryArgs,
}
impl CreateArgs {
/// Executes the command to create a contract
pub async fn run(mut self) -> Result<()> {
let config = self.try_load_config_emit_warnings()?;
// Find Project & Compile
let project = config.project()?;
let target_path = if let Some(ref mut path) = self.contract.path {
canonicalize(project.root().join(path))?
} else {
project.find_contract_path(&self.contract.name)?
};
let mut output = compile::compile_target(&target_path, &project, self.json)?;
let (abi, bin, _) = remove_contract(&mut output, &target_path, &self.contract.name)?;
let bin = match bin.object {
BytecodeObject::Bytecode(_) => bin.object,
_ => {
let link_refs = bin
.link_references
.iter()
.flat_map(|(path, names)| {
names.keys().map(move |name| format!("\t{name}: {path}"))
})
.collect::<Vec<String>>()
.join("\n");
eyre::bail!("Dynamic linking not supported in `create` command - deploy the following library contracts first, then provide the address to link at compile time\n{}", link_refs)
}
};
// Add arguments to constructor
let provider = utils::get_provider(&config)?;
let params = match abi.constructor {
Some(ref v) => {
let constructor_args =
if let Some(ref constructor_args_path) = self.constructor_args_path {
read_constructor_args_file(constructor_args_path.to_path_buf())?
} else {
self.constructor_args.clone()
};
self.parse_constructor_args(v, &constructor_args)?
}
None => vec![],
};
// respect chain, if set explicitly via cmd args
let chain_id = if let Some(chain_id) = self.chain_id() {
chain_id
} else {
provider.get_chain_id().await?
};
if self.unlocked {
// Deploy with unlocked account
let sender = self.eth.wallet.from.expect("required");
self.deploy(abi, bin, params, provider, chain_id, sender, config.transaction_timeout)
.await
} else {
// Deploy with signer
let signer = self.eth.wallet.signer().await?;
let deployer = signer.address();
let provider = ProviderBuilder::<_, _, AnyNetwork>::default()
.wallet(EthereumWallet::new(signer))
.on_provider(provider);
self.deploy(abi, bin, params, provider, chain_id, deployer, config.transaction_timeout)
.await
}
}
/// Returns the provided chain id, if any.
fn chain_id(&self) -> Option<u64> {
self.eth.etherscan.chain.map(|chain| chain.id())
}
/// Ensures the verify command can be executed.
///
/// This is supposed to check any things that might go wrong when preparing a verify request
/// before the contract is deployed. This should prevent situations where a contract is deployed
/// successfully, but we fail to prepare a verify request which would require manual
/// verification.
async fn verify_preflight_check(
&self,
constructor_args: Option<String>,
chain: u64,
) -> Result<()> {
// NOTE: this does not represent the same `VerifyArgs` that would be sent after deployment,
// since we don't know the address yet.
let mut verify = forge_verify::VerifyArgs {
address: Default::default(),
contract: Some(self.contract.clone()),
compiler_version: None,
constructor_args,
constructor_args_path: None,
num_of_optimizations: None,
etherscan: EtherscanOpts {
key: self.eth.etherscan.key.clone(),
chain: Some(chain.into()),
},
rpc: Default::default(),
flatten: false,
force: false,
skip_is_verified_check: true,
watch: true,
retry: self.retry,
libraries: self.opts.libraries.clone(),
root: None,
verifier: self.verifier.clone(),
via_ir: self.opts.via_ir,
evm_version: self.opts.compiler.evm_version,
show_standard_json_input: self.show_standard_json_input,
guess_constructor_args: false,
};
// Check config for Etherscan API Keys to avoid preflight check failing if no
// ETHERSCAN_API_KEY value set.
let config = verify.load_config_emit_warnings();
verify.etherscan.key =
config.get_etherscan_config_with_chain(Some(chain.into()))?.map(|c| c.key);
let context = verify.resolve_context().await?;
verify.verification_provider()?.preflight_verify_check(verify, context).await?;
Ok(())
}
/// Deploys the contract
#[allow(clippy::too_many_arguments)]
async fn deploy<P: Provider<T, AnyNetwork>, T: Transport + Clone>(
self,
abi: JsonAbi,
bin: BytecodeObject,
args: Vec<DynSolValue>,
provider: P,
chain: u64,
deployer_address: Address,
timeout: u64,
) -> Result<()> {
let bin = bin.into_bytes().unwrap_or_else(|| {
panic!("no bytecode found in bin object for {}", self.contract.name)
});
let provider = Arc::new(provider);
let factory = ContractFactory::new(abi.clone(), bin.clone(), provider.clone(), timeout);
let is_args_empty = args.is_empty();
let mut deployer =
factory.deploy_tokens(args.clone()).context("failed to deploy contract").map_err(|e| {
if is_args_empty {
e.wrap_err("no arguments provided for contract constructor; consider --constructor-args or --constructor-args-path")
} else {
e
}
})?;
let is_legacy = self.tx.legacy || Chain::from(chain).is_legacy();
deployer.tx.set_from(deployer_address);
deployer.tx.set_chain_id(chain);
// `to` field must be set explicitly, cannot be None.
if deployer.tx.to.is_none() {
deployer.tx.set_create();
}
deployer.tx.set_nonce(if let Some(nonce) = self.tx.nonce {
Ok(nonce.to())
} else {
provider.get_transaction_count(deployer_address).await
}?);
// set tx value if specified
if let Some(value) = self.tx.value {
deployer.tx.set_value(value);
}
deployer.tx.set_gas_limit(if let Some(gas_limit) = self.tx.gas_limit {
Ok(gas_limit.to())
} else {
provider.estimate_gas(&deployer.tx).await
}?);
if is_legacy {
let gas_price = if let Some(gas_price) = self.tx.gas_price {
gas_price.to()
} else {
provider.get_gas_price().await?
};
deployer.tx.set_gas_price(gas_price);
} else {
let estimate = provider.estimate_eip1559_fees(None).await.wrap_err("Failed to estimate EIP1559 fees. This chain might not support EIP1559, try adding --legacy to your command.")?;
let priority_fee = if let Some(priority_fee) = self.tx.priority_gas_price {
priority_fee.to()
} else {
estimate.max_priority_fee_per_gas
};
let max_fee = if let Some(max_fee) = self.tx.gas_price {
max_fee.to()
} else {
estimate.max_fee_per_gas
};
deployer.tx.set_max_fee_per_gas(max_fee);
deployer.tx.set_max_priority_fee_per_gas(priority_fee);
}
// Before we actually deploy the contract we try check if the verify settings are valid
let mut constructor_args = None;
if self.verify {
if !args.is_empty() {
let encoded_args = abi
.constructor()
.ok_or_else(|| eyre::eyre!("could not find constructor"))?
.abi_encode_input(&args)?;
constructor_args = Some(hex::encode(encoded_args));
}
self.verify_preflight_check(constructor_args.clone(), chain).await?;
}
// Deploy the actual contract
let (deployed_contract, receipt) = deployer.send_with_receipt().await?;
let address = deployed_contract;
if self.json {
let output = json!({
"deployer": deployer_address.to_string(),
"deployedTo": address.to_string(),
"transactionHash": receipt.transaction_hash
});
println!("{output}");
} else {
println!("Deployer: {deployer_address}");
println!("Deployed to: {address}");
println!("Transaction hash: {:?}", receipt.transaction_hash);
};
if !self.verify {
return Ok(());
}
println!("Starting contract verification...");
let num_of_optimizations = if self.opts.compiler.optimize.unwrap_or_default() {
self.opts.compiler.optimizer_runs
} else {
None
};
let verify = forge_verify::VerifyArgs {
address,
contract: Some(self.contract),
compiler_version: None,
constructor_args,
constructor_args_path: None,
num_of_optimizations,
etherscan: EtherscanOpts { key: self.eth.etherscan.key(), chain: Some(chain.into()) },
rpc: Default::default(),
flatten: false,
force: false,
skip_is_verified_check: false,
watch: true,
retry: self.retry,
libraries: self.opts.libraries.clone(),
root: None,
verifier: self.verifier,
via_ir: self.opts.via_ir,
evm_version: self.opts.compiler.evm_version,
show_standard_json_input: self.show_standard_json_input,
guess_constructor_args: false,
};
println!("Waiting for {} to detect contract deployment...", verify.verifier.verifier);
verify.run().await
}
/// Parses the given constructor arguments into a vector of `DynSolValue`s, by matching them
/// against the constructor's input params.
///
/// Returns a list of parsed values that match the constructor's input params.
fn parse_constructor_args(
&self,
constructor: &Constructor,
constructor_args: &[String],
) -> Result<Vec<DynSolValue>> {
let mut params = Vec::with_capacity(constructor.inputs.len());
for (input, arg) in constructor.inputs.iter().zip(constructor_args) {
// resolve the input type directly
let ty = input
.resolve()
.wrap_err_with(|| format!("Could not resolve constructor arg: input={input}"))?;
params.push((ty, arg));
}
let params = params.iter().map(|(ty, arg)| (ty, arg.as_str()));
parse_tokens(params).map_err(Into::into)
}
}
impl figment::Provider for CreateArgs {
fn metadata(&self) -> Metadata {
Metadata::named("Create Args Provider")
}
fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
let mut dict = Dict::default();
if let Some(timeout) = self.timeout {
dict.insert("transaction_timeout".to_string(), timeout.into());
}
Ok(Map::from([(Config::selected_profile(), dict)]))
}
}
/// `ContractFactory` is a [`DeploymentTxFactory`] object with an
/// [`Arc`] middleware. This type alias exists to preserve backwards
/// compatibility with less-abstract Contracts.
///
/// For full usage docs, see [`DeploymentTxFactory`].
pub type ContractFactory<P, T> = DeploymentTxFactory<Arc<P>, P, T>;
/// Helper which manages the deployment transaction of a smart contract. It
/// wraps a deployment transaction, and retrieves the contract address output
/// by it.
///
/// Currently, we recommend using the [`ContractDeployer`] type alias.
#[derive(Debug)]
#[must_use = "ContractDeploymentTx does nothing unless you `send` it"]
pub struct ContractDeploymentTx<B, P, T, C> {
/// the actual deployer, exposed for overriding the defaults
pub deployer: Deployer<B, P, T>,
/// marker for the `Contract` type to create afterwards
///
/// this type will be used to construct it via `From::from(Contract)`
_contract: PhantomData<C>,
}
impl<B, P, T, C> Clone for ContractDeploymentTx<B, P, T, C>
where
B: Clone,
{
fn clone(&self) -> Self {
Self { deployer: self.deployer.clone(), _contract: self._contract }
}
}
impl<B, P, T, C> From<Deployer<B, P, T>> for ContractDeploymentTx<B, P, T, C> {
fn from(deployer: Deployer<B, P, T>) -> Self {
Self { deployer, _contract: PhantomData }
}
}
/// Helper which manages the deployment transaction of a smart contract
#[derive(Debug)]
#[must_use = "Deployer does nothing unless you `send` it"]
pub struct Deployer<B, P, T> {
/// The deployer's transaction, exposed for overriding the defaults
pub tx: WithOtherFields<TransactionRequest>,
abi: JsonAbi,
client: B,
confs: usize,
timeout: u64,
_p: PhantomData<P>,
_t: PhantomData<T>,
}
impl<B, P, T> Clone for Deployer<B, P, T>
where
B: Clone,
{
fn clone(&self) -> Self {
Self {
tx: self.tx.clone(),
abi: self.abi.clone(),
client: self.client.clone(),
confs: self.confs,
timeout: self.timeout,
_p: PhantomData,
_t: PhantomData,
}
}
}
impl<B, P, T> Deployer<B, P, T>
where
B: Borrow<P> + Clone,
P: Provider<T, AnyNetwork>,
T: Transport + Clone,
{
/// Broadcasts the contract deployment transaction and after waiting for it to
/// be sufficiently confirmed (default: 1), it returns a tuple with
/// the [`Contract`](crate::Contract) struct at the deployed contract's address
/// and the corresponding [`AnyReceipt`].
pub async fn send_with_receipt(
self,
) -> Result<(Address, AnyTransactionReceipt), ContractDeploymentError> {
let receipt = self
.client
.borrow()
.send_transaction(self.tx)
.await?
.with_required_confirmations(self.confs as u64)
.get_receipt()
.await?;
let address =
receipt.contract_address.ok_or(ContractDeploymentError::ContractNotDeployed)?;
Ok((address, receipt))
}
}
/// To deploy a contract to the Ethereum network, a `ContractFactory` can be
/// created which manages the Contract bytecode and Application Binary Interface
/// (ABI), usually generated from the Solidity compiler.
///
/// Once the factory's deployment transaction is mined with sufficient confirmations,
/// the [`Contract`](crate::Contract) object is returned.
///
/// # Example
///
/// ```
/// # async fn foo() -> Result<(), Box<dyn std::error::Error>> {
/// use alloy_primitives::Bytes;
/// use ethers_contract::ContractFactory;
/// use ethers_providers::{Provider, Http};
///
/// // get the contract ABI and bytecode
/// let abi = Default::default();
/// let bytecode = Bytes::from_static(b"...");
///
/// // connect to the network
/// let client = Provider::<Http>::try_from("http://localhost:8545").unwrap();
/// let client = std::sync::Arc::new(client);
///
/// // create a factory which will be used to deploy instances of the contract
/// let factory = ContractFactory::new(abi, bytecode, client);
///
/// // The deployer created by the `deploy` call exposes a builder which gets consumed
/// // by the async `send` call
/// let contract = factory
/// .deploy("initial value".to_string())?
/// .confirmations(0usize)
/// .send()
/// .await?;
/// println!("{}", contract.address());
/// # Ok(())
/// # }
#[derive(Debug)]
pub struct DeploymentTxFactory<B, P, T> {
client: B,
abi: JsonAbi,
bytecode: Bytes,
timeout: u64,
_p: PhantomData<P>,
_t: PhantomData<T>,
}
impl<B, P, T> Clone for DeploymentTxFactory<B, P, T>
where
B: Clone,
{
fn clone(&self) -> Self {
Self {
client: self.client.clone(),
abi: self.abi.clone(),
bytecode: self.bytecode.clone(),
timeout: self.timeout,
_p: PhantomData,
_t: PhantomData,
}
}
}
impl<P, T, B> DeploymentTxFactory<B, P, T>
where
B: Borrow<P> + Clone,
P: Provider<T, AnyNetwork>,
T: Transport + Clone,
{
/// Creates a factory for deployment of the Contract with bytecode, and the
/// constructor defined in the abi. The client will be used to send any deployment
/// transaction.
pub fn new(abi: JsonAbi, bytecode: Bytes, client: B, timeout: u64) -> Self {
Self { client, abi, bytecode, timeout, _p: PhantomData, _t: PhantomData }
}
/// Create a deployment tx using the provided tokens as constructor
/// arguments
pub fn deploy_tokens(
self,
params: Vec<DynSolValue>,
) -> Result<Deployer<B, P, T>, ContractDeploymentError>
where
B: Clone,
{
// Encode the constructor args & concatenate with the bytecode if necessary
let data: Bytes = match (self.abi.constructor(), params.is_empty()) {
(None, false) => return Err(ContractDeploymentError::ConstructorError),
(None, true) => self.bytecode.clone(),
(Some(constructor), _) => {
let input: Bytes = constructor
.abi_encode_input(¶ms)
.map_err(ContractDeploymentError::DetokenizationError)?
.into();
// Concatenate the bytecode and abi-encoded constructor call.
self.bytecode.iter().copied().chain(input).collect()
}
};
// create the tx object. Since we're deploying a contract, `to` is `None`
let tx = WithOtherFields::new(TransactionRequest::default().input(data.into()));
Ok(Deployer {
client: self.client.clone(),
abi: self.abi,
tx,
confs: 1,
timeout: self.timeout,
_p: PhantomData,
_t: PhantomData,
})
}
}
#[derive(thiserror::Error, Debug)]
/// An Error which is thrown when interacting with a smart contract
pub enum ContractDeploymentError {
#[error("constructor is not defined in the ABI")]
ConstructorError,
#[error(transparent)]
DetokenizationError(#[from] alloy_dyn_abi::Error),
#[error("contract was not deployed")]
ContractNotDeployed,
#[error(transparent)]
RpcError(#[from] TransportError),
}
impl From<PendingTransactionError> for ContractDeploymentError {
fn from(_err: PendingTransactionError) -> Self {
Self::ContractNotDeployed
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn can_parse_create() {
let args: CreateArgs = CreateArgs::parse_from([
"foundry-cli",
"src/Domains.sol:Domains",
"--verify",
"--retries",
"10",
"--delay",
"30",
]);
assert_eq!(args.retry.retries, 10);
assert_eq!(args.retry.delay, 30);
}
#[test]
fn can_parse_chain_id() {
let args: CreateArgs = CreateArgs::parse_from([
"foundry-cli",
"src/Domains.sol:Domains",
"--verify",
"--retries",
"10",
"--delay",
"30",
"--chain-id",
"9999",
]);
assert_eq!(args.chain_id(), Some(9999));
}
#[test]
fn test_parse_constructor_args() {
let args: CreateArgs = CreateArgs::parse_from([
"foundry-cli",
"src/Domains.sol:Domains",
"--constructor-args",
"Hello",
]);
let constructor: Constructor = serde_json::from_str(r#"{"type":"constructor","inputs":[{"name":"_name","type":"string","internalType":"string"}],"stateMutability":"nonpayable"}"#).unwrap();
let params = args.parse_constructor_args(&constructor, &args.constructor_args).unwrap();
assert_eq!(params, vec![DynSolValue::String("Hello".to_string())]);
}
#[test]
fn test_parse_tuple_constructor_args() {
let args: CreateArgs = CreateArgs::parse_from([
"foundry-cli",
"src/Domains.sol:Domains",
"--constructor-args",
"[(1,2), (2,3), (3,4)]",
]);
let constructor: Constructor = serde_json::from_str(r#"{"type":"constructor","inputs":[{"name":"_points","type":"tuple[]","internalType":"struct Point[]","components":[{"name":"x","type":"uint256","internalType":"uint256"},{"name":"y","type":"uint256","internalType":"uint256"}]}],"stateMutability":"nonpayable"}"#).unwrap();
let _params = args.parse_constructor_args(&constructor, &args.constructor_args).unwrap();
}
}