Factory contracts
A factory is a contract that creates other contracts. It is useful when every user or project needs its own copy, such as one vault per user or one token per launch. The factory keeps a list of what it created so that apps can find them.
You create a contract from code with the new keyword, which deploys it and returns its address. Constructor arguments go in brackets after the name. Creating a contract costs a lot of gas, because the full bytecode is stored on-chain.
To save gas, many factories use minimal proxy clones, defined in EIP-1167. Each clone is a tiny contract that forwards every call to one shared implementation, so deploying a new copy is much cheaper. OpenZeppelin's Clones library creates them.
CREATE2 lets you deploy to an address that you can predict before deployment, using a salt. Add the salt in curly braces after new, as in the example. This is useful for wallets that need an address before they exist, and for contracts that must have the same address on several chains.
contract Vault { address public immutable owner; constructor(address o) { owner = o; } receive() external payable {} } contract VaultFactory { Vault[] public vaults; mapping(address => address[]) public vaultsOf; event VaultCreated(address indexed owner, address vault); function create() external returns (address) { Vault v = new Vault(msg.sender); vaults.push(v); vaultsOf[msg.sender].push(address(v)); emit VaultCreated(msg.sender, address(v)); return address(v); } function create2(bytes32 salt) external returns (address) { Vault v = new Vault{salt: salt}(msg.sender); emit VaultCreated(msg.sender, address(v)); return address(v); } function count() external view returns (uint256) { return vaults.length; } }
Try it yourself
Add a function that returns all vaults created by a given owner. In Remix, call create twice from one account and check vaultsOf.
Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.