Search code examples
ethereumsolidityremix

How to pass a .sol file as a parameter to a function? Solidity


A custom .sol file is created in the front-end. I need to compile and deploy the newly created contract using the external user as a signer, similar to how remix lets others deploy their own contracts.

To do this, my plan was to create a parent contract that compiles and deploys the new child contracts. These newly built child contracts could be passed to a function in the parent contract. Is this possible, and if so how can I do this?

Can I pass a .sol file as a parameter to a function in a solidity contract?


Solution

  • You can pass a compiled bytecode - not the Solidity source - to a factory contract which invokes the low-level create opcode, effectively deploying the contract that you just passed to it.

    Here's an example of such factory contract:

    pragma solidity ^0.8;
    
    contract Target {
        uint public number = 100;
    }
    
    contract Factory {
        event DeployedTo(address);
    
        function deploy(bytes memory code) public returns (address addr) {
            assembly {
                addr := create(0,add(code,0x20), mload(code))
            }
    
            emit DeployedTo(addr);
        }
    
        function deployTarget() public {
            this.deploy(
                hex"60806040526064600055348015601457600080fd5b50607d806100236000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c80638381f58a14602d575b600080fd5b603560005481565b60405190815260200160405180910390f3fea26469706673582212204222f4063ba77f82b7d8339b117fd0142d917b7d473221d6bb362a1467d5d83864736f6c63430008070033"
            );
        }
    }
    

    The Target is here just for reference. deployTarget() passes its bytecode to the deploy() function, and then you can validate its functionality in Remix by loading the Target contract at the deployed address (the blue button "At Address" on the screenshot).

    load contract at address

    working Target contract