Search code examples
ethereumsolidityremix

How can I get contract address of a contract from another contract?


Here how can I find the address of A within Test() function?

contract A {
    uint public target;
    function setTarget(uint _target) public {
        target = _target;
    }
}

contract B {
    A a = Test(0x123abc...);  // address of deployed A
    function editA() public {
        a.setTarget(1);
    }
}

Solution

  • You can get the address by casting the A type to type address.

    contract B {
        A a = Test(0x123abc...);
    
        funciton getAddressA() public view returns (address) {
            return address(a); // typecasting to `address`
        }
    }