forked from foundry-rs/foundry
    
        
        - 
                Notifications
    You must be signed in to change notification settings 
- Fork 6
Support for Factory Contract Dependency in forge create #162
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Open
      
      
            soul022
  wants to merge
  29
  commits into
  master
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
soul022/factoryContracts
  
      
      
   
  
    
  
  
  
 
  
      
    base: master
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
  
     Open
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            29 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      f96402d
              
                wip
              
              
                soul022 c01f6b2
              
                [issue 130] - clean up
              
              
                soul022 b6eb1e3
              
                [issue 130] - fix fmt issues
              
              
                soul022 c3be5c8
              
                [issue 130] - fix fmt issues
              
              
                soul022 f25cf41
              
                [issue - 130] - fix clippy issues
              
              
                soul022 869de53
              
                Merge branch 'master' into soul022/factoryContracts
              
              
                soul022 56bd04b
              
                [issue - 130] - fix fmt issues
              
              
                soul022 850206f
              
                [issue - 130] - fix fmt issues
              
              
                soul022 0efe3a4
              
                [issue - 130] - fix clippy issues
              
              
                soul022 4543076
              
                [issue - 130] - updated code to get bytecode contract from compiler o…
              
              
                soul022 b6328da
              
                [issue - 130] - rustfmt fixes
              
              
                soul022 8b65934
              
                [issue - 130] - added comments to upload_child_contract_alloy
              
              
                soul022 cccbe25
              
                [issue - 130] - rustfmt fixes
              
              
                soul022 bb249c9
              
                [issue - 130] - remove internal libraries used as child contracts
              
              
                soul022 0552ce5
              
                [issue - 130] - clippy fix
              
              
                soul022 64fa04d
              
                [issue - 130] - reading factory contract from compilers
              
              
                soul022 3411a24
              
                [issue - 130] - remove unused code
              
              
                soul022 af8036c
              
                [issue - 130] - fix fmt issues
              
              
                soul022 053f1e4
              
                [issue - 130] - fix fmt issues
              
              
                soul022 145f6da
              
                [issue - 130] - fix fmt issues
              
              
                soul022 ff4e4d1
              
                [issue-130] - factory dependency changed to btree
              
              
                soul022 90d9554
              
                [issue - 130] - extensions changes
              
              
                soul022 1c8fe0a
              
                [issue - 130] - extensions fixes
              
              
                soul022 4c53953
              
                [issue - 130] - fmt fixes
              
              
                soul022 f06ccf9
              
                Merge branch 'master' into soul022/factoryContracts
              
              
                soul022 05fbbcc
              
                Merge remote-tracking branch 'origin/master' into soul022/factoryCont…
              
              
                smiasojed 2dc0615
              
                Fmt
              
              
                smiasojed c36e11c
              
                use factory deps when revive build is enabled
              
              
                smiasojed c58e525
              
                Add forge create tests
              
              
                smiasojed File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
      
      Oops, something went wrong.
      
    
  
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
|  | @@ -10,7 +10,9 @@ use alloy_serde::WithOtherFields; | |
| use alloy_signer::Signer; | ||
| use alloy_transport::TransportError; | ||
| use clap::{Parser, ValueHint}; | ||
| use eyre::{Context, Result}; | ||
|  | ||
| use codec::{Compact, Encode}; | ||
| use eyre::{Context, OptionExt, Result}; | ||
| use forge_verify::{RetryArgs, VerifierArgs, VerifyArgs}; | ||
| use foundry_cli::{ | ||
| opts::{BuildOpts, EthereumOpts, EtherscanOpts, TransactionOpts}, | ||
|  | @@ -22,7 +24,10 @@ use foundry_common::{ | |
| shell, | ||
| }; | ||
| use foundry_compilers::{ | ||
| artifacts::BytecodeObject, info::ContractInfo, utils::canonicalize, ArtifactId, | ||
| artifacts::{ArtifactExtras, BytecodeObject}, | ||
| info::ContractInfo, | ||
| utils::canonicalize, | ||
| Artifact, ArtifactId, ProjectCompileOutput, | ||
| }; | ||
| use foundry_config::{ | ||
| figment::{ | ||
|  | @@ -33,10 +38,99 @@ use foundry_config::{ | |
| merge_impl_figment_convert, Config, | ||
| }; | ||
| use serde_json::json; | ||
| use std::{borrow::Borrow, marker::PhantomData, path::PathBuf, sync::Arc, time::Duration}; | ||
|  | ||
| use std::{ | ||
| borrow::Borrow, collections::BTreeMap, marker::PhantomData, path::PathBuf, sync::Arc, | ||
| time::Duration, | ||
| }; | ||
| merge_impl_figment_convert!(CreateArgs, build, eth); | ||
|  | ||
| /// Finds a contract in the artifacts by its bytecode hash | ||
| fn find_contract_by_hash(output: &ProjectCompileOutput, target_hash: &str) -> Option<Bytes> { | ||
| for (_contract_name, artifact) in output.artifacts() { | ||
| if let Some(bytecode) = artifact.get_bytecode_bytes() { | ||
| let bytecode_bytes = bytecode.into_owned(); | ||
| if !bytecode_bytes.is_empty() { | ||
| // Calculate keccak256 hash of the bytecode | ||
| use alloy_primitives::keccak256; | ||
| let calculated_hash = hex::encode(keccak256(&bytecode_bytes)); | ||
|  | ||
| // Normalize both hashes by removing 0x prefix for comparison | ||
| let normalized_target = target_hash.trim_start_matches("0x"); | ||
| let normalized_calculated = calculated_hash.trim_start_matches("0x"); | ||
|  | ||
| if normalized_calculated == normalized_target { | ||
| return Some(bytecode_bytes); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| None | ||
| } | ||
|  | ||
| /// Handles factory dependencies for a contract deployment | ||
| async fn upload_factory_dependencies( | ||
| output: &ProjectCompileOutput, | ||
| config: &Config, | ||
| private_key: &str, | ||
| ) -> Result<()> { | ||
| // Collect all factory dependencies from all contracts | ||
| let mut all_dependencies = BTreeMap::new(); | ||
|  | ||
| for (_id, contract) in output.artifact_ids() { | ||
| if let ArtifactExtras::Resolc(extras) = &contract.extensions { | ||
| if let Some(factory_dependencies) = &extras.factory_dependencies { | ||
| for (bytecode_hash, contract_name) in factory_dependencies { | ||
| all_dependencies.insert(bytecode_hash, contract_name); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|  | ||
| if all_dependencies.is_empty() { | ||
| return Ok(()); | ||
| } | ||
|  | ||
| // Get RPC URL for factory dependency uploads | ||
| let rpc_url = config.get_rpc_url_or_localhost_http()?; | ||
|  | ||
| // Upload each factory dependency | ||
| for (hash, name) in all_dependencies { | ||
| // Try to find the contract by hash directly (skip name-based lookup) | ||
| let bytecode = find_contract_by_hash(output, hash); | ||
|  | ||
| if let Some(bytecode) = bytecode { | ||
| // Skip child contracts (those with 0x3c04 prefix) | ||
| let bytecode_slice = bytecode.as_ref(); | ||
| if bytecode_slice.len() >= 2 && bytecode_slice[0] == 0x3c && bytecode_slice[1] == 0x04 { | ||
| continue; | ||
| } | ||
|  | ||
| // Upload factory dependency using upload_child_contract_alloy | ||
| let scaled_encoded_bytes = bytecode.encode(); | ||
| let storage_deposit_limit = Compact(10000000000u128); | ||
| let encoded_storage_deposit_limit = storage_deposit_limit.encode(); | ||
| let combined_hex = "0x3c04".to_string() + | ||
| There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It should be based on node metadata. Pallet index may be different between runtimes | ||
| &hex::encode(&scaled_encoded_bytes) + | ||
| &hex::encode(&encoded_storage_deposit_limit); | ||
|  | ||
| let _tx_hash = upload_child_contract_alloy( | ||
| rpc_url.as_ref(), | ||
| private_key.to_string(), | ||
| combined_hex, | ||
| ) | ||
| .await?; | ||
| } else { | ||
| return Err(eyre::eyre!( | ||
| "Could not find contract '{}' (hash: {}) in artifacts", | ||
| name, | ||
| hash | ||
| )); | ||
| } | ||
| } | ||
|  | ||
| Ok(()) | ||
| } | ||
|  | ||
| /// CLI arguments for `forge create`. | ||
| #[derive(Clone, Debug, Parser)] | ||
| pub struct CreateArgs { | ||
|  | @@ -100,11 +194,54 @@ pub struct CreateArgs { | |
| retry: RetryArgs, | ||
| } | ||
|  | ||
| /// Uploads a child contract to a blockchain network using the Alloy framework. | ||
| async fn upload_child_contract_alloy( | ||
| rpc_url: &str, | ||
| private_key: String, | ||
| encoded_bytes: String, | ||
| ) -> Result<String> { | ||
| use alloy_primitives::{Address, U256}; | ||
| use alloy_provider::Provider; | ||
| use alloy_rpc_types::TransactionRequest; | ||
| use alloy_serde::WithOtherFields; | ||
| use alloy_signer_local::PrivateKeySigner; | ||
| use foundry_common::provider::ProviderBuilder; | ||
| use std::str::FromStr; | ||
|  | ||
| // This wallet will be used to sign the deployment transaction | ||
| let wallet = PrivateKeySigner::from_str(&private_key)?; | ||
|  | ||
| // This establishes the connection to the target network and prepares for transaction signing | ||
| let provider = ProviderBuilder::new(rpc_url).build_with_wallet(EthereumWallet::new(wallet))?; | ||
|  | ||
| // Use the special "magic address" for child contract deployment | ||
| let magic_address: Address = "0x6d6f646c70792f70616464720000000000000000".parse()?; | ||
|  | ||
| // Convert the hex-encoded bytecode string to actual bytes for the transaction input | ||
| // Remove "0x" prefix if present before decoding | ||
| let input_bytes = hex::decode(encoded_bytes.trim_start_matches("0x"))?; | ||
|  | ||
| // Construct the transaction request | ||
| let tx = TransactionRequest::default() | ||
| .to(magic_address) | ||
| .input(input_bytes.into()) | ||
| .value(U256::from(0u64)); | ||
|  | ||
| // Wrap the transaction in WithOtherFields for proper serialization | ||
| let wrapped_tx = WithOtherFields::new(tx); | ||
|  | ||
| // Send the transaction to the network and wait for it to be included in a block | ||
| let pending_tx = provider.send_transaction(wrapped_tx).await?; | ||
| let receipt = pending_tx.get_receipt().await?; | ||
|  | ||
| // Return the transaction hash as a string for tracking and verification | ||
| Ok(receipt.transaction_hash.to_string()) | ||
| } | ||
|  | ||
| impl CreateArgs { | ||
| /// Executes the command to create a contract | ||
| pub async fn run(mut self) -> Result<()> { | ||
| let mut config = self.load_config()?; | ||
|  | ||
| // Install missing dependencies. | ||
| if install::install_missing_dependencies(&mut config) && config.auto_detect_remappings { | ||
| // need to re-configure here to also catch additional remappings | ||
|  | @@ -120,9 +257,10 @@ impl CreateArgs { | |
| project.find_contract_path(&self.contract.name)? | ||
| }; | ||
|  | ||
| let output = compile::compile_target(&target_path, &project, shell::is_json())?; | ||
| let output: foundry_compilers::ProjectCompileOutput = | ||
| compile::compile_target(&target_path, &project, shell::is_json())?; | ||
|  | ||
| let (abi, bin, id) = remove_contract(output, &target_path, &self.contract.name)?; | ||
| let (abi, bin, id) = remove_contract(output.clone(), &target_path, &self.contract.name)?; | ||
|  | ||
| let bin = match bin.object { | ||
| BytecodeObject::Bytecode(_) => bin.object, | ||
|  | @@ -153,6 +291,13 @@ impl CreateArgs { | |
|  | ||
| let provider = utils::get_provider(&config)?; | ||
|  | ||
| // Handle factory dependencies before deploying the main contract | ||
| if self.broadcast && self.build.compiler.resolc_opts.resolc_compile.unwrap_or_default() { | ||
| let private_key = | ||
| self.eth.wallet.raw.private_key.clone().ok_or_eyre("Private key not provided")?; | ||
| upload_factory_dependencies(&output, &config, &private_key).await?; | ||
| } | ||
|  | ||
| // respect chain, if set explicitly via cmd args | ||
| let chain_id = if let Some(chain_id) = self.chain_id() { | ||
| chain_id | ||
|  | ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why do we need this check?