Smart Contract Development Lifecycle
Overview
Smart contract development follows a rigorous lifecycle that mirrors traditional software engineering while incorporating blockchain-specific constraints such as immutability, gas costs, and security requirements.
âšī¸
Smart contracts are immutable once deployed. A single bug can result in millions of dollars in losses. The development lifecycle must account for this permanent nature.
Development Workflow
The smart contract development workflow consists of several critical phases:
Phase 1: Design & Architecture
Before writing code, establish the contract architecture:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
interface IContractRegistry {
function getContract(string calldata name) external view returns (address);
function registerContract(string calldata name, address addr) external;
}
Design Principles
| Principle | Description | Trade-off |
|---|---|---|
| Single Responsibility | One contract, one purpose | More contracts to deploy |
| Separation of Concerns | Logic vs storage separation | Increased complexity |
| Fail-Safe Design | Reversible operations | Higher gas costs |
| Upgradeability | Proxy patterns | Centralization risk |
Phase 2: Compilation
Compiler Configuration
{
"compilerVersion": "0.8.19",
"optimizer": {
"enabled": true,
"runs": 200
},
"metadata": {
"bytecodeHash": "ipfs"
},
"outputSelection": {
"*": {
"*": ["abi", "evm.bytecode", "evm.deployedBytecode"],
"": ["ast"]
}
}
}
Optimization Trade-offs
The optimizer runs parameter affects deployment cost vs runtime cost:
| Runs Parameter | Deployment Gas | Runtime Gas | Use Case |
|---|---|---|---|
| 200 (default) | Balanced | Balanced | General purpose |
| 1000 | Higher | Lower | Frequently called |
| 1 | Lower | Higher | Rarely used |
Phase 3: Deployment Strategies
Direct Deployment
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract SimpleDeployment {
address public owner;
constructor() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
_;
}
function changeOwner(address newOwner) public onlyOwner {
owner = newOwner;
}
}
Deterministic Deployment (CREATE2)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract DeterministicDeployment {
function deploy(bytes memory bytecode, bytes32 salt) public returns (address addr) {
assembly {
addr := create2(0, add(bytecode, 0x20), mload(bytecode), salt)
}
require(addr != address(0), "Deployment failed");
}
function computeAddress(bytes32 salt, bytes32 bytecodeHash) public view returns (address) {
return address(uint160(uint256(keccak256(abi.encodePacked(
bytes1(0xff),
address(this),
salt,
bytecodeHash
)))));
}
}
Deployment Cost Analysis
| Method | Gas Cost | Address Determinism | Complexity |
|---|---|---|---|
| CREATE | ~50,000 | No | Low |
| CREATE2 | ~50,000 + 320 | Yes (deterministic) | Medium |
| Minimal Proxy | ~40,000 | Yes | High |
Phase 4: Verification
Contract verification on Etherscan allows source code inspection:
Verification Workflow
Multi-Part Verification
For complex contracts with multiple source files:
npx hardhat verify --constructor-args arguments.js \
--libraries libraries/Utils.sol:0x1234... \
DEPLOYED_ADDRESS
Phase 5: Upgrade Patterns
Transparent Proxy Pattern
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract TransparentProxy {
address public admin;
address public implementation;
mapping(bytes4 => bool) public adminSelectors;
modifier ifAdmin() {
if (msg.sender == admin) {
_;
} else {
_fallback();
}
}
constructor(address _implementation, address _admin) {
admin = _admin;
implementation = _implementation;
}
fallback() external payable {
require(msg.sender != admin, "Admin cannot fallback");
_fallback();
}
function _fallback() internal {
address impl = implementation;
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), impl, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
}
Upgradeability Trade-offs
| Pattern | Pros | Cons |
|---|---|---|
| Transparent Proxy | Low gas, admin controls upgrades | Admin centralization |
| UUPS | Self-contained, no external calls | More complex implementation |
| Beacon | Multiple proxies, one upgrade | Extra infrastructure |
| Diamond | Unlimited logic size | Highest complexity |
Phase 6: Testing Strategies
Test Pyramid for Smart Contracts
Unit Testing Example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
import "../src/Token.sol";
contract TokenTest is Test {
Token public token;
address public user = address(0x1);
function setUp() public {
token = new Token("Test", "TST", 18);
token.mint(user, 1000);
}
function testMint() public {
assertEq(token.balanceOf(user), 1000);
}
function testTransfer() public {
vm.prank(user);
token.transfer(address(0x2), 100);
assertEq(token.balanceOf(address(0x2)), 100);
}
function testFailTransfer() public {
vm.prank(user);
token.transfer(address(0x2), 2000); // Should fail
}
function testFuzzTransfer(uint256 amount) public {
vm.assume(amount <= 1000);
vm.prank(user);
token.transfer(address(0x2), amount);
assertEq(token.balanceOf(address(0x2)), amount);
}
}
Real-World Example: Uniswap V3
Uniswap V3 demonstrates best practices in contract development:
Deployment Statistics
| Metric | Value |
|---|---|
| Total Gas Used | ~4.2M gas |
| Contract Size | ~24KB (max limit) |
| Number of Contracts | 4 main contracts |
| Upgrade Pattern | Non-upgradeable |
| Test Coverage | >95% |
Key Learnings
- Code Optimization: Every byte matters for gas efficiency
- Security First: Multiple audits before deployment
- Documentation: Comprehensive NatSpec comments
- Testing: 100% branch coverage
Trade-offs in Development
| Decision | Option A | Option B | Recommendation |
|---|---|---|---|
| Upgradeability | Flexible upgrades | Immutable, trusted | Use for complex protocols |
| Gas Optimization | Lower runtime cost | Lower deployment cost | Optimize for runtime |
| Testing Depth | High coverage, slow CI | Lower coverage, fast CI | Balance based on risk |
| Verification | Open source transparency | Proprietary code | Always verify |
Common Pitfalls
Interview Questions
-
What are the key differences between CREATE and CREATE2 deployment? When would you use each?
CREATE uses sender address and nonce for address derivation, while CREATE2 uses sender address, salt, and init code hash for deterministic addresses. Use CREATE2 when you need address predictability before deployment or for counterfactual instantiation.
-
Explain the trade-offs between different upgrade patterns. How do you choose the right one?
Consider factors like: upgrade frequency (proxy patterns), contract size constraints (diamond pattern), gas costs (transparent vs UUPS), and governance requirements (admin-controlled vs DAO-controlled).
-
What strategies do you use to optimize smart contract gas consumption?
Key strategies include: storage packing, using events over storage for logs, minimizing on-chain data, using efficient data structures, and profiling with Hardhat's gas reporter.
Quiz Questions
-
What is the maximum contract size on Ethereum mainnet?
- A) 32KB
- B) 24KB
- C) 16KB
- D) 48KB
Answer: B - The maximum contract code size is 24,576 bytes (24KB) as per EIP-170.
-
Which compiler setting affects the deployment cost vs runtime cost trade-off?
- A) Optimizer runs
- B) EVM version
- C) Metadata hash
- D) Source mapping
Answer: A - The optimizer
runsparameter determines whether to optimize for deployment cost (low runs) or runtime cost (high runs). -
What is the primary purpose of contract verification on Etherscan?
- A) Reduce gas costs
- B) Enable upgrades
- C) Enable source code transparency
- D) Speed up deployment
Answer: C - Verification allows users to verify that the deployed bytecode matches the source code, enabling transparency and trust.