[Ethereum] Mapping to contract

contract-designmappingsoliditystorage

Solidity documentation says it is possible to use anything as mapping value, which I assume includes a contract:

_ValueType can actually be any type, including mappings.

but I couldn't find an example or documentation on how to work with it.

If I have the following mapping, how can I know if the contract in the mapping exists, or have suicided?

pragma solidity ^0.4.0;

contract MyContract {
  // ...
}

contract MappingExample {
    mapping(uint32 => MyContract) inner_contracts;

    function do_something(uint32 key) {
        MyContract c;
        if(/* inner_contracts[key] exists??? */) {
            c = inner_contracts[key];
        } else {
            c = new MyContract;
            inner_contracts[key] = c;
        }

        // do stuff with c
    }
}

Best Answer

Here is an example.

pragma solidity ^0.4.19;


contract InnerContract {
    uint public value;
    function setValue(uint new_value) {
        value = new_value;
    }
}

contract Contract {
    mapping(address => InnerContract) public contracts;

    function makeNew() {
        contracts[msg.sender] = new InnerContract();
    }
    function initialize() {
      contracts[msg.sender].setValue(3);
    }
    function get() constant returns (uint) {
      return contracts[msg.sender].value();
    }
}

If you play with this code, you'll notice that calling initialize before makeNew doesn't work. The reason is that mapping has default value filled with zeros. In case of contract it's not a good idea.

how can I know if the contract in the mapping exists, or have suicided?

Let's use another mapping for flags!

mapping(address => InnerContract) public is_contract_initialized;

If value is false(which is by default) then you should initialize your contract.

Related Topic