ethereumsolidityhardhatfoundry-forge

Want to pass address of one contract into another inside Foundry test


I am working through OpenZeppelin's Ethernaut challenges and want to use Foundry. I have two smart contracts in my src folder:

In my test file in the setUp() function I want to instantiate the CoinFlip contract which is easy enough like so:

function setUp() public {
    coinFlip = new CoinFlip();
}

but after I do this I want to pass the address of the CoinFlip contract into the CoinFlipBreak contract. This does NOT work:

 coinFlipBreak = new CoinFlipBreak( coinFlip.address );

How can I get the address of the first contract passed in to the second?


Solution

  • Every contract is an address, and vice versa (when not EOA). And you can cast in both ways:

    CoinFlip coinFlip = new CoinFlip();
    
    // cast to address
    address coinFlipAddress = address(coinFlip);
    
    // cast to contract instance
    CoinFlip coinFlipX = CoinFlip(coinFlipAddress)
    

    An example with hardhat:

    import "hardhat/console.sol";
    
    contract A {
    
    }
    contract B {
        constructor (address addr) {
            A a = A(addr);
            console.log(address(a));
        }
    }
    contract Test {
        constructor () {
            A a = new A();
            B b = new B(address(a));
        }
    }