Testing & Deployment
Because deployed contracts are hard or impossible to change, testing before deployment matters even more than in other software. This lesson gives an overview of the professional workflow: development frameworks, unit tests, test networks and deployment scripts. The framework code below is shown in non-runnable blocks; the testing ideas are demonstrated with runnable Solidity.
The toolchain
| Tool | What it is |
|---|---|
Foundry (forge, cast, anvil) |
Fast Rust-based toolkit; tests are written in Solidity |
| Hardhat | JavaScript/TypeScript framework; tests usually in TypeScript with ethers.js or viem |
| Remix | Browser IDE, good for quick experiments |
| anvil / Hardhat Network | Local development chains with pre-funded test accounts |
| Testnets (e.g. Sepolia) | Public networks with valueless test ether |
| Slither, Mythril, Echidna | Static analysis, symbolic execution, fuzzing |
The account 0xf39F…2266 that this playground uses is the first default test account of Hardhat and anvil, so you'll recognize it later.
Tests in Solidity (Foundry)
A Foundry test is a contract whose functions start with test. setUp() runs before each test, and "cheatcodes" on the vm object control the environment: impersonate an account, set the time, expect a revert.
// test/Counter.t.sol
import { Test } from "forge-std/Test.sol";
import { Counter } from "../src/Counter.sol";
contract CounterTest is Test {
Counter counter;
function setUp() public {
counter = new Counter();
}
function test_IncrementAddsOne() public {
counter.increment();
assertEq(counter.count(), 1);
}
function test_RevertWhen_NotOwnerResets() public {
vm.prank(address(0xBAD)); // next call comes from 0xBAD
vm.expectRevert("not owner");
counter.reset();
}
function testFuzz_IncrementBy(uint8 n) public { // random inputs, many runs
for (uint256 i = 0; i < n; i++) counter.increment();
assertEq(counter.count(), n);
}
}forge test -vv # run all tests with logs
forge test --gas-report # gas used per function
forge coverage # which lines were testedThe same idea, runnable here
Without a framework, a test is simply a contract that sets up a scenario, calls functions and checks results. Main can act as a tiny test runner, using try/catch to check expected reverts:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Counter {
address public owner = msg.sender;
uint256 public count;
function increment() external { count += 1; }
function reset() external {
require(msg.sender == owner, "not owner");
count = 0;
}
}
contract Intruder {
function reset(Counter c) external { c.reset(); }
}
contract Main {
uint256 passed;
uint256 failed;
function check(bool ok, string memory name) internal {
if (ok) { passed++; console.log("PASS", name); }
else { failed++; console.log("FAIL", name); }
}
function main() external {
Counter c = new Counter();
c.increment();
check(c.count() == 1, "increment adds one");
c.increment();
c.reset();
check(c.count() == 0, "owner can reset");
Intruder intruder = new Intruder();
try intruder.reset(c) {
check(false, "non-owner reset reverts");
} catch Error(string memory reason) {
check(keccak256(bytes(reason)) == keccak256("not owner"), "non-owner reset reverts");
}
console.log("passed:", passed, "failed:", failed);
}
}PASS increment adds one
PASS owner can reset
PASS non-owner reset reverts
passed: 3 failed: 0
Test the unhappy paths as carefully as the happy ones: who must not be able to call a function, which inputs must revert, what happens at limits (0, maximum values, empty arrays, deadlines exactly at block.timestamp).
Invariant thinking
Beyond single tests, state invariants: properties that must hold after any sequence of calls. For a token: "the sum of all balances equals totalSupply". Fuzzers like Foundry's invariant tests and Echidna call functions in random orders and check them:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Token {
mapping(address => uint256) public balanceOf;
uint256 public totalSupply;
function mint(address to, uint256 v) external { balanceOf[to] += v; totalSupply += v; }
function transfer(address from, address to, uint256 v) external {
require(balanceOf[from] >= v, "balance");
balanceOf[from] -= v;
balanceOf[to] += v;
}
}
contract Main {
function main() external {
Token t = new Token();
address[3] memory users = [address(0x1), address(0x2), address(0x3)];
t.mint(users[0], 100);
// a deterministic pseudo-random sequence of operations
uint256 seed = 12345;
for (uint256 step = 0; step < 50; step++) {
seed = uint256(keccak256(abi.encode(seed)));
address from = users[seed % 3];
address to = users[(seed >> 8) % 3];
uint256 amount = (seed >> 16) % 40;
try t.transfer(from, to, amount) {} catch {}
if (step % 10 == 0) t.mint(to, 5);
}
uint256 sum = t.balanceOf(users[0]) + t.balanceOf(users[1]) + t.balanceOf(users[2]);
console.log("sum of balances:", sum);
console.log("totalSupply :", t.totalSupply());
console.log("invariant holds?", sum == t.totalSupply());
}
}sum of balances: 125
totalSupply : 125
invariant holds? true
Testing from TypeScript (Hardhat)
import { expect } from "chai";
import { ethers } from "hardhat";
describe("Counter", () => {
it("increments", async () => {
const counter = await ethers.deployContract("Counter");
await counter.increment();
expect(await counter.count()).to.equal(1n);
});
it("rejects strangers", async () => {
const [, stranger] = await ethers.getSigners();
const counter = await ethers.deployContract("Counter");
await expect(counter.connect(stranger).reset()).to.be.revertedWith("not owner");
});
});Deployment
A deployment is just a transaction whose data is the bytecode plus encoded constructor arguments. Frameworks script it:
// script/Deploy.s.sol (Foundry)
import { Script } from "forge-std/Script.sol";
import { Counter } from "../src/Counter.sol";
contract Deploy is Script {
function run() external {
vm.startBroadcast(); // sign with the key given on the command line
new Counter();
vm.stopBroadcast();
}
}forge script script/Deploy.s.sol --rpc-url $SEPOLIA_RPC_URL --account deployer --broadcast --verifyA sensible release process:
- All tests and static analysis pass; coverage of critical paths is high.
- Deploy to a local chain, then a testnet, and try the full user flow there.
- Get a review or audit for anything that will hold other people's assets.
- Deploy to mainnet from a well-protected key (hardware wallet or multisig), never from a key pasted into a script.
- Verify the source code on a block explorer so users can read what they interact with.
- Hand admin rights to a multisig/timelock and set up monitoring of events.
Warning: Never commit private keys or seed phrases to a repository, and never reuse a test account's well-known key on a real network: those keys are public, and anything sent to them is taken immediately.
Test yourself
In Foundry, what does vm.prank(addr) do?
- Deploys a contract at addr
- Makes the next call come from
addras msg.sender - Gives addr ether
- Pauses the test
What is an invariant in contract testing?
- A variable marked
constant - A property that must hold after any sequence of calls
- A test that never changes
- A gas limit
Why verify the contract source on a block explorer after deploying?
- It lowers gas costs
- So anyone can check that the deployed bytecode matches the published source
- It's needed for the contract to run
- It makes the contract upgradeable