Introduction
Solidity's new keyword enables developers to deploy new contract instances from templates. The "XxxContractFactory" naming convention represents a design pattern where a factory contract creates instances of an "XxxContract".
This guide explores:
- The fundamentals of contract factories
- Implementation mechanics
Practical applications like:
Core Implementation
1. Template Contract (Bank.sol)
contract Bank {
uint256 public bank_funds;
address public owner;
address public deployer;
constructor(address _owner, uint256 _funds) {
bank_funds = _funds;
owner = _owner;
deployer = msg.sender;
}
}2. Factory Contract (BankFactory.sol)
contract BankFactory {
Bank[] public list_of_banks;
function createBank(address _owner, uint256 _funds) external {
Bank bank = new Bank(_owner, _funds);
list_of_banks.push(bank);
}
}Key components:
new Bank(_owner, _funds)deploys new instances- Dynamic array tracks deployed contracts
Testing with HardHat
Setup
Initialize project:
npm install --save-dev hardhat npx hardhatAdd this test script:
describe("BankFactory Deployment", () => { it("Should create multiple Bank instances", async () => { const BF = await ethers.getContractFactory('BankFactory'); const bf = await BF.deploy(); await bf.createBank("0x0d8D...6666", 69420); const bankAddress = await bf.list_of_banks(0); // Verify deployment const bank = await ethers.getContractAt("Bank", bankAddress); console.log(`Bank funds: ${await bank.bank_funds()}`); }); });
Key Use Cases
| Application | Example Protocol |
|---|---|
| Decentralized Finance | Uniswap Factories |
| NFT Collections | Adidas 2 |
| Tokenization | ThirdWeb |
FAQ
Q: Why use factory contracts?
A: They enable scalable deployment while reducing gas costs through template reuse.
Q: Can factories call external contracts?
A: Yes, but ensure proper security checks with OpenZeppelin libraries.
Q: How to track deployed contracts?
A: Use dynamic arrays or mappings in the factory contract.
๐ Master Smart Contract Development