Search code examples
ethereumsoliditysmartcontracts

Getting contract address


I saw an example about this, while was searching it on the internet.

I want to deploy a new contract which is ProjectContract. However, I could not get contract address as below. I think this is for old version.

address newProjectAddress = new ProjectContract(name, description, requiredPrice, msg.sender);

And the error message is: This the error message

How can I do that for the new versions?


Solution

  • When you're creating new <contractName>, it returns the contract instance. You can cast it to the address type and get the contract address.

    pragma solidity ^0.8.4;
    
    contract ProjectContract {
        constructor (string memory name, string memory description, uint256 requiredPrice, address owner) {
        }
    }
    
    contract MyContract {
        event LogAddress(address _address);
        
        function createProjectContract(string memory name, string memory description, uint256 requiredPrice) external {
            ProjectContract newProjectInstance = new ProjectContract(name, description, requiredPrice, msg.sender);
            address newProjectAddress = address(newProjectInstance); // here
            emit LogAddress(newProjectAddress);
        }
    }