It's a common pattern to use a hub/factory contract to create multiple instances of a standard contract.
It's also common to require a way to enumerate the addresses of the created contracts.
Is there a simple minimal example of a good approach?
It's a common pattern to use a hub/factory contract to create multiple instances of a standard contract.
It's also common to require a way to enumerate the addresses of the created contracts.
Is there a simple minimal example of a good approach?
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?
Hope it helps.
For accessing the method I created a new function and did it like this
function getCookieFlavor(address cookie) public view returns(string){
return Cookie(cookie).getFlavor();
}
just pass in the address of the cookie which is already created.
cis both aCookieand anaddress? It's created as the former but stored in an array (and returned) as the latter. Why isn'tcontractsan array ofCookie[]instead ofaddress[]? – Teleporting Goat Mar 22 '18 at 09:24return address(c);. We're using an array of address as a list of keys we can use to discover the rest which is more economical than an array of large objects. – Rob Hitchens Mar 22 '18 at 12:35getFlavor()isconstant(would be `pure1 now) so the return value is easily accessible. – Rob Hitchens Feb 23 '19 at 00:37