Blockchain Testing Strategies
Comprehensive testing is essential for smart contract reliability, security, and gas efficiency.
Testing Architecture
Test Networks
Network Configuration
// hardhat.config.js
module.exports = {
networks: {
hardhat: {
forking: {
url: process.env.MAINNET_RPC_URL,
blockNumber: 18000000
}
},
goerli: {
url: process.env.GOERLI_RPC_URL,
accounts: [process.env.PRIVATE_KEY],
chainId: 5
},
sepolia: {
url: process.env.SEPOLIA_RPC_URL,
accounts: [process.env.PRIVATE_KEY],
chainId: 11155111
},
polygonMumbai: {
url: process.env.MUMBAI_RPC_URL,
accounts: [process.env.PRIVATE_KEY],
chainId: 80001
},
arbitrumGoerli: {
url: process.env.ARBITRUM_GOERLI_RPC_URL,
accounts: [process.env.PRIVATE_KEY],
chainId: 421613
}
}
};
Test Network Comparison
| Network | Chain ID | Gas Token | Block Time | Use Case |
|---|---|---|---|---|
| Goerli | 5 | ETH | 12s | Ethereum testing |
| Sepolia | 11155111 | ETH | 12s | Ethereum testing |
| Mumbai | 80001 | MATIC | 2s | Polygon testing |
| Arbitrum Goerli | 421613 | ETH | 0.25s | Arbitrum testing |
| Optimism Goerli | 420 | ETH | 2s | Optimism testing |
| BSC Testnet | 97 | BNB | 3s | BSC testing |
Mainnet Forking
Fork Configuration
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
import "forge-std/Vm.sol";
contract MainnetForkTest is Test {
uint256 constant FORK_BLOCK = 18000000;
function setUp() public {
// Create mainnet fork
vm.createSelectFork(
vm.envString("MAINNET_RPC_URL"),
FORK_BLOCK
);
// Impersonate account
vm.prank(whaleAddress);
// Setup test fixtures
_setupTestContracts();
}
function testSwapOnUniswap() public {
// Fork mainnet state
address uniswapRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
// Execute swap on forked mainnet
IUniswapV2Router router = IUniswapV2Router(uniswapRouter);
uint256 amountIn = 1 ether;
uint256 amountOutMin = router.getAmountsOut(
amountIn,
path
)[path.length - 1] * 95 / 100;
router.swapExactTokensForTokens(
amountIn,
amountOutMin,
path,
address(this),
block.timestamp
);
// Verify swap
assertGt(tokenOut.balanceOf(address(this)), 0);
}
}
Fork Testing Patterns
// Fork testing with Hardhat
import { ethers, network } from "hardhat";
describe("Mainnet Fork Tests", function () {
beforeEach(async function () {
// Reset to forked state
await network.provider.request({
method: "hardhat_reset",
params: [{
forking: {
jsonRpcUrl: process.env.MAINNET_RPC_URL,
blockNumber: 18000000
}
}]
});
// Impersonate account
const [signer] = await ethers.getSigners();
const whale = "0x0000000000000000000000000000000000000000";
await network.provider.request({
method: "hardhat_impersonateAccount",
params: [whale]
});
const whaleSigner = await ethers.getSigner(whale);
// Get whale ETH
await signer.sendTransaction({
to: whale,
value: ethers.parseEther("10")
});
});
it("should interact with real contracts", async function () {
const [signer] = await ethers.getSigners();
// Interact with real Uniswap
const router = await ethers.getContractAt(
"IUniswapV2Router",
"0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D"
);
// Execute swap
const WETH = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2";
const DAI = "0x6B175474E89094C44Da98b954EedeAC495271d0F";
await router.swapExactETHForTokens(
0,
[WETH, DAI],
signer.address,
Math.floor(Date.now() / 1000) + 60 * 20,
{ value: ethers.parseEther("1") }
);
});
});
Gas Snapshot
Gas Reporting
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
import "../src/MyContract.sol";
contract GasTest is Test {
MyContract public myContract;
function setUp() public {
myContract = new MyContract();
}
function testGasTransfer() public {
// Measure gas for transfer
uint256 gasBefore = gasleft();
myContract.transfer(recipient, amount);
uint256 gasUsed = gasBefore - gasleft();
// Assert gas usage
assertLe(gasUsed, 50000, "Gas too high");
}
function testGasBatchTransfer() public {
address[] memory recipients = new address[](100);
uint256[] memory amounts = new uint256[](100);
for (uint256 i = 0; i < 100; i++) {
recipients[i] = address(uint160(i + 1));
amounts[i] = 1 ether;
}
uint256 gasBefore = gasleft();
myContract.batchTransfer(recipients, amounts);
uint256 gasUsed = gasBefore - gasleft();
// Compare with individual transfers
uint256 individualGas = 100 * 50000;
uint256 savings = ((individualGas - gasUsed) * 100) / individualGas;
console.log("Gas savings:", savings, "%");
assertGe(savings, 50, "Insufficient gas savings");
}
}
Gas Optimization Analysis
// Gas analysis script
import { ethers } from "hardhat";
async function analyzeGas() {
const MyContract = await ethers.getContractFactory("MyContract");
const contract = await MyContract.deploy();
const methods = [
"transfer",
"batchTransfer",
"approve",
"transferFrom"
];
const results = [];
for (const method of methods) {
const tx = await contract[method](...getArgs(method));
const receipt = await tx.wait();
results.push({
method,
gasUsed: receipt.gasUsed.toString(),
effectiveGasPrice: receipt.effectiveGasPrice.toString()
});
}
console.table(results);
// Generate report
const report = {
timestamp: new Date().toISOString(),
contract: contract.target,
results
};
fs.writeFileSync(
`gas-report-${Date.now()}.json`,
JSON.stringify(report, null, 2)
);
}
Invariant Testing
Property-Based Testing
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
import "../src/Vault.sol";
contract VaultInvariantTest is Test {
Vault public vault;
IERC20 public token;
uint256 public invariant_totalSupply_equals_deposits;
function setUp() public {
vault = new Vault();
token = new MockToken("Mock", "MCK", 18);
}
// Invariant: Total supply equals total deposits
function invariant_totalSupplyEqualsDeposits() public view {
uint256 totalDeposits = vault.totalDeposits();
uint256 totalSupply = token.balanceOf(address(vault));
assertEq(totalDeposits, totalSupply);
}
// Invariant: User balance never exceeds total
function invariant_userBalanceNeverExceedsTotal() public view {
for (uint256 i = 0; i < 10; i++) {
address user = address(uint160(i + 1));
uint256 userBalance = vault.balances(user);
uint256 totalBalance = vault.totalDeposits();
assertLe(userBalance, totalBalance);
}
}
// Invariant: No unauthorized withdrawals
function invariant_noUnauthorizedWithdrawals() public {
// Fuzz test with random inputs
for (uint256 i = 0; i < 100; i++) {
address user = address(uint160(i + 1));
uint256 amount = bound(i * 1 ether, 0, 100 ether);
vm.prank(user);
vault.withdraw(amount);
// Verify withdrawal was authorized
assertLe(vault.balances(user), amount);
}
}
}
Invariant Testing Framework
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
contract InvariantTest is Test {
struct HandlerState {
uint256 depositCount;
uint256 withdrawCount;
mapping(address => bool) hasDeposited;
}
HandlerState public handlerState;
Vault public vault;
function setUp() public {
vault = new Vault();
targetContract(address(vault));
}
// Handler function for deposits
function deposit(uint256 amount) external {
amount = bound(amount, 1 ether, 100 ether);
deal(address(token), address(this), amount);
token.approve(address(vault), amount);
vault.deposit(amount);
handlerState.depositCount++;
handlerState.hasDeposited[msg.sender] = true;
// Log for debugging
emit Deposit(msg.sender, amount);
}
// Handler function for withdrawals
function withdraw(uint256 amount) external {
amount = bound(amount, 0.1 ether, 10 ether);
vault.withdraw(amount);
handlerState.withdrawCount++;
emit Withdraw(msg.sender, amount);
}
// Invariant properties
function invariant_depositCountGteWithdrawCount() public view {
assertGe(
handlerState.depositCount,
handlerState.withdrawCount
);
}
function invariant_vaultNeverNegative() public view {
assertGe(address(vault).balance, 0);
}
}
Stress Testing
Load Testing
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
contract StressTest is Test {
Vault public vault;
function testStressDeposit() public {
uint256 concurrentUsers = 100;
uint256[] memory amounts = new uint256[](concurrentUsers);
for (uint256 i = 0; i < concurrentUsers; i++) {
amounts[i] = 1 ether;
}
// Execute concurrent deposits
for (uint256 i = 0; i < concurrentUsers; i++) {
address user = address(uint160(i + 1));
vm.deal(user, amounts[i]);
vm.prank(user);
vault.deposit{value: amounts[i]}();
}
// Verify final state
assertEq(
address(vault).balance,
concurrentUsers * 1 ether
);
}
function testStressWithdraw() public {
// Setup: deposit from multiple users
for (uint256 i = 0; i < 100; i++) {
address user = address(uint160(i + 1));
vm.deal(user, 1 ether);
vm.prank(user);
vault.deposit{value: 1 ether}();
}
// Execute concurrent withdrawals
for (uint256 i = 0; i < 100; i++) {
address user = address(uint160(i + 1));
vm.prank(user);
vault.withdraw(1 ether);
}
// Verify final state
assertEq(address(vault).balance, 0);
}
}
Performance Metrics
| Metric | Target | Measurement |
|---|---|---|
| Gas per Deposit | < 50,000 | Gas used |
| Gas per Withdrawal | < 60,000 | Gas used |
| Max Concurrent Users | 1,000+ | Transactions |
| Block Gas Limit | 30M | Gas per block |
| State Growth | < 1MB/year | Storage bytes |
Load Testing
Transaction Load Test
// load-test.js
import { ethers } from "hardhat";
class LoadTester {
constructor(contract, provider) {
this.contract = contract;
this.provider = provider;
this.results = [];
}
async runLoadTest(transactionsPerSecond, duration) {
const startTime = Date.now();
const endTime = startTime + (duration * 1000);
console.log(`Starting load test: ${transactionsPerSecond} tx/s for ${duration}s`);
while (Date.now() < endTime) {
const batch = [];
for (let i = 0; i < transactionsPerSecond; i++) {
batch.push(this.executeTransaction());
}
const results = await Promise.allSettled(batch);
this.results.push(...results);
await this.sleep(1000);
}
return this.analyzeResults();
}
async executeTransaction() {
const startTime = Date.now();
try {
const tx = await this.contract.deposit({
value: ethers.parseEther("0.01")
});
const receipt = await tx.wait();
return {
status: "success",
gasUsed: receipt.gasUsed.toString(),
blockNumber: receipt.blockNumber,
latency: Date.now() - startTime
};
} catch (error) {
return {
status: "error",
error: error.message,
latency: Date.now() - startTime
};
}
}
analyzeResults() {
const successful = this.results.filter(r => r.status === "success");
const failed = this.results.filter(r => r.status === "error");
const avgGas = successful.reduce((sum, r) => sum + parseInt(r.gasUsed), 0) / successful.length;
const avgLatency = successful.reduce((sum, r) => sum + r.latency, 0) / successful.length;
return {
totalTransactions: this.results.length,
successful: successful.length,
failed: failed.length,
successRate: (successful.length / this.results.length) * 100,
avgGasUsed: avgGas,
avgLatency: avgLatency,
transactionsPerSecond: successful.length / (duration || 1)
};
}
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
Trade-offs
| Testing Type | Coverage | Speed | Cost | Complexity |
|---|---|---|---|---|
| Unit Tests | Low | Fast | Low | Low |
| Integration | Medium | Medium | Medium | Medium |
| Fork Tests | High | Slow | High | Medium |
| Invariant | Very High | Slow | Medium | High |
| Stress Tests | Medium | Slow | Medium | Medium |
Real-World Example: Compound V2 Testing
// Compound V2 test suite
contract CompoundV2Test is Test {
Comptroller public comptroller;
CToken public cToken;
function setUp() public {
// Fork mainnet
vm.createSelectFork(
vm.envString("MAINNET_RPC_URL"),
18000000
);
// Deploy on fork
comptroller = ComptrollerDeployer.deploy();
cToken = CTokenDeployer.deploy();
}
function testBorrowAndRepay() public {
// Supply collateral
deal(address(token), address(this), 10 ether);
token.approve(address(cToken), 10 ether);
cToken.mint(10 ether);
// Borrow
uint256 borrowAmount = 5 ether;
cToken.borrow(borrowAmount);
// Verify borrow
assertEq(cToken.borrowBalanceCurrent(address(this)), borrowAmount);
// Repay
token.approve(address(cToken), borrowAmount);
cToken.repayBorrow(borrowAmount);
// Verify repay
assertEq(cToken.borrowBalanceCurrent(address(this)), 0);
}
function testLiquidation() public {
// Setup positions
_setupCollateralPosition();
_setupBorrowPosition();
// Drop collateral price
oracle.setUnderlyingPrice(cToken, 0.5 ether);
// Attempt liquidation
vm.prank(liquidator);
comptroller.liquidateBorrow(
borrower,
repayAmount,
cTokenCollateral
);
// Verify liquidation
assertGt(cTokenCollateral.balanceOf(liquidator), 0);
}
}
Interview Questions
-
Explain the difference between unit tests, integration tests, and fork tests. When would you use each approach?
-
How does invariant testing work, and what are its advantages over traditional property-based testing?
-
Design a comprehensive testing strategy for a DeFi protocol that handles $100M+ in TVL. What testing stages would you implement?
Quiz Questions
-
What is the primary advantage of mainnet forking in testing?
- A) Faster execution
- B) Lower gas costs
- C) Real-world state testing
- D) Better documentation
-
Which testing framework uses invariant properties for smart contract testing?
- A) Hardhat
- B) Foundry
- C) Truffle
- D) Remix
-
What is the recommended gas usage target for a simple ERC20 transfer?
- A) < 21,000 gas
- B) < 50,000 gas
- C) < 100,000 gas
- D) < 200,000 gas