## Understanding Factory Contracts in Solidity
### Introduction
Today at **Blockfuse Labs**, I learned about the **Factory Pattern** in Solidity a concept that allows one contract to **deploy and manage other contracts**.
It’s a simple but powerful pattern used in **DeFi protocols, NFT collections, DAOs,** and **launchpads**, where you need to create many similar smart contracts automatically.
---
### The Factory Concept
A **Factory Contract** acts like a manager that produces multiple instances of another contract.
Instead of deploying contracts manually, you can deploy them programmatically through the factory using the `new` keyword.
Example (very short):
```solidity
pragma solidity ^0.8.20;
contract Product {
string public name;
constructor(string memory _name) { name = _name; }
}
contract Factory {
address[] public products;
function create(string memory _name) public {
Product p = new Product(_name);
products.push(address(p));
}
}
```
Each time you call `create("ClemProduct")`, the factory automatically deploys a new **Product contract** and stores its address.
---
### Scripting with Foundry
After writing the contracts, we use **Foundry scripting** to deploy and interact with them easily.
Scripting in Foundry is done with `.s.sol` files inside the **`script/`** directory.
A script is just a Solidity contract that uses Foundry’s special cheat codes to perform blockchain actions like deployment or interaction.
---
### Example Script
```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "forge-std/Script.sol";
import "../src/Factory.sol";
contract FactoryScript is Script {
function run() external {
vm.startBroadcast(); // start sending transactions
Factory factory = new Factory(); // deploy factory
factory.create("ClemProduct"); // deploy new product through factory
vm.stopBroadcast(); // stop broadcasting transactions
}
}
```
---
### Explanation of the Script
Here’s what happens step-by-step:
1. **`import "forge-std/Script.sol";`**
* This gives access to Foundry’s scripting tools like `vm.startBroadcast()` and `vm.stopBroadcast()`.
2. **`vm.startBroadcast()`**
* Tells Foundry to start sending real transactions to the network using your wallet’s private key.
3. **`new Factory()`**
* Deploys the **Factory** contract on the blockchain.
4. **`factory.create("ClemProduct")`**
* Uses the Factory to create a new **Product** contract.
5. **`vm.stopBroadcast()`**
* Ends the transaction broadcast.
---
### Running the Script
To run your script, use:
```bash
forge script script/Factory.s.sol --rpc-url <your_rpc_url> --private-key <your_private_key> --broadcast
```
This command will:
* Compile your code
* Deploy the **Factory** contract
* Automatically call the `create()` function
* Broadcast everything to the network (local, testnet, or mainnet)
---