Here's a simple hub (Bakery) that deploys contracts (Cookie) from a template and keeps track of the contracts created.
Note that Cookie
is part of the source file so Bakery
can "see it" during compilation. Cookie
's ByteCode will become part of Bakery so the new Cookie()
invocation knows what to do.
Deploy the hub/factory (Bakery
). It's not necessary to deploy the template (Cookie
). You can create as many of the latter as needed by calling a function in the former.
pragma solidity ^0.4.8;
contract Bakery {
// index of created contracts
address[] public contracts;
// useful to know the row count in contracts index
function getContractCount()
public
constant
returns(uint contractCount)
{
return contracts.length;
}
// deploy a new contract
function newCookie()
public
returns(address newContract)
{
Cookie c = new Cookie();
contracts.push(c);
return c;
}
}
contract Cookie {
// suppose the deployed contract has a purpose
function getFlavor()
public
constant
returns (string flavor)
{
return "mmm ... chocolate chip";
}
}
If you need more functionality in the index (e.g. is 0x123 a contract?) consider more feature-complete storage patterns: Are there well-solved and simple storage patterns for Solidity?Are there well-solved and simple storage patterns for Solidity?
Hope it helps.