Testing Smart Contracts
Smart contracts are immutable once deployed. Bugs can lead to permanent loss of funds. Rigorous testing before deployment is not optional — it is essential.
Testing Pyramid
┌──────────────┐
│ Manual / │
│ Audit │ ← Fewest, most expensive
├──────────────┤
│ Integration │
│ Tests │ ← Multiple contracts interacting
├──────────────┤
│ Unit │
│ Tests │ ← Most tests, cheapest
└──────────────┘
Unit Tests: Test individual functions in isolation
Integration Tests: Test contract interactions
Audits: Professional security review
Unit Testing with Hardhat
const { expect } = require("chai");
const { ethers } = require("hardhat");
describe("Token", function () {
let token, owner, addr1;
beforeEach(async function () {
[owner, addr1] = await ethers.getSigners();
const Token = await ethers.getContractFactory("Token");
token = await Token.deploy("MyToken", "MTK", 1000000);
});
it("Should set correct name and symbol", async function () {
expect(await token.name()).to.equal("MyToken");
expect(await token.symbol()).to.equal("MTK");
});
it("Should assign total supply to deployer", async function () {
expect(await token.balanceOf(owner.address))
.to.equal(1000000);
});
it("Should transfer tokens between accounts", async function () {
await token.transfer(addr1.address, 100);
expect(await token.balanceOf(addr1.address))
.to.equal(100);
});
it("Should fail if sender lacks balance", async function () {
await expect(
token.connect(addr1).transfer(owner.address, 1)
).to.be.revertedWith("Insufficient balance");
});
});
Integration Testing
describe("DeFi Integration", function () {
it("Should deposit, borrow, and repay", async function () {
// Deploy both LendingPool and Token contracts
// Deposit collateral
// Borrow against collateral
// Verify balances
// Repay loan
// Verify full cycle
});
});
Security Audit Checklist
✓ Reentrancy vulnerabilities
✓ Integer overflow/underflow
✓ Access control (onlyOwner, roles)
✓ Front-running risks
✓ Flash loan attack vectors
✓ Oracle manipulation
✓ Denial of service (DoS)
✓ Unchecked external calls
✓ Centralization risks
✓ Gas limit and DoS with block gas