Contract Functions – Calling Function from Another Contract Argument

contract-debuggingcontract-deploymentremixsolcsolidity

Im Trying to create a DAPP with two contracts generating assets. One is acting as the "factory" for the other contracts. From the latter I try to call a function in the factory without knowing its address yet, therefore I want to pass it in as an argument. This throws an error in Remix because that contract obviously doesn't exist yet.

To simplify the situation think about this scenario in Remix (both contracts are written in the same file):

    contract AssetFactory{

    address[] deployedAssets;

      function createAsset(string name) public {
        address newAsset = new Asset(name);
        deployedAssets.push(newAsset);
        return newAsset;
      }

    }

    contract Asset{

     string name;

     function Asset(string name) public{
       name = name;
     }

     function ModifyAssetAndCreateNew(string name, address factory){
       factory.createAsset(name);
       name = name;
     }

   }

Any Ideas or other approaches? I realize that the idea behind the above contract doesn't make much sense in this example but i tried to keep it as short as possible.

Thank you!

Best Answer

There were a number of compilation errors in your example code, but once I fixed those up, and changed address factory to AssetFactory factory, everything looks to be fine.

(I just took a guess at which name you meant in the line factory.createAsset(name). When producing a simple example, make sure it's one you've actually tested.)

pragma solidity ^0.4.23;

contract AssetFactory {
    Asset[] deployedAssets;

    function createAsset(string name) public returns (Asset) {
        Asset newAsset = new Asset(name);
        deployedAssets.push(newAsset);
        return newAsset;
    }

}

contract Asset {
    string name;

    constructor(string _name) public {
        name = _name;
    }

    function modifyAssetAndCreateNew(string _name, AssetFactory factory) public {
        factory.createAsset(_name);
        name = _name;
    }
}
Related Topic